auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public OutputStream create(String filename, HdfsSinkConnectorConfig conf, boolean overwrite) { final Path path = new Path(filename); try { return new OutputStream() { FileSystem fs = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()); OutputStream file = fs.create(new Path(filename), overwrite); @Override public void write(final int b) throws IOException { file.write(b); } @Override public void write(final byte[] b) throws IOException { file.write(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { file.write(b, off, len); } @Override public void flush() throws IOException { file.flush(); } @Override public void close() throws IOException { file.close(); fs.close(); } }; } catch (IOException e) { throw new ConnectException(e); } }

Target:
public OutputStream create(String filename, HdfsSinkConnectorConfig conf, boolean overwrite) { final Path path = new Path(filename); try { return new OutputStream() { FileSystem fs = FileSystem.newInstance(path.toUri(), conf.getHadoopConfiguration()); OutputStream file = fs.create(new Path(filename), overwrite); @Override public void write(final int b) throws IOException { file.write(b); } @Override public void write(final byte[] b) throws IOException { file.write(b); } @Override public void write(final byte[] b, final int off, final int len) throws IOException { file.write(b, off, len); } @Override public void flush() throws IOException { file.flush(); } @Override public void close() throws IOException { try { file.close(); } finally { try { fs.close(); } catch (Throwable t) { log.error("Could not close FileSystem", t); } } } }; } catch (IOException e) { throw new ConnectException(e); } }
Source:
public void exportDMSHits() { ExportDms export = new ExportDms(); for (Process proz : (List<Process>) this.page.getCompleteList()) { try { export.startExport(proz); } catch (Exception e) { Helper.setErrorMessage("ExportError", logger, e); } } Helper.setMeldung(null, "ExportFinished", ""); logger.info(Helper.getTranslation("ExportFinished")); }

Target:
public void exportDMSHits() { ExportDms export = new ExportDms(); for (Process proz : (List<Process>) this.page.getCompleteList()) { try { export.startExport(proz); } catch (Exception e) { Helper.setErrorMessage("ExportError", logger, e); } } logger.info(Helper.getTranslation("ExportFinished")); Helper.setMeldung(null, "ExportFinished", ""); }
Source:
public synchronized void trackContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException { LogGetHandle handle = dockerAccess.getLogAsync(containerId, createLogCallback(spec)); logHandles.put(containerId, handle); }

Target:
public synchronized void trackContainerLog(String containerId, LogOutputSpec spec) throws FileNotFoundException { LogGetHandle handle = dockerAccess.getLogAsync(containerId, new DefaultLogCallback(spec)); logHandles.put(containerId, handle); }
Source:
private static CloseableHttpClient createClient() { return HttpClientBuilder.create() .useSystemProperties() .disableConnectionState() .setConnectionManager( httpClientConnectionManager ) .setRetryHandler( createRetryHandler() ) .setServiceUnavailableRetryStrategy( new SimpleServiceUnavailableRetryStrategy( 10, 1000 ) ) .setDefaultAuthSchemeRegistry( createAuthSchemeRegistry() ) .build(); }

Target:
private static CloseableHttpClient createClient() { return HttpClientBuilder.create() .useSystemProperties() .disableConnectionState() .setConnectionManager( httpClientConnectionManager ) .setRetryHandler( createRetryHandler() ) .setServiceUnavailableRetryStrategy( createServiceUnavailableRetryStrategy() ) .setDefaultAuthSchemeRegistry( createAuthSchemeRegistry() ) .build(); }
Source:
public static boolean setRequestSchema(String schema) { if(schema!=null && schema.trim().length() > 0) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null && requestAttributes.getRequest() != null) { HttpServletRequest request = requestAttributes.getRequest(); request.setAttribute("requestSchema", schema); return true; } else { CoreResources.tenantSchema.set(schema); } } return false; }

Target:
public static boolean setRequestSchema(String schema) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null && requestAttributes.getRequest() != null) { HttpServletRequest request = requestAttributes.getRequest(); request.setAttribute("requestSchema", schema); return true; } else { CoreResources.tenantSchema.set(schema); } return false; }
Source:
public SimpleMessage(String message, String key, String topic) { if (topic == null) throw new IllegalArgumentException("topic==null"); if (message == null) throw new IllegalArgumentException("message==null"); this.topic = topic; this.key = key; this.message = message; }

