auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String putBlob(Router router, BlobProperties blobProperties, byte[] usermetadata, byte[] content, RouterOperationCallback<String> putBlobCallback) throws Exception { byte[] buf = new byte[content.length]; Utils.readBytesFromStream(new ByteArrayInputStream(content), buf, 0, content.length); ReadableStreamChannel blobDataChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(buf)); Future<String> putBlobFuture; if (putBlobCallback == null) { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel); } else { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel, putBlobCallback); if (!putBlobCallback.awaitCallback(1, TimeUnit.SECONDS)) { throw new IllegalStateException("putBlob() timed out"); } else if (putBlobCallback.getException() != null) { verifyExceptionMatch(putBlobCallback, putBlobFuture); throw putBlobCallback.getException(); } assertTrue("PutBlob: Future is not done but callback has been received", putBlobFuture.isDone()); assertEquals("PutBlob: Future BlobId and callback BlobId do not match", putBlobFuture.get(), putBlobCallback.getResult()); } return putBlobFuture.get(); }

Target:
private String putBlob(Router router, BlobProperties blobProperties, byte[] usermetadata, byte[] content, RouterOperationCallback<String> putBlobCallback) throws Exception { ReadableStreamChannel blobDataChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(content)); Future<String> putBlobFuture; if (putBlobCallback == null) { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel); } else { putBlobFuture = router.putBlob(blobProperties, usermetadata, blobDataChannel, putBlobCallback); if (putBlobCallback.awaitCallback(1, TimeUnit.SECONDS)) { assertTrue("PutBlob: Future is not done but callback has been received", putBlobFuture.isDone()); if (putBlobCallback.getException() == null) { assertEquals("PutBlob: Future BlobId and callback BlobId do not match", putBlobFuture.get(), putBlobCallback.getResult()); } else { verifyFutureCallbackExceptionMatch(putBlobCallback, putBlobFuture); throw putBlobCallback.getException(); } } else { throw new IllegalStateException("putBlob() timed out"); } } return putBlobFuture.get(); }
Source:
public Patient createFHIRPatient(Patient patient) { List<String> errors = new ArrayList<String>(); org.openmrs.Patient omrsPatient = FHIRPatientUtil.generateOmrsPatient(patient, errors); if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } org.openmrs.api.PatientService patientService = Context.getPatientService(); omrsPatient = patientService.savePatient(omrsPatient); return FHIRPatientUtil.generatePatient(omrsPatient); }

Target:
public Patient createFHIRPatient(Patient patient) { List<String> errors = new ArrayList<String>(); org.openmrs.Patient omrsPatient = FHIRPatientUtil.generateOmrsPatient(patient, errors); if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } org.openmrs.api.PatientService patientService = Context.getPatientService(); try { omrsPatient = patientService.savePatient(omrsPatient); } catch (Exception e) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to the following issues \n"); errorMessage.append(e.getMessage()); throw new UnprocessableEntityException(errorMessage.toString()); } return FHIRPatientUtil.generatePatient(omrsPatient); }
Source:
private static void enforceTaskCountLimit(int size) { if (size > Limits.maxWorkflowTasks()) { throw new ConfigException("Too many for_range subtasks. Limit: " + Limits.maxWorkflowTasks()); } }

Target:
private static void enforceTaskCountLimit(int size) { if (size > Limits.maxWorkflowTasks()) { throw new ConfigException("Too many for_range subtasks (" + size + "). Limit: " + Limits.maxWorkflowTasks()); } }
Source:
public void testAllCases() throws IOException { boolean crNewline = true; test("", new String[]{}, 5); test("1234\n", new String[]{"1234", "\n"}, 10); test("1234", new String[]{"1234", ""}, 10); test("123\r\n123\r\nabc\n", new String[]{"123", "\r\n", "123", "\r\n", "abc", "\n"}, 20); test("123\r123\r\nabc\n", new String[]{"123", "\r", "123", "\r\n", "abc", "\n"}, 20); test("1234\r", new String[]{"1234", "\r"}, 5); test("1234\r\nabc\r\n", new String[]{"1234", "\r\n", "abc", "\r\n"}, 5); test( "123456", new String[]{"123456", ""}, 5); test( "12345", new String[]{"12345", ""}, 5); test( "1234\rA", new String[]{"1234", "\r", "A", ""}, 5); }

Target:
public void testAllCases() throws IOException { for (int size = 1; size <= 20; ++size) { test("", new String[]{}, size); test("1234\n", new String[]{"1234", "\n"}, size); test("1234", new String[]{"1234", ""}, size); test("123\r\n123\r\nabc\n", new String[]{"123", "\r\n", "123", "\r\n", "abc", "\n"}, size); test("123\r123\r\nabc\n", new String[]{"123", "\r", "123", "\r\n", "abc", "\n"}, size); test("1234\r", new String[]{"1234", "\r"}, size); test("1234\r\nabc\r\n", new String[]{"1234", "\r\n", "abc", "\r\n"}, size); test( "123456", new String[]{"123456", ""}, size); test( "12345", new String[]{"12345", ""}, size); test( "1234\rA", new String[]{"1234", "\r", "A", ""}, size); } }
Source:
public void stop() { log.info("Stopping task"); try { writer.closeQuietly(); } finally { try { dialect.close(); } finally { dialect = null; } } }

