auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void logChangeStatusToConnecting(long timeoutToFence) { AuditLogableBase auditLogableBase = new AuditLogableBase(cachedVds.getId()); AuditLogDirector.log(auditLogableBase, AuditLogType.VDS_HOST_RECONNECTING); log.warn("Host '{}' is not responding. It will stay in Connecting state for a grace period " + "of seconds and after that an attempt to fence the host will be issued.", cachedVds.getName(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence)); AuditLogableBase logable = new AuditLogableBase(); logable.setVdsId(cachedVds.getId()); logable.addCustomValue("Seconds", Long.toString(TimeUnit.MILLISECONDS.toSeconds(timeoutToFence))); AuditLogDirector.log(logable, AuditLogType.VDS_HOST_NOT_RESPONDING_CONNECTING); }

Target:
private void logChangeStatusToConnecting(long timeoutToFence) { AuditLogableBase auditLogableBase = new AuditLogableBase(cachedVds.getId()); AuditLogDirector.log(auditLogableBase, AuditLogType.VDS_HOST_RECONNECTING); log.warn("Host '{}' is not responding. It will stay in Connecting state for a grace period " + "of seconds and after that an attempt to fence the host will be issued.", cachedVds.getName(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence)); AuditLogableBase logable = new AuditLogableBase(); logable.setVdsId(cachedVds.getId()); logable.addCustomValue("Seconds", Long.toString(TimeUnit.MILLISECONDS.toSeconds(timeoutToFence))); auditLogDirector.log(logable, AuditLogType.VDS_HOST_NOT_RESPONDING_CONNECTING); }
Source:
public void start(final ServiceProvider serviceProvider) { final ManagementRegistryService managementRegistry = serviceProvider.getService(ManagementRegistryService.class); final Context cmContext = managementRegistry.getConfiguration().getContext(); final CacheManager cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); if (cacheManager instanceof ObservableCacheManager) { final ObservableCacheManager observableCacheManager = (ObservableCacheManager)cacheManager; observableCacheManager.registerListener(new CacheManagerListener() { @Override public void cacheAdded(String alias, Cache<?, ?> cache) { } @Override public void cacheRemoved(String alias, Cache<?, ?> cache) { } @Override public void stateTransition(Status from, Status to) { switch (to) { case AVAILABLE: delegates.put(cmContext, managementRegistry); break; case UNINITIALIZED: delegates.remove(cmContext); observableCacheManager.deregisterListener(this); break; case MAINTENANCE: break; default: throw new AssertionError(to); } } }); } }

Target:
public void start(final ServiceProvider serviceProvider) { final ManagementRegistryService managementRegistry = serviceProvider.getService(ManagementRegistryService.class); final Context cmContext = managementRegistry.getConfiguration().getContext(); final InternalCacheManager cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); cacheManager.registerListener(new CacheManagerListener() { @Override public void cacheAdded(String alias, Cache<?, ?> cache) { } @Override public void cacheRemoved(String alias, Cache<?, ?> cache) { } @Override public void stateTransition(Status from, Status to) { switch (to) { case AVAILABLE: delegates.put(cmContext, managementRegistry); break; case UNINITIALIZED: delegates.remove(cmContext); cacheManager.deregisterListener(this); break; case MAINTENANCE: break; default: throw new AssertionError(to); } } }); }
Source:
private static String getExpression(EventPosition eventPosition) { final String isInclusiveFlag = eventPosition.isInclusive() ? "=" : ""; if (eventPosition.getOffset() != null) { return String.format( AmqpConstants.AMQP_ANNOTATION_FORMAT, OFFSET_ANNOTATION_NAME.getValue(), isInclusiveFlag, eventPosition.getOffset()); } if (eventPosition.getSequenceNumber() != null) { return String.format( AmqpConstants.AMQP_ANNOTATION_FORMAT, SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), isInclusiveFlag, eventPosition.getSequenceNumber()); } if (eventPosition.getEnqueuedDateTime() != null) { String ms; try { ms = Long.toString(eventPosition.getEnqueuedDateTime().toEpochMilli()); } catch (ArithmeticException ex) { ms = Long.toString(Long.MAX_VALUE); } return String.format( AmqpConstants.AMQP_ANNOTATION_FORMAT, ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), isInclusiveFlag, ms); } throw new IllegalArgumentException("No starting position was set."); }

Target:
private String getExpression(EventPosition eventPosition) { final String isInclusiveFlag = eventPosition.isInclusive() ? "=" : ""; if (eventPosition.getOffset() != null) { return String.format( AmqpConstants.AMQP_ANNOTATION_FORMAT, OFFSET_ANNOTATION_NAME.getValue(), isInclusiveFlag, eventPosition.getOffset()); } if (eventPosition.getSequenceNumber() != null) { return String.format( AmqpConstants.AMQP_ANNOTATION_FORMAT, SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), isInclusiveFlag, eventPosition.getSequenceNumber()); } if (eventPosition.getEnqueuedDateTime() != null) { String ms; try { ms = Long.toString(eventPosition.getEnqueuedDateTime().toEpochMilli()); } catch (ArithmeticException ex) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT, "Event position for enqueued DateTime could not be parsed. Value: '%s'", eventPosition.getEnqueuedDateTime()), ex)); } return String.format(AmqpConstants.AMQP_ANNOTATION_FORMAT, ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), isInclusiveFlag, ms); } throw logger.logExceptionAsError(new IllegalArgumentException("No starting position was set.")); }
Source:
synchronized public void process(WatchedEvent event) { KeeperState state = event.getState(); if (state == KeeperState.SyncConnected) { connected = true; syncConnected = true; } else if (state == KeeperState.ConnectedReadOnly) { connected = true; } else { connected = false; syncConnected = false; } notifyAll(); if (connected) { clientConnected.countDown(); } }