Target:
public SimpleMessage(String message, String key, String topic) { if (message == null) throw new IllegalArgumentException("message==null"); this.topic = topic; this.key = key; this.message = message; }
Source:
public Map<String, Object> getStats() { try { return getCurrentTotalStats(); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public Map<String, Map<String, Object>> getStats() { try { return getCurrentTotalStats(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error(ie, "getStats() interrupted."); throw new RuntimeException(ie); } catch (ExecutionException | TimeoutException eete) { throw new RuntimeException(eete); } }
Source:
private List<Long> replOpenTxnForTest(long startId, int numTxn, String replPolicy) throws Exception { conf.setIntVar(HiveConf.ConfVars.HIVE_TXN_MAX_OPEN_BATCH, numTxn); long lastId = startId + numTxn - 1; OpenTxnRequest rqst = new OpenTxnRequest(numTxn, "me", "localhost"); rqst.setReplPolicy(replPolicy); rqst.setReplSrcTxnIds(LongStream.rangeClosed(startId, lastId) .boxed().collect(Collectors.toList())); int numTxnPresentStart = TxnDbUtil.countQueryAgent(conf, "select count(*) from TXNS"); OpenTxnsResponse openedTxns = txnHandler.openTxns(rqst); List<Long> txnList = openedTxns.getTxn_ids(); assertEquals(txnList.size(), numTxn); int numTxnPresentNow = TxnDbUtil.countQueryAgent(conf, "select count(*) from TXNS"); assertEquals(numTxn + numTxnPresentStart, numTxnPresentNow); checkReplTxnForTest(startId, lastId, replPolicy, txnList); return txnList; }

Target:
private List<Long> replOpenTxnForTest(long startId, int numTxn, String replPolicy) throws Exception { conf.setIntVar(HiveConf.ConfVars.HIVE_TXN_MAX_OPEN_BATCH, numTxn); long lastId = startId + numTxn - 1; OpenTxnRequest rqst = new OpenTxnRequest(numTxn, "me", "localhost"); rqst.setReplPolicy(replPolicy); rqst.setReplSrcTxnIds(LongStream.rangeClosed(startId, lastId) .boxed().collect(Collectors.toList())); OpenTxnsResponse openedTxns = txnHandler.openTxns(rqst); List<Long> txnList = openedTxns.getTxn_ids(); assertEquals(txnList.size(), numTxn); int numTxnPresentNow = TxnDbUtil.countQueryAgent(conf, "select count(*) from TXNS where TXN_ID >= " + txnList.get(0) + " and TXN_ID <= " + txnList.get(numTxn - 1)); assertEquals(numTxn, numTxnPresentNow); checkReplTxnForTest(startId, lastId, replPolicy, txnList); return txnList; }
Source:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (int i = 0 ; i < volume.getBricks().size(); i++) { GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } if(upCount > 1 && downCount > 1) { return downCount; } } return downCount; }

Target:
public int countDownBricks(GlusterVolumeEntity volume) { int downCount = 0; int upCount = 0; for (int i = 0 ; i < volume.getBricks().size(); i++) { GlusterBrickEntity brick = volume.getBricks().get(i); if(brick.getStatus() == GlusterStatus.UP) { upCount++; }else { downCount++; } if(upCount > 0 && downCount > 0) { return downCount; } } return downCount; }
Source:
public void close() throws IOException { tarArchiveOutputStream.close(); }

Target:
public void close() throws Exception { tarArchiveOutputStream.close(); }
Source:
public void testNoWorkHomeSpecifier_EMAIL() throws Throwable { final String request = "<iq id='v1' to='user@igniterealtime.org/mobile' type='result'>" + "<vCard xmlns='vcard-temp'><EMAIL><USERID>foo@fee.www.bar</USERID></EMAIL></vCard>" + "</iq>"; IQ iqRequest = (IQ) PacketParserUtils.parseStanza(request); assertTrue(iqRequest instanceof VCard); VCard vCard = (VCard) iqRequest; assertEquals("foo@fee.www.bar", vCard.getEmailHome()); }

Target:
public void testNoWorkHomeSpecifier_EMAIL() throws Throwable { final String request = "<iq id='v1' to='user@igniterealtime.org/mobile' type='result'>" + "<vCard xmlns='vcard-temp'><EMAIL><USERID>foo@fee.www.bar</USERID></EMAIL></vCard>" + "</iq>"; VCard vCard = (VCard) PacketParserUtils.parseStanza(request); assertEquals("foo@fee.www.bar", vCard.getEmailHome()); }
Source:
public void handle(LoginSuccess loginSuccess) throws Exception { Preconditions.checkState( thisState == State.LOGIN_SUCCESS, "Not expecting LOGIN_SUCCESS" ); ch.setProtocol( Protocol.GAME ); thisState = State.LOGIN; if ( user.getServer() != null && user.getForgeClientHandler().isHandshakeComplete() && !user.getForgeClientHandler().isForgeOutdated() ) { user.getForgeClientHandler().resetHandshake(); } throw CancelSendSignal.INSTANCE; }

Target:
public void handle(LoginSuccess loginSuccess) throws Exception { Preconditions.checkState( thisState == State.LOGIN_SUCCESS, "Not expecting LOGIN_SUCCESS" ); ch.setProtocol( Protocol.GAME ); thisState = State.LOGIN; if ( user.getServer() != null && user.getForgeClientHandler().isForgeClient() && !user.getForgeClientHandler().isForgeOutdated() ) { user.getForgeClientHandler().resetHandshake(); } throw CancelSendSignal.INSTANCE; }
Source:
public WorkspaceAndPluginsResourceDialog(Shell parent, boolean allowMultiple, List<String> extensions) { super(parent, WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(), new DeferredWorkbenchContentProvider()); this.extensions = extensions; setAllowMultiple(allowMultiple); if (allowMultiple) { setTitle("Select files"); } else { setTitle("Select a file"); } setInput(new WorkbenchProxyObject()); addFilter(new FileExtensionFilter()); }

Target:
public WorkspaceAndPluginsResourceDialog(Shell parent, boolean allowMultiple, List<String> extensions) { super(parent, WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(), new DeferredWorkbenchContentProvider()); this.extensions = extensions; setAllowMultiple(allowMultiple); if (allowMultiple) { setTitle(SiriusTransPlugin.INSTANCE.getString("titleSelectFiles")); } else { setTitle(SiriusTransPlugin.INSTANCE.getString("titleSelectAFile")); } setInput(new WorkbenchProxyObject()); addFilter(new FileExtensionFilter()); }
Source:
public double getStdDev() { return fNbSegments > 2 ? Math.sqrt(fVariance / fNbSegments) : Double.NaN; }

Target:
public double getStdDev() { return fNbSegments > 2 ? Math.sqrt(fVariance / (fNbSegments - 1)) : Double.NaN; }
Source:
@Override public void updateInitial(long start, long delta) { try { update(start + delta); } catch (IgniteCheckedException e) { } initCntr = get(); }

Target:
@Override public synchronized void updateInitial(long start, long delta) { update(start + delta); initCntr = get(); }
Source:
public Optional<EventMessage<?>> readKafkaMessage(ConsumerRecord<String, byte[]> consumerRecord) { try { Headers headers = consumerRecord.headers(); if (isAxonMessage(headers)) { byte[] messageBody = consumerRecord.value(); SerializedMessage<?> message = extractSerializedMessage(headers, messageBody); long timestamp = valueAsLong(headers, MESSAGE_TIMESTAMP); return headers.lastHeader(AGGREGATE_ID) != null ? domainEvent(headers, message, timestamp) : event(message, timestamp); } } catch (Exception e) { logger.trace("Error converting to axon, {}", consumerRecord, e); } return Optional.empty(); }

Target:
public Optional<EventMessage<?>> readKafkaMessage(ConsumerRecord<String, byte[]> consumerRecord) { try { Headers headers = consumerRecord.headers(); if (isAxonMessage(headers)) { byte[] messageBody = consumerRecord.value(); SerializedMessage<?> message = extractSerializedMessage(headers, messageBody); return buildMessage(headers, message); } } catch (Exception e) { logger.trace("Error converting to axon", consumerRecord, e); } return Optional.empty(); }
Source:
public void junit_assert_that() { assertThat("aaa", org.junit.matchers.JUnitMatchers.containsString("a")); }

Target:
public void junit_assert_that() { org.junit.Assert.assertThat("aaa", org.junit.matchers.JUnitMatchers.containsString("a")); }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; BlockTree block = methodTree.block(); if (block != null) { NpeVisitor visitor = new NpeVisitor(methodTree.parameters()); block.accept(visitor); for (Tree issueTree : visitor.getIssueTrees()) { addIssue(issueTree, "NPE!"); } } }

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } MethodTree methodTree = (MethodTree) tree; BlockTree block = methodTree.block(); if (block != null) { NpeVisitor visitor = new NpeVisitor(methodTree.parameters()); block.accept(visitor); for (Tree issueTree : visitor.getIssueTrees()) { String name = getNameFrom(issueTree); String methodName = visitor.isTreeMethodParam(issueTree); if (StringUtils.isNotBlank(methodName)) { if (issueTree.is(Tree.Kind.NULL_LITERAL)) { addIssue(issueTree, "method '" + methodName + "' does not accept nullable argument"); } else { addIssue(issueTree, "'" + name + "' is nullable here and method '" + methodName + "' does not accept nullable argument"); } } else { addIssue(issueTree, "NullPointerException might be thrown as '" + name + "' is nullable here"); } } } }
Source:
public InstanceMonitor(String clusterName, String participantName, ObjectName objectName) throws JMException { _clusterName = clusterName; _participantName = participantName; _tags = ImmutableList.of(ClusterStatusMonitor.DEFAULT_TAG); _initObjectName = objectName; createMetrics(); register(); }