Target:
public void stop() { log.info("Stopping task"); try { writer.closeQuietly(); } finally { try { if (dialect != null) { dialect.close(); } } catch (Throwable t) { log.warn("Error while closing the dialect: ", dialect, t); } finally { dialect = null; } } }
Source:
public void run() { SmppSession smppSession = smppClient.getSession(); if (smppSession != null && smppSession.isBound()) { try { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { Log.warning("Enquire link failed, executing reconnect: " + error); smppClient.reconnect(); } catch (InterruptedException error) { Log.info("Enquire link interrupted, probably killed by reconnecting"); } } else { Log.error("Enquire link running while session is not connected"); } }

Target:
public void run() { SmppSession smppSession = smppClient.getSession(); if (smppSession != null && smppSession.isBound()) { try { smppSession.enquireLink(new EnquireLink(), enquireLinkTimeout); } catch (SmppTimeoutException | SmppChannelException | RecoverablePduException | UnrecoverablePduException error) { Log.warning("Enquire link failed, executing reconnect: ", error); smppClient.reconnect(); } catch (InterruptedException error) { Log.info("Enquire link interrupted, probably killed by reconnecting"); } } else { Log.warning("Enquire link running while session is not connected"); } }
Source:
protected void postProcessing(boolean closeEarly) { if (sortGraph) { if (ghStorage.isCHPossible() && isCHPrepared()) throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12"); GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage); GHUtility.sortDFS(ghStorage, newGraph); logger.info("graph sorted (" + getMemInfo() + ")"); ghStorage = newGraph; } if (!hasInterpolated() && hasElevation()) { interpolateBridgesAndOrTunnels(); } initLocationIndex(); importPublicTransit(); if (lmPreparationHandler.isEnabled()) lmPreparationHandler.createPreparations(ghStorage, locationIndex); loadOrPrepareLM(closeEarly); if (chPreparationHandler.isEnabled()) chPreparationHandler.createPreparations(ghStorage); if (isCHPrepared()) { for (CHProfile profile : chPreparationHandler.getCHProfiles()) { if (!getProfileHash(profile.getProfile()).isEmpty() && !getProfileHash(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) throw new IllegalArgumentException("CH preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); } } else { prepareCH(closeEarly); } }

Target:
protected void postProcessing(boolean closeEarly) { if (sortGraph) { if (ghStorage.isCHPossible() && isCHPrepared()) throw new IllegalArgumentException("Sorting a prepared CHGraph is not possible yet. See #12"); GraphHopperStorage newGraph = GHUtility.newStorage(ghStorage); GHUtility.sortDFS(ghStorage, newGraph); logger.info("graph sorted (" + getMemInfo() + ")"); ghStorage = newGraph; } if (!hasInterpolated() && hasElevation()) { interpolateBridgesAndOrTunnels(); } initLocationIndex(); importPublicTransit(); if (lmPreparationHandler.isEnabled()) lmPreparationHandler.createPreparations(ghStorage, locationIndex); loadOrPrepareLM(closeEarly); if (chPreparationHandler.isEnabled()) chPreparationHandler.createPreparations(ghStorage); if (isCHPrepared()) { for (CHProfile profile : chPreparationHandler.getCHProfiles()) { if (!getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion())) throw new IllegalArgumentException("CH preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration"); } } else { prepareCH(closeEarly); } }
Source:
private Long getFirstValidPrivateId(List<InstanceGroup> instanceGroups) { LOGGER.debug("Get first valid PrivateId of instanceGroups"); long highest = instanceGroups.stream() .flatMap(ig -> ig.getAllInstanceMetaData().stream()) .filter(im -> im.getPrivateId() != null) .map(InstanceMetaData::getPrivateId) .max(Long::compare) .orElse(0L); LOGGER.debug("Highest privateId: {}", highest); return highest == 0 ? 0 : highest + 1; }

Target:
private Long getFirstValidPrivateId(List<InstanceGroup> instanceGroups) { LOGGER.debug("Get first valid PrivateId of instanceGroups"); long id = instanceGroups.stream() .flatMap(ig -> ig.getAllInstanceMetaData().stream()) .filter(im -> im.getPrivateId() != null) .map(InstanceMetaData::getPrivateId) .map(i -> i + 1) .max(Long::compare) .orElse(0L); LOGGER.debug("First valid privateId: {}", id); return id; }
Source:
public Node(String name, Id id) throws NodeException { Objects.requireNonNull(name); Objects.requireNonNull(id); this.mName = name; this.mId = id; }

Target:
public Node(String name, Id id) throws NodeException { this.mName = Objects.requireNonNull(name); this.mId = Objects.requireNonNull(id); }
Source:
public boolean Validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = configurator.getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().AsConvertible().Integer(); getModel().getNumOfDesktops().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid()); getModel().setIsPoolTabValid(true); return super.Validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid(); }

Target:
public boolean Validate() { boolean isNew = getModel().getIsNew(); int maxAllowedVms = getMaxVmsInPool(); int assignedVms = getModel().getAssignedVms().AsConvertible().Integer(); getModel().getNumOfDesktops().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new LengthValidation(4), new IntegerValidation(isNew ? 1 : 0, isNew ? maxAllowedVms : maxAllowedVms - assignedVms) }); getModel().getPrestartedVms().ValidateEntity( new IValidation[] { new NotEmptyValidation(), new IntegerValidation(0, assignedVms) }); getModel().setIsGeneralTabValid(getModel().getIsGeneralTabValid() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid()); getModel().setIsPoolTabValid(true); return super.Validate() && getModel().getName().getIsValid() && getModel().getNumOfDesktops().getIsValid() && getModel().getPrestartedVms().getIsValid(); }
Source:
synchronized void flush() { if (_kafkaProducer != null) { try { CompletableFutureUtils.within(CompletableFuture.runAsync(() -> _kafkaProducer.flush()), Duration.ofMillis(_flushTimeout)).join(); } catch (CompletionException e) { Throwable cause = e.getCause(); if (cause instanceof InterruptException) { _log.warn("Kafka producer flush interrupted, closing producer {}.", _kafkaProducer); shutdownProducer(); throw (InterruptException) cause; } else if (cause instanceof java.util.concurrent.TimeoutException) { _log.warn("Kafka producer flush timed out after {}ms. Destination topic may be unavailable.", _flushTimeout); } throw e; } } }