Target:
synchronized public void process(WatchedEvent event) { KeeperState state = event.getState(); if (state == KeeperState.SyncConnected) { connected = true; syncConnected = true; } else if (state == KeeperState.ConnectedReadOnly) { connected = true; syncConnected = false; } else { connected = false; syncConnected = false; } notifyAll(); if (connected) { clientConnected.countDown(); } }
Source:
public void test() { connect(); Assert.assertEquals(jq("$innerLabel").text(), "someValue"); }

Target:
public void test() { connect(); Assert.assertTrue(jq("$innerLabel").exists()); Assert.assertEquals(jq("$innerLabel").text(), "someValue"); }
Source:
private boolean validateVmSnapshotStatus() { SnapshotsValidator snapshotsValidator = getSnapshotsValidator(); for (Pair<VM, VmDevice> pair : getVmsWithVmDeviceInfoForDiskId()) { VM vm = pair.getFirst(); if (!validate(snapshotsValidator.vmNotInPreview(vm.getId())) || !validate(snapshotsValidator.vmNotDuringSnapshot(vm.getId()))) { return false; } } return true; }

Target:
private boolean validateVmSnapshotStatus() { SnapshotsValidator snapshotsValidator = getSnapshotsValidator(); for (Pair<VM, VmDevice> pair : getVmsWithVmDeviceInfoForDiskId()) { VmDevice vmDevice = pair.getSecond(); if (vmDevice.getSnapshotId() == null) { VM vm = pair.getFirst(); if (!validate(snapshotsValidator.vmNotInPreview(vm.getId())) || !validate(snapshotsValidator.vmNotDuringSnapshot(vm.getId()))) { return false; } } } return true; }
Source:
public void validate(Diagram diagram, Consumer<Collection<DomainViolation>> resultConsumer) { Iterator<Element> it = diagram.getGraph().nodes().iterator(); Map<String, String> dataObjectsMap = new HashMap<>(); List<DomainViolation> violations = new ArrayList<>(); while (it.hasNext()) { Element element = it.next(); if (element.getContent() instanceof View && ((View) element.getContent()).getDefinition() instanceof DataObject) { DataObject dataObject = (DataObject) ((View) element.getContent()).getDefinition(); String name = dataObject.getName().getValue(); String type = dataObject.getType().getValue().getType(); String containedType = dataObjectsMap.get(name); if (containedType != null && !type.equals(containedType)) { BPMNViolation bpmnViolation = new BPMNViolation("Data Object Exists with Same Name and Different Type: " + name, Violation.Type.WARNING, element.getUUID()); violations.add(bpmnViolation); } else { dataObjectsMap.put(name, type); } if (!name.matches(ALLOWED_CHARS)) { BPMNViolation bpmnViolation = new BPMNViolation("Data Object with Invalid Name Exists: " + name, Violation.Type.WARNING, element.getUUID()); violations.add(bpmnViolation); } } } resultConsumer.accept(violations); }

Target:
public void validate(Diagram diagram, Consumer<Collection<DomainViolation>> resultConsumer) { Iterator<Element> it = diagram.getGraph().nodes().iterator(); Map<String, String> dataObjectsMap = new HashMap<>(); List<DomainViolation> violations = new ArrayList<>(); while (it.hasNext()) { Element element = it.next(); if (element.getContent() instanceof View && ((View) element.getContent()).getDefinition() instanceof DataObject) { DataObject dataObject = (DataObject) ((View) element.getContent()).getDefinition(); String name = dataObject.getName().getValue(); String type = dataObject.getType().getValue().getType(); String containedType = dataObjectsMap.get(name); if (containedType != null && !type.equals(containedType)) { BPMNViolation bpmnViolation = new BPMNViolation(translationService.getValue(StunnerWidgetsConstants.MarshallingResponsePopup_DataObjectsSameNameDifferentType) + " : " + name, Violation.Type.WARNING, element.getUUID()); violations.add(bpmnViolation); } else { dataObjectsMap.put(name, type); } if (name.matches(ILLEGAL_CHARS)) { BPMNViolation bpmnViolation = new BPMNViolation(translationService.getValue(StunnerWidgetsConstants.MarshallingResponsePopup_dataObjectWithName) + ": " + name + " " + translationService.getValue(StunnerWidgetsConstants.MarshallingResponsePopup_dataObjectWithIllegalCharacters), Violation.Type.WARNING, element.getUUID()); violations.add(bpmnViolation); } if (!name.matches(ALLOWED_CHARS)) { BPMNViolation bpmnViolation = new BPMNViolation(translationService.getValue(StunnerWidgetsConstants.MarshallingResponsePopup_dataObjectWithInvalidName) + " : " + name, Violation.Type.WARNING, element.getUUID()); violations.add(bpmnViolation); } } } resultConsumer.accept(violations); }
Source:
public void testGetLedgerMetaService() throws Exception { baseConf.setZkServers(zkUtil.getZooKeeperConnectString()); BookKeeper.DigestType digestType = BookKeeper.DigestType.CRC32; int numLedgers = 4; int numMsgs = 100; LedgerHandle[] lh = new LedgerHandle[numLedgers]; for (int i = 0; i < numLedgers; i++) { lh[i] = bkc.createLedger(digestType, "".getBytes()); } String content = "Apache BookKeeper is cool!"; for (int i = 0; i < numMsgs; i++) { for (int j = 0; j < numLedgers; j++) { lh[j].addEntry(content.getBytes()); } } for (int i = 0; i < numLedgers; i++) { lh[i].close(); } HttpService getLedgerMetaService = bkHttpServiceProvider.provideGetLedgerMetaService(); HttpServiceRequest request1 = new HttpServiceRequest(null, HttpServer.Method.GET, null); HttpServiceResponse response1 = getLedgerMetaService.handle(request1); assertEquals(HttpServer.StatusCode.NOT_FOUND.getValue(), response1.getStatusCode()); HashMap<String, String> params = Maps.newHashMap(); Long ledgerId = Long.valueOf(lh[0].getId()); params.put("ledger_id", ledgerId.toString()); HttpServiceRequest request2 = new HttpServiceRequest(null, HttpServer.Method.GET, params); HttpServiceResponse response2 = getLedgerMetaService.handle(request2); assertEquals(HttpServer.StatusCode.OK.getValue(), response2.getStatusCode()); @SuppressWarnings("unchecked") HashMap<String, String> respBody = JsonUtil.fromJson(response2.getBody(), HashMap.class); assertEquals(1, respBody.size()); }