Target:
public InstanceMonitor(String clusterName, String participantName, ObjectName objectName) { _clusterName = clusterName; _participantName = participantName; _tags = ImmutableList.of(ClusterStatusMonitor.DEFAULT_TAG); _initObjectName = objectName; createMetrics(); }
Source:
public static <E> AbstractGroupExpression<E, Set<E>> sortedSet(Expression<E> expression, Comparator<? super E> comparator) { return GSet.createSorted(expression, comparator); }

Target:
public static <E> AbstractGroupExpression<E, SortedSet<E>> sortedSet(Expression<E> expression, Comparator<? super E> comparator) { return GSet.createSorted(expression, comparator); }
Source:
private Jar getSources(Tool tool, Processor context, String path) throws Exception { Jar jar = toJar(context, path); if (path != null && jar == null) { logger.warn( "A sources path was set in the -maven-release instuction, but no sources could be found in (base path: {}) ", path, context.getBaseURI() .toString()); } if (jar != null) { tool.setSources(jar, ""); } else { jar = tool.doSource(); } jar.ensureManifest(); jar.setName(Archive.SOURCES_CLASSIFIER); tool.addClose(jar); return jar; }

Target:
private Jar getSources(Tool tool, Processor context, String path) throws Exception { Jar jar = toJar(context, path); if (path != null && jar == null) { logger.warn( "A sources path was set in the -maven-release instuction, but no sources could be found in (base path: {}) ", path, context.getBase()); } if (jar != null) { tool.setSources(jar, ""); } else { jar = tool.doSource(); } jar.ensureManifest(); jar.setName(Archive.SOURCES_CLASSIFIER); tool.addClose(jar); return jar; }
Source:
private void handleIdentifyResults(List<IdentifyLayerResult> identifyLayerResults) { String message = ""; int totalCount = 0; for (IdentifyLayerResult identifyLayerResult : identifyLayerResults) { int count = geoElementsCountFromResult(identifyLayerResult); String layerName = identifyLayerResult.getLayerContent().getName(); message += layerName + ": " + count; if (!identifyLayerResult.equals(identifyLayerResults.get(identifyLayerResults.size() - 1))) { message += "\n"; } totalCount += count; } if (totalCount > 0) { showAlertDialog(message); } else { Toast.makeText(this, "No element found", Toast.LENGTH_SHORT).show(); Log.i(TAG, "No element found."); } }