Target:
synchronized void flush() { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<?> future = executor.submit(super::flush); try { future.get(_flushTimeoutMs, TimeUnit.MILLISECONDS); } catch (TimeoutException ex) { _log.warn("Flush call timed out after {}ms. Cancelling flush", _flushTimeoutMs); future.cancel(true); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof InterruptException) { throw (InterruptException) cause; } else { _log.warn("Flush failed.", cause); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } }
Source:
public void testPropertyNameOnMethodName() throws NoSuchMethodException { class Hotel { String hotelName; public String getHotelName() { return hotelName; } } Method m = Hotel.class.getDeclaredMethod("getHotelName"); assertMemberValue(m, "getHotelName"); }

Target:
public void testPropertyNameOnMethodName() throws NoSuchMethodException { class LocalHotel { String hotelName; public String getHotelName() { return hotelName; } } Method m = LocalHotel.class.getDeclaredMethod("getHotelName"); assertNull(serializer.convertMemberName(m)); }
Source:
void oneParameterAndStatementUtilityConstructor() { LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseStatement("return 5;")); assertEquals("a -> return 5;", expr.toString()); }

Target:
void oneParameterAndStatementUtilityConstructor() { LambdaExpr expr = new LambdaExpr(new Parameter(new UnknownType(), "a"), parseBlock("{return 5;}")); assertEqualsNoEol("a -> {\n return 5;\n}", expr.toString()); }
Source:
public void useDefaultKeyPair() throws KeyStoreException { String alias = Config.<String>GetValue(ConfigValues.CertAlias); String p12 = Config.<String>GetValue(ConfigValues.keystoreUrl); char[] password = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); KeyStore.PrivateKeyEntry entry; InputStream in = null; try { in = new FileInputStream(p12); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); entry = (KeyStore.PrivateKeyEntry)ks.getEntry( alias, new KeyStore.PasswordProtection(password) ); } catch (Exception e) { throw new KeyStoreException( String.format( "Failed to get certificate entry from key store: %1$s/%2$s", p12, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } if (entry == null) { throw new KeyStoreException( String.format( "Bad key store: %1$s/%2$s", p12, alias ) ); } setKeyPair( new KeyPair( entry.getCertificate().getPublicKey(), entry.getPrivateKey() ) ); }

Target:
public void useDefaultKeyPair() throws KeyStoreException { final String alias = Config.<String>GetValue(ConfigValues.CertAlias); final String p12 = Config.<String>GetValue(ConfigValues.keystoreUrl); final char[] password = Config.<String>GetValue(ConfigValues.keystorePass).toCharArray(); KeyStore.PrivateKeyEntry entry; InputStream in = null; try { in = new FileInputStream(p12); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, password); entry = (KeyStore.PrivateKeyEntry)ks.getEntry( alias, new KeyStore.PasswordProtection(password) ); } catch (Exception e) { throw new KeyStoreException( String.format( "Failed to get certificate entry from key store: %1$s/%2$s", p12, alias ), e ); } finally { Arrays.fill(password, '*'); if (in != null) { try { in.close(); } catch(IOException e) { log.error("Cannot close key store", e); } } } if (entry == null) { throw new KeyStoreException( String.format( "Bad key store: %1$s/%2$s", p12, alias ) ); } setKeyPair( new KeyPair( entry.getCertificate().getPublicKey(), entry.getPrivateKey() ) ); }
Source:
protected void endVmCommand() { Snapshot createdSnapshot = getSnapshotDao().get(getVmId(), getParameters().getSnapshotType(), SnapshotStatus.LOCKED); boolean taskGroupSucceeded = createdSnapshot != null && getParameters().getTaskGroupSuccess(); boolean liveSnapshotRequired = isLiveSnapshotApplicable(); boolean liveSnapshotSucceeded = false; if (taskGroupSucceeded) { getSnapshotDao().updateStatus(createdSnapshot.getId(), SnapshotStatus.OK); if (liveSnapshotRequired) { liveSnapshotSucceeded = performLiveSnapshot(createdSnapshot); } else { if (getParameters().isSaveMemory() && createdSnapshot.containsMemory()) { logMemorySavingFailed(); getSnapshotDao().removeMemoryFromSnapshot(createdSnapshot.getId()); removeMemoryVolumesOfSnapshot(createdSnapshot); } } } else { if (createdSnapshot != null) { revertToActiveSnapshot(createdSnapshot.getId()); if (getParameters().isSaveMemory() && createdSnapshot.containsMemory()) { removeMemoryVolumesOfSnapshot(createdSnapshot); } } else { log.warnFormat("No snapshot was created for VM {0} which is in LOCKED status", getVmId()); } } boolean archSupportSnapshot = isSnapshotSupportedByArchitecture(getVm().getClusterArch(), getVm().getVdsGroupCompatibilityVersion()); if (getParameters().isSaveMemory() && (archSupportSnapshot || !FeatureSupported.memorySnapshot(getVm().getVdsGroupCompatibilityVersion()))) { log.warnFormat("A memory snapshot was required but not created, since VM architecture does not support it.", getVmId()); } incrementVmGeneration(); endActionOnDisks(); setSucceeded(taskGroupSucceeded && (!liveSnapshotRequired || liveSnapshotSucceeded)); getReturnValue().setEndActionTryAgain(false); }