Target:
public void testGetLedgerMetaService() throws Exception { baseConf.setZkServers(zkUtil.getZooKeeperConnectString()); BookKeeper.DigestType digestType = BookKeeper.DigestType.CRC32; int numLedgers = 4; int numMsgs = 100; LedgerHandle[] lh = new LedgerHandle[numLedgers]; for (int i = 0; i < numLedgers; i++) { lh[i] = bkc.createLedger(digestType, "password".getBytes()); } String content = "Apache BookKeeper is cool!"; for (int i = 0; i < numMsgs; i++) { for (int j = 0; j < numLedgers; j++) { lh[j].addEntry(content.getBytes()); } } for (int i = 0; i < numLedgers; i++) { lh[i].close(); } HttpEndpointService getLedgerMetaService = bkHttpServiceProvider .provideHttpEndpointService(HttpServer.ApiType.GET_LEDGER_META); HttpServiceRequest request1 = new HttpServiceRequest(null, HttpServer.Method.GET, null); HttpServiceResponse response1 = getLedgerMetaService.handle(request1); assertEquals(HttpServer.StatusCode.NOT_FOUND.getValue(), response1.getStatusCode()); HashMap<String, String> params = Maps.newHashMap(); Long ledgerId = Long.valueOf(lh[0].getId()); params.put("ledger_id", ledgerId.toString()); HttpServiceRequest request2 = new HttpServiceRequest(null, HttpServer.Method.GET, params); HttpServiceResponse response2 = getLedgerMetaService.handle(request2); assertEquals(HttpServer.StatusCode.OK.getValue(), response2.getStatusCode()); @SuppressWarnings("unchecked") HashMap<String, String> respBody = JsonUtil.fromJson(response2.getBody(), HashMap.class); assertEquals(1, respBody.size()); assertTrue(respBody.get(ledgerId.toString()).toString() .equals(new String(lh[0].getLedgerMetadata().serialize()))); }
Source:
public PriorityLevel getPriorityLevel() { String value = getPriority(); return (value != null) ? PriorityLevel.fromString(value) : null; }

Target:
public PriorityLevel getPriorityLevel() { String valueLabel = getPriority(); if (valueLabel != null && PriorityLevel.isValidPriority(valueLabel)) { return PriorityLevel.fromString(valueLabel); } TaskAttribute attribute = taskData.getRoot().getMappedAttribute(TaskAttribute.PRIORITY); if (attribute != null) { return getTaskData().getAttributeMapper().getPriorityLevel(attribute, attribute.getValue()); } return null; }
Source:
public static void init() throws ServletException, LifecycleException, FileNotFoundException, IOException, DBException, InterruptedException { String webappDirLocation = "WebContent/"; while (!Utils.available(port)) { port++; } tomcat.setPort(Integer.valueOf(port)); Context context = tomcat.addWebapp("/webService", new File(webappDirLocation).getAbsolutePath()); Tomcat.addServlet(context, "jersey-container-servlet", resourceConfig()); context.addServletMapping("/rest/*", "jersey-container-servlet"); tomcat.start(); Thread.sleep(1000); }

Target:
public static void init() throws ServletException, LifecycleException, FileNotFoundException, IOException, DBException, InterruptedException { String webappDirLocation = IntegrationTest.class.getClassLoader().getResource("WebContent").getPath(); while (!Utils.available(port)) { port++; } tomcat = new Tomcat(); tomcat.setPort(Integer.valueOf(port)); Context context = tomcat.addWebapp("/webService", new File(webappDirLocation).getAbsolutePath()); Tomcat.addServlet(context, "jersey-container-servlet", resourceConfig()); context.addServletMapping("/rest/*", "jersey-container-servlet"); tomcat.start(); Thread.sleep(1000); }
Source:
public static Ethertype forValue(String value) { if (value != null) { for (Ethertype s : Ethertype.values()) { if (s.name().equalsIgnoreCase(value)) { return s; } } } return Ethertype.IPv4; }

Target:
public static Ethertype forValue(String value) { if (value != null) { for (Ethertype s : Ethertype.values()) { if (s.name().equalsIgnoreCase(value)) { return s; } } } return UNRECOGNIZED; }
Source:
private void validateUserFields(UserDTO userResource) { if (userResource.getFirstName() == null || userResource.getFirstName().trim().length() == 0) { throw new InvalidDataException("error.user.firstname"); } if (userResource.getLastName() == null || userResource.getLastName().trim().length() == 0) { throw new InvalidDataException("error.user.lastname"); } if (userResource.getEmailAddress() == null || userResource.getEmailAddress().trim().length() == 0) { throw new InvalidDataException("error.user.email.address"); } if (!EmailValidator.getInstance().isValid(userResource.getEmailAddress())) { throw new InvalidDataException("error.user.email.address.invalid", userResource.getEmailAddress()); } if (userResource.getMobileNumber() == null || userResource.getMobileNumber().trim().length() == 0) { throw new InvalidDataException("error.user.mobile.number"); } if (!REGEX_PHONE.matcher(userResource.getMobileNumber()).matches()) { throw new InvalidDataException("error.user.mobile.number.invalid"); } }