Target:
private void handleIdentifyResults(List<IdentifyLayerResult> identifyLayerResults) { StringBuilder message = new StringBuilder(); int totalCount = 0; for (IdentifyLayerResult identifyLayerResult : identifyLayerResults) { int count = geoElementsCountFromResult(identifyLayerResult); String layerName = identifyLayerResult.getLayerContent().getName(); message.append(layerName).append(": ").append(count); if (!identifyLayerResult.equals(identifyLayerResults.get(identifyLayerResults.size() - 1))) { message.append("\n"); } totalCount += count; } if (totalCount > 0) { showAlertDialog(message); } else { Toast.makeText(this, "No element found", Toast.LENGTH_SHORT).show(); Log.i(TAG, "No element found."); } }
Source:
public void deleteNodeTestNodeException_puppet_1() throws NodeExecutionException, Exception { HttpResponse httpResponse = mock(HttpResponse.class); StatusLine statusLine = mock(StatusLine.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); when(httpResponse.getStatusLine().getStatusCode()).thenReturn(500); when(client.execute((HttpUriRequest) anyObject())).thenReturn(httpResponse); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); nodeManager.nodeDelete("test", "testError", "token"); verify(httpResponse, times(1)).getStatusLine(); }

Target:
public void deleteNodeTestNodeException_puppet_1() throws Exception { HttpResponse httpResponse = mock(HttpResponse.class); StatusLine statusLine = mock(StatusLine.class); when(httpResponse.getStatusLine()).thenReturn(statusLine); when(httpResponse.getStatusLine().getStatusCode()).thenReturn(500); when(client.execute((HttpUriRequest) anyObject())).thenReturn(httpResponse); when(propertiesProvider.getProperty(anyString())).thenReturn("URL"); nodeManager.nodeDelete("test", "testError", "token"); }
Source:
private Throwable getRootCause(Throwable e) { Throwable root = e.getCause(); if (root == null) { return e; } else { while(true) { if (root.getCause() == null) { return root; } else { root = root.getCause(); } } } }

Target:
private Throwable getRootCause(Throwable e) { Throwable root = e.getCause(); if (root == null || root == e) { return e; } else { while(true) { Throwable cause = root.getCause(); if (cause == null || cause == root) { return root; } root = root.getCause(); } } }
Source:
public void testFindAndDeleteGarbage() throws Exception { Ignite ignite = startGrids(2); ignite.cluster().active(true); injectTestSystemOut(); ignite.createCaches(Arrays.asList( new CacheConfiguration<>("garbage1").setGroupName("groupGarbage"), new CacheConfiguration<>("garbage2").setGroupName("groupGarbage"))); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", ignite(0).localNode().id().toString(), "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "groupGarbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); }

Target:
public void testFindAndDeleteGarbage() throws Exception { Ignite ignite = startGrids(2); ignite.cluster().active(true); injectTestSystemOut(); ignite.createCaches(Arrays.asList( new CacheConfiguration<>("garbage1").setGroupName("groupGarbage"), new CacheConfiguration<>("garbage2").setGroupName("groupGarbage"))); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", ignite(0).localNode().id().toString(), "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); testOut.reset(); assertEquals(EXIT_CODE_OK, execute("--cache", "find_garbage", "groupGarbage", "--port", "11212")); assertTrue(testOut.toString().contains("garbage not found")); }
Source:
public void start() { PathHandler pathHandler = Handlers.path().addExactPath("/", this); AllowedMethodsHandler allowedMethodsHandler = new AllowedMethodsHandler(pathHandler, Methods.GET); gracefulShutdownHandler = Handlers.gracefulShutdown(allowedMethodsHandler); server = Undertow.builder() .addHttpListener(0, "localhost") .setHandler(gracefulShutdownHandler).build(); server.start(); }