Target:
protected void endVmCommand() { Snapshot createdSnapshot = getSnapshotDao().get(getVmId(), getParameters().getSnapshotType(), SnapshotStatus.LOCKED); boolean taskGroupSucceeded = createdSnapshot != null && getParameters().getTaskGroupSuccess(); boolean liveSnapshotRequired = isLiveSnapshotApplicable(); boolean liveSnapshotSucceeded = false; if (taskGroupSucceeded) { getSnapshotDao().updateStatus(createdSnapshot.getId(), SnapshotStatus.OK); if (liveSnapshotRequired) { liveSnapshotSucceeded = performLiveSnapshot(createdSnapshot); } else { if (getParameters().isSaveMemory() && createdSnapshot.containsMemory()) { logMemorySavingFailed(); getSnapshotDao().removeMemoryFromSnapshot(createdSnapshot.getId()); removeMemoryVolumesOfSnapshot(createdSnapshot); } } } else { if (createdSnapshot != null) { revertToActiveSnapshot(createdSnapshot.getId()); if (getParameters().isSaveMemory() && createdSnapshot.containsMemory()) { removeMemoryVolumesOfSnapshot(createdSnapshot); } } else { log.warnFormat("No snapshot was created for VM {0} which is in LOCKED status", getVmId()); } } if (getParameters().isSaveMemory() && !isMemorySnapshotSupported()) { log.warnFormat("A memory snapshot was required but not created, since VM architecture does not support it."); } incrementVmGeneration(); endActionOnDisks(); setSucceeded(taskGroupSucceeded && (!liveSnapshotRequired || liveSnapshotSucceeded)); getReturnValue().setEndActionTryAgain(false); }
Source:
public static void main(String[] args) throws Exception { Optional.ofNullable(System.getProperty("logback.configurationFile")) .stream() .forEach(file -> System.err.println("Load logging config from " + file)); Configuration configuration = Configuration.builder() .useWorkingDirectoryEnvProperty() .build(); LOGGER.info("Loading configuration {}", configuration); GuiceJamesServer server = createServer(configuration) .combineWith(new JMXServerModule()); JamesServerMain.main(server); }

Target:
public static void main(String[] args) throws Exception { Configuration configuration = Configuration.builder() .useWorkingDirectoryEnvProperty() .build(); LOGGER.info("Loading configuration {}", configuration.toString()); GuiceJamesServer server = createServer(configuration) .combineWith(new JMXServerModule()); JamesServerMain.main(server); }
Source:
public String createNewProcess() { try { createProcessHierarchy(); if (Objects.nonNull(PrimeFaces.current())) { PrimeFaces.current().executeScript("PF('sticky-notifications').renderMessage({'summary':'" + Helper.getTranslation("processSaving") + "','detail':'" + Helper.getTranslation( "youWillBeRedirected") + "','severity':'info'});"); } return processListPath; } catch (DataException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.PROCESS.getTranslationSingular() }, logger, e); } catch (IOException | ProcessGenerationException e) { logger.error(e.getLocalizedMessage()); } return this.stayOnCurrentPage; }

Target:
public String createNewProcess() { try { createProcessHierarchy(); if (Objects.nonNull(PrimeFaces.current()) && Objects.nonNull(FacesContext.getCurrentInstance())) { PrimeFaces.current().executeScript("PF('sticky-notifications').renderMessage({'summary':'" + Helper.getTranslation("processSaving") + "','detail':'" + Helper.getTranslation( "youWillBeRedirected") + "','severity':'info'});"); } return processListPath; } catch (DataException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.PROCESS.getTranslationSingular() }, logger, e); } catch (IOException | ProcessGenerationException e) { logger.error(e.getLocalizedMessage()); } return this.stayOnCurrentPage; }
Source:
private static void appendLib(StringBuilder classpath, String libDirName, boolean useLibJarsFormat) { File libDir = new File(libDirName); if (!libDir.exists()) { System.err.println("ERROR - Directory needed for classpath does not exist: " + libDirName); System.exit(-1); } if (useLibJarsFormat) { File[] files = libDir.listFiles(); Arrays.sort(files); for (File f : files) { if (f.isFile() && f.getName().endsWith(".jar")) { if (classpath.length() != 0) { classpath.append(","); } classpath.append(f.getAbsolutePath()); } } } else { if (classpath.length() != 0) { classpath.append(":"); } classpath.append(libDir + "/*"); } }

Target:
private static void appendLib(StringBuilder classpath, String libDirName, boolean useLibJarsFormat) { File libDir = new File(libDirName); if (!libDir.exists()) { System.err.println("ERROR - Directory needed for classpath does not exist: " + libDirName); System.exit(-1); } if (useLibJarsFormat) { File[] files = libDir.listFiles(); Arrays.sort(files); for (File f : files) { if (f.isFile() && f.getName().endsWith(".jar")) { if (classpath.length() != 0) { classpath.append(","); } classpath.append(f.getAbsolutePath()); } } } else { if (classpath.length() != 0) { classpath.append(":"); } classpath.append(libDir.getAbsolutePath() + "/*"); } }
Source:
public boolean close() { synchronized (startStopLock) { if (!started.get() || executorService.isShutdown()) { LOG.info("Already shutdown, ignoring"); return false; } started.set(false); executorService.shutdownNow(); final ListenableFuture<?> future = this.future; if (future != null) { if (!future.isDone() && !future.cancel(true) && !future.isDone()) { LOG.error("Error cancelling future for topic [%s]", getKafkaTopic()); return false; } } if (!cacheManager.delete(factoryId)) { LOG.error("Error removing [%s] for topic [%s] from cache", factoryId, getKafkaTopic()); return false; } if (consumerConnector != null) { consumerConnector.shutdown(); } return true; } }

Target:
public boolean close() { synchronized (started) { if (!started.get() || executorService.isShutdown()) { LOG.info("Already shutdown, ignoring"); return !started.get(); } started.set(false); executorService.shutdownNow(); final ListenableFuture<?> future = this.future; if (future != null) { if (!future.isDone() && !future.cancel(true) && !future.isDone()) { LOG.error("Error cancelling future for topic [%s]", getKafkaTopic()); return false; } } if (!cacheManager.delete(factoryId)) { LOG.error("Error removing [%s] for topic [%s] from cache", factoryId, getKafkaTopic()); return false; } return true; } }
Source:
public Metadata(Map<String, String[]> metadata) { md = metadata; }