Target:
private void validateUserFields(UserDTO userResource) { if (StringUtils.isBlank(userResource.getFirstName())) { throw new InvalidDataException("error.user.firstname"); } if (StringUtils.isBlank(userResource.getLastName())) { throw new InvalidDataException("error.user.lastname"); } if (StringUtils.isBlank(userResource.getEmailAddress())) { throw new InvalidDataException("error.user.email.address"); } if (!EmailValidator.getInstance().isValid(userResource.getEmailAddress())) { throw new InvalidDataException("error.user.email.address.invalid", userResource.getEmailAddress()); } if (StringUtils.isBlank(userResource.getMobileNumber())) { throw new InvalidDataException("error.user.mobile.number"); } if (!REGEX_PHONE.matcher(userResource.getMobileNumber()).matches()) { throw new InvalidDataException("error.user.mobile.number.invalid"); } }
Source:
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { manager.completeWorkItem(workItem.getId(), null); } catch(Throwable cause) { handleException(cause); manager.abortWorkItem(workItem.getId()); } }

Target:
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { manager.completeWorkItem(workItem.getId(), null); } catch(Throwable cause) { handleException(cause); } }
Source:
public static <T> T parse(Class<T> cls, String value) throws InstantiationException, IllegalAccessException, ParseException { if (cls.isEnum()) { final Map<Class<?>, Map<String, String>> member = SCHEMA_TO_ENUM_DICTIONARIES.getMember(); String val = value; final Map<String, String> stringToEnumDict = member.get(cls); if (stringToEnumDict != null) { final String strEnumName = stringToEnumDict.get(value); if (strEnumName != null) { val = strEnumName; } } for (T o : cls.getEnumConstants()) { if (o.toString().equals(val)) { return o; } } return null; } else if (cls.isAssignableFrom(Number.class)) { Integer o = Integer.parseInt(value); return (T) o; } else if (cls.isAssignableFrom(Date.class)) { DateFormat df = createDateFormat(XML_SCHEMA_DATE_TIME_FORMAT); return (T) df.parse(value); } else if (cls.isAssignableFrom(Boolean.class)) { Object o = Boolean.parseBoolean(value); return (T) o; } else if (cls.isAssignableFrom(String.class)) { return (T) value; } else if (cls.isAssignableFrom(Double.class)) { Object o = Double.parseDouble(value); return (T) o; } return null; }

Target:
public static <T> T parse(Class<T> cls, String value) throws InstantiationException, IllegalAccessException, ParseException { if (cls.isEnum()) { final Map<Class<?>, Map<String, String>> member = SCHEMA_TO_ENUM_DICTIONARIES.getMember(); String val = value; final Map<String, String> stringToEnumDict = member.get(cls); if (stringToEnumDict != null) { final String strEnumName = stringToEnumDict.get(value); if (strEnumName != null) { val = strEnumName; } } for (T o : cls.getEnumConstants()) { if (o.toString().equals(val)) { return o; } } return null; } else if (cls.isAssignableFrom(Double.class)) { return (T) ((Double) Double.parseDouble(value)); } else if (cls.isAssignableFrom(Number.class)) { return (T) ((Integer) Integer.parseInt(value)); } else if (cls.isAssignableFrom(Date.class)) { DateFormat df = createDateFormat(XML_SCHEMA_DATE_TIME_FORMAT); return (T) df.parse(value); } else if (cls.isAssignableFrom(Boolean.class)) { return (T) ((Boolean) Boolean.parseBoolean(value)); } else if (cls.isAssignableFrom(String.class)) { return (T) value; } return null; }
Source:
public TComplexProperty getPropertyAtIndex(int index) throws IllegalArgumentException { if (index < 0 || index >= this.getCount()) { throw new IllegalArgumentException("parameter \'index\' : " + "index is out of range."); } return this.items.get(index); }

Target:
public TComplexProperty getPropertyAtIndex(int index) throws IllegalArgumentException { if (index < 0 || index >= this.getCount()) { throw new IllegalArgumentException( String.format("index %d is out of range [0..%d[.", index, this.getCount()) ); } return this.items.get(index); }
Source:
public void delete_directory_parallel() throws Exception { GoogleCloudStorageFileSystemOptions gcsFsOptions = newGcsFsOptions().setStatusParallelEnabled(true).build(); TrackingHttpRequestInitializer gcsRequestsTracker = new TrackingHttpRequestInitializer(httpRequestsInitializer); GoogleCloudStorageFileSystem gcsFs = newGcsFs(gcsFsOptions, gcsRequestsTracker); String bucketName = gcsfsIHelper.sharedBucketName1; URI bucketUri = new URI("gs://" + bucketName + "/"); String dirObject = getTestResource(); gcsfsIHelper.createObjectsWithSubdirs(bucketName, dirObject + "/f1"); gcsFs.delete(bucketUri.resolve(dirObject + "/f1"), false); assertThat(gcsRequestsTracker.getAllRequestStrings()) .containsExactly( getRequestString(bucketName, dirObject + "/"), getRequestString(bucketName, dirObject + "/f1"), listRequestWithTrailingDelimiter( bucketName, dirObject + "/f1/", 1, null), deleteRequestString(bucketName, dirObject + "/f1", 1)); assertThat(gcsFs.exists(bucketUri.resolve(dirObject + "/f1"))).isFalse(); }

Target:
public void delete_directory_parallel() throws Exception { delete_directory( true); }
Source:
public void start() { try { restoreRestorableTasks(); cleanupStaleAnnouncements(); registerRunListener(); registerLocationListener(); pathChildrenCache.start(); exec.submit( new Runnable() { @Override public void run() { mainLoop(); } } ); } catch (Exception e) { log.makeAlert(e, "Exception starting WorkerTaskMonitor") .emit(); throw Throwables.propagate(e); } }