Target:
public void start() { PathHandler pathHandler = Handlers.path().addExactPath("/", this); AllowedMethodsHandler allowedMethodsHandler = new AllowedMethodsHandler(pathHandler, Methods.GET); gracefulShutdownHandler = Handlers.gracefulShutdown(allowedMethodsHandler); server = Undertow.builder() .setIoThreads(1) .setWorkerThreads(1) .addHttpListener(0, "localhost") .setHandler(gracefulShutdownHandler) .build(); server.start(); }
Source:
protected IStatus validate() { final Boolean unixSocketBindingMode = (Boolean) this.unixSocketBindingModeModelObservable .getValue(); final String unixSocketPath = (String) this.unixSocketPathModelObservable .getValue(); if (unixSocketBindingMode) { if (unixSocketPath == null || unixSocketPath.isEmpty()) { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.missingUnixSocket.msg")); } try { final URI unixSocketURI = new URI(unixSocketPath); if (unixSocketURI.getScheme() != null && !unixSocketURI.getScheme().equals("unix")) { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketScheme.msg")); } if (unixSocketURI.getPath() != null) { final File unixSocket = new File( unixSocketURI.getPath()); if (!unixSocket.exists()) { return ValidationStatus .error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketPath.msg")); } else if (!unixSocket.canRead() || !unixSocket.canRead()) { return ValidationStatus .error(WizardMessages.getString( "NewDockerConnectionPage.validation.unreadableUnixSocket.msg")); } } else { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketPath.msg")); } } catch (URISyntaxException e) { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketPath.msg")); } } return ValidationStatus.ok(); }

Target:
protected IStatus validate() { final Boolean unixSocketBindingMode = (Boolean) this.unixSocketBindingModeModelObservable .getValue(); final String unixSocketPath = (String) this.unixSocketPathModelObservable .getValue(); if (unixSocketBindingMode) { if (unixSocketPath == null || unixSocketPath.isEmpty()) { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.missingUnixSocket.msg")); } try { final URI unixSocketURI = new URI(unixSocketPath); if (unixSocketURI.getScheme() != null && !unixSocketURI.getScheme().equals("unix")) { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketScheme.msg")); } if (unixSocketURI.getPath() != null) { final File unixSocket = new File( unixSocketURI.getPath()); if (!unixSocket.exists()) { return ValidationStatus .error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketPath.msg")); } else if (!unixSocket.canRead() || !unixSocket.canWrite()) { return ValidationStatus .error(WizardMessages.getString( "NewDockerConnectionPage.validation.unreadableUnixSocket.msg")); } } else { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketPath.msg")); } } catch (URISyntaxException e) { return ValidationStatus.error(WizardMessages.getString( "NewDockerConnectionPage.validation.invalidUnixSocketPath.msg")); } } return ValidationStatus.ok(); }
Source:
private CompletionStage<RestResponse> getInfo(RestRequest request) { NettyRestResponse.Builder responseBuilder = checkCacheManager(request); if (responseBuilder.getHttpStatus() == NOT_FOUND) return completedFuture(responseBuilder.build()); CacheManagerInfo cacheManagerInfo = Security.doAs(request.getSubject(), (PrivilegedAction<CacheManagerInfo>) () -> cacheManager.getCacheManagerInfo()); try { byte[] bytes = objectMapper.writeValueAsBytes(cacheManagerInfo); responseBuilder.contentType(APPLICATION_JSON) .entity(bytes) .status(OK); } catch (JsonProcessingException e) { responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return completedFuture(responseBuilder.build()); }

Target:
private CompletionStage<RestResponse> getInfo(RestRequest request) { NettyRestResponse.Builder responseBuilder = checkCacheManager(request); if (responseBuilder.getHttpStatus() == NOT_FOUND) return completedFuture(responseBuilder.build()); try { byte[] bytes = objectMapper.writeValueAsBytes(cacheManager.getCacheManagerInfo()); responseBuilder.contentType(APPLICATION_JSON) .entity(bytes) .status(OK); } catch (JsonProcessingException e) { responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return completedFuture(responseBuilder.build()); }
Source:
public void put(String parentUniqueId, SimpleObject post, RequestContext context) throws ResponseException { Patient patient = Context.getPatientService().getPatientByUuid(parentUniqueId); if (patient == null) { throw new ObjectNotFoundException(); } if (post.size() != 0) { throw new ObjectNotFoundException(); } Allergies allergies = Context.getPatientService().getAllergies(patient); if (allergies.size() != 0) { throw new ObjectNotFoundException(); } allergies.confirmNoKnownAllergies(); Context.getPatientService().setAllergies(patient, allergies); }

Target:
public void put(String parentUniqueId, SimpleObject post, RequestContext context) throws ResponseException { Patient patient = Context.getPatientService().getPatientByUuid(parentUniqueId); if (patient == null) { throw new ObjectNotFoundException(); } if (post.size() != 0) { throw new ResourceDoesNotSupportOperationException(); } Allergies allergies = Context.getPatientService().getAllergies(patient); if (allergies.size() != 0) { throw new ResourceDoesNotSupportOperationException(); } allergies.confirmNoKnownAllergies(); Context.getPatientService().setAllergies(patient, allergies); }
Source:
private void startAMQPServer() throws ConfigurationException { boolean isServerStarted = false; int port; if (brokerService.getIfSSLOnly()) { port = brokerService.getAMQPSSLPort(); } else { port = brokerService.getAMQPPort(); } if (AndesConfigurationManager.<Boolean>readValue(AndesConfiguration.TRANSPORTS_AMQP_ENABLED)) { while (!isServerStarted) { Socket socket = null; try { InetAddress address = InetAddress.getByName(getAMQPTransportBindAddress()); socket = new Socket(address, port); log.info("AMQP Host Address : " + address.getHostAddress() + " Port : " + port); isServerStarted = socket.isConnected(); if (isServerStarted) { log.info("Successfully connected to AMQP server " + "on port " + port); } } catch (IOException e) { log.error("Wait until Qpid server starts on port " + port, e); try { Thread.sleep(500); } catch (InterruptedException ignore) { } } finally { try { if ((socket != null) && (socket.isConnected())) { socket.close(); } } catch (IOException e) { log.error("Can not close the socket which is used to check the server " + "status ", e); } } } } else { log.warn("AMQP Transport is disabled as per configuration."); } }

Target:
private void startAMQPServer() throws ConfigurationException { boolean isServerStarted = false; int port; if (brokerService.getIfSSLOnly()) { port = brokerService.getAMQPSSLPort(); } else { port = brokerService.getAMQPPort(); } if (AndesConfigurationManager.<Boolean>readValue(AndesConfiguration.TRANSPORTS_AMQP_ENABLED)) { while (!isServerStarted) { Socket socket = null; try { InetAddress address = InetAddress.getByName(getAMQPTransportBindAddress()); socket = new Socket(address, port); log.info("AMQP Host Address : " + address.getHostAddress() + " Port : " + port); isServerStarted = socket.isConnected(); if (isServerStarted) { log.info("Successfully connected to AMQP server " + "on port " + port); } } catch (IOException e) { log.error("Wait until Qpid server starts on port " + port, e); try { Thread.sleep(500); } catch (InterruptedException ignore) { } } finally { try { if ((socket != null) && (socket.isConnected())) { socket.close(); } } catch (IOException e) { log.error("Can not close the socket which is used to check the server status ", e); } } } } else { log.warn("AMQP Transport is disabled as per configuration."); } }
Source:
public void handle(Patient patient, User originalVoidingUser, Date origParentVoidedDate, String unused) { if (patient.getId() != null) { EncounterService es = Context.getEncounterService(); EncounterSearchCriteria encounterSearchCriteria = new EncounterSearchCriteriaBuilder() .setPatient(patient) .setIncludeVoided(true) .createEncounterSearchCriteria(); List<Encounter> encounters = es.getEncounters(encounterSearchCriteria); if (CollectionUtils.isNotEmpty(encounters)) { for (Encounter encounter : encounters) { if (encounter.isVoided() && encounter.getDateVoided().equals(origParentVoidedDate) && encounter.getVoidedBy().equals(originalVoidingUser)) { es.unvoidEncounter(encounter); } } } OrderService os = Context.getOrderService(); List<Order> orders = os.getAllOrdersByPatient(patient); if (CollectionUtils.isNotEmpty(orders)) { for (Order order : orders) { if (order.isVoided() && order.getDateVoided().equals(origParentVoidedDate) && order.getVoidedBy().equals(originalVoidingUser)) { os.unvoidOrder(order); } } } if (!patient.getVoided()) { CohortService cs = Context.getCohortService(); cs.patientVoided(patient); } } }

Target:
public void handle(Patient patient, User originalVoidingUser, Date origParentVoidedDate, String unused) { if (patient.getId() != null) { EncounterService es = Context.getEncounterService(); EncounterSearchCriteria encounterSearchCriteria = new EncounterSearchCriteriaBuilder() .setPatient(patient) .setIncludeVoided(true) .createEncounterSearchCriteria(); List<Encounter> encounters = es.getEncounters(encounterSearchCriteria); if (CollectionUtils.isNotEmpty(encounters)) { for (Encounter encounter : encounters) { if (encounter.isVoided() && encounter.getDateVoided().equals(origParentVoidedDate) && encounter.getVoidedBy().equals(originalVoidingUser)) { es.unvoidEncounter(encounter); } } } OrderService os = Context.getOrderService(); List<Order> orders = os.getAllOrdersByPatient(patient); if (CollectionUtils.isNotEmpty(orders)) { for (Order order : orders) { if (order.isVoided() && order.getDateVoided().equals(origParentVoidedDate) && order.getVoidedBy().equals(originalVoidingUser)) { os.unvoidOrder(order); } } } CohortService cs = Context.getCohortService(); cs.patientUnvoided(patient, patient.getVoidedBy(), patient.getDateVoided(), patient.getVoidReason()); } }
Source:
private OBrowsePage nextPage(int clusterId, long lastPosition) { try { checkOpenness(); stateLock.acquireReadLock(); try { checkOpenness(); final OCluster cluster = doGetAndCheckCluster(clusterId); OPhysicalPosition[] nexts = cluster.higherPositions(new OPhysicalPosition(lastPosition)); if (nexts.length > 0) { lastPosition = nexts[nexts.length - 1].clusterPosition; List<OBrowsePage.OBrowseEntry> nexv = new ArrayList<>(); for (OPhysicalPosition pos : nexts) { final ORawBuffer buff = cluster.readRecord(pos.clusterPosition, false); nexv.add(new OBrowsePage.OBrowseEntry(pos.clusterPosition, buff)); } return new OBrowsePage(nexv, lastPosition); } else { return null; } } finally { stateLock.releaseReadLock(); } } catch (RuntimeException ee) { throw logAndPrepareForRethrow(ee); } catch (Error ee) { throw logAndPrepareForRethrow(ee); } catch (Throwable t) { throw logAndPrepareForRethrow(t); } }

Target:
private OClusterBrowsePage nextPage(int clusterId, long lastPosition) { try { checkOpenness(); stateLock.acquireReadLock(); try { checkOpenness(); final OCluster cluster = doGetAndCheckCluster(clusterId); OPhysicalPosition[] nextPositions = cluster.higherPositions(new OPhysicalPosition(lastPosition)); if (nextPositions.length > 0) { long newLastPosition = nextPositions[nextPositions.length - 1].clusterPosition; List<OClusterBrowseEntry> nexv = new ArrayList<>(); for (OPhysicalPosition pos : nextPositions) { final ORawBuffer buff = cluster.readRecord(pos.clusterPosition, false); nexv.add(new OClusterBrowseEntry(pos.clusterPosition, buff)); } return new OClusterBrowsePage(nexv, newLastPosition); } else { return null; } } finally { stateLock.releaseReadLock(); } } catch (RuntimeException ee) { throw logAndPrepareForRethrow(ee); } catch (Error ee) { throw logAndPrepareForRethrow(ee); } catch (Throwable t) { throw logAndPrepareForRethrow(t); } }
Source:
private Map<String, String> covertRichUserToSubject(RichUser richUser) throws InternalErrorException { Map<String,String> richUserInMap = new HashMap<String,String>(); String mapping = getAttributes().get("xmlMapping"); String[] mappingArray = mapping.split(",\n"); String login = ""; for(UserExtSource ues: richUser.getUserExtSources()) { if(ues.getExtSource() != null && ues.getExtSource().getName().equals(extSourceNameForLogin)) { login = ues.getLogin(); break; } } if(login == null) throw new InternalErrorException("Login can't be null."); for(int i=0; i<mappingArray.length; i++) { String attr = mappingArray[i].trim(); int index = attr.indexOf("="); if(index <= 0) throw new InternalErrorException("There is no text in xmlMapping attribute or there is no '=' character."); String name = attr.substring(0, index); String value = attr.substring(index +1); Matcher attributeMatcher = attributePattern.matcher(value); if (attributeMatcher.find()) { if(attributeMatcher.group(1).equals("login")) { value = attributeMatcher.replaceFirst(login); } else { String replacement = lookingForValueInRichUserAttributes(attributeMatcher.group(1), richUser); if(replacement != null) { value = attributeMatcher.replaceFirst(replacement); } else { value = attributeMatcher.replaceFirst(""); } if(value.isEmpty()) value = null; } } else if (value.startsWith("urn:perun:")) { value = lookingForValueInRichUserAttributes(value, richUser); } richUserInMap.put(name.trim(), value); } return richUserInMap; }

Target:
private Map<String, String> covertRichUserToSubject(RichUser richUser) throws InternalErrorException { Map<String,String> richUserInMap = new HashMap<String,String>(); String mapping = getAttributes().get("xmlMapping"); String[] mappingArray = mapping.split(",\n"); String login = ""; for(UserExtSource ues: richUser.getUserExtSources()) { if(ues.getExtSource() != null && ues.getExtSource().getName().equals(extSourceNameForLogin)) { login = ues.getLogin(); break; } } if(login == null) throw new InternalErrorException("There is missing login for user " + richUser + " and extSource " + extSourceNameForLogin); for(int i=0; i<mappingArray.length; i++) { String attr = mappingArray[i].trim(); int index = attr.indexOf("="); if(index <= 0) throw new InternalErrorException("There is no text in xmlMapping attribute or there is no '=' character."); String name = attr.substring(0, index); String value = attr.substring(index +1); Matcher attributeMatcher = attributePattern.matcher(value); if (attributeMatcher.find()) { if(attributeMatcher.group(1).equals("login")) { value = attributeMatcher.replaceFirst(login); } else { String replacement = lookingForValueInRichUserAttributes(attributeMatcher.group(1), richUser); if(replacement == null) replacement = ""; value = attributeMatcher.replaceFirst(replacement); if(value.isEmpty()) value = null; } } else if (value.startsWith("urn:perun:")) { value = lookingForValueInRichUserAttributes(value, richUser); } richUserInMap.put(name.trim(), value); } return richUserInMap; }
Source:
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) throws Exception { ReferenceCountUtil.retain(frame); RequestInfo requestInfo = ctx.channel().attr(Http2NetworkClient.REQUEST_INFO).get(); requestInfo.responseFramesCount++; if (frame instanceof Http2HeadersFrame) { requestInfo.setStreamHeaderFrameReceiveTime(System.currentTimeMillis()); http2NetworkClient.getHttp2ClientMetrics().http2StreamRoundTripTime.update( System.currentTimeMillis() - requestInfo.getStreamSendTime()); logger.debug("Header Frame received. Request: {}", requestInfo.toString()); } else if (frame instanceof Http2DataFrame) { logger.debug("Data Frame size: {}. Request: {}", ((Http2DataFrame) frame).content().readableBytes(), requestInfo.toString()); } if (frame instanceof Http2DataFrame && ((Http2DataFrame) frame).isEndStream()) { long time = System.currentTimeMillis() - requestInfo.getStreamHeaderFrameReceiveTime(); http2NetworkClient.getHttp2ClientMetrics().http2StreamFirstToLastFrameTime.update(time); http2NetworkClient.getHttp2ClientMetrics().http2ResponseFrameCount.update(requestInfo.responseFramesCount); logger.debug("All Frame received. Time: {}ms. Request: {}", time, requestInfo.toString()); } ctx.fireChannelRead(frame); }

Target:
protected void channelRead0(ChannelHandlerContext ctx, Http2Frame frame) throws Exception { ReferenceCountUtil.retain(frame); RequestInfo requestInfo = ctx.channel().attr(Http2NetworkClient.REQUEST_INFO).get(); requestInfo.responseFramesCount++; if (frame instanceof Http2HeadersFrame) { requestInfo.setStreamHeaderFrameReceiveTime(System.currentTimeMillis()); http2NetworkClient.getHttp2ClientMetrics().http2StreamRoundTripTime.update( System.currentTimeMillis() - requestInfo.getStreamSendTime()); logger.debug("Header Frame received. Request: {}", requestInfo); } else if (frame instanceof Http2DataFrame) { logger.debug("Data Frame size: {}. Request: {}", ((Http2DataFrame) frame).content().readableBytes(), requestInfo); } if (frame instanceof Http2DataFrame && ((Http2DataFrame) frame).isEndStream()) { long time = System.currentTimeMillis() - requestInfo.getStreamHeaderFrameReceiveTime(); http2NetworkClient.getHttp2ClientMetrics().http2StreamFirstToLastFrameTime.update(time); http2NetworkClient.getHttp2ClientMetrics().http2ResponseFrameCount.update(requestInfo.responseFramesCount); logger.debug("All Frame received. Time: {}ms. Request: {}", time, requestInfo); } ctx.fireChannelRead(frame); }
Source:
private void init(long maxIdleTimeForIndexerInSecs, long idleTimeCheckIntervalInSecs) throws IndexingException, URISyntaxException { IndexingSettingsGenerator settingsGeneratorForDefaultEnv = new IndexingSettingsGenerator(indexingProperties); IndexingSettingsGenerator settingsGeneratorForAnotherEnv = new IndexingSettingsGenerator(TargetIndexingEnvironment.ALTERNATIVE, indexingProperties); IndexingSettings indexingSettingsForPreviewDbInDefaultEnv = settingsGeneratorForDefaultEnv.generateForPreview(); IndexingSettings indexingSettingsForPublishDbInDefaultEnv = settingsGeneratorForDefaultEnv.generateForPublish(); IndexingSettings indexingSettingsForPreviewDbInAnotherEnv = settingsGeneratorForAnotherEnv.generateForPreview(); IndexingSettings indexingSettingsForPublishDbInAnotherEnv = settingsGeneratorForAnotherEnv.generateForPublish(); indexerPoolForPreviewDbInDefaultEnv = new IndexerPool(indexingSettingsForPreviewDbInDefaultEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); indexerPoolForPublishDbInDefaultEnv = new IndexerPool(indexingSettingsForPublishDbInDefaultEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); if (indexingSettingsForPreviewDbInAnotherEnv != null) { indexerPoolForPreviewDbInAnotherEnv = new IndexerPool(indexingSettingsForPreviewDbInAnotherEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); } if (indexingSettingsForPublishDbInAnotherEnv != null) { indexerPoolForPublishDbInAnotherEnv = new IndexerPool(indexingSettingsForPublishDbInAnotherEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); } }

Target:
private void init(long maxIdleTimeForIndexerInSecs, long idleTimeCheckIntervalInSecs) throws IndexingException, URISyntaxException { IndexingSettingsGenerator settingsGeneratorForDefaultEnv = new IndexingSettingsGenerator(indexingProperties); IndexingSettingsGenerator settingsGeneratorForAnotherEnv = new IndexingSettingsGenerator(TargetIndexingEnvironment.ALTERNATIVE, indexingProperties); IndexingSettings indexingSettingsForPreviewDbInDefaultEnv = settingsGeneratorForDefaultEnv.generateForPreview(); IndexingSettings indexingSettingsForPublishDbInDefaultEnv = settingsGeneratorForDefaultEnv.generateForPublish(); IndexingSettings indexingSettingsForPreviewDbInAnotherEnv = settingsGeneratorForAnotherEnv.generateForPreview(); IndexingSettings indexingSettingsForPublishDbInAnotherEnv = settingsGeneratorForAnotherEnv.generateForPublish(); indexerPoolForPreviewDbInDefaultEnv = initIndexerPool(indexingSettingsForPreviewDbInDefaultEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); indexerPoolForPublishDbInDefaultEnv = initIndexerPool(indexingSettingsForPublishDbInDefaultEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); if (indexingSettingsForPreviewDbInAnotherEnv != null) { indexerPoolForPreviewDbInAnotherEnv = initIndexerPool(indexingSettingsForPreviewDbInAnotherEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); } if (indexingSettingsForPublishDbInAnotherEnv != null) { indexerPoolForPublishDbInAnotherEnv = initIndexerPool(indexingSettingsForPublishDbInAnotherEnv, maxIdleTimeForIndexerInSecs, idleTimeCheckIntervalInSecs); } }
Source:
public static String generateName(String desiredName, List<String> existingNames) { String availableName = desiredName; if (existingNames.contains(desiredName)) { List<String> existingSuffixes = existingNames.stream() .filter(existing -> existing.startsWith(desiredName) && !existing.equalsIgnoreCase(desiredName)) .map(existing -> existing.substring(existing.indexOf(desiredName, 0) + desiredName.length())) .collect(Collectors.toList()); int index = 1; while (existingSuffixes.contains(Integer.toString(index))) { index++; } availableName = desiredName + Integer.toString(index); } return availableName; }

Target:
public static String generateName(String desiredName, List<String> existingNames) { String availableName = desiredName; if (!existingNames.contains(desiredName)) { return availableName; } List<String> existingSuffixes = existingNames.stream() .filter(existing -> existing.startsWith(desiredName) && !existing.equalsIgnoreCase(desiredName)) .map(existing -> existing.substring(existing.indexOf(desiredName, 0) + desiredName.length())) .collect(Collectors.toList()); int index = 1; while (existingSuffixes.contains(Integer.toString(index))) { index++; } availableName = desiredName + Integer.toString(index); return availableName; }
Source:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (!AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType()) || (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken()))) { return null; } OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration); OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(clientCredentialsGrantRequest); return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken()); }