Target:
public Metadata(Map<String, String[]> metadata) { if (metadata == null) throw new NullPointerException(); md = metadata; }
Source:
private void evaluateXPath() { Document document = getWebSourceCode().getDocument(expression.contains(":")); try { NodeList nodes = (NodeList) getXPathExpressionForDocument(document).evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { int lineNumber = getWebSourceCode().getLineForNode(nodes.item(i)); createViolation(lineNumber); } } catch (XPathExpressionException exceptionNodeSet) { try { Boolean result = (Boolean) getXPathExpressionForDocument(document).evaluate(document, XPathConstants.BOOLEAN); if (result) { createViolation(0); } } catch (XPathExpressionException exceptionBoolean) { throw new IllegalStateException(String.format("Can't evaluate expression \"%s\"", expression), exceptionBoolean); } } }

Target:
private void evaluateXPath() { Document document = getWebSourceCode().getDocument(expression.contains(":")); XPathExpression xPathExpression = getXPathExpressionForDocument(document); try { evaluateXPathForNodeSet(document, xPathExpression); } catch (XPathExpressionException exceptionNodeSet) { evaluateXPathForBoolean(document, xPathExpression); } }
Source:
protected PageableResult doGetAll(RequestContext context) throws ResponseException { return new AlreadyPaged<AutoGenerationOption>(Context.getService(IdentifierSourceService.class).getAutoGenerationOption(3), context); }

Target:
protected PageableResult doGetAll(RequestContext context) throws ResponseException { IdentifierSourceService identifierSourceService = Context.getService(IdentifierSourceService.class); List<AutoGenerationOption> optionMap = new ArrayList<AutoGenerationOption>(); List<PatientIdentifierType> identifierTypes = new ArrayList<PatientIdentifierType>(); Map<PatientIdentifierType, List<IdentifierSource>> availableSources = identifierSourceService.getIdentifierSourcesByType(false); for (PatientIdentifierType patientIdentifierType : Context.getPatientService().getAllPatientIdentifierTypes()) { List<AutoGenerationOption> options = identifierSourceService.getAutoGenerationOptions(patientIdentifierType); if (options != null && options.size() > 0) { optionMap.addAll(options); } if (availableSources.get(patientIdentifierType) != null && availableSources.get(patientIdentifierType).size() > 0) { identifierTypes.add(patientIdentifierType); } } return new NeedsPaging<AutoGenerationOption>(optionMap, context); }
Source:
protected BinaryLogicalFilterPredicate(FilterPredicate left, FilterPredicate right) { Preconditions.checkNotNull(left, "left"); Preconditions.checkNotNull(right, "right"); this.left = left; this.right = right; String name = getClass().getSimpleName().toLowerCase(); this.toString = name + "(" + left + ", " + right + ")"; }

Target:
protected BinaryLogicalFilterPredicate(FilterPredicate left, FilterPredicate right) { this.left = checkNotNull(left, "left"); this.right = checkNotNull(right, "right"); String name = getClass().getSimpleName().toLowerCase(); this.toString = name + "(" + left + ", " + right + ")"; }
Source:
public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) { enforceConnectivityInternalPermission(); enforceCrossUserPermission(userId); if (LockdownVpnTracker.isEnabled()) { return false; } synchronized (mVpns) { Vpn vpn = mVpns.get(userId); if (vpn == null) { Slog.w(TAG, "User " + userId + " has no Vpn configuration"); return false; } if (!vpn.setAlwaysOnPackage(packageName, lockdown)) { return false; } if (!startAlwaysOnVpn(userId)) { vpn.setAlwaysOnPackage(null, false); return false; } } return true; }

Target:
public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) { enforceConnectivityInternalPermission(); enforceCrossUserPermission(userId); synchronized (mVpns) { if (LockdownVpnTracker.isEnabled()) { return false; } Vpn vpn = mVpns.get(userId); if (vpn == null) { Slog.w(TAG, "User " + userId + " has no Vpn configuration"); return false; } if (!vpn.setAlwaysOnPackage(packageName, lockdown)) { return false; } if (!startAlwaysOnVpn(userId)) { vpn.setAlwaysOnPackage(null, false); return false; } } return true; }
Source:
private FilterExpression parseQualifierContent(QualifierType type) { if (type == QualifierType.SORT) { return parseSortKeys(); } else if (isCompoundId(type, lookAhead())) { return parseCompoundId(); } else if (isRangeOperatorToken(lookAhead())) { return parseRangeOperator(type, lookAhead()); } else if (isDateToken(lookAhead())) { return parseDateOrDateRange(type); } else if (isNumberToken(lookAhead())) { return parseNumberOrNumberRange(type); } else if (isQuotedContentToken(lookAhead())) { Token quotedContent = consume(); return parseQuotedContent(type, quotedContent); } else if (isKeywordToken(lookAhead())) { return new Qualifier(type, consume().getValue()); } else { throw new ParseException(String.format("Invalid content for qualifier %s: %s", type, lookAhead())); } }

Target:
private FilterExpression parseQualifierContent(QualifierType type) { if (type == QualifierType.SORT) { return parseSortKeys(); } else if (isCompoundIdToken(type, lookAhead())) { return parseCompoundId(); } else if (isRangeOperatorToken(lookAhead())) { return parseRangeOperator(type, lookAhead()); } else if (isDateToken(lookAhead())) { return parseDateOrDateRange(type); } else if (isNumberToken(lookAhead())) { return parseNumberOrNumberRange(type); } else if (isQuotedContentToken(lookAhead())) { Token quotedContent = consume(); return parseQuotedContent(type, quotedContent); } else if (isKeywordToken(lookAhead())) { return new Qualifier(type, consume().getValue()); } else { throw new ParseException(String.format("Invalid content for qualifier %s: %s", type, lookAhead())); } }
Source:
protected Optional<DominantHandProperty> getForEntity(Entity entity) { if(!(entity instanceof EntityPlayer)) return Optional.empty(); EnumHandSide hand = ((EntityPlayer) entity).getPrimaryHand(); HandType type = (HandType) (Object) hand; return Optional.of(new DominantHandProperty(type)); }