Target:
public void start() { synchronized (lifecycleLock) { Preconditions.checkState(!started, "already started"); Preconditions.checkState(!exec.isShutdown(), "already stopped"); started = true; try { restoreRestorableTasks(); cleanupStaleAnnouncements(); registerRunListener(); registerLocationListener(); pathChildrenCache.start(); exec.submit( new Runnable() { @Override public void run() { mainLoop(); } } ); log.info("Started WorkerTaskMonitor."); started = true; } catch (Exception e) { log.makeAlert(e, "Exception starting WorkerTaskMonitor") .emit(); throw Throwables.propagate(e); } } }
Source:
public NumberValue divideBy( NumberValue numberValue ) { if ( numberValue instanceof IntegralValue ) { return dividedBy( numberValue.longValue() ); } else if ( numberValue instanceof FloatingPointValue ) { return dividedBy( numberValue.doubleValue() ); } else { throw new IllegalArgumentException( "Cannot add " + numberValue ); } }

Target:
public NumberValue divideBy( NumberValue numberValue ) { if ( numberValue instanceof IntegralValue ) { return dividedBy( numberValue.longValue() ); } else if ( numberValue instanceof FloatingPointValue ) { return dividedBy( numberValue.doubleValue() ); } else { throw new IllegalArgumentException( "Cannot divide by " + numberValue ); } }
Source:
public void sendMessage(){ String[] recipients = et_recipient.getText().toString().split(" "); for (int i=0; i<recipients.length; ++i){ recipients[i] = recipients[i].substring(1); } String subject = et_subject.getText().toString(); String content = et_message.getText().toString(); if(subject.length() == 0){ subject = getString(R.string.no_subject); } if(content.length() == 0){ subject = getString(R.string.no_content); } String content_type = Mail.PLAIN_TEXT; if (content.startsWith("<html>") && content.endsWith("</html>")) content_type = Mail.HTML_TEXT; SendMailData data = new SendMailData(recipients, subject, content, content_type); if (isAnswer){ if (attachments.size()>0) HandlerAPIConnect.answerMailWithAttachment(data, mail.handler_id, this, attachments); else HandlerAPIConnect.answerMail(data, mail.handler_id, this); } else { if (attachments.size()>0) HandlerAPIConnect.sendMailWithAttachment(data, this, attachments); else HandlerAPIConnect.sendMail(data, this); } finish(); }

Target:
public void sendMessage(){ String[] recipients = et_recipient.getText().toString().split(" "); for (int i=0; i<recipients.length; ++i){ recipients[i] = recipients[i].substring(1); } String subject = et_subject.getText().toString(); String content = et_message.getText().toString(); if(TextUtils.isEmpty(subject)){ subject = getString(R.string.no_subject); } if(TextUtils.isEmpty(content)){ subject = getString(R.string.no_content); } String content_type = Mail.PLAIN_TEXT; if (content.startsWith("<html>") && content.endsWith("</html>")) content_type = Mail.HTML_TEXT; SendMailData data = new SendMailData(recipients, subject, content, content_type); if (isAnswer){ if (!attachments.isEmpty()) HandlerAPIConnect.answerMailWithAttachment(data, mail.handler_id, this, attachments); else HandlerAPIConnect.answerMail(data, mail.handler_id, this); } else { if (!attachments.isEmpty()) HandlerAPIConnect.sendMailWithAttachment(data, this, attachments); else HandlerAPIConnect.sendMail(data, this); } finish(); }
Source:
protected Connection tryConnectionInsideLock() throws JMSException { if (m_closing) { throw new ProcessingException("closed"); } if (m_impl != null) { return m_impl; } final Connection c = m_connectionFunction.create(); if (m_connectionRetryCount > 0) { c.setExceptionListener(new ExceptionListener() { @Override public void onException(JMSException e1) { if (m_connectionRetryCount > 0) { LOG.info("JMS connection dropped with '{}'; starting failover", e1); invalidate(e1); } else { BEANS.get(MomExceptionHandler.class).handle(e1); } } }); } m_impl = c; return m_impl; }

