src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
SearchInDoubleDimArray { public static boolean findByBinarySearch(int target, int [][] array) { if (array.length <= 0){ return false; } if (array[0].length <= 0){ return false; } int rowSize = array.length; int rankSize = array[0].length; if (target < array[0][0] || target > array[rowSize-1][rankSize-1]){ return false; } AtomicBoolean result = new AtomicBoolean(false); Arrays.stream(array).forEach(row -> { if (Arrays.binarySearch(row,target) >= 0){ result.set(true); } }); return result.get(); } static boolean findByBinarySearch(int target, int [][] array); static boolean convertListQuery(int target, int [][] array); static void main(String[] args); } | @Test void find() { Random random = new Random(); inputs.forEach(array -> { int randomInt = random.nextInt(40)*10; boolean reault = SearchInDoubleDimArray.findByBinarySearch(randomInt,array); System.out.println(randomInt + " result " + reault); }); } |
DoubleStackArithmeticExpression { public int calculate(String expression){ Stack<Integer> vals = new Stack<>(); Stack<Character> op = new Stack<>(); for (char var : expression.toCharArray()){ } return 0; } int calculate(String expression); } | @Test void calculate() { String expression = "(2+(2*4))"; int expected = 10; int result = doubleStackArithmeticExpression.calculate(expression); Assert.assertEquals(expected,result); } |
FirstMissingPositive { public int firstMissingPositive(int[] nums) { int n = nums.length; if (n == 0) { return 1; } if (n == 1) { return nums[0] == 1 ? 2 : 1; } for (int i = 0; i < n; i++) { while (nums[i] > 0 && nums[i] < n && nums[i] != nums[nums[i]]) { swap(nums, i, nums[i]); } } for (int i = 1; i < n; i++) { if (nums[i] != i) { return i; } } return nums[0] == n ? n + 1 : n; } int firstMissingPositive(int[] nums); int firstMissingPositive2(int[] nums); } | @Test void test1() { Assert.assertEquals(3, firstMissingPositive.firstMissingPositive(new int[]{1,2,0})); Assert.assertEquals(2, firstMissingPositive.firstMissingPositive(new int[]{3,4,-1,1})); Assert.assertEquals(1, firstMissingPositive.firstMissingPositive(new int[]{7,8,9,11,12})); } |
FirstMissingPositive { public int firstMissingPositive2(int[] nums) { if (nums.length == 0) { return 1; } if (nums.length == 1) { return nums[0] == 1 ? 2 : 1; } int min = 1; while (contain(nums, min) || min < 1) { ++min; } return min; } int firstMissingPositive(int[] nums); int firstMissingPositive2(int[] nums); } | @Test void firstMissingPositive2() { Assert.assertEquals(3, firstMissingPositive.firstMissingPositive2(new int[]{1,2,0})); Assert.assertEquals(2, firstMissingPositive.firstMissingPositive2(new int[]{3,4,-1,1})); Assert.assertEquals(1, firstMissingPositive.firstMissingPositive2(new int[]{7,8,9,11,12})); } |
RabbitmqClientDemo implements ClientDemo { @Override public void declareQueue() throws IOException { Connection connection = connection(connectionFactory()); Channel channel = connection.createChannel(); try { channel.queueDeclare("demo1",true,false,false,null); }catch (IOException e){ if ("406".equals(((AMQImpl.Channel.Close) (((ShutdownSignalException)e.getCause())).getReason()).getReplyCode())){ channel = connection.createChannel(); channel.queueDelete("demo1"); channel.queueDeclare("demo1",false,false,false,null); } } } ConnectionFactory connectionFactory(); Connection connection(ConnectionFactory connectionFactory); @Override void declareQueue(); } | @Test void declareQueue() throws IOException { new RabbitmqClientDemo().declareQueue(); } |
TwoSum { public int[] twoSum(int[] nums, int target) { int len = nums.length; HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < len; ++i) { if (map.containsKey(nums[i])) { return new int[]{map.get(nums[i]), i}; } map.put(target - nums[i], i); } return null; } int[] twoSum(int[] nums, int target); int[] twoSum1(int[] nums, int target); } | @Test void twoSum() { } |
MethodMonitorProcessor { @Around("pointcut() && @annotation(monitor)") public Object logExecutionTime(ProceedingJoinPoint joinPoint, MethodMonitor monitor) throws Throwable { MethodMonitor.LogPrintLogic logPrintLogic; try { logPrintLogic = context.getBean(monitor.logic()); }catch (Exception ex){ log.error("未找到日志打印逻辑: {}, 将使用默认逻辑打印日志!", monitor.logic()); logPrintLogic = context.getBean(DefaultLogPrintLogic.class); } return logPrintLogic.build(joinPoint); } @Around("pointcut() && @annotation(monitor)") Object logExecutionTime(ProceedingJoinPoint joinPoint, MethodMonitor monitor); @Bean DefaultLogPrintLogic logPrintLogic(); } | @Test void logExecutionTime() { userService.addUser("xiaoming"); assertThrows(NullPointerException.class, () -> userService.addUser("小明", 123)); } |
StaticJdkProxyDemo implements UserService { @Override public void addUser(String name) { log.warn("before add user"); userService.addUser(name); log.warn("after add user"); } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); @Override String getUsernameFromSelf(String name); } | @Test void addUser() { staticJdkProxyDemo.addUser("xiaoming"); } |
StaticJdkProxyDemo implements UserService { @Override public void removeUser(String name) { log.warn("before remove user"); userService.removeUser(name); log.warn("after remove user"); } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); @Override String getUsernameFromSelf(String name); } | @Test void removeUser() { staticJdkProxyDemo.getUsernameFromSelf("xiaoming"); } |
StaticJdkProxyDemo implements UserService { @Override public String getUsername(String name) { log.warn("before get username"); String username = userService.getUsername(name); log.warn("after get username"); return username; } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); @Override String getUsernameFromSelf(String name); } | @Test void getUsername() { } |
StaticCglibProxyDemo extends UserServiceImpl { @Override public void addUser(String name) { log.warn("before add user"); super.addUser(name); log.warn("after add user"); } @Override void addUser(String name); @Override void removeUser(String name); @Override String getUsername(String name); } | @Test void addUser() { cglibProxyDemo.addUser("xiaoming"); } |
PollexorRequestTransformer implements RequestTransformer { @NonNull @Override public Request transformRequest(@NonNull Request request) { if (request.resourceId != 0) { return request; } Uri uri = request.uri; if (uri == null) { throw new IllegalArgumentException("Null uri passed to " + getClass().getCanonicalName()); } String scheme = uri.getScheme(); if (!"https".equals(scheme) && !"http".equals(scheme)) { return request; } if (!request.hasSize() && !alwaysTransform) { return request; } Request.Builder newRequest = request.newBuilder(); ThumborUrlBuilder urlBuilder = thumbor.buildImage(uri.toString()); if (request.hasSize()) { urlBuilder.resize(request.targetWidth, request.targetHeight); newRequest.clearResize(); } if (request.centerInside) { urlBuilder.fitIn(); newRequest.clearCenterInside(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { urlBuilder.filter(format(ImageFormat.WEBP)); } newRequest.setUri(Uri.parse(urlBuilder.toUrl())); return newRequest.build(); } PollexorRequestTransformer(@NonNull Thumbor thumbor); PollexorRequestTransformer(@NonNull Thumbor thumbor, boolean alwaysTransform); @NonNull @Override Request transformRequest(@NonNull Request request); } | @Test public void resourceIdRequestsAreNotTransformed() { Request input = new Request.Builder(12).build(); Request output = transformer.transformRequest(input); assertThat(output).isSameAs(input); }
@Test public void simpleResizeWithCenterInsideAndEncryption() { Request input = new Request.Builder(IMAGE_URI).resize(50, 50).centerInside().build(); Request output = secureTransformer.transformRequest(input); assertThat(output).isNotSameAs(input); assertThat(output.hasSize()).isFalse(); assertThat(output.centerInside).isFalse(); String expected = Thumbor.create(HOST, KEY).buildImage(IMAGE).resize(50, 50).fitIn().toUrl(); assertThat(output.uri.toString()).isEqualTo(expected); }
@Test public void resourceIdRequestsAreNotTransformedWhenAlwaysTransformIsTrue() { Request input = new Request.Builder(12).build(); Request output = alwaysResizeTransformer.transformRequest(input); assertThat(output).isSameAs(input); }
@Test public void nonHttpRequestsAreNotTransformed() { Request input = new Request.Builder(IMAGE_URI).build(); Request output = transformer.transformRequest(input); assertThat(output).isSameAs(input); }
@Test public void nonResizedRequestsAreNotTransformed() { Request input = new Request.Builder(IMAGE_URI).build(); Request output = transformer.transformRequest(input); assertThat(output).isSameAs(input); }
@Test public void nonResizedRequestsAreTransformedWhenAlwaysTransformIsSet() { Request input = new Request.Builder(IMAGE_URI).build(); Request output = alwaysResizeTransformer.transformRequest(input); assertThat(output).isNotSameAs(input); assertThat(output.hasSize()).isFalse(); String expected = Thumbor.create(HOST).buildImage(IMAGE).toUrl(); assertThat(output.uri.toString()).isEqualTo(expected); }
@Test public void simpleResize() { Request input = new Request.Builder(IMAGE_URI).resize(50, 50).build(); Request output = transformer.transformRequest(input); assertThat(output).isNotSameAs(input); assertThat(output.hasSize()).isFalse(); String expected = Thumbor.create(HOST).buildImage(IMAGE).resize(50, 50).toUrl(); assertThat(output.uri.toString()).isEqualTo(expected); }
@Config(sdk = 18) @Test public void simpleResizeOnJbMr2UsesWebP() { Request input = new Request.Builder(IMAGE_URI).resize(50, 50).build(); Request output = transformer.transformRequest(input); assertThat(output).isNotSameAs(input); assertThat(output.hasSize()).isFalse(); String expected = Thumbor.create(HOST) .buildImage(IMAGE) .resize(50, 50) .filter(format(ImageFormat.WEBP)) .toUrl(); assertThat(output.uri.toString()).isEqualTo(expected); }
@Test public void simpleResizeWithCenterCrop() { Request input = new Request.Builder(IMAGE_URI).resize(50, 50).centerCrop().build(); Request output = transformer.transformRequest(input); assertThat(output).isNotSameAs(input); assertThat(output.hasSize()).isFalse(); assertThat(output.centerCrop).isFalse(); String expected = Thumbor.create(HOST).buildImage(IMAGE).resize(50, 50).toUrl(); assertThat(output.uri.toString()).isEqualTo(expected); }
@Test public void simpleResizeWithCenterInside() { Request input = new Request.Builder(IMAGE_URI).resize(50, 50).centerInside().build(); Request output = transformer.transformRequest(input); assertThat(output).isNotSameAs(input); assertThat(output.hasSize()).isFalse(); assertThat(output.centerInside).isFalse(); String expected = Thumbor.create(HOST).buildImage(IMAGE).resize(50, 50).fitIn().toUrl(); assertThat(output.uri.toString()).isEqualTo(expected); }
@Test public void simpleResizeWithEncryption() { Request input = new Request.Builder(IMAGE_URI).resize(50, 50).build(); Request output = secureTransformer.transformRequest(input); assertThat(output).isNotSameAs(input); assertThat(output.hasSize()).isFalse(); String expected = Thumbor.create(HOST, KEY).buildImage(IMAGE).resize(50, 50).toUrl(); assertThat(output.uri.toString()).isEqualTo(expected); } |
ClientWave { public Wavelet fetchWavelet(WaveId waveId, WaveletId waveletId) throws ClientWaveException { return fetchWavelet(waveId, waveletId, null); } ClientWave(JSONRpcHandler jsonHandler); List<JsonRpcResponse> submit(Wavelet wavelet); Wavelet blindWavelet(WaveId waveId, WaveletId waveletId); Wavelet blindWavelet(WaveId waveId, WaveletId waveletId,
String proxyForId); Wavelet blindWavelet(WaveId waveId, WaveletId waveletId,
String proxyForId, Map<String, Blip> blips); Wavelet newWave(String domain, Set<String> participants); Wavelet newWave(String domain, Set<String> participants,
String proxyForId); Wavelet newWave(String domain, Set<String> participants, String msg,
String proxyForId); Wavelet newWaveWithSubmit(String domain, Set<String> participants,
String msg, String proxyForId); Wavelet fetchWavelet(WaveId waveId, WaveletId waveletId); Wavelet fetchWavelet(WaveId waveId, WaveletId waveletId,
String proxyForId); SearchResult search(String query, int index, int numResults); void folder(FolderAction action, WaveId waveId); } | @Test public void testEmptyDeserialize() throws Exception { ClientWave wave = new ClientWave(new JSONRpcHandler() { public String request(String jsonBody) throws Exception { Assert .assertEquals( "[{\"method\":\"wave.robot.fetchWave\",\"id\":\"op1\",\"params\":{\"waveId\":\"googlewave.com!testwaveid\",\"waveletId\":\"googlewave.com!conv+root\"}}]", jsonBody); return "[{\"id\":\"op1\",\"data\":{}}]"; } }); Wavelet wavelet = wave.fetchWavelet(new WaveId("googlewave.com", "testwaveid"), new WaveletId("googlewave.com", "conv+root")); Assert.assertNull(wavelet); } |
DatastoreFactory { public HttpRequestFactory makeClient(DatastoreOptions options) { Credential credential = options.getCredential(); HttpTransport transport = options.getTransport(); if (transport == null) { transport = credential == null ? new NetHttpTransport() : credential.getTransport(); transport = transport == null ? new NetHttpTransport() : transport; } return transport.createRequestFactory(credential); } static DatastoreFactory get(); Datastore create(DatastoreOptions options); HttpRequestFactory makeClient(DatastoreOptions options); static void logMethodCalls(); static final String VERSION; static final String DEFAULT_HOST; } | @Test public void makeClient_Default() { DatastoreOptions options = new DatastoreOptions.Builder() .projectId(PROJECT_ID) .build(); HttpRequestFactory f = factory.makeClient(options); assertNotNull(f.getTransport()); assertTrue(f.getTransport() instanceof NetHttpTransport); }
@Test public void makeClient_WithCredential() { NetHttpTransport transport = new NetHttpTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(transport) .build(); DatastoreOptions options = new DatastoreOptions.Builder() .projectId(PROJECT_ID) .credential(credential) .build(); HttpRequestFactory f = factory.makeClient(options); assertEquals(transport, f.getTransport()); }
@Test public void makeClient_WithTransport() { NetHttpTransport transport = new NetHttpTransport(); DatastoreOptions options = new DatastoreOptions.Builder() .projectId(PROJECT_ID) .transport(transport) .build(); HttpRequestFactory f = factory.makeClient(options); assertEquals(transport, f.getTransport()); }
@Test public void makeClient_WithCredentialTransport() { NetHttpTransport credTransport = new NetHttpTransport(); NetHttpTransport transport = new NetHttpTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(credTransport) .build(); DatastoreOptions options = new DatastoreOptions.Builder() .projectId(PROJECT_ID) .credential(credential) .transport(transport) .build(); HttpRequestFactory f = factory.makeClient(options); assertNotSame(credTransport, f.getTransport()); assertEquals(transport, f.getTransport()); } |
Datastore { public AllocateIdsResponse allocateIds(AllocateIdsRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("allocateIds", request)) { return AllocateIdsResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("allocateIds", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); } | @Test public void initializer() throws Exception { options.initializer(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { request.getHeaders().setCookie("magic"); } }); Datastore datastore = factory.create(options.build()); MockDatastoreFactory mockClient = (MockDatastoreFactory) factory; AllocateIdsRequest request = AllocateIdsRequest.newBuilder().build(); AllocateIdsResponse response = AllocateIdsResponse.newBuilder().build(); mockClient.setNextResponse(response); assertEquals(response, datastore.allocateIds(request)); assertEquals("magic", mockClient.lastCookies.get(0)); }
@Test public void allocateIds() throws Exception { AllocateIdsRequest.Builder request = AllocateIdsRequest.newBuilder(); AllocateIdsResponse.Builder response = AllocateIdsResponse.newBuilder(); expectRpc("allocateIds", request.build(), response.build()); } |
Datastore { public LookupResponse lookup(LookupRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("lookup", request)) { return LookupResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("lookup", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); } | @Test public void lookup() throws Exception { LookupRequest.Builder request = LookupRequest.newBuilder(); LookupResponse.Builder response = LookupResponse.newBuilder(); expectRpc("lookup", request.build(), response.build()); } |
Datastore { public BeginTransactionResponse beginTransaction(BeginTransactionRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("beginTransaction", request)) { return BeginTransactionResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("beginTransaction", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); } | @Test public void beginTransaction() throws Exception { BeginTransactionRequest.Builder request = BeginTransactionRequest.newBuilder(); BeginTransactionResponse.Builder response = BeginTransactionResponse.newBuilder(); response.setTransaction(ByteString.copyFromUtf8("project-id")); expectRpc("beginTransaction", request.build(), response.build()); } |
Datastore { public CommitResponse commit(CommitRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("commit", request)) { return CommitResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("commit", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); } | @Test public void commit() throws Exception { CommitRequest.Builder request = CommitRequest.newBuilder(); request.setTransaction(ByteString.copyFromUtf8("project-id")); CommitResponse.Builder response = CommitResponse.newBuilder(); expectRpc("commit", request.build(), response.build()); } |
Datastore { public ReserveIdsResponse reserveIds(ReserveIdsRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("reserveIds", request)) { return ReserveIdsResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("reserveIds", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); } | @Test public void reserveIds() throws Exception { ReserveIdsRequest.Builder request = ReserveIdsRequest.newBuilder(); ReserveIdsResponse.Builder response = ReserveIdsResponse.newBuilder(); expectRpc("reserveIds", request.build(), response.build()); } |
Datastore { public RollbackResponse rollback(RollbackRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("rollback", request)) { return RollbackResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("rollback", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); } | @Test public void rollback() throws Exception { RollbackRequest.Builder request = RollbackRequest.newBuilder(); request.setTransaction(ByteString.copyFromUtf8("project-id")); RollbackResponse.Builder response = RollbackResponse.newBuilder(); expectRpc("rollback", request.build(), response.build()); } |
Datastore { public RunQueryResponse runQuery(RunQueryRequest request) throws DatastoreException { try (InputStream is = remoteRpc.call("runQuery", request)) { return RunQueryResponse.parseFrom(is); } catch (IOException exception) { throw invalidResponseException("runQuery", exception); } } Datastore(RemoteRpc remoteRpc); void resetRpcCount(); int getRpcCount(); AllocateIdsResponse allocateIds(AllocateIdsRequest request); BeginTransactionResponse beginTransaction(BeginTransactionRequest request); CommitResponse commit(CommitRequest request); LookupResponse lookup(LookupRequest request); ReserveIdsResponse reserveIds(ReserveIdsRequest request); RollbackResponse rollback(RollbackRequest request); RunQueryResponse runQuery(RunQueryRequest request); } | @Test public void runQuery() throws Exception { RunQueryRequest.Builder request = RunQueryRequest.newBuilder(); request.getQueryBuilder(); RunQueryResponse.Builder response = RunQueryResponse.newBuilder(); response.getBatchBuilder() .setEntityResultType(EntityResult.ResultType.FULL) .setMoreResults(QueryResultBatch.MoreResultsType.NOT_FINISHED); expectRpc("runQuery", request.build(), response.build()); } |
DatastoreEmulator extends Datastore { @Deprecated public synchronized void start(String emulatorDir, String projectId, String... commandLineOptions) throws DatastoreEmulatorException { checkNotNull(emulatorDir, "emulatorDir cannot be null"); checkNotNull(projectId, "projectId cannot be null"); checkState(state == State.NEW, "Cannot call start() more than once."); try { startEmulatorInternal( emulatorDir + "/cloud_datastore_emulator", projectId, Arrays.asList(commandLineOptions)); state = State.STARTED; } finally { if (state != State.STARTED) { state = State.STOPPED; } } } DatastoreEmulator(RemoteRpc rpc, String localHost, DatastoreEmulatorOptions options); void clear(); @Deprecated synchronized void start(String emulatorDir, String projectId, String... commandLineOptions); synchronized void start(); synchronized void stop(); synchronized File getProjectDirectory(); } | @Test public void testArgs() throws DatastoreEmulatorException { DatastoreEmulator datastore = new DatastoreEmulator(null, "blar", options) { @Override void startEmulatorInternal( String emulatorDir, String projectId, List<String> cmdLineOpts) { } }; try { datastore.start(null, "projectId"); fail("expected exception"); } catch (NullPointerException npe) { } try { datastore.start("path/to/emulator", null); fail("expected exception"); } catch (NullPointerException npe) { } datastore.start("path/to/emulator", "projectId"); } |
DatastoreHelper { public static Key.Builder makeKey(Object... elements) { Key.Builder key = Key.newBuilder(); PartitionId partitionId = null; for (int pathIndex = 0; pathIndex < elements.length; pathIndex += 2) { PathElement.Builder pathElement = PathElement.newBuilder(); Object element = elements[pathIndex]; if (element instanceof Key) { Key subKey = (Key) element; if (partitionId == null) { partitionId = subKey.getPartitionId(); } else if (!partitionId.equals(subKey.getPartitionId())) { throw new IllegalArgumentException("Partition IDs did not match, found: " + partitionId + " and " + subKey.getPartitionId()); } key.addAllPath(((Key) element).getPathList()); pathIndex--; } else { String kind; try { kind = (String) element; } catch (ClassCastException e) { throw new IllegalArgumentException("Expected string or Key, got: " + element.getClass()); } pathElement.setKind(kind); if (pathIndex + 1 < elements.length) { Object value = elements[pathIndex + 1]; if (value instanceof String) { pathElement.setName((String) value); } else if (value instanceof Long) { pathElement.setId((Long) value); } else if (value instanceof Integer) { pathElement.setId((Integer) value); } else if (value instanceof Short) { pathElement.setId((Short) value); } else { throw new IllegalArgumentException( "Expected string or integer, got: " + value.getClass()); } } key.addPath(pathElement); } } if (partitionId != null && !partitionId.equals(PartitionId.getDefaultInstance())) { key.setPartitionId(partitionId); } return key; } private DatastoreHelper(); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile); static Credential getServiceAccountCredential(String serviceAccountId,
String privateKeyFile, Collection<String> serviceAccountScopes); static Credential getServiceAccountCredential(String serviceAccountId,
PrivateKey privateKey, Collection<String> serviceAccountScopes); static DatastoreOptions.Builder getOptionsFromEnv(); @Nullable static String getProjectIdFromComputeEngine(); static Datastore getDatastoreFromEnv(); static QuerySplitter getQuerySplitter(); static Comparator<Key> getKeyComparator(); static PropertyOrder.Builder makeOrder(String property,
PropertyOrder.Direction direction); static Filter.Builder makeAncestorFilter(Key ancestor); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value value); static Filter.Builder makeFilter(String property, PropertyFilter.Operator operator,
Value.Builder value); static Filter.Builder makeAndFilter(Filter... subfilters); static Filter.Builder makeAndFilter(Iterable<Filter> subfilters); static PropertyReference.Builder makePropertyReference(String propertyName); static Value.Builder makeValue(Iterable<Value> values); static Value.Builder makeValue(Value value1, Value value2, Value... rest); static Value.Builder makeValue(Value.Builder value1, Value.Builder value2,
Value.Builder... rest); static Value.Builder makeValue(Key key); static Value.Builder makeValue(Key.Builder key); static Value.Builder makeValue(long key); static Value.Builder makeValue(double value); static Value.Builder makeValue(boolean value); static Value.Builder makeValue(String value); static Value.Builder makeValue(Entity entity); static Value.Builder makeValue(Entity.Builder entity); static Value.Builder makeValue(ByteString blob); static Value.Builder makeValue(Date date); static Value.Builder makeValue(LatLng value); static Value.Builder makeValue(LatLng.Builder value); static Key.Builder makeKey(Object... elements); static double getDouble(Value value); static Key getKey(Value value); static ByteString getByteString(Value value); static Entity getEntity(Value value); static String getString(Value value); static boolean getBoolean(Value value); static long getLong(Value value); static long getTimestamp(Value value); static List<Value> getList(Value value); static Date toDate(Value value); static Mutation.Builder makeInsert(Entity entity); static Mutation.Builder makeUpdate(Entity entity); static Mutation.Builder makeUpsert(Entity entity); static Mutation.Builder makeDelete(Key key); static final String SCATTER_PROPERTY_NAME; static final String KEY_PROPERTY_NAME; static final String PROJECT_ID_ENV_VAR; static final String LOCAL_HOST_ENV_VAR; static final String SERVICE_ACCOUNT_ENV_VAR; static final String PRIVATE_KEY_FILE_ENV_VAR; } | @Test public void testMakeKey_BadTypeForKind() { try { DatastoreHelper.makeKey(new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } }
@Test public void testMakeKey_BadTypeForNameId() { try { DatastoreHelper.makeKey("kind", new Object()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } }
@Test public void testMakeKey_Empty() { assertEquals(Key.newBuilder().build(), DatastoreHelper.makeKey().build()); }
@Test public void testMakeKey_Incomplete() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Foo")) .build(), makeKey("Foo").build()); }
@Test public void testMakeKey_IdInt() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Foo").setId(1)) .build(), makeKey("Foo", 1).build()); }
@Test public void testMakeKey_IdLong() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Foo").setId(1)) .build(), makeKey("Foo", 1L).build()); }
@Test public void testMakeKey_IdShort() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Foo").setId(1)) .build(), makeKey("Foo", (short) 1).build()); }
@Test public void testMakeKey_Name() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Foo").setName("hi")) .build(), makeKey("Foo", "hi").build()); }
@Test public void testMakeKey_KindNameKind() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Foo").setName("hi")) .addPath(Key.PathElement.newBuilder().setKind("Bar")) .build(), makeKey("Foo", "hi", "Bar").build()); }
@Test public void testMakeKey_KeyKind() { assertEquals( Key.newBuilder() .addPath(PARENT.getPath(0)) .addPath(Key.PathElement.newBuilder().setKind("Child")) .build(), makeKey(PARENT, "Child").build()); }
@Test public void testMakeKey_KindIdKeyKind() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Grandparent").setId(24L)) .addPath(PARENT.getPath(0)) .addPath(Key.PathElement.newBuilder().setKind("Child")) .build(), makeKey("Grandparent", 24L, PARENT, "Child").build()); }
@Test public void testMakeKey_KindIdKey() { assertEquals( Key.newBuilder() .addPath(Key.PathElement.newBuilder().setKind("Grandparent").setId(24L)) .addPath(PARENT.getPath(0)) .build(), makeKey("Grandparent", 24L, PARENT).build()); }
@Test public void testMakeKey_KeyKindIdKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(Key.PathElement.newBuilder().setKind("Parent").setId(23L)) .addPath(CHILD.getPath(0)) .build(), makeKey(GRANDPARENT, "Parent", 23, CHILD).build()); }
@Test public void testMakeKey_Key() { assertEquals( Key.newBuilder() .addPath(CHILD.getPath(0)) .build(), makeKey(CHILD).build()); }
@Test public void testMakeKey_KeyKey() { assertEquals( Key.newBuilder() .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(PARENT, CHILD).build()); }
@Test public void testMakeKey_KeyKeyKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(GRANDPARENT, PARENT, CHILD).build()); }
@Test public void testMakeKey_KeyMultiLevelKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(GRANDPARENT, makeKey(PARENT, CHILD).build()).build()); }
@Test public void testMakeKey_MultiLevelKeyKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(makeKey(GRANDPARENT, PARENT).build(), CHILD).build()); }
@Test public void testMakeKey_MultiLevelKey() { assertEquals( Key.newBuilder() .addPath(GRANDPARENT.getPath(0)) .addPath(PARENT.getPath(0)) .addPath(CHILD.getPath(0)) .build(), makeKey(makeKey(GRANDPARENT, PARENT, CHILD).build()).build()); }
@Test public void testMakeKey_PartitionId() { PartitionId partitionId = PartitionId.newBuilder() .setNamespaceId("namespace-id") .build(); Key parent = PARENT.toBuilder() .setPartitionId(partitionId) .build(); assertEquals( Key.newBuilder() .setPartitionId(partitionId) .addPath(PARENT.getPath(0)) .addPath(Key.PathElement.newBuilder().setKind("Child")) .build(), makeKey(parent, "Child").build()); }
@Test public void testMakeKey_NonMatchingPartitionId2() { PartitionId partitionId1 = PartitionId.newBuilder() .setNamespaceId("namespace-id") .build(); PartitionId partitionId2 = PartitionId.newBuilder() .setNamespaceId("another-namespace-id") .build(); try { makeKey( PARENT.toBuilder().setPartitionId(partitionId1).build(), CHILD.toBuilder().setPartitionId(partitionId2).build()); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } |
RemoteRpc { public static DatastoreException makeException(String url, String methodName, Code code, String message, Throwable cause) { logger.fine("remote datastore call " + methodName + " against " + url + " failed: " + message); return new DatastoreException(methodName, code, message, cause); } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | @Test public void testException() { Status statusProto = Status.newBuilder() .setCode(Code.UNAUTHENTICATED_VALUE) .setMessage("The request does not have valid authentication credentials.") .build(); DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.UNAUTHENTICATED, exception.getCode()); assertEquals("The request does not have valid authentication credentials.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testInvalidProtoException() { DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream("<invalid proto>".getBytes()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals("Unable to parse Status protocol buffer: HTTP status code was 401.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testEmptyProtoException() { Status statusProto = Status.newBuilder().build(); DatastoreException exception = RemoteRpc.makeException( "url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 404); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals( "Unexpected OK error code with HTTP status code of 404. Message: .", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testEmptyProtoExceptionUnauthenticated() { Status statusProto = Status.newBuilder().build(); DatastoreException exception = RemoteRpc.makeException( "url", METHOD_NAME, new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.UNAUTHENTICATED, exception.getCode()); assertEquals("Unauthenticated.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); }
@Test public void testPlainTextException() { DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME, new ByteArrayInputStream("Text Error".getBytes()), "text/plain", Charsets.UTF_8, new RuntimeException(), 401); assertEquals(Code.INTERNAL, exception.getCode()); assertEquals( "Non-protobuf error: Text Error. HTTP status code was 401.", exception.getMessage()); assertEquals(METHOD_NAME, exception.getMethodName()); } |
RemoteRpc { public InputStream call(String methodName, MessageLite request) throws DatastoreException { logger.fine("remote datastore call " + methodName); long startTime = System.currentTimeMillis(); try { HttpResponse httpResponse; try { rpcCount.incrementAndGet(); ProtoHttpContent payload = new ProtoHttpContent(request); HttpRequest httpRequest = client.buildPostRequest(resolveURL(methodName), payload); httpRequest.getHeaders().put(API_FORMAT_VERSION_HEADER, API_FORMAT_VERSION); httpRequest.setThrowExceptionOnExecuteError(false); httpRequest.setReadTimeout(65 * 1000); if (initializer != null) { initializer.initialize(httpRequest); } httpResponse = httpRequest.execute(); if (!httpResponse.isSuccessStatusCode()) { try (InputStream content = httpResponse.getContent()) { throw makeException(url, methodName, content, httpResponse.getContentType(), httpResponse.getContentCharset(), null, httpResponse.getStatusCode()); } } return httpResponse.getContent(); } catch (SocketTimeoutException e) { throw makeException(url, methodName, Code.DEADLINE_EXCEEDED, "Deadline exceeded", e); } catch (IOException e) { throw makeException(url, methodName, Code.UNAVAILABLE, "I/O error", e); } } finally { long elapsedTime = System.currentTimeMillis() - startTime; logger.fine("remote datastore call " + methodName + " took " + elapsedTime + " ms"); } } RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url); InputStream call(String methodName, MessageLite request); String getUrl(); static DatastoreException makeException(String url, String methodName, Code code,
String message, Throwable cause); } | @Test public void testGzip() throws IOException, DatastoreException { BeginTransactionResponse response = newBeginTransactionResponse(); InjectedTestValues injectedTestValues = new InjectedTestValues(gzip(response), new byte[1], true); RemoteRpc rpc = newRemoteRpc(injectedTestValues); InputStream is = rpc.call("beginTransaction", BeginTransactionResponse.getDefaultInstance()); BeginTransactionResponse parsedResponse = BeginTransactionResponse.parseFrom(is); is.close(); assertEquals(response, parsedResponse); assertEquals(-1, injectedTestValues.inputStream.read()); } |
Patterns { public static Pattern newMustacheTagPattern(Configuration configuration) { StringBuilder regex = new StringBuilder(); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.START_DELIMITER))); regex.append(".*?"); regex.append(Pattern.quote(configuration .getStringPropertyValue(EngineConfigurationKey.END_DELIMITER))); return Pattern.compile(regex.toString()); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } | @Test public void testMustacheTagPattern() { String text = "{{foo }} and {{#bar}}...{{/bar}}"; Pattern tagPattern = Patterns .newMustacheTagPattern(MustacheEngineBuilder.newBuilder() .build().getConfiguration()); Matcher matcher = tagPattern.matcher(text); StringBuffer result = new StringBuffer(); int occurences = 0; while (matcher.find()) { System.out.println(matcher.group(0)); matcher.appendReplacement(result, "FOUND"); occurences++; } matcher.appendTail(result); assertEquals(3, occurences); assertEquals("FOUND and FOUND...FOUND", result.toString()); } |
IOUtils { public static String toString(Reader input) throws IOException { return toString(input, DEFAULT_BUFFER_SIZE); } private IOUtils(); static String toString(Reader input); static String toString(Reader input, int bufferSize); static String toString(Reader input, int bufferSize, boolean close); static void copy(Readable in, Appendable out, int bufferSize); } | @Test public void testToString() throws IOException { assertEquals("foo", IOUtils.toString(new StringReader("foo"))); assertEquals("foo", IOUtils.toString(new StringReader("foo"), 1)); } |
Checker { @SuppressWarnings("rawtypes") public static boolean isFalsy(Object value) { if (value == null) { return true; } else if (value instanceof Boolean) { return !(Boolean) value; } else if (value instanceof Collection) { return ((Collection) value).isEmpty(); } else if (value instanceof Iterable) { return !((Iterable) value).iterator().hasNext(); } else if (value.getClass().isArray()) { return Array.getLength(value) == 0; } else if (value instanceof CharSequence) { return ((CharSequence) value).length() == 0; } else if (value instanceof Number) { return isZero((Number) value); } return false; } private Checker(); static void checkArgument(boolean condition, String errorMessage); static void checkArgumentsNotNull(Object... arguments); static void checkArgumentNotNull(Object argument); static void checkArgumentNotEmpty(String argument); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); @SuppressWarnings("rawtypes") static boolean isFalsy(Object value); } | @Test public void testIsFalsy() { assertTrue(Checker.isFalsy(null)); assertTrue(Checker.isFalsy(false)); assertTrue(Checker.isFalsy(new String[] {})); assertTrue(Checker.isFalsy(Collections.emptyList())); assertTrue(Checker.isFalsy("")); assertTrue(Checker.isFalsy(new StringBuilder())); assertTrue(Checker.isFalsy(0)); assertTrue(Checker.isFalsy(BigDecimal.ZERO)); assertTrue(Checker.isFalsy(new BigDecimal("0.000"))); assertFalse(Checker.isFalsy(Boolean.TRUE)); assertFalse(Checker.isFalsy(new Object[] { "foo" })); assertFalse(Checker.isFalsy(Collections.singleton("foo"))); assertFalse(Checker.isFalsy("foo")); assertFalse(Checker.isFalsy(new StringBuilder().append("foo"))); assertFalse(Checker.isFalsy(-10)); assertFalse(Checker.isFalsy(BigDecimal.TEN)); assertFalse(Checker.isFalsy(0.2)); assertFalse(Checker.isFalsy(new BigDecimal("-0.01"))); } |
ReflectionResolver extends AbstractResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } MemberWrapper wrapper; MemberKey key = MemberKey.newInstance(contextObject, name); if (memberCache != null) { wrapper = memberCache.get(key).orElse(null); } else { wrapper = findWrapper(key).orElse(null); } if (wrapper == null) { return null; } try { return wrapper.getValue(contextObject); } catch (Exception e) { throw new MustacheException( MustacheProblem.RENDER_REFLECT_INVOCATION_ERROR, e); } } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); static final int REFLECTION_RESOLVER_PRIORITY; static final String COMPUTING_CACHE_CONSUMER_ID; static final ConfigurationKey MEMBER_CACHE_MAX_SIZE_KEY; static final ConfigurationKey HINT_FALLBACK_ENABLED_KEY; static final String GET_PREFIX; static final String IS_PREFIX; } | @Test public void testResolution() { ReflectionResolver resolver = new ReflectionResolver(); MustacheEngineBuilder.newBuilder().omitServiceLoaderConfigurationExtensions().addResolver(resolver).build(); Hammer hammer = new Hammer(); assertNull(resolver.resolve(null, "whatever", null)); assertNotNull(resolver.resolve(hammer, "age", null)); assertEquals(10, resolver.resolve(hammer, "age", null)); assertNull(resolver.resolve(hammer, "getAgeForName", null)); } |
ReflectionResolver extends AbstractResolver { @Override public void init() { long memberCacheMaxSize = configuration .getLongPropertyValue(MEMBER_CACHE_MAX_SIZE_KEY); LOGGER.debug("Initialized [memberCacheMaxSize: {}]", memberCacheMaxSize); if (memberCacheMaxSize > 0) { memberCache = configuration.getComputingCacheFactory().create( COMPUTING_CACHE_CONSUMER_ID, ReflectionResolver::findWrapper, null, memberCacheMaxSize, null); } hintFallbackEnabled = configuration .getBooleanPropertyValue(HINT_FALLBACK_ENABLED_KEY); } ReflectionResolver(); ReflectionResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); void invalidateMemberCache(Predicate<Class<?>> predicate); static final int REFLECTION_RESOLVER_PRIORITY; static final String COMPUTING_CACHE_CONSUMER_ID; static final ConfigurationKey MEMBER_CACHE_MAX_SIZE_KEY; static final ConfigurationKey HINT_FALLBACK_ENABLED_KEY; static final String GET_PREFIX; static final String IS_PREFIX; } | @Test(expected = IllegalStateException.class) public void testMultipleInit() { ReflectionResolver resolver = new ReflectionResolver(); MustacheEngineBuilder.newBuilder().omitServiceLoaderConfigurationExtensions().addResolver(resolver).build(); resolver.init(null); } |
DateTimeFormatResolver extends TransformResolver { @Override public void init() { super.init(); customPattern = configuration .getStringPropertyValue(CUSTOM_PATTERN_KEY); LOGGER.info("Initialized [customPattern: {}]", customPattern); } DateTimeFormatResolver(); DateTimeFormatResolver(int priority); @Override Object transform(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); static final int DATE_TIME_FORMAT_RESOLVER_PRIORITY; static final ConfigurationKey CUSTOM_PATTERN_KEY; } | @Test(expected = IllegalStateException.class) public void testMultipleInit() { DateTimeFormatResolver resolver = new DateTimeFormatResolver(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver).build(); resolver.init(null); } |
IndexResolver extends AbstractResolver { protected boolean notAnIndex(String name) { return !isAnIndex(name); } IndexResolver(int priority); } | @Test public void testNotAnIndex() { IndexResolver indexResolver = new IndexResolver(0) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { return null; } }; assertTrue(indexResolver.notAnIndex("-1")); assertTrue(indexResolver.notAnIndex("size")); assertTrue(indexResolver.notAnIndex(".1")); assertTrue(indexResolver.notAnIndex("1,5")); assertFalse(indexResolver.notAnIndex("1500")); } |
DummyTransformResolver extends TransformResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null && matches(name)) { return marker; } else if (contextObject != null && contextObject.equals(marker)) { return performTransformation(contextObject, name, context); } return null; } DummyTransformResolver(int priority,
String... matchNames); DummyTransformResolver(int priority,
Transformer transformer, String... matchNames); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); } | @Test public void testResolution() { MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver).build(); assertNull(resolver.resolve(null, "whatever", null)); Object marker = resolver.resolve(null, "ng", null); assertNotNull(marker); assertEquals("{{FOO}}", resolver.resolve(marker, "foo", null)); } |
Decorator implements Mapper { public static <T> Builder<T> decorate(T delegate) { return new Builder<T>(delegate); } private Decorator(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); static Builder<T> decorate(T delegate); static Decorator<T> decorate(T delegate, Map<String, Function<T, Object>> mappings, String delegateKey,
Configuration configuration); @SuppressWarnings("unchecked") static T unwrap(T instance); @Override Object get(String key); @Override String toString(); static final String KEY_GET_DELEGATE; } | @Test public void testGetDelegate() { Hammer hammer = new Hammer(); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{delegate.name}}") .render(decorate(hammer).compute("name", h -> h.getName().toUpperCase()).build(engine))); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{foo.name}}").render( decorate(hammer).delegateKey("foo").compute("name", h -> h.getName().toUpperCase()).build(engine))); }
@Test public void testNestedDecorator() { Hammer hammer = new Hammer(5); assertEquals("5:Edgar:bar", engine.compileMustache("{{age}}:{{foo}}:{{bar}}") .render(decorate(decorate(hammer).compute("foo", h -> h.getName()).build(engine)) .put("bar", "bar").build(engine))); } |
MapResolver extends AbstractResolver { @SuppressWarnings("rawtypes") @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null) { return null; } if (contextObject instanceof Map) { Map map = (Map) contextObject; return map.get(name); } if (contextObject instanceof Mapper) { Mapper mapper = (Mapper) contextObject; return mapper.get(name); } return null; } MapResolver(); MapResolver(int priority); @SuppressWarnings("rawtypes") @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); static final int MAP_RESOLVER_PRIORITY; } | @Test public void testResolution() { MapResolver resolver = new MapResolver(); assertNull(resolver.resolve(null, "foo", null)); assertNotNull( resolver.resolve(ImmutableMap.of("bar", "baz"), "bar", null)); assertNull( resolver.resolve(ImmutableMap.of("bar", "baz"), "qux", null)); } |
Patterns { public static Pattern newSetDelimitersContentPattern() { return Pattern.compile("(\\S+)(\\s+)(\\S+)"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } | @Test public void testSetDelimitersPattern() { String set1 = "<% %>"; String set2 = "[ ]"; String set3 = "= ="; Pattern setDelimitersPattern = Patterns .newSetDelimitersContentPattern(); Matcher set1Matcher = setDelimitersPattern.matcher(set1); assertEquals(true, set1Matcher.find()); assertEquals("<%", set1Matcher.group(1)); assertEquals("%>", set1Matcher.group(3)); Matcher set2Matcher = setDelimitersPattern.matcher(set2); assertEquals(true, set2Matcher.find()); assertEquals("[", set2Matcher.group(1)); assertEquals("]", set2Matcher.group(3)); Matcher set3Matcher = setDelimitersPattern.matcher(set3); assertEquals(true, set3Matcher.find()); assertEquals("=", set3Matcher.group(1)); assertEquals("=", set3Matcher.group(3)); } |
HelperExecutionHandler { static Iterator<String> splitHelperName(String name, Segment segment) { Character stringLiteral = null; boolean arrayLiteral = false; boolean space = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char character = name.charAt(i); if (character == ' ') { if (!space) { if (stringLiteral == null && !arrayLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } space = true; } else { buffer.append(character); } } } else { if (!arrayLiteral && Strings.isStringLiteralSeparator(character)) { if (stringLiteral != null) { if (character == stringLiteral.charValue()) { stringLiteral = null; } } else { stringLiteral = character; } } else if (stringLiteral == null && Strings.isListLiteralStart(character)) { arrayLiteral = true; } else if (stringLiteral == null && Strings.isListLiteralEnd(character)) { arrayLiteral = false; } space = false; buffer.append(character); } } if (buffer.length() > 0) { if (stringLiteral != null || arrayLiteral) { throw new MustacheException( MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE, "Unterminated string or array literal detected: %s", segment); } parts.add(buffer.toString()); } return parts.iterator(); } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } | @Test public void testSplitHelperName() { assertHelperNameParts("name foo.bar", "name", "foo.bar"); assertHelperNameParts("name hash1=\"DD-MM-yyyy HH:mm\"", "name", "hash1=\"DD-MM-yyyy HH:mm\""); assertHelperNameParts("name key='value'", "name", "key='value'"); assertHelperNameParts("name key=''value''", "name", "key=''value''"); assertHelperNameParts("key='value foo=' 'bar'", "key='value foo='", "'bar'"); assertHelperNameParts("'key'='value foo=' 'bar'", "'key'='value foo='", "'bar'"); assertHelperNameParts("foo='bar = \n baz' qux", "foo='bar = \n baz'", "qux"); assertHelperNameParts("[ 'foo', 'bar', qux] foo", "[ 'foo', 'bar', qux]", "foo"); assertHelperNameParts("1 20 ['', '1'] foo", "1", "20", "['', '1']", "foo"); assertHelperNameParts("'[1, 2]'", "'[1, 2]'"); assertHelperNameParts("'[1, '2', 'alpha']'", "'[1, '2', 'alpha']'"); assertHelperNameParts("foo=[1, '2']", "foo=[1, '2']"); assertHelperNameParts("if \"var eq 'value_without_space'\"", "if", "\"var eq 'value_without_space'\""); assertHelperNameParts("key='value\" foo=' 'bar'", "key='value\" foo='", "'bar'"); assertHelperNameParts("if \"var eq 'value with space'\"", "if", "\"var eq 'value with space'\""); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> assertHelperNameParts("name key=''value'")) .check(() -> assertHelperNameParts("name key=value'")) .check(() -> assertHelperNameParts("name key='value foo")) .check(() -> assertHelperNameParts("name key=value' foo")) .check(() -> assertHelperNameParts("'name key=value")) .check(() -> assertHelperNameParts("key=\"value \" and\"")) .check(() -> assertHelperNameParts("foo='bar\"")); } |
HelperExecutionHandler { static int getFirstDeterminingEqualsCharPosition(String part) { boolean stringLiteral = false; for (int i = 0; i < part.length(); i++) { if (Strings.isStringLiteralSeparator(part.charAt(i))) { if (i == 0) { return -1; } stringLiteral = !stringLiteral; } else { if (!stringLiteral && part.charAt(i) == '=') { return i; } } } return -1; } private HelperExecutionHandler(Helper helper,
OptionsBuilder optionsBuilder); } | @Test public void testGetFirstDeterminingEqualsCharPosition() { assertEquals(3, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("foo=bar")); assertEquals(3, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("foo='bar='")); assertEquals(1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("1='bar='")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("'m=n'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition(" ' m=n'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("'1'")); assertEquals(-1, HelperExecutionHandler .getFirstDeterminingEqualsCharPosition("\"foo\"")); } |
ConfigurationProperties { static String buildPropertyKey(String propertyName, String[] prefixParts) { return buildPropertyKey(propertyName, Strings.UNDERSCORE, prefixParts); } private ConfigurationProperties(); } | @Test public void testBuildPropertyKey() { assertEquals("org.trimou.engine.config.myPropertyName", ConfigurationProperties.buildPropertyKey("MY_PROPERTY_NAME", new String[] { ConfigurationPropertiesTest.class .getPackage().getName() })); assertEquals("org.trimou.engine.config.myPropertyName", ConfigurationProperties.buildPropertyKey("MY.PROPERTY.NAME", ".", new String[] { ConfigurationPropertiesTest.class .getPackage().getName() })); } |
ConfigurationProperties { static Object convertConfigValue(Class<?> defaultValueType, Object value) { if (defaultValueType.equals(String.class)) { return value.toString(); } else if (defaultValueType.equals(Boolean.class)) { return Boolean.valueOf(value.toString()); } else if (defaultValueType.equals(Long.class)) { return Long.valueOf(value.toString()); } else if (defaultValueType.equals(Integer.class)) { return Integer.valueOf(value.toString()); } throw new IllegalStateException( "Unsupported default value type: " + defaultValueType); } private ConfigurationProperties(); } | @Test public void testConvertConfigValue() { assertEquals(10, ConfigurationProperties .convertConfigValue(Integer.class, "10")); assertEquals(10L, ConfigurationProperties.convertConfigValue(Long.class, "10")); assertEquals(Boolean.FALSE, ConfigurationProperties .convertConfigValue(Boolean.class, "10")); }
@Test(expected = IllegalStateException.class) public void testConvertConfigValueFails() { ConfigurationProperties.convertConfigValue(BigDecimal.class, "10"); } |
ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public String getKey() { return key; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); } | @Test public void testGetKey() { final AtomicReference<String> key = new AtomicReference<>(); MustacheEngineBuilder .newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver( new AbstractResolver( 1) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { key.set(context.getKey()); return null; } }).build().compileMustache("getkey", "{{my.key.foo}}") .render(null); assertEquals("my.key.foo", key.get()); } |
ValueWrapper extends AbstractReleaseCallbackContainer implements ResolutionContext { @Override public int getKeyPartIndex() { return keyPartIndex; } ValueWrapper(String key); Object get(); boolean isNull(); @Override String getKey(); @Override int getKeyPartIndex(); Hint getHint(); } | @Test public void testGetKeyPartIndex() { final List<Integer> indexes = new ArrayList<>(); MustacheEngineBuilder .newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(new AbstractResolver(1) { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { indexes.add(context.getKeyPartIndex()); return "OK"; } }).build().compileMustache("getkeypartindex", "{{my.key.foo}}") .render(null); assertEquals(3L, indexes.size()); assertEquals(Integer.valueOf(0), indexes.get(0)); assertEquals(Integer.valueOf(1), indexes.get(1)); assertEquals(Integer.valueOf(2), indexes.get(2)); } |
DefaultLiteralSupport extends AbstractConfigurationAware implements LiteralSupport { @Override public Object getLiteral(String value, MustacheTagInfo tagInfo) { if (Strings.isEmpty(value)) { return null; } Object literal = null; if (Strings.isStringLiteralSeparator(value.charAt(0))) { literal = value.substring(1, value.length() - 1); } else if (value.equals("true")) { literal = Boolean.TRUE; } else if (value.equals("false")) { literal = Boolean.FALSE; } else if (integerLiteralPattern.matcher(value).matches()) { try { literal = Integer.parseInt(value); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse integer literal: " + value, e); } } else if (longLiteralPattern.matcher(value).matches()) { try { literal = Long .parseLong(value.substring(0, value.length() - 1)); } catch (NumberFormatException e) { LOGGER.warn("Unable to parse long literal: " + value, e); } } return literal; } @Override Object getLiteral(String value, MustacheTagInfo tagInfo); } | @Test public void testGetLiteral() { LiteralSupport literalSupport = new DefaultLiteralSupport(); assertNull(literalSupport.getLiteral("foo", null)); assertNull(literalSupport.getLiteral("1.0", null)); assertEquals(10, literalSupport.getLiteral("+10", null)); assertEquals(-2010, literalSupport.getLiteral("-2010", null)); assertEquals("foo", literalSupport.getLiteral("'foo'", null)); assertEquals("bar.me", literalSupport.getLiteral("\"bar.me\"", null)); assertEquals(10L, literalSupport.getLiteral("10L", null)); assertEquals(-2010L, literalSupport.getLiteral("-2010l", null)); assertNull(literalSupport.getLiteral("2.0", null)); assertEquals(Boolean.TRUE, literalSupport.getLiteral("true", null)); assertEquals(Boolean.FALSE, literalSupport.getLiteral("false", null)); } |
BracketDotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS)) { return Iterables.singletonIterator(key); } boolean stringLiteral = false; boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (!stringLiteral) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } else { buffer.append(key.charAt(i)); } } } else { if (Strings.isStringLiteralSeparator(key.charAt(i))) { stringLiteral = !stringLiteral; } else { buffer.append(key.charAt(i)); } separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); } | @Test public void testSplit() { BracketDotKeySplitter splitter = new BracketDotKeySplitter(); assertIterator(splitter.split("a..bar:.c"), "a", "bar:", "c"); assertIterator(splitter.split(". "), " "); assertIterator(splitter.split("."), "."); assertIterator(splitter.split("foo"), "foo"); assertIterator(splitter.split("foo[\"bar\"]"), "foo", "bar"); assertIterator(splitter.split("foo[\"a.b.c\"]"), "foo", "a.b.c"); assertIterator(splitter.split("foo[\"bar\"].baz"), "foo", "bar", "baz"); assertIterator(splitter.split("a[\"b\"].c.d[\"e\"][\"f\"]"), "a", "b", "c", "d", "e", "f"); assertIterator(splitter.split("foo['bar']"), "foo", "bar"); assertIterator(splitter.split("foo['bar dot'][\"qux\"].me"), "foo", "bar dot", "qux", "me"); } |
DotKeySplitter extends AbstractConfigurationAware implements KeySplitter { @Override public Iterator<String> split(String key) { if (key.equals(Strings.DOT) || key.equals(Strings.THIS) || !key.contains(Strings.DOT)) { return Iterables.singletonIterator(key); } boolean separator = false; List<String> parts = new ArrayList<>(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < key.length(); i++) { if (isSeparator(key.charAt(i))) { if (!separator) { if (buffer.length() > 0) { parts.add(buffer.toString()); buffer = new StringBuilder(); } separator = true; } } else { buffer.append(key.charAt(i)); separator = false; } } if (buffer.length() > 0) { parts.add(buffer.toString()); } return parts.iterator(); } @Override Iterator<String> split(String key); } | @Test public void testSplit() { DotKeySplitter splitter = new DotKeySplitter(); assertIterator(splitter.split("a..bar:.c"), "a", "bar:", "c"); assertIterator(splitter.split(". "), " "); assertIterator(splitter.split("."), "."); assertIterator(splitter.split("foo"), "foo"); } |
Patterns { public static Pattern newHelperIntegerLiteralPattern() { return Pattern.compile("(\\+|-)?\\d{1,10}"); } private Patterns(); static Pattern newMustacheTagPattern(Configuration configuration); static Pattern newSetDelimitersContentPattern(); static Pattern newHelperIntegerLiteralPattern(); static Pattern newHelperLongLiteralPattern(); } | @Test public void testHelperIntOrLongLiteralPattern() { assertFalse(Patterns.newHelperIntegerLiteralPattern() .matcher("\"foo\"").matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("1") .matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("+12") .matches()); assertTrue(Patterns.newHelperIntegerLiteralPattern().matcher("-10000") .matches()); assertFalse(Patterns.newHelperIntegerLiteralPattern().matcher("1.0") .matches()); assertFalse(Patterns.newHelperIntegerLiteralPattern() .matcher("1000000000000").matches()); } |
FileSystemTemplateLocator extends FilePathTemplateLocator { public static Builder builder() { return new Builder(); } FileSystemTemplateLocator(int priority, String rootPath); FileSystemTemplateLocator(int priority, String rootPath,
String suffix); @Override Reader locateRealPath(String realPath); static Builder builder(); } | @Test public void testLocatorNoSuffix() throws IOException { TemplateLocator locator = FileSystemTemplateLocator.builder() .setRootPath("src/test/resources/locator/file").build(); MustacheEngineBuilder.newBuilder().addTemplateLocator(locator).build(); Set<String> ids = locator.getAllIdentifiers(); assertEquals(7, ids.size()); assertTrue(ids.contains("index.foo")); assertTrue(ids.contains("home.foo")); assertTrue(ids.contains("foo.foo")); assertTrue(ids.contains("detail.html")); assertTrue(ids.contains("encoding.html")); assertTrue(ids.contains("sub/bar.foo")); assertTrue(ids.contains("sub/subsub/qux.foo")); assertEquals("{{foo}}", read(locator.locate("index.foo"))); assertEquals("bar", read(locator.locate("home.foo"))); assertEquals("foo", read(locator.locate("foo.foo"))); assertEquals("<html/>", read(locator.locate("detail.html"))); assertEquals("{{foo}}", read(locator.locate("sub/bar.foo"))); assertEquals("{{bar}}", read(locator.locate("sub/subsub/qux.foo"))); }
@Test public void testCustomVirtualPathSeparator() throws IOException { TemplateLocator locator = FileSystemTemplateLocator.builder() .setPriority(1).setRootPath("src/test/resources/locator/file") .setSuffix("foo").build(); MustacheEngineBuilder.newBuilder().addTemplateLocator(locator) .setProperty(PathTemplateLocator.VIRTUAL_PATH_SEPARATOR_KEY, "*") .build(); Set<String> names = locator.getAllIdentifiers(); assertEquals(5, names.size()); assertTrue(names.contains("index")); assertTrue(names.contains("home")); assertTrue(names.contains("foo")); assertTrue(names.contains("sub*bar")); assertTrue(names.contains("sub*subsub*qux")); assertEquals("{{foo}}", read(locator.locate("index"))); assertEquals("bar", read(locator.locate("home"))); assertEquals("{{foo}}", read(locator.locate("sub*bar"))); assertEquals("{{bar}}", read(locator.locate("sub*subsub*qux"))); } |
SegmentBases { static boolean isStandaloneLine(List<SegmentBase> line) { boolean standaloneCandidate = false; for (SegmentBase segment : line) { if (SegmentType.VALUE.equals(segment.getType())) { return false; } else if (SegmentType.TEXT.equals(segment.getType())) { if (!Strings.containsOnlyWhitespace(segment.getContent())) { return false; } } else if (isStandaloneCandidate(segment.getType())) { standaloneCandidate = true; } } return standaloneCandidate; } private SegmentBases(); } | @Test public void testIsStandaloneLine() { assertTrue(SegmentBases.isStandaloneLine(ImmutableList.of( new SegmentBase(SegmentType.LINE_SEPARATOR, Strings.LINE_SEPARATOR_LF, 0, 0), new SegmentBase(SegmentType.TEXT, " ", 0, 0), new ContainerSegmentBase(SegmentType.SECTION, "test", 0, 0)))); assertFalse(SegmentBases.isStandaloneLine(ImmutableList.of( new SegmentBase(SegmentType.LINE_SEPARATOR, Strings.LINE_SEPARATOR_LF, 0, 0), new SegmentBase(SegmentType.TEXT, "Not empty", 0, 0), new ContainerSegmentBase(SegmentType.SECTION, "test", 0, 0)))); } |
EnhancedStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); static final String COMPUTING_CACHE_CONSUMER_ID; } | @Test public void testClearData() { EnhancedStatsCollector collector = new EnhancedStatsCollector(); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("bar", "BAR"); mustache.render(null); assertEquals(1, collector.getStats(mustache).getFinished()); collector.clearData(); assertNull(collector.getStats(mustache)); } |
EnhancedStatsCollector extends AbstractStatsCollector { public Stats getStats(Mustache mustache) { Checker.checkArgumentNotNull(mustache); ConcurrentMap<Long, ExecutionData> times = data.getIfPresent(mustache .getGeneratedId()); if (times != null) { return parseData(mustache.getName(), mustache.getGeneratedId(), times.values()); } return null; } EnhancedStatsCollector(); EnhancedStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void renderingStarted(MustacheRenderingEvent event); @Override void renderingFinished(MustacheRenderingEvent event); Stats getStats(Mustache mustache); Set<Stats> getStats(); Collection<ExecutionData> getRawData(Mustache mustache); void clearData(); static final String COMPUTING_CACHE_CONSUMER_ID; } | @Test public void testCustomPredicate() { EnhancedStatsCollector collector = new EnhancedStatsCollector( (t) -> false, TimeUnit.DAYS); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("qux", "Oops"); mustache.render(null); assertNull(collector.getStats(mustache)); } |
SimpleStatsCollector extends AbstractStatsCollector { public void clearData() { data.clear(); } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); static final String COMPUTING_CACHE_CONSUMER_ID; } | @Test public void testClearData() { SimpleStatsCollector collector = new SimpleStatsCollector(); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("bar", "BAR"); mustache.render(null); assertEquals(1, collector.getSimpleStats("bar").getExecutions()); collector.clearData(); assertNull(collector.getSimpleStats("bar")); } |
SimpleStatsCollector extends AbstractStatsCollector { public SimpleStats getSimpleStats(String templateId) { ComputingCache<Long, AtomicLong> entry = data.getIfPresent(templateId); if (entry != null) { return new SimpleStats(templateId, entry.getAllPresent()); } return null; } SimpleStatsCollector(); SimpleStatsCollector(Predicate<String> templatePredicate,
TimeUnit timeUnit); @Override void init(); @Override void renderingStarted(final MustacheRenderingEvent event); void clearData(); Map<Long, Long> getData(String templateId); Map<String, Map<Long, Long>> getData(); SimpleStats getSimpleStats(String templateId); Set<SimpleStats> getSimpleStats(); static final String COMPUTING_CACHE_CONSUMER_ID; } | @Test public void testCustomPredicate() { SimpleStatsCollector collector = new SimpleStatsCollector((t) -> false, TimeUnit.DAYS); Mustache mustache = MustacheEngineBuilder.newBuilder() .addMustacheListener(collector).build() .compileMustache("qux", "Oops"); mustache.render(null); assertNull(collector.getSimpleStats("qux")); } |
ObjectToDateConverter implements Converter<Object, Date> { @Override public Date convert(Object value) { Date converted = null; if (value instanceof Date) { converted = (Date) value; } else if (value instanceof Calendar) { converted = ((Calendar) value).getTime(); } else if (value instanceof LocalDateTime) { converted = Date.from(((LocalDateTime) value) .atZone(ZoneId.systemDefault()).toInstant()); } else if (value instanceof LocalDate) { converted = Date.from(((LocalDate) value) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } else if (value instanceof Long) { converted = new Date((Long) value); } else if (value instanceof BigDecimal) { converted = new Date(((BigDecimal) value).longValue()); } else if (value instanceof String && pattern != null) { try { converted = new SimpleDateFormat(pattern).parse((String) value); } catch (ParseException e) { throw new MustacheException( MustacheProblem.RENDER_GENERIC_ERROR, "Unable to parse the string value %s using pattern %s", value, pattern); } } return converted; } ObjectToDateConverter(); ObjectToDateConverter(String pattern); @Override Date convert(Object value); } | @Test public void testConverter() { String pattern = "yyyy.MM.dd HH:mm:ss.SSS"; SimpleDateFormat format = new SimpleDateFormat(pattern); ObjectToDateConverter converter = new ObjectToDateConverter(pattern); Date now = new Date(); Calendar cal = Calendar.getInstance(); Calendar midnight = Calendar.getInstance(); midnight.set(Calendar.HOUR_OF_DAY, 0); midnight.set(Calendar.MINUTE, 0); midnight.set(Calendar.SECOND, 0); midnight.set(Calendar.MILLISECOND, 0); LocalDateTime dateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()); LocalDate date = LocalDateTime.ofInstant(midnight.toInstant(), ZoneId.systemDefault()).toLocalDate(); assertNull(converter.convert(Float.MIN_NORMAL)); assertEquals(now, converter.convert(BigDecimal.valueOf(now.getTime()))); assertEquals(now, converter.convert(now)); assertEquals(now, converter.convert(now.getTime())); assertEquals(cal.getTime(), converter.convert(cal)); assertEquals(now, converter.convert(format.format(now))); assertEquals(now, converter.convert(dateTime)); assertEquals(midnight.getTime(), converter.convert(date)); } |
DecoratorConverter extends AbstractConfigurationAware implements ContextConverter { public static <T> Builder<T> decorate(Class<T> delegateType) { return decorate(o -> (delegateType.isAssignableFrom(Decorator.unwrap(o).getClass()))); } private DecoratorConverter(Predicate<Object> test, String delegateKey, Map<String, Function<T, Object>> mappings); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override Object convert(Object from); } | @SuppressWarnings("unchecked") @Test public void testInterpolation() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addContextConverter(decorate(String.class) .compute("reverse", string -> new StringBuilder(string).reverse().toString()).build()) .addContextConverter(decorate(Hammer.class).put("translate", "kladivo") .compute("name", hammer -> hammer.getName().toUpperCase()).build()) .addContextConverter(decorate(List.class).compute("reversed", list -> { List<?> reversed = new ArrayList<>(list); Collections.reverse(reversed); return reversed; }).build()).build(); assertEquals("ooF", engine.compileMustache("{{reverse}}").render("Foo")); assertEquals("kladivo EDGAR 10", engine.compileMustache("{{translate}} {{name}} {{age}}").render(new Hammer())); assertEquals("bravo:charlie:alpha:", engine.compileMustache("{{#each this.reversed}}{{.}}:{{/each}}") .render(ImmutableList.of("alpha", "charlie", "bravo"))); assertEquals("EDGAR 1000", engine.compileMustache("{{name}} {{age}}") .render(decorate(new Hammer()).put("age", 1000).build(engine))); }
@Test public void testGetDelegate() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addContextConverter(decorate(Hammer.class).compute("name", h -> h.getName().toUpperCase()).build()) .build(); Hammer hammer = new Hammer(); assertEquals("EDGAR vs Edgar", engine.compileMustache("{{name}} vs {{delegate.name}}").render(hammer)); } |
Strings { public static String replace(String text, String search, String replacement) { if (isEmpty(text) || isEmpty(search) || replacement == null) { return text; } int start = 0; int end = text.indexOf(search, start); if (end == -1) { return text; } StringBuilder builder = new StringBuilder(); while (end != -1) { builder.append(text.substring(start, end)); builder.append(replacement); start = end + search.length(); end = text.indexOf(search, start); } builder.append(text.substring(start)); return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } | @Test public void testReplace() { assertEquals("foobar", Strings.replace("foo:bar", ":", "")); } |
LogHelper extends BasicValueHelper { public LogHelper(LoggerAdapter adapter, Level defaultLevel, boolean appendTemplateInfo) { Checker.checkArgumentsNotNull(adapter, defaultLevel); this.defaultLevel = defaultLevel; this.adapter = adapter; this.appendTemplateInfo = appendTemplateInfo; } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); } | @Test public void testLogHelper() { String name = "MyLogger"; TestLoggerAdapter adapter = new TestLoggerAdapter(name); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().setDefaultLevel(Level.INFO) .setLoggerAdapter(adapter).build()) .build()) .build(); String msg = "Hello me!"; engine.compileMustache("log_helper1", "{{log \"" + msg + "\" level=\"WARN\"}}").render(null); assertEquals(Level.WARN, adapter.getLevels().get(0)); assertEquals(msg + " [log_helper1:1]", adapter.getMessages().get(0)); assertEquals(adapter.getParameters().get(0).length, 0); msg = "Hello {}!"; engine.compileMustache("log_helper2", "{{log this \"me\"}}") .render(msg); assertEquals(Level.INFO, adapter.getLevels().get(1)); assertEquals(msg + " [log_helper2:1]", adapter.getMessages().get(1)); assertEquals(adapter.getParameters().get(1).length, 1); engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().setAppendTemplateInfo(false) .setDefaultLevel(Level.INFO) .setLoggerAdapter(adapter).build()) .build()) .build(); engine.compileMustache("log_helper3", "{{log \"" + msg + "\"}}") .render(null); assertEquals(Level.INFO, adapter.getLevels().get(2)); assertEquals(msg, adapter.getMessages().get(2)); assertEquals(adapter.getParameters().get(2).length, 0); } |
LogHelper extends BasicValueHelper { public static Builder builder() { return new Builder(); } LogHelper(LoggerAdapter adapter, Level defaultLevel,
boolean appendTemplateInfo); @Override void execute(Options options); static Builder builder(); } | @Test public void testLogHelperValidation() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("log", LogHelper.builder().build()).build()) .build(); MustacheExceptionAssert .expect(MustacheProblem.COMPILE_HELPER_VALIDATION_FAILURE) .check(() -> engine.compileMustache("log_helper_validation01", "{{#log \"Foo\"}}{{/log}}")) .check(() -> engine.compileMustache("log_helper_validation02", "{{log}}")); } |
DecoratorHelper extends BasicSectionHelper { public static <T> Builder<T> decorate(Class<T> delegateType) { return new Builder<>(o -> delegateType.isAssignableFrom(o.getClass())); } private DecoratorHelper(Predicate<Object> test, Map<String, Function<T, Object>> mappings, String delegateKey); static Builder<T> decorate(Class<T> delegateType); static Builder<T> decorate(Predicate<Object> test); @SuppressWarnings("unchecked") @Override void execute(Options options); } | @SuppressWarnings("unchecked") @Test public void testHelper() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelper("decorateCat", decorate(Cat.class).put("const", "Cat") .compute("name", cat -> cat.getName().toUpperCase()) .compute("overweight", (cat) -> cat.getWeight() > 4500 ? cat.getWeight() - 4500 : 0).build()) .registerHelper("decorateIntList", decorate(List.class) .compute("sum", l -> l.stream().mapToInt(e -> Integer.valueOf(e.toString())).sum()).build()) .registerHelper("dummy", decorate(String.class).delegateKey("foo").compute("toUpperCase", s -> s.toLowerCase()).build()) .registerHelper("decorateStr", decorate(String.class) .compute("reverse", s -> new StringBuilder(s).reverse().toString()).build()) .build(); assertEquals("ooF", engine.compileMustache("{{#decorateStr}}{{reverse}}{{/decorateStr}}").render("Foo")); List<Cat> cats = new ArrayList<>(); cats.add(new Cat("Mikes", 3000)); cats.add(new Cat("Mourek", 5000)); assertEquals("Cat MIKES [3000g] has overweight 0g.Cat MOUREK [5000g] has overweight 500g.", engine.compileMustache( "{{#each}}{{#decorateCat}}{{const}} {{name}} [{{weight}}g] has overweight {{overweight}}g.{{/decorateCat}}{{/each}}") .render(cats)); try { engine.compileMustache("{{#decorateCat}}{{name}}{{/decorateCat}}").render("foo"); fail(); } catch (IllegalStateException expected) { } assertEquals("6:123", engine.compileMustache("{{#decorateIntList}}{{sum}}:{{#each}}{{.}}{{/each}}{{/decorateIntList}}") .render(Arrays.asList(1, 2, 3))); assertEquals("lu vs LU", engine.compileMustache("{{#dummy}}{{toUpperCase}} vs {{foo.toUpperCase}}{{/dummy}}").render("Lu")); } |
EqualsHelper extends BasicSectionHelper { public EqualsHelper() { this(false); } EqualsHelper(); EqualsHelper(boolean testInequality); @Override void execute(Options options); } | @Test public void testEqualsHelper() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .addGlobalData("archiveType", ArchiveType.class) .registerHelpers(HelpersBuilder.empty().addIsEqual() .addIsNotEqual().build()) .build(); assertEquals("EQUALS", engine.compileMustache("equals_helper1", "{{#isEq this.age this.age}}EQUALS{{/isEq}}") .render(new Hammer())); assertEquals( "EQUALS", engine .compileMustache("equals_helper2", "{{#isEq this}}EQUALS{{/isEq}}") .render(new Hammer())); assertEquals("NOT_EQUALS", engine.compileMustache("equals_helper3", "{{#isNotEq this.age}}NOT_EQUALS{{/isNotEq}}") .render(new Hammer())); assertEquals("NOT_EQUALS", engine.compileMustache("equals_helper4", "{{#isNotEq this.age this.toString}}NOT_EQUALS{{/isNotEq}}") .render(new Hammer())); assertEquals("It's a WAR!", engine .compileMustache("equals_helper5", "{{#with this.archiveType}}" + "{{#isEq archiveType.WAR}}" + "It's a WAR!" + "{{/isEq}}" + "{{#isEq archiveType.EAR}}" + "It's an EAR!" + "{{/isEq}}" + "{{/with}}") .render(new Hammer())); } |
InvokeHelper extends BasicHelper { public static InvokeHelper of(String defaultMethodName) { return new InvokeHelper(null, defaultMethodName); } InvokeHelper(); InvokeHelper(ClassLoader classLoader); InvokeHelper(ClassLoader classLoader, String defaultMethodName); static InvokeHelper of(String defaultMethodName); @Override void execute(Options options); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); static final ConfigurationKey METHOD_CACHE_MAX_SIZE_KEY; } | @Test public void testHelper() { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addInvoke().build()) .build(); List<String> list = ImmutableList.of("foo", "bar", "baz"); Map<String, Object> data = ImmutableMap.of("string", "foo", "list", list); assertEquals("oo", engine .compileMustache("invoke_01", "{{invoke 1 m='substring'}}") .render("foo")); assertEquals("bar", engine.compileMustache("invoke_02", "{{invoke 1 m='get'}}") .render(list)); assertEquals("FOOBARBAZ", engine.compileMustache("invoke_03", "{{#invoke 'list' m='get'}}{{#each this}}{{toUpperCase}}{{/each}}{{/invoke}}") .render(data)); assertEquals("3", engine .compileMustache("invoke_04", "{{invoke on=list m='size'}}") .render(data)); assertEquals( "false", engine .compileMustache("invoke_05", "{{invoke on=list method='isEmpty'}}") .render(data)); assertEquals("boo", engine.compileMustache("invoke_06", "{{invoke 'f' 'b' on='foo' m='replace'}}") .render(null)); assertEquals("2", engine.compileMustache("invoke_07", "{{#invoke ':' on='foo:bar' m='split'}}{{this.length}}{{/invoke}}") .render(null)); }
@Test public void testDefaultMethodName() { MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty() .add("substring", InvokeHelper.of("substring")) .build()) .build(); assertEquals("345", engine .compileMustache("invoke_defmethodname_01", "{{substring 3}}") .render("012345")); assertEquals("lo", engine .compileMustache("invoke_defmethodname_01", "{{substring 3 on='hello' m='whatever'}}") .render(null)); } |
NullCheckHelper extends MatchingSectionHelper { public NullCheckHelper() { this(false); } NullCheckHelper(); NullCheckHelper(boolean testNotNull); } | @Test public void testNullCheckHelper() { MustacheEngine engine = MustacheEngineBuilder .newBuilder() .registerHelpers( HelpersBuilder.empty() .addIsNull() .addIsNotNull() .build()).build(); assertEquals( "NULL|NOTNULL", engine.compileMustache( "nullcheck_helper1", "{{#isNull this.getNull}}NULL{{/isNull}}|{{#isNotNull this.toString}}NOTNULL{{/isNotNull}}") .render(new Hammer())); assertEquals( "NULL", engine.compileMustache( "nullcheck_helper2", "{{#isNull this.getNull this.null}}NULL{{/isNull}}") .render(new Hammer())); assertEquals( "NULL", engine.compileMustache( "nullcheck_helper3", "{{#isNull this.getNull this.age logic=\"or\"}}NULL{{/isNull}}") .render(new Hammer())); assertEquals( "NOTNULL", engine.compileMustache( "nullcheck_helper3", "{{#isNotNull this.getNull this.age logic=\"or\"}}NOTNULL{{/isNotNull}}") .render(new Hammer())); assertEquals( "ISNULL", engine.compileMustache( "nullcheck_helper4", "{{#isNotNull this.getNull else='ISNULL'}}NOTNULL{{/isNotNull}}") .render(new Hammer())); } |
CacheHelper extends BasicSectionHelper { public void invalidateFragments() { if (fragments == null) { return; } fragments.clear(); } @Override void execute(Options options); void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void validate(HelperDefinition definition); void invalidateFragments(); void invalidateFragments(final String keyPart); static final ConfigurationKey FRAGMENT_CACHE_MAX_SIZE_KEY; } | @Test public void testHelper() throws InterruptedException { final MustacheEngine engine = MustacheEngineBuilder.newBuilder() .registerHelpers(HelpersBuilder.empty().addCache().build()) .build(); CacheHelper cacheHelper = (CacheHelper) engine.getConfiguration() .getHelpers().get(HelpersBuilder.CACHE); final AtomicInteger hits = new AtomicInteger(); Mustache mustache = engine.compileMustache("cache_01", "{{#cache}}{{this.age}}{{/cache}}"); Hammer hammer = new Hammer() { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; assertEquals("10", mustache.render(hammer)); assertEquals("10", mustache.render(hammer)); hammer.setAge(11); assertEquals("10", mustache.render(hammer)); assertEquals(1, hits.get()); cacheHelper.invalidateFragments(); hammer.setAge(1); mustache = engine.compileMustache("cache_02", "{{#cache expire=1 unit='MILLISECONDS'}}{{this.age}}{{/cache}}"); assertEquals("1", mustache.render(hammer)); Thread.sleep(50); hammer.setAge(2); assertEquals("2", mustache.render(hammer)); cacheHelper.invalidateFragments(); hammer.setAge(5); mustache = engine.compileMustache("cache_03", "{{#cache guard=this.age}}{{this.age}}{{/cache}}"); assertEquals("5", mustache.render(hammer)); assertEquals("5", mustache.render(hammer)); hammer.setAge(50); assertEquals("50", mustache.render(hammer)); cacheHelper.invalidateFragments(); mustache = engine.compileMustache("cache_04", "{{#cache key=this.id}}{{this.age}}{{/cache}}"); hammer.setAge(1000); Hammer hammer2 = new Hammer(2000) { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; Hammer hammer3 = new Hammer(3000) { @Override public Integer getAge() { hits.incrementAndGet(); return super.getAge(); } }; assertEquals("1000", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); hammer.setAge(1001); hammer2.setAge(2001); hammer3.setAge(3001); assertEquals("1000", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); cacheHelper.invalidateFragments(hammer.getId()); assertEquals("1001", mustache.render(hammer)); assertEquals("2000", mustache.render(hammer2)); assertEquals("3000", mustache.render(hammer3)); } |
HelpersBuilder { public static HelpersBuilder builtin() { return empty().addBuiltin(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); static final String EACH; static final String IF; static final String UNLESS; static final String WITH; static final String IS; static final String IS_EVEN; static final String IS_ODD; static final String SET; static final String INCLUDE; static final String EMBED; static final String IS_EQUAL; static final String IS_NOT_EQUAL; static final String IS_NULL; static final String IS_NOT_NULL; static final String CHOOSE; static final String WHEN; static final String OTHERWISE; static final String SWITCH; static final String CASE; static final String DEFAULT; static final String JOIN; static final String EVAL; static final String NUMERIC_EXPRESSION; static final String ASYNC; static final String INVOKE; static final String ALT; static final String MIN; static final String MAX; static final String CACHE; static final String REPEAT; static final String FMT; static final String TAG; } | @Test public void testBuiltin() { Map<String, Helper> helpers = HelpersBuilder.builtin().build(); assertEquals(5, helpers.size()); assertTrue(helpers.containsKey(HelpersBuilder.EACH)); assertTrue(helpers.containsKey(HelpersBuilder.IF)); assertTrue(helpers.containsKey(HelpersBuilder.IS)); assertTrue(helpers.containsKey(HelpersBuilder.UNLESS)); assertTrue(helpers.containsKey(HelpersBuilder.WITH)); } |
HelpersBuilder { public static HelpersBuilder extra() { return empty().addExtra(); } private HelpersBuilder(); HelpersBuilder add(String name, Helper helper); HelpersBuilder addEach(); HelpersBuilder addIf(); HelpersBuilder addIf(String elseStartDelimiter, String elseEndDelimiter); HelpersBuilder addUnless(); HelpersBuilder addWith(); HelpersBuilder addIs(); HelpersBuilder addIsEven(); HelpersBuilder addIsOdd(); HelpersBuilder addSet(); HelpersBuilder addInclude(); HelpersBuilder addEmbed(); HelpersBuilder addEmbed(SourceProcessor processor); HelpersBuilder addIsEqual(); HelpersBuilder addIsNotEqual(); HelpersBuilder addIsNull(); HelpersBuilder addIsNotNull(); HelpersBuilder addChoose(); HelpersBuilder addSwitch(); HelpersBuilder addSwitch(boolean caseDefaultIsBreak); HelpersBuilder addJoin(); HelpersBuilder addEval(); HelpersBuilder addEval(Notation notation); HelpersBuilder addNumExpr(); HelpersBuilder addNumExpr(Operator defaultOperator); HelpersBuilder addAsync(); HelpersBuilder addInvoke(); HelpersBuilder addAlt(); HelpersBuilder addAlt(Selector selector); HelpersBuilder addMin(); HelpersBuilder addMax(); HelpersBuilder addCache(); HelpersBuilder addRepeat(); HelpersBuilder addFmt(); HelpersBuilder addTag(); HelpersBuilder addBuiltin(); HelpersBuilder addExtra(); Map<String, Helper> build(); static HelpersBuilder empty(); static HelpersBuilder builtin(); static HelpersBuilder extra(); static HelpersBuilder all(); static final String EACH; static final String IF; static final String UNLESS; static final String WITH; static final String IS; static final String IS_EVEN; static final String IS_ODD; static final String SET; static final String INCLUDE; static final String EMBED; static final String IS_EQUAL; static final String IS_NOT_EQUAL; static final String IS_NULL; static final String IS_NOT_NULL; static final String CHOOSE; static final String WHEN; static final String OTHERWISE; static final String SWITCH; static final String CASE; static final String DEFAULT; static final String JOIN; static final String EVAL; static final String NUMERIC_EXPRESSION; static final String ASYNC; static final String INVOKE; static final String ALT; static final String MIN; static final String MAX; static final String CACHE; static final String REPEAT; static final String FMT; static final String TAG; } | @Test public void testExtra() { Map<String, Helper> helpers = HelpersBuilder.extra().build(); assertEquals(27, helpers.size()); assertTrue(helpers.containsKey(HelpersBuilder.EMBED)); assertTrue(helpers.containsKey(HelpersBuilder.INCLUDE)); assertTrue(helpers.containsKey(HelpersBuilder.IS_EQUAL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NOT_EQUAL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NULL)); assertTrue(helpers.containsKey(HelpersBuilder.IS_NOT_NULL)); assertTrue(helpers.containsKey(HelpersBuilder.SET)); assertTrue(helpers.containsKey(HelpersBuilder.IS_EVEN)); assertTrue(helpers.containsKey(HelpersBuilder.IS_ODD)); assertTrue(helpers.containsKey(HelpersBuilder.SWITCH)); assertTrue(helpers.containsKey(HelpersBuilder.CHOOSE)); assertTrue(helpers.containsKey(HelpersBuilder.JOIN)); assertTrue(helpers.containsKey(HelpersBuilder.EVAL)); assertTrue(helpers.containsKey(HelpersBuilder.NUMERIC_EXPRESSION)); assertTrue(helpers.containsKey(HelpersBuilder.ASYNC)); assertTrue(helpers.containsKey(HelpersBuilder.INVOKE)); assertTrue(helpers.containsKey(HelpersBuilder.ALT)); assertTrue(helpers.containsKey(HelpersBuilder.MIN)); assertTrue(helpers.containsKey(HelpersBuilder.MAX)); assertTrue(helpers.containsKey(HelpersBuilder.CACHE)); assertTrue(helpers.containsKey(HelpersBuilder.REPEAT)); assertTrue(helpers.containsKey(HelpersBuilder.FMT)); assertTrue(helpers.containsKey(HelpersBuilder.TAG)); } |
Strings { public static boolean containsWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (Character.isWhitespace(text.charAt(i))) { return true; } } return false; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } | @Test public void testContainsWhitespace() { assertTrue(Strings.containsWhitespace("foo bar")); assertTrue(Strings .containsWhitespace(System.getProperty("line.separator"))); assertFalse(Strings.containsWhitespace("foobar")); } |
PrettyTimeHelper extends LocaleAwareValueHelper { public static Builder builder() { return new Builder(); } PrettyTimeHelper(); PrettyTimeHelper(PrettyTimeFactory prettyTimeFactory); PrettyTimeHelper(PrettyTimeFactory factory,
Converter<Object, Date> converter); @Override void init(Configuration configuration); @Override void execute(Options options); static Builder builder(); static final String COMPUTING_CACHE_CONSUMER_ID; static final String DEFAULT_NAME; } | @Test public void testCustomConverter() { final Calendar day = Calendar.getInstance(); day.set(Calendar.YEAR, day.get(Calendar.YEAR) - 1); day.set(Calendar.MONTH, day.get(Calendar.MONTH) - 1); MustacheEngine engine = MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setLocaleSupport(FixedLocaleSupport.from(Locale.ENGLISH)) .addResolver(new ThisResolver()) .registerHelper("pretty", PrettyTimeHelper.builder() .setConverter(from -> day.getTime()).build()) .build(); assertEquals("1 year ago", engine.compileMustache("pretty_conv", "{{pretty this}}") .render(Calendar.getInstance())); } |
TrimouTemplateAvailabilityProvider implements TemplateAvailabilityProvider { public boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader, final ResourceLoader resourceLoader) { if (ClassUtils.isPresent("org.trimou.Mustache", classLoader)) { final PropertyResolver resolver = new RelaxedPropertyResolver(environment, TrimouProperties.PROPERTY_PREFIX + '.'); final String prefix = resolver.getProperty("prefix", SpringResourceTemplateLocator.DEFAULT_PREFIX); final String suffix = resolver.getProperty("suffix", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final String resourceLocation = prefix + view + suffix; return resourceLoader.getResource(resourceLocation).exists(); } return false; } boolean isTemplateAvailable(final String view, final Environment environment, final ClassLoader classLoader,
final ResourceLoader resourceLoader); } | @Test public void availabilityOfTemplateInDefaultLocation() throws Exception { assertThat(provider.isTemplateAvailable("home", environment, getClass().getClassLoader(), resourceLoader), is(true)); assertThat(provider.isTemplateAvailable("prefix/prefixed", environment, getClass().getClassLoader(), resourceLoader), is(true)); }
@Test public void availabilityOfTemplateThatDoesNotExist() throws Exception { assertThat(provider.isTemplateAvailable("unknown", environment, getClass().getClassLoader(), resourceLoader), is(false)); }
@Test public void availabilityOfTemplateWithCustomPrefix() throws Exception { environment.setProperty("trimou.prefix", "classpath:/custom-templates/"); assertThat(provider.isTemplateAvailable("custom", environment, getClass().getClassLoader(), resourceLoader), is(true)); }
@Test public void availabilityOfTemplateWithCustomSuffix() throws Exception { environment.setProperty("trimou.suffix", ".html"); assertThat(provider.isTemplateAvailable("suffixed", environment, getClass().getClassLoader(), resourceLoader), is(true)); } |
HttpServletRequestResolver extends AbstractResolver implements MustacheListener, Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject != null) { return null; } if (NAME_REQUEST.equals(name)) { HttpServletRequestWrapper wrapper = REQUEST_WRAPPER.get(); if (wrapper == null) { HttpServletRequest request = RequestHolder.getCurrentRequest(); if (request != null) { wrapper = new HttpServletRequestWrapper(request); REQUEST_WRAPPER.set(wrapper); } else { LOGGER.warn("Unable to get the current HTTP request"); } } return wrapper; } return null; } HttpServletRequestResolver(); HttpServletRequestResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override void renderingStarted(MustacheRenderingEvent event); @Override boolean isValid(); static final int SERVLET_REQUEST_RESOLVER_PRIORITY; static final ConfigurationKey ENABLED_KEY; } | @Test public void testNulltIsResolved() { HttpServletRequestResolver resolver = new HttpServletRequestResolver(); assertNull(resolver.resolve("whatever", "request", null)); assertNull(resolver.resolve(null, "foo", null)); } |
JsonElementResolver extends IndexResolver { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonElement)) { return null; } JsonElement element = (JsonElement) contextObject; if (element.isJsonArray() && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) element; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonElementIfNecessary(jsonArray.get(index), unwrapJsonPrimitive); } } else if (element.isJsonObject()) { JsonObject jsonObject = (JsonObject) element; JsonElement member = jsonObject.get(name); if (member != null) { return unwrapJsonElementIfNecessary(member, unwrapJsonPrimitive); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonElementIfNecessary(element, true); } return null; } JsonElementResolver(); JsonElementResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override void init(); @Override Set<ConfigurationKey> getConfigurationKeys(); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); static final int JSON_ELEMENT_RESOLVER_PRIORITY; static final String NAME_UNWRAP_THIS; static final ConfigurationKey UNWRAP_JSON_PRIMITIVE_KEY; } | @Test public void testResolution() { JsonElementResolver resolver = new JsonElementResolver(); ResolutionContext ctx = new DummyResolutionContext(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .setProperty(JsonElementResolver.UNWRAP_JSON_PRIMITIVE_KEY, true) .setProperty(GsonValueConverter.ENABLED_KEY, false) .addResolver(resolver).build(); assertNull(resolver.resolve(null, "foo", ctx)); assertNull(resolver.resolve("bar", "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(new JsonPrimitive(true), "unwrapThis", ctx)); assertNull(resolver.resolve(new JsonPrimitive(true), "whatever", ctx)); assertEquals(Placeholder.NULL, resolver.resolve(JsonNull.INSTANCE, "unwrapThis", ctx)); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("foo", "bar"); jsonObject.addProperty("baz", true); assertEquals("bar", resolver.resolve(jsonObject, "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(jsonObject, "baz", ctx)); JsonArray jsonArray = new JsonArray(); jsonArray.add(new JsonPrimitive(true)); jsonArray.add(new JsonPrimitive(1)); assertEquals(true, resolver.resolve(jsonArray, "0", ctx)); assertEquals(1, resolver.resolve(jsonArray, "1", ctx)); } |
JsonValueResolver extends IndexResolver implements Validateable { @Override public Object resolve(Object contextObject, String name, ResolutionContext context) { if (contextObject == null || !(contextObject instanceof JsonValue)) { return null; } JsonValue jsonValue = (JsonValue) contextObject; if (ValueType.ARRAY.equals(jsonValue.getValueType()) && isAnIndex(name)) { JsonArray jsonArray = (JsonArray) jsonValue; final Integer index = getIndexValue(name, context.getKey(), jsonArray.size()); if (index != null) { return unwrapJsonValueIfNecessary(jsonArray.get(index)); } } else if (ValueType.OBJECT.equals(jsonValue.getValueType())) { JsonObject jsonObject = (JsonObject) jsonValue; JsonValue member = jsonObject.get(name); if (member != null) { return unwrapJsonValueIfNecessary(member); } } else if (name.equals(NAME_UNWRAP_THIS)) { return unwrapJsonValueIfNecessary(jsonValue); } return null; } JsonValueResolver(); JsonValueResolver(int priority); @Override Object resolve(Object contextObject, String name,
ResolutionContext context); @Override Hint createHint(Object contextObject, String name,
ResolutionContext context); @Override void init(Configuration configuration); @Override Set<ConfigurationKey> getConfigurationKeys(); static final int JSON_VALUE_RESOLVER_PRIORITY; static final ConfigurationKey ENABLED_KEY; static final String NAME_UNWRAP_THIS; } | @Test public void testResolution() { JsonValueResolver resolver = new JsonValueResolver(); ResolutionContext ctx = new DummyResolutionContext(); MustacheEngineBuilder.newBuilder() .omitServiceLoaderConfigurationExtensions() .addResolver(resolver) .setProperty(JsonValueResolver.ENABLED_KEY, true).build(); assertNull(resolver.resolve(null, "foo", ctx)); assertNull(resolver.resolve("bar", "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(JsonValue.TRUE, "unwrapThis", ctx)); assertNull(resolver.resolve(JsonValue.TRUE, "whatever", ctx)); assertEquals(Placeholder.NULL, resolver.resolve(JsonValue.NULL, "unwrapThis", ctx)); JsonObject jsonObject = Json.createObjectBuilder().add("foo", "bar") .add("baz", true).build(); assertEquals("bar", resolver.resolve(jsonObject, "foo", ctx)); assertEquals(Boolean.TRUE, resolver.resolve(jsonObject, "baz", ctx)); JsonArray jsonArray = Json.createArrayBuilder().add(true).add(1) .build(); assertEquals(true, resolver.resolve(jsonArray, "0", ctx)); assertEquals(BigDecimal.ONE, resolver.resolve(jsonArray, "1", ctx)); } |
SpringResourceTemplateLocator extends AbstractTemplateLocator implements ResourceLoaderAware { public Reader locate(final String name) { final String resourceLocation = prefix + name + suffix; try { if (Strings.isEmpty(charset)) { return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream()); } return new InputStreamReader(resourceLoader.getResource(resourceLocation).getInputStream(), charset); } catch (UnsupportedEncodingException e) { LOGGER.warn("Charset not supported: {}", charset); } catch (IOException e) { LOGGER.warn("Template not found: {}", resourceLocation); } return null; } SpringResourceTemplateLocator(); SpringResourceTemplateLocator(final int priority, final String prefix, final String suffix); void setResourceLoader(final ResourceLoader resourceLoader); Reader locate(final String name); String getPrefix(); void setPrefix(final String prefix); String getSuffix(); void setSuffix(final String suffix); String getCharset(); void setCharset(final String charset); static final String DEFAULT_PREFIX; static final String DEFAULT_SUFFIX; } | @Test public void availabilityOfTemplateInDefaultLocation() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(); final Reader r1 = loader.locate("home"); assertThat(readContent(r1), is("home")); final Reader r2 = loader.locate("prefix/prefixed"); assertThat(readContent(r2), is("prefixed")); }
@Test public void availabilityOfTemplateThatDoesNotExist() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(); assertThat(loader.locate("unknown"), is(nullValue())); }
@Test public void availabilityOfTemplateWithCustomPrefix() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(1, "classpath:/custom-templates/", SpringResourceTemplateLocator.DEFAULT_SUFFIX); final Reader reader = loader.locate("custom"); assertThat(readContent(reader), is("custom")); }
@Test public void availabilityOfTemplateWithCustomSuffix() throws Exception { final SpringResourceTemplateLocator loader = new SpringResourceTemplateLocator(1, SpringResourceTemplateLocator.DEFAULT_PREFIX, ".html"); final Reader reader = loader.locate("suffixed"); assertThat(readContent(reader), is("suffixed")); } |
Strings { public static boolean containsOnlyWhitespace(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isWhitespace(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } | @Test public void testContainsOnlyWhitespace() { assertTrue(Strings.containsOnlyWhitespace(" ")); assertTrue(Strings.containsOnlyWhitespace( " " + System.getProperty("line.separator"))); assertFalse(Strings.containsOnlyWhitespace(" !")); } |
TrimouViewResolver extends AbstractTemplateViewResolver { @Override public boolean isCache() { return engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.TEMPLATE_CACHE_ENABLED) && !engine.getConfiguration().getBooleanPropertyValue(EngineConfigurationKey.DEBUG_MODE) && super.isCache(); } TrimouViewResolver(); TrimouViewResolver(final MustacheEngine engine); @Override boolean isCache(); void setEngine(final MustacheEngine engine); @Override void setPrefix(final String prefix); @Override void setSuffix(final String suffix); } | @Test public void cacheEnabled() throws Exception { assertThat(resolver.isCache(), is(true)); } |
Strings { public static boolean containsOnlyDigits(String text) { if (isEmpty(text)) { return false; } for (int i = 0; i < text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return false; } } return true; } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } | @Test public void testContainsOnlyDigits() { assertTrue(Strings.containsOnlyDigits("123")); assertFalse(Strings.containsOnlyDigits("5!")); } |
Strings { public static String repeat(String text, int times, String separator) { if (isEmpty(text) || times < 0) { return text; } if (times == 0) { return EMPTY; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(text); if (i + 1 < times) { builder.append(separator); } } return builder.toString(); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } | @Test public void testRepeat() { assertEquals("foo,foo", Strings.repeat("foo", 2, ",")); assertEquals("ooo", Strings.repeat("o", 3, "")); assertEquals("o", Strings.repeat("o", -3, "")); assertEquals("", Strings.repeat("ouch", 0, "")); } |
Strings { public static String substringAfter(String text, String delimiter) { Checker.checkArgumentsNotNull(text, delimiter); int index = text.indexOf(delimiter); if (index == -1) { return EMPTY; } return text.substring(index + delimiter.length()); } private Strings(); static boolean isStringLiteralSeparator(char character); static boolean isEmpty(CharSequence sequence); static String uncapitalize(String word); static String capitalizeFully(String text, Character delimiter); static String replace(String text, String search,
String replacement); static String removeSuffix(String text, String suffix); static List<String> split(String text, String delimiter); static boolean containsWhitespace(String text); static boolean containsOnlyWhitespace(String text); static boolean containsOnlyDigits(String text); static String repeat(String text, int times, String separator); static String substringAfter(String text, String delimiter); static boolean isListLiteralStart(char character); static boolean isListLiteralEnd(char character); static boolean isListLiteral(String value); static final String EMPTY; static final String GAP; static final String LINE_SEPARATOR; static final String LINE_SEPARATOR_LF; static final String LINE_SEPARATOR_CRLF; static final String LINE_SEPARATOR_CR; static final String SLASH; static final String FILE_SEPARATOR; static final String DOT; static final String UNDERSCORE; static final String NOT_AVAILABLE; static final String URL_PROCOTOL_FILE; static final String THIS; static final String HASH; } | @Test public void testSubstringAfter() { assertEquals("o", Strings.substringAfter("foo", "o")); assertEquals("", Strings.substringAfter("foo", "a")); } |
Arrays { public static boolean contains(Object[] array, Object object) { if (array == null) { return false; } for (final Object element : array) { if ((object != null && object.equals(element)) || (object == null && element == null)) { return true; } } return false; } static boolean contains(Object[] array, Object object); static final Object[] EMPTY_OBJECT_ARRAY; } | @Test public void testContains() { assertTrue(Arrays.contains(new Character[] { 'v', 'o', 'j', 't', 'a' }, 'a')); assertFalse( Arrays.contains(new Character[] { 'j', 'a', 's', 'a' }, null)); assertTrue(Arrays.contains(new Character[] { 'l', null }, null)); } |
HelloWorld implements ActionBlock { public int execute(FlowContext ctx) throws FlowExecutionException { String name = (String) ctx.get(IN_NAME); String message = "Hello World! "; if (name != null) { message += name; } logger.debug("Message: {}", message); ctx.put(OUT_MESSAGE, message); return NEXT; } int execute(FlowContext ctx); } | @Test public void testHelloWorld(){ HelloWorld helloWorld = new HelloWorld(); FlowContext context = new FlowContext(); context.put("name", "John"); try { int result = helloWorld.execute(context); context.get("message"); assertEquals(ActionBlock.NEXT, result); assertEquals("Hello World! John", context.get("message")); } catch (FlowExecutionException e) { e.printStackTrace(); } } |
Vehicle { protected double getSpeedMph(double timeSec){ double v = 2.0*this.engine.getHorsePower()*746; v = v*timeSec*32.174/this.weightPounds; return Math.round(Math.sqrt(v)*0.68); } Vehicle(int weightPounds, Engine engine); int getWeightPounds(); Engine getEngine(); } | @Test public void testGetSpeedMph(){ double timeSec = 10.0; int engineHorsePower = 246; int vehicleWeightPounds = 4000; Engine engine = new Engine(); engine.setHorsePower(engineHorsePower); Vehicle vehicle = new Vehicle(vehicleWeightPounds, engine); double speed = vehicle.getSpeedMph(timeSec); assertEquals("Assert vehicle (" + engineHorsePower + " hp, " + vehicleWeightPounds + " lb) speed in " + timeSec + " sec: ", 117, speed, 0.001 * speed); } |
TrafficDensity3 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | @Test public void testCalcSpeed(){ double timeSec = 10.0; TrafficDensity3 trafficDensity = new TrafficDensity3(); Vehicle vehicle = Mockito.mock(Vehicle.class); Mockito.when(vehicle.getSpeedMph(timeSec)).thenReturn(100d); double traction = 0.2; double speed = trafficDensity.calcSpeed(vehicle, traction, timeSec); assertEquals("Assert speed (traction=" + traction + ") in " + timeSec + " sec: ", 20, speed, 0.001 * speed); } |
TrafficDensity3 { protected int calcLaneNumber(int lanesCount, double[] speedLimitByLane, double speed){ for(int i = 1; i <= lanesCount; i++){ if(speed <= speedLimitByLane[i - 1]){ return i; } } return lanesCount; } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | @Test public void testCalcLaneNumber() { double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; double[] speedLimitByLane = {4.5, 8.5, 12.5}; int[] expectedLaneNumber = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3}; TrafficDensityTestCalcLaneNumber trafficDensity = new TrafficDensityTestCalcLaneNumber(); for(int i = 0; i < speeds.length; i++){ int ln = trafficDensity.calcLaneNumber(speedLimitByLane.length, speedLimitByLane, speeds[i]); assertEquals("Assert lane number of speed " + speeds + " with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedLaneNumber[i], ln); } } |
TrafficDensity3 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = new HashMap<>(); for(int i = 1; i <= lanesCount; i++){ trafficByLane.put(i, 0); } stream.limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> calcSpeed(tuw.getVehicle(), tuw.getTraction(), timeSec)) .forEach(speed -> trafficByLane.computeIfPresent(calcLaneNumber(lanesCount, speedLimitByLane, speed), (k, v) -> ++v)); return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | @Test public void testCalcLaneNumber2() { int[] count ={0}; double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; Integer[] expectedCountByLane = {4, 4, 4}; TrafficDensity3 trafficDensity = new TrafficDensity3(){ @Override protected double calcSpeed(Vehicle vehicle, double traction, double timeSec) { return speeds[count[0]++]; } }; double timeSec = 10.0; int trafficUnitsNumber = speeds.length; double[] speedLimitByLane = {4.5, 8.5, 12.5}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + speeds.length + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } |
TrafficDensity2 { protected double calcSpeed(Vehicle vehicle, double traction, double timeSec){ double speed = vehicle.getSpeedMph(timeSec); return Math.round(speed * traction); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | @Test public void testCalcSpeed(){ double timeSec = 10.0; TrafficDensity2 trafficDensity = new TrafficDensity2(); Vehicle vehicle = Mockito.mock(Vehicle.class); Mockito.when(vehicle.getSpeedMph(timeSec)).thenReturn(100d); double traction = 0.2; double speed = trafficDensity.calcSpeed(vehicle, traction, timeSec); assertEquals("Assert speed (traction=" + traction + ") in " + timeSec + " sec: ", 20, speed, 0.001 * speed); } |
TrafficDensity2 { private CountByLane countByLane(int lanesNumber, double[] speedLimit, double speed){ for(int i = 1; i <= lanesNumber; i++){ if(speed <= speedLimit[i - 1]){ return new CountByLane(1, i); } } return new CountByLane(1, lanesNumber); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | @Test public void testCountByLane() { int[] count ={0}; double[] speeds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; TrafficDensity2 trafficDensity = new TrafficDensity2(){ @Override protected double calcSpeed(Vehicle vehicle, double traction, double timeSec) { return speeds[count[0]++]; } }; double timeSec = 10.0; int trafficUnitsNumber = speeds.length; double[] speedLimitByLane = {4.5, 8.5, 12.5}; Integer[] expectedCountByLane = {4, 4, 4}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + speeds.length + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } |
TrafficDensity1 { public Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec, SpeedModel speedModel, double[] speedLimitByLane) { int lanesCount = speedLimitByLane.length; Map<Integer, Integer> trafficByLane = stream .limit(trafficUnitsNumber) .map(TrafficUnitWrapper::new) .map(tuw -> tuw.setSpeedModel(speedModel)) .map(tuw -> tuw.calcSpeed(timeSec)) .map(speed -> countByLane(lanesCount, speedLimitByLane, speed)) .collect(Collectors.groupingBy(CountByLane::getLane, Collectors.summingInt(CountByLane::getCount))); for(int i = 1; i <= lanesCount; i++){ trafficByLane.putIfAbsent(i, 0); } return trafficByLane.values().toArray(new Integer[lanesCount]); } Integer[] trafficByLane(Stream<TrafficUnit> stream, int trafficUnitsNumber, double timeSec,
SpeedModel speedModel, double[] speedLimitByLane); } | @Test public void testTrafficByLane() { TrafficDensity1 trafficDensity = new TrafficDensity1(); double timeSec = 10.0; int trafficUnitsNumber = 120; double[] speedLimitByLane = {30, 50, 65}; Integer[] expectedCountByLane = {30, 30, 60}; Integer[] trafficByLane = trafficDensity.trafficByLane(getTrafficUnitStream2(trafficUnitsNumber), trafficUnitsNumber, timeSec, FactorySpeedModel.getSpeedModel(), speedLimitByLane ); assertArrayEquals("Assert count of " + trafficUnitsNumber + " vehicles by " + speedLimitByLane.length + " lanes with speed limit " + Arrays.stream(speedLimitByLane).mapToObj(Double::toString).collect(Collectors.joining(", ")), expectedCountByLane, trafficByLane); } |
Asn1Buffer { public void put( byte b ) { if ( pos == buffer.length ) { extend( 1 ); } pos++; buffer[buffer.length - pos] = b; } Asn1Buffer(); int getPos(); void setPos( int pos ); void put( byte b ); void put( byte[] bytes ); ByteBuffer getBytes(); int getSize(); void clear(); @Override String toString(); } | @Test @Disabled public void testBytesPerf() { long t0 = System.currentTimeMillis(); for ( int j = 0; j < 1000; j++ ) { Asn1Buffer buffer = new Asn1Buffer(); for ( int i = 0; i < 409600; i++ ) { buffer.put( new byte[] { 0x01, ( byte ) i } ); } } long t1 = System.currentTimeMillis(); System.out.println( "Delta: " + ( t1 - t0 ) ); } |
MaxValueCountItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxValueCountItem ) { MaxValueCountItem that = ( MaxValueCountItem ) o; return items.equals( that.items ); } return false; } MaxValueCountItem( Set<MaxValueCountElem> items ); Iterator<MaxValueCountElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testNotEqualDiffValue() throws Exception { assertFalse( maxValueCountItemA.equals( maxValueCountItemC ) ); assertFalse( maxValueCountItemC.equals( maxValueCountItemA ) ); assertFalse( maxValueCountItemA.equals( maxValueCountItemD ) ); assertFalse( maxValueCountItemD.equals( maxValueCountItemA ) ); }
@Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( maxValueCountItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( maxValueCountItemA.equals( null ) ); } |
RestrictedByItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof RestrictedByItem ) { RestrictedByItem that = ( RestrictedByItem ) o; if ( items != null ) { if ( that.items == null ) { return false; } if ( items.size() != that.items.size() ) { return false; } for ( RestrictedByElem item : items ) { if ( !that.items.contains( item ) ) { return false; } } return true; } else { return that.items == null; } } return false; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( restrictedByItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( restrictedByItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( restrictedByItemA.equals( restrictedByItemC ) ); assertFalse( restrictedByItemC.equals( restrictedByItemA ) ); assertFalse( restrictedByItemA.equals( restrictedByItemD ) ); assertFalse( restrictedByItemD.equals( restrictedByItemA ) ); } |
RestrictedByItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( items != null ) { for ( RestrictedByElem item : items ) { if ( item != null ) { hash = hash * item.hashCode(); } else { hash = hash * 37; } } } return hash; } RestrictedByItem( Set<RestrictedByElem> items ); Iterator<RestrictedByElem> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testHashCodeReflexive() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemACopy.hashCode() ); assertEquals( restrictedByItemACopy.hashCode(), restrictedByItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( restrictedByItemA.hashCode(), restrictedByItemACopy.hashCode() ); assertEquals( restrictedByItemACopy.hashCode(), restrictedByItemB.hashCode() ); assertEquals( restrictedByItemA.hashCode(), restrictedByItemB.hashCode() ); } |
AttributeValueItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof AttributeValueItem ) { AttributeValueItem that = ( AttributeValueItem ) o; if ( attributes != null ) { if ( ( that.attributes == null ) || ( that.attributes.size() != attributes.size() ) ) { return false; } for ( Attribute attribute : attributes ) { if ( !that.attributes.contains( attribute ) ) { return false; } } return true; } else { return attributes == null; } } return false; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( attributeValueItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( attributeValueItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( attributeValueItemA.equals( attributeValueItemC ) ); assertFalse( attributeValueItemC.equals( attributeValueItemA ) ); assertFalse( attributeValueItemA.equals( attributeValueItemD ) ); assertFalse( attributeValueItemD.equals( attributeValueItemA ) ); } |
AttributeValueItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( attributes != null ) { for ( Attribute attribute : attributes ) { hash = hash * 17 + attribute.hashCode(); } } return hash; } AttributeValueItem( Set<Attribute> attributes ); Iterator<Attribute> iterator(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testHashCodeReflexive() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemACopy.hashCode() ); assertEquals( attributeValueItemACopy.hashCode(), attributeValueItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( attributeValueItemA.hashCode(), attributeValueItemACopy.hashCode() ); assertEquals( attributeValueItemACopy.hashCode(), attributeValueItemB.hashCode() ); assertEquals( attributeValueItemA.hashCode(), attributeValueItemB.hashCode() ); } |
GeneralizedTime implements Comparable<GeneralizedTime> { public String toGeneralizedTime() { return toGeneralizedTime( upFormat, upFractionDelimiter, upFractionLength, upTimeZoneFormat ); } GeneralizedTime( Date date ); GeneralizedTime( Calendar calendar ); GeneralizedTime( long timeInMillis ); GeneralizedTime( String generalizedTime ); String toGeneralizedTime(); String toGeneralizedTimeWithoutFraction(); String toGeneralizedTime( Format format, FractionDelimiter fractionDelimiter, int fractionLength,
TimeZoneFormat timeZoneFormat ); Calendar getCalendar(); @Override String toString(); @Override int hashCode(); @Override boolean equals( Object obj ); @Override int compareTo( GeneralizedTime other ); long getTime(); Date getDate(); int getYear(); int getMonth(); int getDay(); int getHour(); int getMinutes(); int getSeconds(); int getFraction(); static Date getDate( String zuluTime ); } | @Test public void testYearMonthDayHourMinSecMinusHourMin() throws ParseException { String gt = "20080102121314-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinSecDotFractionZulu() throws ParseException { String gt = "20080102121314.987Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinSecDotFractionPlusHour() throws ParseException { String gt = "20080102121314.987+0100"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinSecDotFractionMinusHourMin() throws ParseException { String gt = "20080102121314.987-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinSecCommaFractionZulu() throws ParseException { String gt = "20080102121314,987Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinSecCommaFractionPlusHour() throws ParseException { String gt = "20080102121314,987+0100"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinSecCommaFractionMinusHourMin() throws ParseException { String gt = "20080102121314,987-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinZulu() throws ParseException { String gt = "200801021213Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinPlusHour() throws ParseException { String gt = "200801021213+04"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinMinusHourMin() throws ParseException { String gt = "200801021213-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinDotFractionZulu() throws ParseException { String gt = "200801021213.987Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinDotFractionPlusHour() throws ParseException { String gt = "200801021213.987+0100"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinDotFractionMinusHourMin() throws ParseException { String gt = "200801021213.987-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinCommaFractionZulu() throws ParseException { String gt = "200801021213,987Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinCommaFractionPlusHour() throws ParseException { String gt = "200801021213,987+0100"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinCommaFractionMinusHourMin() throws ParseException { String gt = "200801021213,987-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourZulu() throws ParseException { String gt = "2008010212Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourPlusHour() throws ParseException { String gt = "2008010212+04"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinusHourMin() throws ParseException { String gt = "2008010212-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourDotFractionZulu() throws ParseException { String gt = "200801021213.987Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourDotFractionPlusHour() throws ParseException { String gt = "2008010212.987+0100"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourDotFractionMinusHourMin() throws ParseException { String gt = "2008010212.987-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourCommaFractionZulu() throws ParseException { String gt = "2008010212,987Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourCommaFractionPlusHour() throws ParseException { String gt = "2008010212,987+0100"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourCommaFractionMinusHourMin() throws ParseException { String gt = "2008010212,987-1030"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testFormatting() throws ParseException { String gt = "20080102121314Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); result = generalizedTime.toGeneralizedTime( Format.YEAR_MONTH_DAY_HOUR_MIN, null, 0, TimeZoneFormat.Z ); assertEquals( "200801021213Z", result ); result = generalizedTime.toGeneralizedTime( Format.YEAR_MONTH_DAY_HOUR, null, 0, TimeZoneFormat.Z ); assertEquals( "2008010212Z", result ); result = generalizedTime.toGeneralizedTime( Format.YEAR_MONTH_DAY_HOUR_MIN, null, 0, TimeZoneFormat.DIFF_HOUR_MINUTE ); assertEquals( "200801021213+0000", result ); result = generalizedTime.toGeneralizedTime( Format.YEAR_MONTH_DAY_HOUR, null, 0, TimeZoneFormat.DIFF_HOUR_MINUTE ); assertEquals( "2008010212+0000", result ); }
@Test public void testAdjustWhileFormatting() throws ParseException { String gt = "20080102121314+0130"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); result = generalizedTime.toGeneralizedTime( Format.YEAR_MONTH_DAY_HOUR_MIN_SEC, null, 0, TimeZoneFormat.Z ); assertEquals( "20080102104314Z", result ); }
@Test public void testFebruary29inLeapYear() throws ParseException { String gt = "20080229000000Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testCalendar() throws ParseException { Calendar calendar = new GregorianCalendar( GMT, Locale.ROOT ); calendar.set( Calendar.YEAR, 2008 ); calendar.set( Calendar.MONTH, 0 ); calendar.set( Calendar.DAY_OF_MONTH, 2 ); calendar.set( Calendar.HOUR_OF_DAY, 12 ); calendar.set( Calendar.MINUTE, 13 ); calendar.set( Calendar.SECOND, 14 ); calendar.set( Calendar.MILLISECOND, 222 ); calendar.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); GeneralizedTime generalizedTime = new GeneralizedTime( calendar ); String result = generalizedTime.toGeneralizedTime(); assertEquals( "20080102121314.222Z", result ); }
@Test public void testYearMonthDayHourMinSecZulu() throws ParseException { String gt = "20080102121314Z"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); }
@Test public void testYearMonthDayHourMinSecPlusHour() throws ParseException { String gt = "20080102121314+04"; GeneralizedTime generalizedTime = new GeneralizedTime( gt ); String result = generalizedTime.toGeneralizedTime(); assertEquals( gt, result ); } |
ClassesItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof ClassesItem ) { ClassesItem that = ( ClassesItem ) o; if ( classes == null ) { return that.classes == null; } return classes.equals( that.classes ); } return false; } ClassesItem( ExprNode classes ); ExprNode getClasses(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( classesItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( classesItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( classesItemA.equals( classesItemC ) ); assertFalse( classesItemC.equals( classesItemA ) ); } |
ClassesItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; if ( classes != null ) { hash = hash * 17 + classes.hashCode(); } else { hash = hash * 17 + getClass().getName().hashCode(); } return hash; } ClassesItem( ExprNode classes ); ExprNode getClasses(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testHashCodeReflexive() throws Exception { assertEquals( classesItemA.hashCode(), classesItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( classesItemA.hashCode(), classesItemACopy.hashCode() ); assertEquals( classesItemACopy.hashCode(), classesItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( classesItemA.hashCode(), classesItemACopy.hashCode() ); assertEquals( classesItemACopy.hashCode(), classesItemB.hashCode() ); assertEquals( classesItemA.hashCode(), classesItemB.hashCode() ); } |
MaxImmSubItem extends ProtectedItem { @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o instanceof MaxImmSubItem ) { MaxImmSubItem that = ( MaxImmSubItem ) o; return this.value == that.value; } return false; } MaxImmSubItem( int value ); int getValue(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testEqualsNotInstanceOf() throws Exception { assertFalse( maxImmSubItemA.equals( UndefinedNode.UNDEFINED_NODE ) ); }
@Test public void testEqualsNull() throws Exception { assertFalse( maxImmSubItemA.equals( null ) ); }
@Test public void testNotEqualDiffValue() throws Exception { assertFalse( maxImmSubItemA.equals( maxImmSubItemC ) ); assertFalse( maxImmSubItemC.equals( maxImmSubItemA ) ); } |
MaxImmSubItem extends ProtectedItem { @Override public int hashCode() { int hash = 37; hash = hash * 17 + value; return hash; } MaxImmSubItem( int value ); int getValue(); @Override int hashCode(); @Override boolean equals( Object o ); @Override String toString(); } | @Test public void testHashCodeReflexive() throws Exception { assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemA.hashCode() ); }
@Test public void testHashCodeSymmetric() throws Exception { assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemACopy.hashCode() ); assertEquals( maxImmSubItemACopy.hashCode(), maxImmSubItemA.hashCode() ); }
@Test public void testHashCodeTransitive() throws Exception { assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemACopy.hashCode() ); assertEquals( maxImmSubItemACopy.hashCode(), maxImmSubItemB.hashCode() ); assertEquals( maxImmSubItemA.hashCode(), maxImmSubItemB.hashCode() ); } |
LdapUrl { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append( scheme ); if ( host != null ) { switch ( hostType ) { case IPV4: case REGULAR_NAME: sb.append( host ); break; case IPV6: case IPV_FUTURE: sb.append( '[' ).append( host ).append( ']' ); break; default: throw new IllegalArgumentException( I18n.err( I18n.ERR_13012_UNEXPECTED_HOST_TYPE_ENUM, hostType ) ); } } if ( port != -1 ) { sb.append( ':' ).append( port ); } if ( dn != null ) { sb.append( '/' ).append( urlEncode( dn.getName(), false ) ); if ( !attributes.isEmpty() || forceScopeRendering || ( ( scope != SearchScope.OBJECT ) || ( filter != null ) || !extensionList.isEmpty() ) ) { sb.append( '?' ); boolean isFirst = true; for ( String attribute : attributes ) { if ( isFirst ) { isFirst = false; } else { sb.append( ',' ); } sb.append( urlEncode( attribute, false ) ); } } if ( forceScopeRendering ) { sb.append( '?' ); sb.append( scope.getLdapUrlValue() ); } else { if ( ( scope != SearchScope.OBJECT ) || ( filter != null ) || !extensionList.isEmpty() ) { sb.append( '?' ); switch ( scope ) { case ONELEVEL: case SUBTREE: sb.append( scope.getLdapUrlValue() ); break; default: break; } if ( ( filter != null ) || ( !extensionList.isEmpty() ) ) { sb.append( "?" ); if ( filter != null ) { sb.append( urlEncode( filter, false ) ); } if ( !extensionList.isEmpty() ) { sb.append( '?' ); boolean isFirst = true; if ( !extensionList.isEmpty() ) { for ( Extension extension : extensionList ) { if ( !isFirst ) { sb.append( ',' ); } else { isFirst = false; } if ( extension.isCritical ) { sb.append( '!' ); } sb.append( urlEncode( extension.type, false ) ); if ( extension.value != null ) { sb.append( '=' ); sb.append( urlEncode( extension.value, true ) ); } } } } } } } } else { sb.append( '/' ); } return sb.toString(); } LdapUrl(); LdapUrl( String string ); boolean isValidInet4Address( String inet4Address ); boolean isValidInet6Address( String inet6Address ); static String urlEncode( String url, boolean doubleEncode ); @Override String toString(); List<String> getAttributes(); Dn getDn(); List<Extension> getExtensions(); Extension getExtension( String type ); String getExtensionValue( String type ); String getFilter(); String getHost(); int getPort(); SearchScope getScope(); String getScheme(); int getNbBytes(); byte[] getBytesReference(); byte[] getBytesCopy(); String getString(); @Override int hashCode(); @Override boolean equals( Object obj ); void setScheme( String scheme ); void setHost( String host ); void setPort( int port ); void setDn( Dn dn ); void setAttributes( List<String> attributes ); void setScope( int scope ); void setScope( SearchScope scope ); void setFilter( String filter ); void setForceScopeRendering( boolean forceScopeRendering ); static final String LDAPS_SCHEME; static final String LDAP_SCHEME; static final LdapUrl EMPTY_URL; } | @Test public void testLdapUrlNull() { assertEquals( "ldap: }
@Test public void testDnEmpty() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnSimple() throws LdapURLEncodingException { assertEquals( "ldap: .toString() ); }
@Test public void testDnWithMinus() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHost1() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHost2() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHost3() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHost4() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHost5() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHost6() throws LdapURLEncodingException { assertEquals( "ldap: new LdapUrl( "ldap: }
@Test public void testDnBadHost7() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnIPV4Host() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnIPV4HostPort() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHostIP1() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHostIP2() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnBadHostIP3() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnNotAnIP() throws LdapURLEncodingException { assertEquals( "ldap: }
@Test public void testDnIPv6Host() throws LdapURLEncodingException { assertEquals( "ldap: assertEquals( "ldap: assertEquals( "ldap: assertEquals( "ldap: assertEquals( "ldap: assertEquals( "ldap: }
@Test public void testDnSimpleDN() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testDnSimpleDN2() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testDnSimpleDNEncoded() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testDnUniqueAttribute() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testDnAttributes() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testDnDuplicatedAttributes() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapNoDNAttributes() throws LdapURLEncodingException { assertEquals( "ldap: new LdapUrl( "ldap: }
@Test public void testLdapRFC2255_1() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapRFC2255_2() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapRFC2255_3() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapRFC2255_4() throws LdapURLEncodingException { assertEquals( "ldap: new LdapUrl( "ldap: }
@Test public void testLdapRFC2255_5() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapRFC2255_6() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapRFC2255_7() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapRFC2255_8() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testLdapRFC2255_9() throws LdapURLEncodingException { assertEquals( "ldap: "ldap: }
@Test public void testDnEmptyLdaps() throws LdapURLEncodingException { assertEquals( "ldaps: }
@Test public void testDnSimpleLdaps() throws LdapURLEncodingException { assertEquals( "ldaps: .toString() ); }
@Test public void testLdapURLNoHostDN() throws LdapURLEncodingException { try { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: } catch ( LdapURLEncodingException luee ) { fail(); } }
@Test public void testLdapURLHostNoPortDN() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDN() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrs() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsNoScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsNoScopeNoFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDN() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrs() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrs() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScopeBase() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsDefaultScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScopeBase() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsDefaultScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScopeBase() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsDefaultScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScopeBase() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsDefaultScope() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsNoScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsNoScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsNoScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScopeBaseFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScopeBaseFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScopeBaseFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsNoScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScopeFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScopeBaseFilter() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsNoScopeNoFilterNoExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsNoScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsNoScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScopeBaseNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNNoAttrsScopeBaseFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsNoScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsNoScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScopeBaseNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLNoDNAttrsScopeBaseFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsNoScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsNoScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScopeBaseNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNNoAttrsScopeBaseFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsNoScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsNoScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScopeNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScopeBaseNoFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScopeFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLDNAttrsScopeBaseFilterExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: }
@Test public void testLdapURLExtensionAfterEmptyExtension() throws LdapURLEncodingException { LdapUrl url = new LdapUrl( "ldap: assertEquals( "ldap: } |
Oid { public static Oid fromBytes( byte[] oidBytes ) throws DecoderException { if ( ( oidBytes == null ) || ( oidBytes.length < 1 ) ) { throw new DecoderException( I18n.err( I18n.ERR_00003_INVALID_OID, Arrays.toString( oidBytes ) ) ); } StringBuilder builder = new StringBuilder(); long value = 0; int valStart = 0; int valLength = 0; boolean firstArc = true; for ( int i = 0; i < oidBytes.length; i++ ) { value |= oidBytes[i] & 0x7F; if ( oidBytes[i] < 0 ) { value = value << 7; valLength++; } else { valLength++; if ( valLength > 8 ) { int nbBytes = valLength * 7 / 8; if ( valLength % 7 != 0 ) { nbBytes++; } byte[] result = new byte[nbBytes]; int pos = nbBytes - 1; int valEnd = valStart + valLength - 1; int j = 0; while ( j < valLength - 8 ) { result[pos--] = ( byte ) ( ( oidBytes[valEnd - j - 1] << 7 ) | ( oidBytes[valEnd - j] & 0x7F ) ); result[pos--] = ( byte ) ( ( oidBytes[valEnd - j - 2] << 6 ) | ( ( oidBytes[valEnd - j - 1] & 0x7E ) >> 1 ) ); result[pos--] = ( byte ) ( ( oidBytes[valEnd - j - 3] << 5 ) | ( ( oidBytes[valEnd - j - 2] & 0x7C ) >> 2 ) ); result[pos--] = ( byte ) ( ( oidBytes[valEnd - j - 4] << 4 ) | ( ( oidBytes[valEnd - j - 3] & 0x78 ) >> 3 ) ); result[pos--] = ( byte ) ( ( oidBytes[valEnd - j - 5] << 3 ) | ( ( oidBytes[valEnd - j - 4] & 0x70 ) >> 4 ) ); result[pos--] = ( byte ) ( ( oidBytes[valEnd - j - 6] << 2 ) | ( ( oidBytes[valEnd - j - 5] & 0x60 ) >> 5 ) ); result[pos--] = ( byte ) ( ( oidBytes[valEnd - j - 7] << 1 ) | ( ( oidBytes[valEnd - j - 6] & 0x40 ) >> 6 ) ); j += 8; } switch ( valLength - j ) { case 7 : result[pos--] = ( byte ) ( ( oidBytes[5] << 7 ) | ( oidBytes[6] & 0x7F ) ); result[pos--] = ( byte ) ( ( oidBytes[4] << 6 ) | ( ( oidBytes[5] & 0x7E ) >> 1 ) ); result[pos--] = ( byte ) ( ( oidBytes[3] << 5 ) | ( ( oidBytes[4] & 0x7C ) >> 2 ) ); result[pos--] = ( byte ) ( ( oidBytes[2] << 4 ) | ( ( oidBytes[3] & 0x78 ) >> 3 ) ); result[pos--] = ( byte ) ( ( oidBytes[1] << 3 ) | ( ( oidBytes[2] & 0x70 ) >> 4 ) ); result[pos--] = ( byte ) ( ( oidBytes[0] << 2 ) | ( ( oidBytes[1] & 0x60 ) >> 5 ) ); result[pos] = ( byte ) ( ( oidBytes[0] & 0x40 ) >> 6 ); break; case 6 : result[pos--] = ( byte ) ( ( oidBytes[4] << 7 ) | ( oidBytes[5] & 0x7F ) ); result[pos--] = ( byte ) ( ( oidBytes[3] << 6 ) | ( ( oidBytes[4] & 0x7E ) >> 1 ) ); result[pos--] = ( byte ) ( ( oidBytes[2] << 5 ) | ( ( oidBytes[3] & 0x7C ) >> 2 ) ); result[pos--] = ( byte ) ( ( oidBytes[1] << 4 ) | ( ( oidBytes[2] & 0x78 ) >> 3 ) ); result[pos--] = ( byte ) ( ( oidBytes[0] << 3 ) | ( ( oidBytes[1] & 0x70 ) >> 4 ) ); result[pos] = ( byte ) ( ( oidBytes[0] & 0x60 ) >> 5 ); break; case 5 : result[pos--] = ( byte ) ( ( oidBytes[3] << 7 ) | ( oidBytes[4] & 0x7F ) ); result[pos--] = ( byte ) ( ( oidBytes[2] << 6 ) | ( ( oidBytes[3] & 0x7E ) >> 1 ) ); result[pos--] = ( byte ) ( ( oidBytes[1] << 5 ) | ( ( oidBytes[2] & 0x7C ) >> 2 ) ); result[pos--] = ( byte ) ( ( oidBytes[0] << 4 ) | ( ( oidBytes[1] & 0x78 ) >> 3 ) ); result[pos] = ( byte ) ( ( oidBytes[0] & 0x70 ) >> 4 ); break; case 4 : result[pos--] = ( byte ) ( ( oidBytes[2] << 7 ) | ( oidBytes[3] & 0x7F ) ); result[pos--] = ( byte ) ( ( oidBytes[1] << 6 ) | ( ( oidBytes[2] & 0x7E ) >> 1 ) ); result[pos--] = ( byte ) ( ( oidBytes[0] << 5 ) | ( ( oidBytes[1] & 0x7C ) >> 2 ) ); result[pos] = ( byte ) ( ( oidBytes[0] & 0x78 ) >> 3 ); break; case 3 : result[pos--] = ( byte ) ( ( oidBytes[1] << 7 ) | ( oidBytes[2] & 0x7F ) ); result[pos--] = ( byte ) ( ( oidBytes[0] << 6 ) | ( ( oidBytes[1] & 0x7E ) >> 1 ) ); result[pos] = ( byte ) ( ( oidBytes[0] & 0x7C ) >> 2 ); break; case 2 : result[pos--] = ( byte ) ( ( oidBytes[0] << 7 ) | ( oidBytes[1] & 0x7F ) ); result[pos] = ( byte ) ( ( oidBytes[0] & 0x7E ) >> 1 ); break; case 1 : result[pos] = ( byte ) ( oidBytes[0] & 0x7F ); break; default : break; } BigInteger bigInteger; if ( ( result[0] & 0x80 ) == 0x80 ) { byte[] newResult = new byte[result.length + 1]; System.arraycopy( result, 0, newResult, 1, result.length ); result = newResult; } bigInteger = new BigInteger( result ); if ( firstArc ) { bigInteger = bigInteger.subtract( JOINT_ISO_ITU_T ); builder.append( '2' ); } builder.append( '.' ).append( bigInteger.toString() ); } else { if ( firstArc ) { if ( value >= 80 ) { builder.append( '2' ); value = value - 80; } else { long one = value / 40; long two = value % 40; if ( ( one < 0 ) || ( one > 2 ) || ( two < 0 ) || ( ( one < 2 ) && ( two > 39 ) ) ) { throw new DecoderException( I18n.err( I18n.ERR_00003_INVALID_OID, Arrays.toString( oidBytes ) ) ); } if ( one < 2 ) { builder.append( one ); value = two; } } firstArc = false; } builder.append( '.' ).append( value ); } valStart = i; valLength = 0; value = 0; } } return new Oid( builder.toString(), oidBytes ); } private Oid( String oidString, byte[] oidBytes ); @Override boolean equals( Object other ); static Oid fromBytes( byte[] oidBytes ); static Oid fromString( String oidString ); int getEncodedLength(); @Override int hashCode(); static boolean isOid( String oidString ); byte[] toBytes(); @Override String toString(); void writeBytesTo( ByteBuffer buffer ); void writeBytesTo( OutputStream outputStream ); } | @Test public void fromBytes() throws DecoderException { for ( int i = 0; i < 2; i++ ) { for ( int j = 0; j < 40; j++ ) { assertEquals( i + "." + j, Oid.fromBytes( new byte[] { ( byte ) ( i * 40 + j ) } ) .toString() ); } } assertEquals( "1.2.840.113554.1.2.2", Oid.fromBytes( new byte[] { 0x2A, ( byte ) 0x86, 0x48, ( byte ) 0x86, ( byte ) 0xF7, 0x12, 0x01, 0x02, 0x02 } ).toString() ); assertEquals( "2.123456", Oid.fromBytes( new byte[] { ( byte ) 0x87, ( byte ) 0xC5, 0x10 } ).toString() ); }
@Test public void testNewOidNull() { try { Oid.fromBytes( ( byte[] ) null ); fail( "Should not reach this point ..." ); } catch ( DecoderException de ) { assertTrue( true ); } }
@Test public void testNewOidEmpty() { try { Oid.fromBytes( new byte[] {} ); fail( "Should not reach this point ..." ); } catch ( DecoderException de ) { assertTrue( true ); } } |
LdapTlsHandshakeException extends LdapException { @Override public String getMessage() { String message = super.getMessage(); message += ", reason: " + failCause.getReasonPhrase(); Throwable rootCause = failCause.getRootCause(); if ( rootCause != null && rootCause != this ) { message += ": " + rootCause.getMessage(); } return message; } LdapTlsHandshakeException( String message, Throwable cause ); LdapTlsHandshakeFailCause getFailCause(); @Override String getMessage(); } | @Test public void testClassifyNull() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", null ); assertThat( e.getMessage(), equalTo( "msg, reason: Unspecified" ) ); }
@Test public void testClassifyOther() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new IOException( "foo" ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Unspecified: foo" ) ); }
@Test public void testClassifyCertificateExpiredException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new CertificateExpiredException( "foo" ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Certificate expired: foo" ) ); }
@Test public void testClassifyCertificateNotYetValidException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new CertificateNotYetValidException( "foo" ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Certificate not yet valid: foo" ) ); }
@Test public void testClassifyCertPathBuilderException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new Exception( new CertPathBuilderException( "foo" ) ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Failed to build certification path: foo" ) ); }
@Test public void testClassifyCertPathValidatorException() { LdapTlsHandshakeException e = new LdapTlsHandshakeException( "msg", new Exception( new Exception( new Exception( new Exception( new CertPathValidatorException( "foo", null, null, -1, BasicReason.ALGORITHM_CONSTRAINED ) ) ) ) ) ); assertThat( e.getMessage(), equalTo( "msg, reason: Failed to verify certification path: foo" ) ); } |
LdapTlsHandshakeExceptionClassifier { public static LdapTlsHandshakeFailCause classify( Throwable cause ) { return classify( cause, null ); } private LdapTlsHandshakeExceptionClassifier(); static LdapTlsHandshakeFailCause classify( Throwable cause ); static LdapTlsHandshakeFailCause classify( Throwable cause, X509Certificate certificate ); } | @Test public void testClassifyNull() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier.classify( null ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.UNSPECIFIED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Unspecified" ) ); assertThat( classification.getRootCause(), equalTo( null ) ); }
@Test public void testClassifyOther() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new IOException( "foo" ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.UNSPECIFIED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Unspecified" ) ); assertThat( classification.getRootCause(), instanceOf( IOException.class ) ); }
@Test public void testClassifyCertificateExpiredException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new CertificateExpiredException( "foo" ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.EXPIRED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Certificate expired" ) ); assertThat( classification.getRootCause(), instanceOf( CertificateExpiredException.class ) ); }
@Test public void testClassifyCertificateNotYetValidException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new CertificateNotYetValidException( "foo" ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.NOT_YET_VALID ) ); assertThat( classification.getReasonPhrase(), equalTo( "Certificate not yet valid" ) ); assertThat( classification.getRootCause(), instanceOf( CertificateNotYetValidException.class ) ); }
@Test public void testClassifyCertPathBuilderException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier .classify( new Exception( new CertPathBuilderException( "foo" ) ) ); assertThat( classification.getReason(), equalTo( ( Reason ) LdapApiReason.NO_VALID_CERTIFICATION_PATH ) ); assertThat( classification.getReasonPhrase(), equalTo( "Failed to build certification path" ) ); assertThat( classification.getRootCause(), instanceOf( CertPathBuilderException.class ) ); }
@Test public void testClassifyCertPathValidatorException() { LdapTlsHandshakeFailCause classification = LdapTlsHandshakeExceptionClassifier.classify( new Exception( new Exception( new Exception( new Exception( new CertPathValidatorException( "foo", null, null, -1, BasicReason.ALGORITHM_CONSTRAINED ) ) ) ) ) ); assertThat( classification.getReason(), equalTo( ( Reason ) BasicReason.ALGORITHM_CONSTRAINED ) ); assertThat( classification.getReasonPhrase(), equalTo( "Failed to verify certification path" ) ); assertThat( classification.getRootCause(), instanceOf( CertPathValidatorException.class ) ); } |