Target:
protected Optional<DominantHandProperty> getForEntity(Entity entity) { if(!(entity instanceof EntityPlayer)) return Optional.empty(); EnumHandSide hand = ((EntityPlayer) entity).getPrimaryHand(); HandSide type = (HandSide) (Object) hand; return Optional.of(new DominantHandProperty(type)); }
Source:
private boolean isUnregisteredDisk() { DiskImage unregisteredDisk; storagePoolId = BackendDataCenterHelper.lookupByStorageDomainId(this, storageDomainId); try { GetUnregisteredDiskQueryParameters getDiskParams = new GetUnregisteredDiskQueryParameters(guid, storageDomainId, storagePoolId); unregisteredDisk = getEntity(DiskImage.class, QueryType.GetUnregisteredDisk, getDiskParams, guid.toString()); } catch (WebApplicationException e) { if (e.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) { return false; } throw e; } return unregisteredDisk != null; }

Target:
private boolean isUnregisteredDisk() { DiskImage unregisteredDisk; Guid storagePoolId = BackendDataCenterHelper.lookupByStorageDomainId(this, storageDomainId); try { GetUnregisteredDiskQueryParameters getDiskParams = new GetUnregisteredDiskQueryParameters(guid, storageDomainId, storagePoolId); unregisteredDisk = getEntity(DiskImage.class, QueryType.GetUnregisteredDisk, getDiskParams, guid.toString()); } catch (WebApplicationException e) { if (e.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode()) { return false; } throw e; } return unregisteredDisk != null; }
Source:
public long getFileSize(String ext) { Long size = sizeMap.get(ext); return (size == null) ? 0 : size.longValue(); }

Target:
public long getFileSize(String ext) { Long size = sizeMap.get(ext); return size == null ? 0 : size.longValue(); }
Source:
public boolean tryAdvance(Consumer<? super BytesHandle> action) { try { FormatEntry nextEntry = getNextEntry(); if (nextEntry == null) { return false; } BytesHandle nextBytesHandle = readEntry(nextEntry); action.accept(nextBytesHandle); splitter.count++; } catch (IOException e) { e.printStackTrace(); } return true; }