Target:
protected Connection tryConnectionInsideLock() throws JMSException { if (m_closing) { throw new ProcessingException("closed"); } if (m_impl != null) { return m_impl; } final Connection c = m_connectionFunction.create(); if (m_connectionRetryCount > 0) { c.setExceptionListener(new ExceptionListener() { @Override public void onException(JMSException e1) { if (m_connectionRetryCount > 0) { LOG.info("JMS connection dropped with '{}'; starting failover", e1.getMessage()); invalidate(e1); } else { BEANS.get(MomExceptionHandler.class).handle(e1); } } }); } m_impl = c; return m_impl; }
Source:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", mimeType, this::setContentType); before("/*", mimeType, this::setContentType); before("", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", mimeType, this::index); get(Routes.Packages.SHOW, mimeType, this::show); post("", mimeType, this::create); put(Routes.Packages.SHOW, mimeType, this::update); delete(Routes.Packages.SHOW, mimeType, this::remove); }); }

Target:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", mimeType, this::setContentType); before("/*", mimeType, this::setContentType); before("", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, this.apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", mimeType, this::index); get(Routes.Packages.PACKAGE_ID, mimeType, this::show); post("", mimeType, this::create); put(Routes.Packages.PACKAGE_ID, mimeType, this::update); delete(Routes.Packages.PACKAGE_ID, mimeType, this::remove); }); }
Source:
public void insertCard(@NonNull Card card, int position) { cards.add(position, card); removeHiddenCard(card); if (updateListener != null) { updateListener.update(cards); } }

Target:
public void insertCard(@NonNull Card card, int position) { cards.add(position, card); unHideCard(card); if (updateListener != null) { updateListener.update(cards); } }
Source:
private void recoverSortMenuState(Menu menu){ if(menu != null) { menu.findItem(R.id.action_sort_descending).setChecked(!com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); switch (com.owncloud.android.db.PreferenceManager.getSortOrder(this,FileStorageUtils.FILE_DISPLAY_SORT)) { case FileStorageUtils.SORT_NAME: menu.findItem(R.id.action_sort_by_name).setChecked(true); sortByName(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_SIZE: menu.findItem(R.id.action_sort_by_size).setChecked(true); sortBySize(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_DATE: menu.findItem(R.id.action_sort_by_date).setChecked(true); sortByDate(com.owncloud.android.db.PreferenceManager.getSortAscending(this,FileStorageUtils.FILE_DISPLAY_SORT)); break; } } }

Target:
private void recoverSortMenuState(Menu menu) { if (menu != null) { menu.findItem(R.id.action_sort_descending).setChecked( !PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); switch (PreferenceManager.getSortOrder(this, FileStorageUtils.FILE_DISPLAY_SORT)) { case FileStorageUtils.SORT_NAME: menu.findItem(R.id.action_sort_by_name).setChecked(true); sortByName(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_SIZE: menu.findItem(R.id.action_sort_by_size).setChecked(true); sortBySize(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; case FileStorageUtils.SORT_DATE: menu.findItem(R.id.action_sort_by_date).setChecked(true); sortByDate(PreferenceManager.getSortAscending(this, FileStorageUtils.FILE_DISPLAY_SORT)); break; } } }
Source:
public ComplexMetricExtractor getExtractor() { return new ComplexMetricExtractor() { @Override public Class<HyperLogLogCollector> extractedClass() { return HyperLogLogCollector.class; } @Override public HyperLogLogCollector extractValue(InputRow inputRow, String metricName) { Object rawValue = inputRow.getRaw(metricName); if (rawValue instanceof HyperLogLogCollector) { return (HyperLogLogCollector) rawValue; } else { HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); List<String> dimValues = inputRow.getDimension(metricName); if (dimValues == null) { return collector; } for (String dimensionValue : dimValues) { collector.add(dimensionValue); } return collector; } } }; }

Target:
public ComplexMetricExtractor getExtractor() { return new ComplexMetricExtractor() { @Override public Class<HyperLogLogCollector> extractedClass() { return HyperLogLogCollector.class; } @Override public HyperLogLogCollector extractValue(InputRow inputRow, String metricName) { Object rawValue = inputRow.getRaw(metricName); if (rawValue instanceof HyperLogLogCollector) { return (HyperLogLogCollector) rawValue; } else { HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); List<String> dimValues = inputRow.getDimension(metricName); if (dimValues == null) { return collector; } for (String dimensionValue : dimValues) { collector.add(hyperLogLogHash.hash(dimensionValue)); } return collector; } } }; }
Source:
public List<SourceWithKeys> splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) throws Exception { List<SourceWithKeys> newSplits = split(estimatedSize, desiredBundleSizeBytes, startKey, stopKey); if (LOG.isDebugEnabled()) { LOG.debug("Splitting split with into {}", this, newSplits); } return newSplits; }

Target:
public List<SourceWithKeys> splitIntoBundles(long desiredBundleSizeBytes, PipelineOptions options) throws Exception { List<SourceWithKeys> newSplits = split(estimatedSize, desiredBundleSizeBytes, startKey, stopKey); if (LOG.isDebugEnabled()) { LOG.debug("Splitting split into {}", this, newSplits); } return newSplits; }
Source:
public String getHref() { return "/pools/" + getId(); }

Target:
public String getHref() { return this.getId() != null ? String.format("/pools/%s", this.getId()) : null; }
Source:
public ItemsFilter(SearchPattern searchPattern) { patternMatcher = searchPattern; String stringPattern = ""; if (pattern != null && !pattern.getText().equals("*")) { stringPattern = pattern.getText(); } if (stringPattern.indexOf("*") != 0) { stringPattern = "*" + stringPattern; } patternMatcher.setPattern(stringPattern); }

Target:
public ItemsFilter(SearchPattern searchPattern) { patternMatcher = searchPattern; String stringPattern = ""; if (pattern != null && !pattern.getText().equals("*")) { stringPattern = pattern.getText(); } if (stringPattern.indexOf("*") != 0 && stringPattern.indexOf("?") != 0 && stringPattern.indexOf(".") != 0) { stringPattern = "*" + stringPattern; } patternMatcher.setPattern(stringPattern); }
Source:
public Location createLocation(Location location) { org.openmrs.Location omrsLocation=null; List<String> errors = new ArrayList<String>(); omrsLocation = FHIRLocationUtil.generateOpenMRSLocation(location, errors); if (!errors.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The request cannot be processed due to following issues \n"); for (int i = 0; i < errors.size(); i++) { errorMessage.append((i + 1) + " : " + errors.get(i) + "\n"); } throw new UnprocessableEntityException(errorMessage.toString()); } omrsLocation=Context.getLocationService().saveLocation(omrsLocation); return FHIRLocationUtil.generateLocation(omrsLocation); }

Target:
public Location createLocation(Location location) { org.openmrs.Location omrsLocation=null; List<String> errors = new ArrayList<String>(); omrsLocation = FHIRLocationUtil.generateOpenMRSLocation(location, 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()); } omrsLocation=Context.getLocationService().saveLocation(omrsLocation); return FHIRLocationUtil.generateLocation(omrsLocation); }
Source:
public GatewayNotification processNotification(final String notification, final String pluginName, final Iterable<PluginProperty> properties, final CallContext callContext) throws PaymentApiException { return dispatchWithExceptionHandling(null, pluginName, new Callable<PluginDispatcherReturnType<GatewayNotification>>() { @Override public PluginDispatcherReturnType<GatewayNotification> call() throws PaymentApiException { try { final PaymentPluginApi plugin = getPaymentPluginApi(pluginName); final GatewayNotification result = plugin.processNotification(notification, properties, callContext); return PluginDispatcher.createPluginDispatcherReturnType(result == null ? new DefaultNoOpGatewayNotification() : result); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_EXCEPTION, e.getErrorMessage()); } } }, paymentPluginNotificationDispatcher); }

Target:
public GatewayNotification processNotification(final String notification, final String pluginName, final Iterable<PluginProperty> properties, final CallContext callContext) throws PaymentApiException { return dispatchWithExceptionHandling(null, pluginName, new Callable<PluginDispatcherReturnType<GatewayNotification>>() { @Override public PluginDispatcherReturnType<GatewayNotification> call() throws PaymentApiException { final PaymentPluginApi plugin = getPaymentPluginApi(pluginName); try { final GatewayNotification result = plugin.processNotification(notification, properties, callContext); return PluginDispatcher.createPluginDispatcherReturnType(result == null ? new DefaultNoOpGatewayNotification() : result); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(ErrorCode.PAYMENT_PLUGIN_EXCEPTION, e.getErrorMessage()); } } }, paymentPluginNotificationDispatcher); }
Source:
protected void dealWithStringtoStringMap(U field) { Map<String, String> updateDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) updateDocument.getFieldValue(field)); Map<String, String> actualDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) actualDocument.getFieldValue(field)); if (updateDocumentMap.equals(actualDocumentMap)) { return; } Map<String,String> addedMap = updateDocumentMap; Map<String, String> deletedMap = actualDocumentMap; Set<String> commonKeys = Sets.intersection(updateDocumentMap.keySet(), actualDocumentMap.keySet()); for(String id : commonKeys) { String actual = actualDocumentMap.get(id); String update = updateDocumentMap.get(id); if(! actual.equals(update)) { addedMap.put(id, update); deletedMap.put(id, actual); } } documentAdditions.setFieldValue(field, addedMap); documentDeletions.setFieldValue(field, deletedMap); }

Target:
protected void dealWithStringtoStringMap(U field) { Map<String, String> updateDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) updateDocument.getFieldValue(field)); Map<String, String> actualDocumentMap = CommonUtils.nullToEmptyMap( (Map<String, String>) actualDocument.getFieldValue(field)); if (updateDocumentMap.equals(actualDocumentMap)) { return; } Map<String,String> addedMap = updateDocumentMap; Map<String, String> deletedMap = actualDocumentMap; Set<String> commonKeys = Sets.intersection(updateDocumentMap.keySet(), actualDocumentMap.keySet()); for(String id : commonKeys) { String actual = actualDocumentMap.get(id); String update = updateDocumentMap.get(id); if(! Objects.equals(update, actual)) { addedMap.put(id, update); deletedMap.put(id, actual); } } documentAdditions.setFieldValue(field, addedMap); documentDeletions.setFieldValue(field, deletedMap); }
Source:
public void setRatingChange(PlayerStats playerStats) { if (playerStats.getAfterMean() == null || playerStats.getAfterDeviation() == null) { return; } int newRating = RatingUtil.getRating(playerStats.getAfterMean(), playerStats.getAfterDeviation()); int oldRating = RatingUtil.getRating(playerStats.getBeforeMean(), playerStats.getBeforeDeviation()); int ratingChane = newRating - oldRating; ratingChangLabelRoot.setText(i18n.numberWithSign(ratingChane)); ratingChangLabelRoot.pseudoClassStateChanged(ratingChane < 0 ? NEGATIVE : POSITIVE, true); ratingChangLabelRoot.setVisible(true); }

Target:
public void setRatingChange(PlayerStats playerStats) { if (playerStats.getAfterMean() == null || playerStats.getAfterDeviation() == null) { return; } int newRating = RatingUtil.getRating(playerStats.getAfterMean(), playerStats.getAfterDeviation()); int oldRating = RatingUtil.getRating(playerStats.getBeforeMean(), playerStats.getBeforeDeviation()); int ratingChange = newRating - oldRating; ratingChangLabelRoot.setText(i18n.numberWithSign(ratingChange)); ratingChangLabelRoot.pseudoClassStateChanged(ratingChange < 0 ? NEGATIVE : POSITIVE, true); ratingChangLabelRoot.setVisible(true); }
Source:
protected void populateProjects() { Util.PROJECT_SVC.visibleProjects( new ScreenLoadCallback<List<Project>>(this) { @Override protected void preDisplay(final List<Project> result) { projectsTab.display(result); if (firstPopupLoad) { firstPopupLoad = false; displayPopup(); } } }); }

Target:
protected void populateProjects() { Util.PROJECT_SVC.visibleProjects( new GerritCallback<List<Project>>() { @Override public void onSuccess(final List<Project> result) { projectsTab.display(result); if (firstPopupLoad) { firstPopupLoad = false; displayPopup(); } } }); }
Source:
protected AbstractResourceWrapper<?, ?> createNewWrapper(Collection<IResource> resources, IResource r) { AbstractResourceWrapper<?, ?> newWrapper; if (r instanceof IService) { ServiceWrapper newService = new ServiceWrapper(ProjectWrapper.this, (IService) r); Collection<IResource> relatedResources = ServiceResourceMapper.computeRelatedResources((IService) r, resources); newService.initWithResources(relatedResources); newWrapper = newService; } else if ((ResourceKind.DEPLOYMENT_CONFIG.equals(r.getKind()) || (ResourceKind.REPLICATION_CONTROLLER.equals(r.getKind()) && !r.isAnnotatedWith(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME))) && ServiceResourceMapper.getServices((IReplicationController) r, resources).isEmpty()) { ReplicationControllerWrapper dcWrapper = new ReplicationControllerWrapper(this, (IReplicationController) r); Collection<IResource> relatedResource = ResourceKind.DEPLOYMENT_CONFIG.equals(r.getKind())?ServiceResourceMapper.computeRelatedResources((IDeploymentConfig) r, resources) :ServiceResourceMapper.computeRelatedResources((IReplicationController) r, resources); dcWrapper.initWithResources(relatedResource); newWrapper = dcWrapper; } else { newWrapper = new ResourceWrapper(ProjectWrapper.this, r); } return newWrapper; }

Target:
protected AbstractResourceWrapper<?, ?> createNewWrapper(Collection<IResource> resources, IResource r) { AbstractResourceWrapper<?, ?> newWrapper; if (r instanceof IService) { ServiceWrapper newService = new ServiceWrapper(ProjectWrapper.this, (IService) r); Collection<IResource> relatedResources = ServiceResourceMapper.computeRelatedResources((IService) r, resources); newService.initWithResources(relatedResources); newWrapper = newService; } else if ((ResourceKind.DEPLOYMENT_CONFIG.equals(r.getKind()) || (ResourceKind.REPLICATION_CONTROLLER.equals(r.getKind()) && !r.isAnnotatedWith(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME))) && ServiceResourceMapper.getServices((IReplicationController) r, resources).isEmpty()) { ReplicationControllerWrapper dcWrapper = new ReplicationControllerWrapper(this, (IReplicationController) r); Collection<IResource> relatedResource = getRelatedResources(resources, dcWrapper); dcWrapper.initWithResources(relatedResource); newWrapper = dcWrapper; } else { newWrapper = new ResourceWrapper(ProjectWrapper.this, r); } return newWrapper; }
Source:
pathname -> pathname.isFile() && pathname.getName().startsWith(RESERVE_FILE_PREFIX); static final FileFilter FILE_SIZE_DIR_FILTER = pathname -> pathname.isDirectory() && getFileSizeForDirName(pathname.getName()) != null; private final boolean enablePooling; private final File reserveDir; private final File swapReserveDir; private final long requiredSwapSegmentsPerSize; private final StorageManagerMetrics metrics; private final Map<String, ReserveFileMap> storeReserveFiles = new HashMap<>(); private final ReserveFileMap swapReserveFiles = new ReserveFileMap(); private PoolState poolState = PoolState.NOT_INVENTORIED; private Exception inventoryException = null; DiskSpaceAllocator(boolean enablePooling, File reserveDir, long requiredSwapSegmentsPerSize, StorageManagerMetrics metrics) { this.enablePooling = enablePooling; this.reserveDir = reserveDir; swapReserveDir = new File(reserveDir, SWAP_DIR_NAME); this.requiredSwapSegmentsPerSize = requiredSwapSegmentsPerSize; this.metrics = metrics; try { if (enablePooling) { prepareDirectory(reserveDir); prepareDirectory(swapReserveDir); inventoryExistingReserveFiles(); poolState = PoolState.INVENTORIED; } } catch (Exception e) { inventoryException = e; logger.error("Could not inventory preexisting reserve directory", e); } }

Target:
pathname -> pathname.isFile() && pathname.getName().startsWith(RESERVE_FILE_PREFIX); private static final FileFilter FILE_SIZE_DIR_FILTER = pathname -> pathname.isDirectory() && getFileSizeForDirName(pathname.getName()) != null; private static final Logger logger = LoggerFactory.getLogger(DiskSpaceAllocator.class); private final boolean enablePooling; private final File reserveDir; private final File swapReserveDir; private final long requiredSwapSegmentsPerSize; private final StorageManagerMetrics metrics; private final Map<String, ReserveFileMap> storeReserveFiles = new HashMap<>(); private final ReserveFileMap swapReserveFiles = new ReserveFileMap(); private PoolState poolState = PoolState.NOT_INVENTORIED; private Exception inventoryException = null; DiskSpaceAllocator(boolean enablePooling, File reserveDir, long requiredSwapSegmentsPerSize, StorageManagerMetrics metrics) { this.enablePooling = enablePooling; this.reserveDir = reserveDir; swapReserveDir = new File(reserveDir, SWAP_DIR_NAME); this.requiredSwapSegmentsPerSize = requiredSwapSegmentsPerSize; this.metrics = metrics; try { if (enablePooling) { prepareDirectory(reserveDir); prepareDirectory(swapReserveDir); inventoryExistingReserveFiles(); poolState = PoolState.INVENTORIED; } } catch (Exception e) { inventoryException = e; logger.error("Could not inventory preexisting reserve directory", e); } }
Source:
public void updateHandler_queryParams() { final String oldValue = "foo"; final String newValue = "foo bar"; Response response = db.save(new Foo(null, oldValue)); Params params = new Params() .addParam("field", "title") .addParam("value", newValue); String output = db.invokeUpdateHandler("example/example_update", response.getId(), params); Foo foo = db.find(Foo.class, response.getId()); assertNotNull(output); assertEquals(foo.getTitle(), newValue); }

Target:
public void updateHandler_queryParams() { final String oldValue = "foo"; final String newValue = "foo bar+plus=equals&ampersand"; Response response = db.save(new Foo(null, oldValue)); Params params = new Params() .addParam("field", "title") .addParam("value", newValue); String output = db.invokeUpdateHandler("example/example_update", response.getId(), params); Foo foo = db.find(Foo.class, response.getId()); assertNotNull(output); assertEquals(foo.getTitle(), newValue); }
Source:
public static @Nonnull Document parse(@Nonnull Reader stream) throws SAXException, IOException { DocumentBuilder docBuilder; try { docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unexpected error creating DocumentBuilder.", e); } return docBuilder.parse(new InputSource(stream)); }

Target:
public static @Nonnull Document parse(@Nonnull Reader stream) throws SAXException, IOException { DocumentBuilder docBuilder; try { docBuilder = newDocumentBuilderFactory().newDocumentBuilder(); docBuilder.setEntityResolver(RestrictiveEntityResolver.INSTANCE); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unexpected error creating DocumentBuilder.", e); } return docBuilder.parse(new InputSource(stream)); }