Target:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); ClientRegistration clientRegistration = context.getClientRegistration(); if (!AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType())) { return null; } OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) { return null; } OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration); OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(clientCredentialsGrantRequest); return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken()); }
Source:
@Override public boolean moveNext() { if (!isInitialized) { isInitialized = true; return enumerator.moveNext(); } else { return curAccumulator != null; } }

Target:
@Override public boolean moveNext() { if (!isInitialized) { isInitialized = true; if (!enumerator.moveNext()) { isLastMoveNextFalse = true; return false; } } else if (curAccumulator == null) { isLastMoveNextFalse = true; return false; } if (curAccumulator == null) { curAccumulator = accumulatorInitializer.apply(); } curResult = null; TSource o = enumerator.current(); TKey prevKey = keySelector.apply(o); curAccumulator = accumulatorAdder.apply(curAccumulator, o); while (enumerator.moveNext()) { o = enumerator.current(); TKey curKey = keySelector.apply(o); if (comparator.compare(prevKey, curKey) != 0) { curResult = resultSelector.apply(prevKey, curAccumulator); curAccumulator = accumulatorInitializer.apply(); break; } curAccumulator = accumulatorAdder.apply(curAccumulator, o); prevKey = curKey; } if (curResult == null) { curResult = resultSelector.apply(prevKey, curAccumulator); curAccumulator = null; } return true; }
Source:
public void onClick(View view) { if (eventListener != null && batchSelected.isEmpty() && messageRecord.isMms() && !((MmsMessageRecord) messageRecord).getSharedContacts().isEmpty()) { eventListener.onSharedContactDetailsClicked(((SharedContactView) view).getContact(), ((SharedContactView) view).getAvatarView()); } else { passthroughClickListener.onClick(view); } }

Target:
public void onClick(View view) { if (eventListener != null && batchSelected.isEmpty() && messageRecord.isMms() && !((MmsMessageRecord) messageRecord).getSharedContacts().isEmpty()) { eventListener.onSharedContactDetailsClicked(((MmsMessageRecord) messageRecord).getSharedContacts().get(0), sharedContactStub.get().getAvatarView()); } else { passthroughClickListener.onClick(view); } }
Source:
public void test_contains_Currency() { CurrencyPair test = CurrencyPair.of(GBP, USD); assertEquals(test.contains(GBP), true); assertEquals(test.contains(USD), true); assertEquals(test.contains(EUR), false); }

Target:
public void test_contains_Currency() { CurrencyPair test = CurrencyPair.of(GBP, USD); assertEquals(test.contains(GBP), true); assertEquals(test.contains(USD), true); assertEquals(test.contains(EUR), false); assertEquals(test.contains(null), false); }