Target:
public boolean tryAdvance(Consumer<? super BytesHandle> action) { try { FormatEntry nextEntry = getNextEntry(); if (nextEntry == null) { return false; } BytesHandle nextBytesHandle = readEntry(nextEntry); action.accept(nextBytesHandle); splitter.count++; } catch (IOException e) { throw new RuntimeException("Could not read ZipEntry", e); } return true; }
Source:
public static ViewGroup.OnHierarchyChangeListener tryGetOnHierarchyChangeListenerHack( ViewGroup viewGroup) { if (sOnHierarchyChangeListenerField == null) { return null; } try { return (ViewGroup.OnHierarchyChangeListener)sOnHierarchyChangeListenerField.get(viewGroup); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }

Target:
public static ViewGroup.OnHierarchyChangeListener tryGetOnHierarchyChangeListenerHack( ViewGroup viewGroup) { if (sOnHierarchyChangeListenerField == null) { return null; } return (ViewGroup.OnHierarchyChangeListener)ReflectionUtil.getFieldValue( sOnHierarchyChangeListenerField, viewGroup); }
Source:
private HullConfig read(String shipName) { final HullConfig.Data configData = new HullConfig.Data(); configData.internalName = shipName; Json json = Assets.getJson(shipName); try { readProperties(json.getJsonValue(), configData); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("The JSON of ship " + shipName + " is missing, or has malformed, a required parameter" + e.getMessage().split(":")[1]); } catch (SerializationException e) { throw new SerializationException("The JSON of ship " + shipName + " has invalid syntax" + e.getMessage().split(":")[1]); } configData.tex = Assets.getAtlasRegion(shipName); configData.icon = Assets.getAtlasRegion(shipName + "Icon"); validateEngineConfig(configData); json.dispose(); return new HullConfig(configData); }

Target:
private HullConfig read(String shipName) { final HullConfig.Data configData = new HullConfig.Data(); configData.internalName = shipName; Json json = Assets.getJson(shipName); try { readProperties(json.getJsonValue(), configData); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("The JSON of ship " + shipName + " is missing, or has malformed, a required parameter" + e.getMessage().split(":")[1]); } catch (SerializationException e) { throw new SerializationException("The JSON of ship " + shipName + " has invalid syntax at " + e.getMessage().split(" near")[0].split("on ")[1]); } configData.tex = Assets.getAtlasRegion(shipName); configData.icon = Assets.getAtlasRegion(shipName + "Icon"); validateEngineConfig(configData); json.dispose(); return new HullConfig(configData); }
Source:
public ImmutableValue<Entity> leashHolder() { return new ImmutableSpongeEntityValue<>(Keys.LEASH_HOLDER, getValue()); }

Target:
public ImmutableValue<Entity> leashHolder() { return this.value; }
Source:
public void configurePipeline(PipelineConfigurer configurer) throws IllegalArgumentException { super.configurePipeline(configurer); if (this.config.format == null || this.config.format.isEmpty()) { throw new IllegalArgumentException("Format is not specified. Allowed values are DEFAULT, EXCEL, MYSQL," + " RFC4180, PDL & TDF"); } if (!this.config.format.equalsIgnoreCase("DEFAULT") && !this.config.format.equalsIgnoreCase("EXCEL") && !this.config.format.equalsIgnoreCase("MYSQL") && !this.config.format.equalsIgnoreCase("RFC4180") && !this.config.format.equalsIgnoreCase("TDF") && !this.config.format.equalsIgnoreCase("PDL")) { throw new IllegalArgumentException("Format specified is not one of the allowed values. Allowed values are " + "DEFAULT, EXCEL, MYSQL, RFC4180, PDL & TDF"); } if (configurer.getStageConfigurer().getInputSchema() != null) { Schema.Field inputSchemaField = configurer.getStageConfigurer().getInputSchema().getField(config.field); if (inputSchemaField == null) { throw new IllegalArgumentException( "Field " + config.field + " is not present in the input schema, it is expected"); } else { if (!inputSchemaField.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( "Field Type " + config.field + " should be String"); } } } try { Schema outputSchema = Schema.parseJson(this.config.schema); configurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }

Target:
public void configurePipeline(PipelineConfigurer configurer) throws IllegalArgumentException { super.configurePipeline(configurer); if (this.config.format == null || this.config.format.isEmpty()) { throw new IllegalArgumentException("Format is not specified. Allowed values are DEFAULT, EXCEL, MYSQL," + " RFC4180, PDL & TDF"); } if (!this.config.format.equalsIgnoreCase("DEFAULT") && !this.config.format.equalsIgnoreCase("EXCEL") && !this.config.format.equalsIgnoreCase("MYSQL") && !this.config.format.equalsIgnoreCase("RFC4180") && !this.config.format.equalsIgnoreCase("TDF") && !this.config.format.equalsIgnoreCase("PDL")) { throw new IllegalArgumentException("Format specified is not one of the allowed values. Allowed values are " + "DEFAULT, EXCEL, MYSQL, RFC4180, PDL & TDF"); } if (configurer.getStageConfigurer().getInputSchema() != null) { Schema.Field inputSchemaField = configurer.getStageConfigurer().getInputSchema().getField(config.field); if (inputSchemaField == null) { throw new IllegalArgumentException( "Field " + config.field + " is not present in the input schema"); } else { if (!inputSchemaField.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( "Type for field " + config.field + " must be String"); } } } try { Schema outputSchema = Schema.parseJson(this.config.schema); configurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }
Source:
private void applyProperties(AssociationKey associationKey, RowKey rowKey, Relationship relationship) { String[] rowKeyIndexColumnNames = associationKey.getRowKeyIndexColumnNames(); for ( int i = 0; i < rowKeyIndexColumnNames.length; i++ ) { for ( int j = 0; j < rowKey.getColumnNames().length; j++ ) { if ( rowKeyIndexColumnNames[i].equals( rowKey.getColumnNames()[j] ) ) { relationship.setProperty( rowKeyIndexColumnNames[i], rowKey.getColumnValues()[j] ); break; } } } }

Target:
private void applyProperties(AssociationKey associationKey, RowKey rowKey, Relationship relationship) { String[] indexColumns = associationKey.getMetadata().getRowKeyIndexColumnNames(); for ( int i = 0; i < indexColumns.length; i++ ) { String propertyName = indexColumns[i]; Object propertyValue = rowKey.getColumnValue( propertyName ); relationship.setProperty( propertyName, propertyValue ); } }
Source:
private Diagnostic handleMigrationOptions() { Diagnostic migrationMismatchDiagnostic = null; VSMVersionSAXParser parser = new VSMVersionSAXParser(uri); String loadedVersion = parser.getVersion(new NullProgressMonitor()); boolean migrationIsNeeded = true; if (loadedVersion != null) { Version parsedLoadedVersion = Version.parseVersion(loadedVersion); Version lastMigrationVersion = VSMMigrationService.getInstance().getLastMigrationVersion(); boolean attemptToLoadMoreRecentVSM = lastMigrationVersion.compareTo(parsedLoadedVersion) < 0; if (attemptToLoadMoreRecentVSM) { migrationMismatchDiagnostic = new XMIException(MessageFormat.format(Messages.DescriptionResourceImpl_versionMismatchMessage, uri, parsedLoadedVersion, lastMigrationVersion)); } migrationIsNeeded = VSMMigrationService.getInstance().isMigrationNeeded(parsedLoadedVersion); } Object versionOption = this.getDefaultLoadOptions().get(AbstractSiriusMigrationService.OPTION_RESOURCE_MIGRATION_LOADEDVERSION); if (!migrationIsNeeded && versionOption != null) { removeMigrationMechanism(); } else if (migrationIsNeeded && (versionOption == null || !versionOption.equals(loadedVersion))) { DescriptionResourceImpl.addMigrationOptions(loadedVersion, this.getDefaultLoadOptions(), this.getDefaultSaveOptions()); } return migrationMismatchDiagnostic; }

Target:
private Diagnostic handleMigrationOptions() { Diagnostic migrationMismatchDiagnostic = null; VSMVersionSAXParser parser = new VSMVersionSAXParser(uri); String loadedVersion = parser.getVersion(new NullProgressMonitor()); boolean migrationIsNeeded = true; if (loadedVersion != null) { Version parsedLoadedVersion = Version.parseVersion(loadedVersion); Version lastMigrationVersion = VSMMigrationService.getInstance().getLastMigrationVersion(); boolean attemptToLoadMoreRecentVSM = lastMigrationVersion.compareTo(parsedLoadedVersion) < 0; if (attemptToLoadMoreRecentVSM) { migrationMismatchDiagnostic = new ResourceVersionMismatchDiagnostic(uri, parsedLoadedVersion, lastMigrationVersion); } migrationIsNeeded = VSMMigrationService.getInstance().isMigrationNeeded(parsedLoadedVersion); } Object versionOption = this.getDefaultLoadOptions().get(AbstractSiriusMigrationService.OPTION_RESOURCE_MIGRATION_LOADEDVERSION); if (!migrationIsNeeded && versionOption != null) { removeMigrationMechanism(); } else if (migrationIsNeeded && (versionOption == null || !versionOption.equals(loadedVersion))) { DescriptionResourceImpl.addMigrationOptions(loadedVersion, this.getDefaultLoadOptions(), this.getDefaultSaveOptions()); } return migrationMismatchDiagnostic; }
Source:
public <T> T get(String key, String field) { RedisConnection<byte[], byte[]> redisCommands = null; try { redisCommands = getRedisConnection(); byte[] serializedData = redisCommands.hget(key.getBytes(), field.getBytes()); T deserializeObject = new JavaSerializer().deserializeObject(serializedData); return deserializeObject; } catch (Exception e) { logger.error("Exception Occurred while getting a value from redis", e); } finally { closeConnection(redisCommands); } return null; }

Target:
public <T> T get(String key, String field) { RedisConnection<byte[], byte[]> redisCommands = null; try { redisCommands = getRedisConnection(); byte[] serializedData = redisCommands.hget(key.getBytes(), field.getBytes()); T deserializeObject = codec.deserializeObject(serializedData); return deserializeObject; } finally { closeConnection(redisCommands); } }
Source:
public void testScaffoldSetup() throws Exception { Project project = projectHelper.createWebProject(); try (CommandController c = testHarness.createWizardController(ScaffoldSetupWizard.class, project.getRoot())) { c.initialize(); c.setValueFor("provider", "Mock Scaffold Provider"); c.setValueFor("webRoot", ""); Assert.assertTrue(c.isValid()); Result result = c.execute(); Assert.assertNotNull(result); } }

Target:
public void testScaffoldSetup() throws Exception { Project project = projectHelper.createWebProject(); Imported<ScaffoldProvider> providerInstances = registry.getServices(ScaffoldProvider.class); ScaffoldProvider scaffoldProvider = providerInstances.get(); Assert.assertFalse(scaffoldProvider.isSetup(new ScaffoldSetupContext("", project))); try (WizardCommandController c = testHarness.createWizardController(ScaffoldSetupWizard.class, project.getRoot())) { c.initialize(); c.setValueFor("provider", "Mock Scaffold Provider"); c.setValueFor("webRoot", ""); Assert.assertTrue(c.isValid()); Assert.assertFalse(c.canMoveToNextStep()); Result result = c.execute(); Assert.assertNotNull(result); Assert.assertFalse(result instanceof Failed); Assert.assertTrue(scaffoldProvider.isSetup(new ScaffoldSetupContext("", project))); } }
Source:
private Set<Integer> getTimeseriesLayerIds(int layerId) throws ActionException { Set<Integer> timeseriesLayerIds = new HashSet<>(); for (OskariLayer layer : mapLayerService.findAll()) { JSONObject options = layer.getOptions(); try { if (options != null && options.has("timeseries")) { JSONObject timeseriesOptions = options.getJSONObject("timeseries"); Integer metadataLayerId = timeseriesOptions.getJSONObject("metadata").getInt("layer"); if (metadataLayerId == layerId) { timeseriesLayerIds.add(layer.getId()); } } } catch (JSONException e) { throw new ActionException("Cannot parse layer metadata options for layer: " + layer.getName() + ", id: " + layer.getId()); } } return timeseriesLayerIds; }

Target:
private Set<Integer> getTimeseriesLayerIds(int layerId) throws ActionException { Set<Integer> timeseriesLayerIds = new HashSet<>(); for (OskariLayer layer : mapLayerService.findAll()) { JSONObject options = layer.getOptions(); try { if (options != null && options.has("timeseries")) { JSONObject timeseriesOptions = options.getJSONObject("timeseries"); JSONObject timeseriesMetadata = timeseriesOptions.optJSONObject("metadata"); if (timeseriesMetadata == null) { continue; } Integer metadataLayerId = timeseriesMetadata.getInt("layer"); if (metadataLayerId == layerId) { timeseriesLayerIds.add(layer.getId()); } } } catch (JSONException e) { throw new ActionException("Cannot parse layer metadata options for layer: " + layer.getName() + ", id: " + layer.getId()); } } return timeseriesLayerIds; }
Source:
public void testRecover() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(2); final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listner = new NotifyListener() { @Override public void notify(List<URL> urls) { notified.set(Boolean.TRUE); } }; MockRegistry mockRegistry = new MockRegistry(registryUrl, countDownLatch); mockRegistry.register(serviceUrl); mockRegistry.subscribe(serviceUrl, listner); Assert.assertEquals(mockRegistry.getRegistered().size(), 1); Assert.assertEquals(mockRegistry.getSubscribed().size(), 1); mockRegistry.recover(); Assert.assertEquals(mockRegistry.getFailedSubscribed().size(), 1); Assert.assertEquals(countDownLatch.getCount(), 0); }

Target:
public void testRecover() throws Exception { CountDownLatch countDownLatch = new CountDownLatch(4); final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); NotifyListener listener = new NotifyListener() { @Override public void notify(List<URL> urls) { notified.set(Boolean.TRUE); } }; MockRegistry mockRegistry = new MockRegistry(registryUrl, countDownLatch); mockRegistry.register(serviceUrl); mockRegistry.subscribe(serviceUrl, listener); Assert.assertEquals(1, mockRegistry.getRegistered().size()); Assert.assertEquals(1, mockRegistry.getSubscribed().size()); mockRegistry.recover(); countDownLatch.await(); Assert.assertEquals(0, mockRegistry.getFailedRegistered().size()); Assert.assertEquals(null, mockRegistry.getFailedSubscribed().get(registryUrl)); Assert.assertEquals(countDownLatch.getCount(), 0); }
Source:
public int compare(final Account account1, final Account account2) { if (account1.getPreferredEmail() != null && account2.getPreferredEmail() != null) { return account1.getPreferredEmail().compareTo( account2.getPreferredEmail()); } if (account1.getFullName() != null && account2.getFullName() != null) { return account1.getFullName().compareTo(account2.getFullName()); } return Integer.valueOf(account1.getId().get()).compareTo( Integer.valueOf(account2.getId().get())); }

Target:
public int compare(final Account account1, final Account account2) { if (account1.getPreferredEmail() != null && !account1.getPreferredEmail().isEmpty() && account2.getPreferredEmail() != null && !account2.getPreferredEmail().isEmpty()) { return account1.getPreferredEmail().compareTo( account2.getPreferredEmail()); } if (account1.getFullName() != null && !account1.getFullName().isEmpty() && account2.getFullName() != null && !account2.getFullName().isEmpty()) { return account1.getFullName().compareTo(account2.getFullName()); } return Integer.valueOf(account1.getId().get()).compareTo( Integer.valueOf(account2.getId().get())); }