auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean needToCheckIndentation(Element element) { if (element.getChildNodes().getLength() > 1) { return true; } Node previous = element.getPreviousSibling(); if (isNonEmptyTextNode(previous)) { return false; } Node next = element.getNextSibling(); if (isNonEmptyTextNode(next)) { return false; } for (Node parent = element.getParentNode(); parent != null && parent.getChildNodes().getLength() == 1; parent = parent.getParentNode()) { short parentType = parent.getNodeType(); if (parentType == Node.ELEMENT_NODE) { Node parentPrev = parent.getPreviousSibling(); if (null != parentPrev && parentPrev.getNodeType() == Node.TEXT_NODE) { String text = parentPrev.getTextContent(); text = text.trim(); if (!text.isEmpty()) { return false; } } } } return true; }

Target:
private static boolean needToCheckIndentation(Element element) { if (element.getChildNodes().getLength() > 1) { return true; } Node previous = element.getPreviousSibling(); if (isNonEmptyTextNode(previous)) { return false; } Node next = element.getNextSibling(); if (isNonEmptyTextNode(next)) { return false; } for (Node parent = element.getParentNode(); parent != null && parent.getChildNodes().getLength() == 1; parent = parent.getParentNode()) { short parentType = parent.getNodeType(); if (parentType == Node.ELEMENT_NODE && isNonEmptyTextNode(parent.getPreviousSibling())) { return false; } } return true; }
Source:
public void addNewComment(@NonNull DiscussionComment parent) { String parentId = parent.getIdentifier(); if (!TextUtils.isEmpty(parentId)) { for (DiscussionComment response : discussionResponses) { if (parentId.equals(response.getIdentifier())) { response.setChildCount(response.getChildCount() + 1); notifyDataSetChanged(); break; } } } }

Target:
public void addNewComment(@NonNull DiscussionComment parent) { String parentId = parent.getIdentifier(); for (DiscussionComment response : discussionResponses) { if (parentId.equals(response.getIdentifier())) { response.incrementChildCount(); notifyDataSetChanged(); break; } } }
Source:
public boolean commitCursor(final String subscriptionId, final String eventType, final Cursor cursor) throws ServiceUnavailableException, NoSuchSubscriptionException { final String offsetPath = format("/nakadi/subscriptions/{0}/topics/{1}/{2}/offset", subscriptionId, eventType, cursor.getPartition()); try { return runLocked(() -> { final String currentOffset = new String(zkHolder.get().getData().forPath(offsetPath), CHARSET); if (topicRepository.compareOffsets(cursor.getOffset(), currentOffset) > 0) { zkHolder.get().setData().forPath(offsetPath, cursor.getOffset().getBytes(CHARSET)); return true; } else { return false; } }, zkLockFactory.createLock(offsetPath)); } catch (Exception e) { throw new ServiceUnavailableException("Error communicating with zookeeper", e); } }

Target:
private boolean commitCursor(final String subscriptionId, final String eventType, final Cursor cursor) throws ServiceUnavailableException, NoSuchSubscriptionException, InvalidCursorException { final String offsetPath = format("/nakadi/subscriptions/{0}/topics/{1}/{2}/offset", subscriptionId, eventType, cursor.getPartition()); try { return runLocked(() -> { final String currentOffset = new String(zkHolder.get().getData().forPath(offsetPath), CHARSET); if (topicRepository.compareOffsets(cursor.getOffset(), currentOffset) > 0) { zkHolder.get().setData().forPath(offsetPath, cursor.getOffset().getBytes(CHARSET)); return true; } else { return false; } }, zkLockFactory.createLock(offsetPath)); } catch (final IllegalArgumentException e) { throw new InvalidCursorException(CursorError.INVALID_FORMAT, cursor); } catch (Exception e) { throw new ServiceUnavailableException("Error communicating with zookeeper", e); } }
Source:
public void deleteActionDefinition() throws Exception { respondWith(204); HttpResponse resp = service.delete("concat"); assertEquals(resp.getStatus(), 204); }

Target:
public void deleteActionDefinition() throws Exception { respondWith(204); ActionResponse resp = service.delete("concat"); assertEquals(resp.getCode(), 200); }
Source:
public Configuration getConfiguration(GraphContext context) { ConditionBuilder applicationProjectModelsFound = Query .fromType(WindupConfigurationModel.class); AbstractIterationOperation<WindupConfigurationModel> addApplicationReport = new AbstractIterationOperation<WindupConfigurationModel>() { @Override public void perform(GraphRewrite event, EvaluationContext context, WindupConfigurationModel payload) { for (FileModel inputPath : payload.getInputPaths()) { ProjectModel projectModel = inputPath.getProjectModel(); if (projectModel == null) { throw new WindupException("Error, no project found in: " + inputPath.getFilePath()); } createReport(event.getGraphContext(), projectModel); } } @Override public String toString() { return "CreateJavaApplicationOverviewReport"; } }; return ConfigurationBuilder.begin() .addRule() .when(applicationProjectModelsFound) .perform(addApplicationReport); }

Target:
public Configuration getConfiguration(GraphContext context) { ConditionBuilder applicationProjectModelsFound = Query .fromType(WindupConfigurationModel.class); AbstractIterationOperation<WindupConfigurationModel> addApplicationReport = new AbstractIterationOperation<WindupConfigurationModel>() { @Override public void perform(GraphRewrite event, EvaluationContext context, WindupConfigurationModel payload) { for (FileModel inputPath : payload.getInputPaths()) { ProjectModel projectModel = inputPath.getProjectModel(); if (projectModel == null) { throw new WindupException("Error, no project found in: " + inputPath.getFilePath()); } createReport(event.getGraphContext(), projectModel); } } @Override public String toString() { return "CreatePotentialIssuesReportRuleProvider"; } }; return ConfigurationBuilder.begin() .addRule() .when(applicationProjectModelsFound) .perform(addApplicationReport); }
Source:
public static boolean checkImageConfiguration(storage_domain_static storageDomain, DiskImageBase diskInfo, List<String> messages, boolean isCopyCollapse) { boolean result = true; if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW) || !isCopyCollapse && isVolTypeAndFormatSupportedByBlockDevice(storageDomain, diskInfo) || (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) { result = false; messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString()); } return result; }

Target:
public static boolean checkImageConfiguration(storage_domain_static storageDomain, DiskImageBase diskInfo, List<String> messages, boolean isCopyCollapse) { boolean result = true; if ((diskInfo.getvolume_type() == VolumeType.Preallocated && diskInfo.getvolume_format() == VolumeFormat.COW) || (!isCopyCollapse && isVolTypeAndFormatSupportedByBlockDevice(storageDomain, diskInfo)) || (diskInfo.getvolume_format() == VolumeFormat.Unassigned || diskInfo.getvolume_type() == VolumeType.Unassigned)) { result = false; messages.add(VdcBllMessages.ACTION_TYPE_FAILED_DISK_CONFIGURATION_NOT_SUPPORTED.toString()); } return result; }
Source:
private void backupConfig(File backupDir) throws IOException { String configDirectory = systemEnvironment.getConfigDir(); try (ZipOutputStream configZip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File(backupDir, CONFIG_BACKUP_ZIP))));) { File cruiseConfigFile = new File(systemEnvironment.getCruiseConfigFile()); File cipherFile = systemEnvironment.getCipherFile(); new DirectoryStructureWalker(configDirectory, configZip, cruiseConfigFile, cipherFile).walk(); configZip.putNextEntry(new ZipEntry(cruiseConfigFile.getName())); IOUtils.write(goConfigService.xml(), configZip); configZip.putNextEntry(new ZipEntry(cipherFile.getName())); IOUtils.write(new CipherProvider(systemEnvironment).getKey(), configZip); } }

Target:
private void backupConfig(File backupDir) throws IOException { String configDirectory = systemEnvironment.getConfigDir(); try (ZipOutputStream configZip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(new File(backupDir, CONFIG_BACKUP_ZIP))))) { File cruiseConfigFile = new File(systemEnvironment.getCruiseConfigFile()); File cipherFile = systemEnvironment.getCipherFile(); new DirectoryStructureWalker(configDirectory, configZip, cruiseConfigFile, cipherFile).walk(); configZip.putNextEntry(new ZipEntry(cruiseConfigFile.getName())); IOUtils.write(goConfigService.xml(), configZip); configZip.putNextEntry(new ZipEntry(cipherFile.getName())); IOUtils.write(new CipherProvider(systemEnvironment).getKey(), configZip); } }
Source:
private HttpHost getHttpProxy(OMElement profile, String targetHosts) throws AxisFault { String proxyHost; String proxyPortStr; QName proxyHostQName = new QName("proxyHost"); QName proxyPortQName = new QName("proxyPort"); OMElement proxyHostEle = profile.getFirstChildWithName(proxyHostQName); if (proxyHostEle != null) { proxyHost = proxyHostEle.getText(); OMElement proxyPortEle = profile.getFirstChildWithName(proxyPortQName); if (proxyPortEle != null) { proxyPortStr = proxyPortEle.getText(); } else { throw new AxisFault("Proxy Port didn't configure correctly in proxy profile ["+targetHosts+"]"); } } else { throw new AxisFault("Proxy Host didn't configure correctly in proxy profile ["+targetHosts+"]"); } int proxyPort = Integer.parseInt(proxyPortStr); return new HttpHost(proxyHost, proxyPort >= 0 ? proxyPort : 80); }

Target:
private HttpHost getHttpProxy(OMElement profile, String targetHosts) throws AxisFault { String proxyHost; String proxyPortStr; OMElement proxyHostEle = profile.getFirstChildWithName(Q_PROXY_HOST); if (proxyHostEle != null) { proxyHost = proxyHostEle.getText(); OMElement proxyPortEle = profile.getFirstChildWithName(Q_PROXY_PORT); if (proxyPortEle != null) { proxyPortStr = proxyPortEle.getText(); } else { throw new AxisFault("Proxy Port didn't configure correctly in proxy profile [" + targetHosts + "]"); } } else { throw new AxisFault("Proxy Host didn't configure correctly in proxy profile [" + targetHosts + "]"); } int proxyPort = Integer.parseInt(proxyPortStr); return new HttpHost(proxyHost, proxyPort >= 0 ? proxyPort : 80); }
Source:
private Predicate<? super Node<E>> is(final E element) { return new Predicate<Node<E>>() { public boolean apply(Node<E> input) { return input != null && element != null && element.equals(input.getElement()); } }; }

Target:
private Predicate<? super Node<E>> is(final E element) { return new Predicate<Node<E>>() { public boolean apply(Node<E> input) { return input != null && input.getElement().equals(element); } }; }
Source:
public static void assertResult(TupleQueryResult result, Matcher<BindingSet>... bindingMatchers) { int position = 0; try { for (Matcher<BindingSet> bindingMatcher : bindingMatchers) { position++; assertTrue("There should be at least " + position + " results", result.hasNext()); BindingSet bs = result.next(); assertThat(bs, bindingMatcher); System.out.println("#"+position+" "+bs); } assertFalse("There should be no more than " + position + " result", result.hasNext()); result.close(); } catch (QueryEvaluationException e) { throw new RuntimeException(e); } finally { try { while (result.hasNext()) { position++; BindingSet bs = result.next(); System.out.println("#"+position+" "+bs); } } catch (QueryEvaluationException e) { e.printStackTrace(); } } }

Target:
public static void assertResult(TupleQueryResult result, Matcher<BindingSet>... bindingMatchers) { try { int position = 0; for (Matcher<BindingSet> bindingMatcher : bindingMatchers) { position++; assertTrue("There should be at least " + position + " results", result.hasNext()); assertThat(result.next(), bindingMatcher); } assertFalse("There should be no more than " + position + " result", result.hasNext()); result.close(); } catch (QueryEvaluationException e) { throw new RuntimeException(e); } }
Source:
public void compileInMemoryJarfile(InMemoryJarfile jarfile) throws IOException { List<VoltCompilerReader> ddlReaderList = new ArrayList<>(); Entry<String, byte[]> entry = jarfile.firstEntry(); while (entry != null) { String path = entry.getKey(); if (path.toLowerCase().endsWith(".sql")) { ddlReaderList.add(new VoltCompilerJarFileReader(jarfile, path)); compilerLog.trace("Added SQL file from jarfile to compilation: " + path); } entry = jarfile.higherEntry(entry.getKey()); } ClassLoader originalClassLoader = m_classLoader; try { m_classLoader = jarfile.getLoader(); InMemoryJarfile jarOut = compileInternal(null, null, ddlReaderList, jarfile, false); if (jarOut != null) { compilerLog.debug("Successfully recompiled InMemoryJarfile"); } else { String errString = "Adhoc DDL failed"; if (m_errors.size() > 0) { errString = m_errors.get(m_errors.size() - 1).getLogString(); } int fronttrim = errString.indexOf("DDL Error"); if (fronttrim < 0) { fronttrim = 0; } int endtrim = errString.indexOf(" in statement starting"); if (endtrim < 0) { endtrim = errString.length(); } String trimmed = errString.substring(fronttrim, endtrim); throw new IOException(trimmed); } } finally { m_classLoader = originalClassLoader; } }

Target:
public void compileInMemoryJarfile(InMemoryJarfile jarfile) throws IOException { List<VoltCompilerReader> ddlReaderList = new ArrayList<>(); Entry<String, byte[]> entry = jarfile.firstEntry(); while (entry != null) { String path = entry.getKey(); if (path.toLowerCase().endsWith(".sql")) { ddlReaderList.add(new VoltCompilerJarFileReader(jarfile, path)); compilerLog.trace("Added SQL file from jarfile to compilation: " + path); } entry = jarfile.higherEntry(entry.getKey()); } ClassLoader originalClassLoader = m_classLoader; try { m_classLoader = jarfile.getLoader(); InMemoryJarfile jarOut = compileInternal(null, null, ddlReaderList, jarfile); if (jarOut != null) { compilerLog.debug("Successfully recompiled InMemoryJarfile"); } else { String errString = "Adhoc DDL failed"; if (m_errors.size() > 0) { errString = m_errors.get(m_errors.size() - 1).getLogString(); } int fronttrim = errString.indexOf("DDL Error"); if (fronttrim < 0) { fronttrim = 0; } int endtrim = errString.indexOf(" in statement starting"); if (endtrim < 0) { endtrim = errString.length(); } String trimmed = errString.substring(fronttrim, endtrim); throw new IOException(trimmed); } } finally { m_classLoader = originalClassLoader; } }
Source:
private Description testType(Tree type) { if (type == null) { return Description.NO_MATCH; } Type realType = ASTHelpers.getType(type); if (realType != null && realType.isRaw()) { return buildDescription(type) .setMessage("Avoid raw types; add appropriate type parameters if possible. " + "The type was: " + realType + "\nThis can be suppressed with @SuppressWarnings(\"rawtypes\") " + "where necessary, such as when interacting with older library code.") .build(); } if (type.getKind() == Tree.Kind.PARAMETERIZED_TYPE) { return testTypes(((ParameterizedTypeTree) type).getTypeArguments()); } return Description.NO_MATCH; }

Target:
private Description testType(Tree type) { if (type == null) { return Description.NO_MATCH; } Type realType = ASTHelpers.getType(type); if (realType != null && realType.isRaw()) { return buildDescription(type) .setMessage("Avoid raw types; add appropriate type parameters if possible. " + "The type was: " + MoreSuggestedFixes.prettyType(null, null, realType) + "\nThis can be suppressed with @SuppressWarnings(\"rawtypes\") " + "where necessary, such as when interacting with older library code.") .build(); } if (type.getKind() == Tree.Kind.PARAMETERIZED_TYPE) { return testTypes(((ParameterizedTypeTree) type).getTypeArguments()); } return Description.NO_MATCH; }
Source:
public static void removeDirectoryEntryToDelete(String directoryName, String entryId) { Optional.ofNullable(directoryEntryIdsToDelete.get(directoryName)) .ifPresent(entryIds -> entryIds.remove(entryId)); }

Target:
public static void removeDirectoryEntryToDelete(String directoryName, String entryId) { directoryEntryIdsToDelete.getOrDefault(directoryName, Collections.emptySet()).remove(entryId); }
Source:
private static boolean hasAuthAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { if (annotation.annotationType() == HeaderParam.class) { String value = ((HeaderParam) annotation).value(); if (value.equals(HttpHeaders.AUTHORIZATION)) { return true; } } } return false; }

Target:
private static boolean hasAuthAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { if (HeaderParam.class.equals(annotation.annotationType())) { String value = ((HeaderParam) annotation).value(); if (HttpHeaders.AUTHORIZATION.equals(value)) { return true; } } } return false; }
Source:
private void bindProperty(String prefix, String name, String value) { String key = prefix == null ? name : (prefix + name); Set<String> aliasesForName = bindMap.get(name); if (value == null) { LOG.debug("Binding `{}` to `null`", key); bind(String.class).annotatedWith(Names.named(key)).toProvider(Providers.<String>of(null)); if (aliasesForName != null) { for (String alias : aliasesForName) { LOG.debug("Binding `{}` to `null`", alias); bind(String.class) .annotatedWith(Names.named(prefix == null ? alias : prefix + alias)) .toProvider(Providers.<String>of(null)); } } } else { LOG.debug("Binding `{}` to `{}`", key, value); bindConstant().annotatedWith(Names.named(key)).to(value); if (aliasesForName != null) { for (String alias : aliasesForName) { LOG.debug("Binding `{}` to `{}`", key, value); bindConstant() .annotatedWith(Names.named(prefix == null ? alias : prefix + alias)) .to(value); } } } }

Target:
private void bindProperty(String prefix, String name, String value) { String key = prefix == null ? name : (prefix + name); Set<String> aliasesForName = bindMap.get(name); if (value == null) { LOG.debug("Binding `{}` to `null`", key); bind(String.class).annotatedWith(Names.named(key)).toProvider(Providers.<String>of(null)); if (aliasesForName != null) { for (String alias : aliasesForName) { String bindKey = prefix == null ? alias : prefix + alias; LOG.debug("Binding `{}` to `null`", bindKey); bind(String.class) .annotatedWith(Names.named(bindKey)) .toProvider(Providers.<String>of(null)); } } } else { LOG.debug("Binding `{}` to `{}`", key, value); bindConstant().annotatedWith(Names.named(key)).to(value); if (aliasesForName != null) { for (String alias : aliasesForName) { String bindKey = prefix == null ? alias : prefix + alias; LOG.debug("Binding `{}` to `{}`", bindKey, value); bindConstant().annotatedWith(Names.named(bindKey)).to(value); } } } }
Source:
private void resetCluster(FileSystemMaster fsm) throws Exception { if (!mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().isServing()) { mCluster.mLocalAlluxioCluster.start(); fsm = mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().getMasterProcess() .getMaster(FileSystemMaster.class); } fsm.updateUfsMode(new AlluxioURI(fsm.getUfsAddress()), UfsMode.READ_WRITE); for (FileInfo fileInfo : fsm .listStatus(new AlluxioURI("/"), ListStatusContext.defaults())) { fsm.delete(new AlluxioURI(fileInfo.getPath()), DeleteContext .create(DeletePOptions.newBuilder().setUnchecked(true).setRecursive(true))); } }

Target:
private void resetCluster(FileSystemMaster fsm) throws Exception { fsm.updateUfsMode(new AlluxioURI(fsm.getUfsAddress()), UfsMode.READ_WRITE); for (FileInfo fileInfo : fsm .listStatus(new AlluxioURI("/"), ListStatusContext.defaults())) { fsm.delete(new AlluxioURI(fileInfo.getPath()), DeleteContext .create(DeletePOptions.newBuilder().setUnchecked(true).setRecursive(true))); } }
Source:
private boolean isEntity(Object o){ Class<? extends Object> varClass = o.getClass(); EntityManager em = getEntityManager(); if( em != null ){ Set<EntityType<?>> entities = em.getMetamodel().getEntities(); for( EntityType<?> entity : entities ){ if( varClass.getCanonicalName().equals( entity.getJavaType().getCanonicalName() ) ){ return true; } } } return false; }

Target:
private boolean isEntity(Object o){ Class<? extends Object> varClass = o.getClass(); return managedClasses.contains( varClass.getCanonicalName() ); }
Source:
public void testResolveFragmentWithDistro_FAIL() throws Exception { File f = IO.getFile("testdata/repo9/fragment.bndrun"); File index = IO.getFile("testdata/repo9/index.xml"); File distro = IO.getFile("testdata/release.dxp.distro-7.2.10.jar"); try (Run run = Run.createRun(null, f)) { run.setProperty("-distro", distro.getAbsolutePath() + ";version=file"); BndrunResolveContext context = new BndrunResolveContext(run, run, run.getWorkspace(), log); context.setLevel(0); context.init(); RunResolution resolution = RunResolution.resolve(run, null); if (resolution.isOK()) { fail( "should have failed because there are no 'osgi.wiring.host' capablities added to the system resource"); } } }

Target:
public void testResolveFragmentWithDistro_FAIL() throws Exception { File f = IO.getFile("testdata/repo9/fragment.bndrun"); File distro = IO.getFile("testdata/release.dxp.distro-7.2.10.jar"); try (Run run = Run.createRun(null, f)) { run.setProperty("-distro", distro.getAbsolutePath() + ";version=file"); BndrunResolveContext context = new BndrunResolveContext(run, run, run.getWorkspace(), log); context.setLevel(0); context.init(); RunResolution resolution = RunResolution.resolve(run, null); if (resolution.isOK()) { fail( "should have failed because there are no 'osgi.wiring.host' capablities added to the system resource"); } } }
Source:
public int hashCode() { int result = Objects.hash(type); for (int i = 0; i < values.length; i++) { DataType innerThisType = type.getComponentTypes().get(i); TypeCodec thisCodec = this.codecRegistry().codecFor(innerThisType); if (thisCodec == null) { LOG.warn( "No codec found for tuple type " + innerThisType.toString() + " falling bytes for hashcode"); return 31 * Objects.hash(type) + Arrays.hashCode(values); } Object thisValue = this.codecRegistry() .codecFor(innerThisType) .decode(this.values[i], this.protocolVersion()); result = 31 * result + thisValue.hashCode(); } return result; }

Target:
public int hashCode() { int result = type.hashCode(); for (int i = 0; i < values.length; i++) { DataType innerThisType = type.getComponentTypes().get(i); Object thisValue = this.codecRegistry() .codecFor(innerThisType) .decode(this.values[i], this.protocolVersion()); result = 31 * result + thisValue.hashCode(); } return result; }
Source:
private void performDirectEdit(SelectionRequest request) { NewInstanceDirectEditManager directEditMaanger = getManager(); directEditMaanger.updateRefPosition(new Point(request.getLocation().x, request.getLocation().y)); if (request.getExtendedData().isEmpty()) { directEditMaanger.show(); } else { Object key = request.getExtendedData().keySet().iterator().next(); if (key instanceof String) { directEditMaanger.show((String) key); } } }

Target:
private void performDirectEdit(SelectionRequest request) { NewInstanceDirectEditManager directEditManager = getManager(); directEditManager.updateRefPosition(new Point(request.getLocation().x, request.getLocation().y)); if (request.getExtendedData().isEmpty()) { directEditManager.show(); } else { Object key = request.getExtendedData().keySet().iterator().next(); if (key instanceof String) { directEditManager.show((String) key); } } }
Source:
protected void waitUntilServerIsUp(String host, long time, TimeUnit timeUnit) throws TimeoutException { long startTime = System.currentTimeMillis(); long waitMillis = timeUnit.toMillis(time); boolean connected = false; while (!connected) { if(System.currentTimeMillis() > startTime + waitMillis) { throw new TimeoutException("Server " + host + " is still down after " + waitMillis + " ms"); } try { URL healthUrl = new URL(host + "/dolphin"); URLConnection connection = healthUrl.openConnection(); if(connection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.connect(); if(httpURLConnection.getResponseCode() == 405) { connected = true; } } else { throw new IOException("URL " + healthUrl + " do not provide a HttpURLConnection!"); } } catch (Exception e) { } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } }

Target:
protected void waitUntilServerIsUp(String host, long time, TimeUnit timeUnit) throws TimeoutException { long startTime = System.currentTimeMillis(); long waitMillis = timeUnit.toMillis(time); boolean connected = false; while (!connected) { if(System.currentTimeMillis() > startTime + waitMillis) { throw new TimeoutException("Server " + host + " is still down after " + waitMillis + " ms"); } try { URL healthUrl = new URL(host + "/rest/health"); URLConnection connection = healthUrl.openConnection(); if(connection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) connection; httpURLConnection.connect(); if(httpURLConnection.getResponseCode() == 200) { connected = true; } } else { throw new IOException("URL " + healthUrl + " do not provide a HttpURLConnection!"); } } catch (Exception e) { } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
Source:
public Value valueOf(@Nullable Object object) { if(object == null) { return nullValue(); } Class<?> type = object.getClass(); Collection<Coordinate> line = new ArrayList<Coordinate>(); if(type.equals(getJavaClass())) { if(((Collection<?>) object).isEmpty()) { throw new MagmaRuntimeException("A Line can't be empty"); } for(Object o : (List<?>) object) { if(o.getClass().equals(Coordinate.class)) { line.add((Coordinate) o); } else if(o.getClass().equals(String.class)) { line.add(Coordinate.valueOf((String) o)); } } return Factory.newValue(this, (Serializable) line); } if(type.equals(String.class)) { return valueOf((String) object); } if(type.equals(JSONArray.class)) { return valueOf(object.toString()); } throw new IllegalArgumentException( "Cannot construct " + getClass().getSimpleName() + " from type " + object.getClass() + "."); }

Target:
public Value valueOf(@Nullable Object object) { if(object == null) { return nullValue(); } Class<?> type = object.getClass(); if(type.equals(String.class)) { return valueOf((String) object); } if(type.equals(JSONArray.class)) { return valueOf((JSONArray) object); } if(type.equals(getJavaClass())) { Collection<Coordinate> line = new ArrayList<Coordinate>(); for(Object o : (List<?>) object) { line.add(Coordinate.getCoordinateFrom(o)); } if(line.isEmpty()) { throw new MagmaRuntimeException("The Line can't be empty"); } return Factory.newValue(this, (Serializable) line); } throw new IllegalArgumentException( "Cannot construct " + getClass().getSimpleName() + " from type " + object.getClass() + "."); }
Source:
public void testOpenApiYaml() { JsonResponse<Map<String, Object>> response = client.execute( prepareGet().setUri(uriForOpenJSon("/openapi/api.yaml")).build(), createFullJsonResponseHandler(MAP_CODEC)); assertNotNull(response.getResponseBody()); }

Target:
public void testOpenApiYaml() { StringResponse response = client.execute( prepareGet().setUri(uriForOpenSpec("/admin/openapi.yaml")).build(), createStringResponseHandler()); assertEquals(response.getStatusCode(), 200); assertEquals(response.getHeader("Content-Type"), "application/yaml"); assertContains(response.getBody(), "summary: Testing GET request"); assertContains(response.getBody(), "description: One or more query parameter(s) is null or empty"); }
Source:
public List<AccurevTransaction> filterBySubpath(List<AccurevTransaction> transactions) { List<AccurevTransaction> trans = new ArrayList<>(); logger.info("using subpath:" + getSubpath()); List<String> subpaths = new ArrayList<String>(); final StringTokenizer st = new StringTokenizer(getSubpath(), ","); while (st.hasMoreElements()) { String path = st.nextToken().trim(); path = path.replace("*", ""); logger.info("path:" + path); subpaths.add(path); } logger.info("subpaths size:" + subpaths.size()); for (AccurevTransaction transaction : transactions) { boolean isValid = false; for (String rawPath : transaction.getAffectedRawPaths()) { if (isValid) { logger.info("transaction is valid :" + transaction.getId()); logger.info("no need check files in this transaction"); break; } logger.info("rawPath:" + rawPath); for (String subpath : subpaths) { logger.info("rawPath.contains(subpath):" + rawPath.contains(subpath)); if (rawPath.contains(subpath)) { isValid = true; break; } else { isValid = false; } } } if (!isValid) { logger.info("not adding transaction to list:" + transaction.getId()); } else { logger.info("adding transaction to list:" + transaction.getId()); trans.add(transaction); } } return trans; }

Target:
public List<AccurevTransaction> filterBySubpath(List<AccurevTransaction> transactions) { List<AccurevTransaction> trans = new ArrayList<>(); logger.fine("using subpath:" + getSubpath()); List<String> subpaths = new ArrayList<String>(); final StringTokenizer st = new StringTokenizer(getSubpath(), ","); while (st.hasMoreElements()) { String path = st.nextToken().trim(); path = path.replace("*", ""); logger.fine("path:" + path); subpaths.add(path); } logger.fine("subpaths size:" + subpaths.size()); for (AccurevTransaction transaction : transactions) { boolean isValid = false; for (String rawPath : transaction.getAffectedRawPaths()) { if (isValid) { logger.fine("transaction is valid :" + transaction.getId()); logger.fine("no need check files in this transaction"); break; } logger.fine("rawPath:" + rawPath); for (String subpath : subpaths) { logger.fine("rawPath.contains(subpath):" + rawPath.contains(subpath)); if (rawPath.contains(subpath)) { isValid = true; break; } else { isValid = false; } } } if (!isValid) { logger.fine("not adding transaction to list:" + transaction.getId()); } else { logger.fine("adding transaction to list:" + transaction.getId()); trans.add(transaction); } } return trans; }
Source:
public Boolean getisValueTypeCorrect() { if (this.xmpNode.getChildren().size() != 5) { return Boolean.FALSE; } VeraPDFXMPNode namespace = null; VeraPDFXMPNode prefix = null; VeraPDFXMPNode property = null; VeraPDFXMPNode schema = null; VeraPDFXMPNode valueType = null; for (VeraPDFXMPNode child : this.xmpNode.getChildren()) { if (XMPSchemaRegistryImpl.NS_PDFA_SCHEMA.equals(child.getNamespaceURI())) { switch (child.getName()) { case "namespaceURI": namespace = child; break; case "prefix": prefix = child; break; case "property": property = child; break; case "schema": schema = child; break; case "valueType": valueType = child; break; } } } return Boolean.valueOf(namespace != null && prefix != null && property != null && schema != null && valueType != null); }

Target:
public Boolean getisValueTypeCorrect() { boolean isValid = true; boolean isNamespacePresent = false; boolean isPrefixPresent = false; boolean isPropertyPresent = false; boolean isSchemaPresent = false; boolean isValueTypePresent = false; for (VeraPDFXMPNode child : this.xmpNode.getChildren()) { if (XMPSchemaRegistryImpl.NS_PDFA_SCHEMA.equals(child.getNamespaceURI())) { switch (child.getName()) { case "namespaceURI": if (isNamespacePresent) { isValid = false; } else { isNamespacePresent = true; } break; case "prefix": if (isPrefixPresent) { isValid = false; } else { isPrefixPresent = true; } break; case "property": if (isPropertyPresent) { isValid = false; } else { isPropertyPresent = true; } break; case "schema": if (isSchemaPresent) { isValid = false; } else { isSchemaPresent = true; } break; case "valueType": if (isValueTypePresent) { isValid = false; } else { isValueTypePresent = true; } break; default: isValid = false; } } else { isValid = false; } } return Boolean.valueOf(isValid); }
Source:
public FetchCommand setProgressMonitor(ProgressMonitor monitor) { this.monitor = monitor; return this; }

Target:
public FetchCommand setProgressMonitor(ProgressMonitor monitor) { checkCallable(); this.monitor = monitor; return this; }
Source:
public void close() throws IOException { System.out.println("* * * ** * * * * " + schema.toString()); delegate.close(); }

Target:
public void close() throws IOException { delegate.close(); }
Source:
public void registerJobs() { List<AuthenticationMethod> authenticationMethods; try { authenticationMethods = this.securityService.getAuthenticationMethods(); } catch (Exception e) { logger.warn("Unable to retrieve ldap configuration details. This has most likely occurred as a result" + " of the dashboard database not yet being created."); return; } authenticationMethods.forEach(authenticationMethod -> { if (authenticationMethod.isScheduled()) { LdapDirectorySynchronisationJob job = new LdapDirectorySynchronisationJob(authenticationMethod, this.ldapService, this.securityService); JobDetail jobDetail = this.scheduledJobFactory.createJobDetail (job, BusinessStreamNotificationJob.class, job.getJobName(), "scheduled-ldap"); super.jobDetails.add(jobDetail); super.dashboardJobDetailsMap.put(job.getJobName(), jobDetail); this.dashboardJobsMap.put(jobDetail.getKey().toString(), job); } }); for (JobDetail jobDetail : this.jobDetails) { logger.info(String.format("Registering ldap synchronisation job[%s]", jobDetail.getKey().getName())); this.addJob(jobDetail.getKey().getName()); } }

Target:
public void registerJobs() { List<AuthenticationMethod> authenticationMethods; try { authenticationMethods = this.securityService.getAuthenticationMethods(); } catch (Exception e) { logger.warn("Unable to retrieve ldap configuration details. This has most likely occurred as a result" + " of the dashboard database not yet being created."); return; } authenticationMethods.forEach(authenticationMethod -> { if (authenticationMethod.isScheduled()) { LdapDirectorySynchronisationJob job = new LdapDirectorySynchronisationJob(authenticationMethod, this.ldapService, this.securityService); JobDetail jobDetail = this.scheduledJobFactory.createJobDetail (job, LdapDirectorySynchronisationJob.class, job.getJobName(), "scheduled-ldap"); super.dashboardJobDetailsMap.put(job.getJobName(), jobDetail); super.dashboardJobsMap.put(jobDetail.getKey().toString(), job); } }); for (JobDetail jobDetail : super.dashboardJobDetailsMap.values()) { logger.info(String.format("Registering ldap synchronisation job[%s]", jobDetail.getKey().getName())); this.addJob(jobDetail.getKey().getName()); } }
Source:
private FieldDescriptor getFieldDescriptor(Descriptor messageDescriptor, String attributePath) { FieldDescriptor fd = null; String[] split = attributePath.split("[.]"); for (int i = 0; i < split.length; i++) { String name = split[i]; fd = messageDescriptor.findFieldByName(name); if (fd == null) { throw new IllegalArgumentException("Unknown field " + name + " in type " + messageDescriptor.getFullName()); } IndexingMetadata indexingMetadata = messageDescriptor.getProcessedAnnotation(IndexingMetadata.INDEXED_ANNOTATION); if (indexingMetadata != null && !indexingMetadata.isFieldIndexed(fd.getNumber())) { throw new IllegalArgumentException("Field " + name + " from type " + messageDescriptor.getFullName() + " is not indexed"); } if (i < split.length - 1) { messageDescriptor = fd.getMessageType(); } } return fd; }

Target:
private FieldDescriptor getFieldDescriptor(Descriptor messageDescriptor, String attributePath) { FieldDescriptor fd = null; String[] split = attributePath.split("[.]"); for (int i = 0; i < split.length; i++) { String name = split[i]; fd = messageDescriptor.findFieldByName(name); if (fd == null) { throw log.unknownField(name, messageDescriptor.getFullName()); } IndexingMetadata indexingMetadata = messageDescriptor.getProcessedAnnotation(IndexingMetadata.INDEXED_ANNOTATION); if (indexingMetadata != null && !indexingMetadata.isFieldIndexed(fd.getNumber())) { throw log.fieldIsNotIndexed(name, messageDescriptor.getFullName()); } if (i < split.length - 1) { messageDescriptor = fd.getMessageType(); } } return fd; }
Source:
public void menuDetected(MenuDetectEvent e) { if (null == _timeProvider) { return; } Point p = toControl(e.x, e.y); int idx = getItemIndexAtY(p.y); if (idx >= 0 && idx < _data._expandedItems.length) { Item item = _data._expandedItems[idx]; ITimeGraphEntry entry = item._trace; if (entry.hasTimeEvents()) { ITimeEvent event = Utils.findEvent(entry, getTimeAtX(p.x), 2); if (event != null) { e.data = event; fireMenuEventOnTimeEvent(e); return; } } e.data = entry; fireMenuEventOnTimeGraphEntry(e); } }

Target:
public void menuDetected(MenuDetectEvent e) { fPendingMenuDetectEvent = e; return; }
Source:
protected void onPostExecute(Encounters encountersWithObservations) { if (encountersWithObservations == null) { Toast.makeText(observationsByEncounterAdapter.getContext(),"This patient does not have any SHR data.", Toast.LENGTH_SHORT).show(); return; } if (observationsByEncounterAdapter.getBackgroundListQueryTaskListener() != null) { observationsByEncounterAdapter.getBackgroundListQueryTaskListener().onQueryTaskFinish(); } }

Target:
protected void onPostExecute(Encounters encountersWithObservations) { if (encountersWithObservations == null) { return; } if (observationsByEncounterAdapter.getBackgroundListQueryTaskListener() != null) { observationsByEncounterAdapter.getBackgroundListQueryTaskListener().onQueryTaskFinish(); } }
Source:
protected void updatePreviewContent() { text.setText(formatText(getWizard().getTextForTextView())); if(browser == null) { return; } File f = getFile(); FileUtil.writeFile(f, getWizard().getTextForBrowser()); final Control c = Display.getCurrent().getFocusControl(); if(browser.getUrl() == null || !browser.getUrl().endsWith(f.getName()) ||"mozilla".equals(getBrowserType())) { browser.setUrl(url); } else { browser.refresh(); } if(c != null) { Display.getCurrent().asyncExec(new Runnable() { public void run() { c.forceFocus(); } }); } }

Target:
protected void updatePreviewContent() { text.setText(formatText(getWizard().getTextForTextView())); if(browser == null) { return; } File f = getFile(); FileUtil.writeFile(f, getWizard().getTextForBrowser()); final Control c = Display.getCurrent().getFocusControl(); if(browser.getUrl() == null || !browser.getUrl().endsWith(f.getName()) ||"mozilla".equals(getBrowserType())) { browser.setUrl(sourceURL); } else { browser.refresh(); } if(c != null) { Display.getCurrent().asyncExec(new Runnable() { public void run() { c.forceFocus(); } }); } }
Source:
private void updateButtonsAfterStatusChange() { boolean anyDeselected = false; boolean anySelected = false; for (FormStatus f : formStatuses) { anyDeselected = anyDeselected || !f.isSelected(); anySelected = anySelected || f.isSelected(); } btnTransfer.setEnabled(anySelected && (txtDestinationName == null || !TextUtils.isEmpty(txtDestinationName.getText()))); if (!anyDeselected) { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Clear all"); } else { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Select all"); } }

Target:
private void updateButtonsAfterStatusChange() { boolean anyDeselected = false; boolean anySelected = false; for (FormStatus f : formStatuses) { anyDeselected = anyDeselected || !f.isSelected(); anySelected = anySelected || f.isSelected(); } btnTransfer.setEnabled(anySelected && sourceSelected); if (!anyDeselected) { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Clear all"); } else { FormTransferTableModel.this.btnSelectOrClearAllForms.setText("Select all"); } }
Source:
public static void copy(File source, File destination, File root, boolean overwrite) throws IOException { File sourceFile = new File(source, root.getPath()); if (!sourceFile.exists()) throw new FileNotFoundException("Source: " + sourceFile + " does not exist"); File destinationFile = new File(destination, root.getPath()); if (destinationFile.exists()) if (overwrite) deleteAll(destinationFile); else throw new IOException("Destination: " + destinationFile + " already exists"); if (sourceFile.isDirectory()) { destinationFile.mkdirs(); File[] list = sourceFile.listFiles(); for (File list1 : list) { copy(source, destination, new File(root, list1.getName()), false); } } else { destinationFile.getParentFile().mkdirs(); try (InputStream in = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream out = new BufferedOutputStream(new FileOutputStream(destinationFile));) { copyStream(in, false, out, false); } } }

Target:
public static void copy(File source, File destination, File root, boolean overwrite) throws IOException { File sourceFile = new File(source, root.getPath()); if (!sourceFile.exists()) throw new FileNotFoundException("Source: " + sourceFile + " does not exist"); File destinationFile = new File(destination, root.getPath()); if (destinationFile.exists()) if (overwrite) deleteAll(destinationFile); else throw new IOException("Destination: " + destinationFile + " already exists"); if (sourceFile.isDirectory()) { destinationFile.mkdirs(); File[] list = sourceFile.listFiles(); for (File file : list) { copy(source, destination, new File(root, file.getName()), false); } } else { destinationFile.getParentFile().mkdirs(); try (InputStream in = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream out = new BufferedOutputStream(new FileOutputStream(destinationFile));) { copyStream(in, false, out, false); } } }
Source:
public EventTemplate(String input, EventUtil eventUtil) { this.input = Objects.requireNonNull(input); this.eventUtil = Objects.requireNonNull(eventUtil); this.parameterResolverRegistry = new ExpandableParameterResolverRegistry(); parse(); }

Target:
public EventTemplate(String input, EventUtil eventUtil) { this.input = Objects.requireNonNull(input); this.eventUtil = Objects.requireNonNull(eventUtil); parse(); this.requiresTransaction = tokens.stream().filter(t -> t.requiresTransaction()).findAny().isPresent(); }
Source:
public ArrayList<Object> executePostRequest(HttpPost postRequest) throws OpenStackException { HttpResponse response; CloseableHttpClient httpClient = getHttpClient(); ArrayList<Object> message = new ArrayList(); Date localDate = null; String aux; try { response = httpClient.execute(postRequest); localDate = new Date(); if ((response.getStatusLine().getStatusCode() != 201) && (response.getStatusLine().getStatusCode() != 200)) { log.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String temp = ""; while ((aux = br.readLine()) != null) { temp += aux; } message.add(temp); String aux1 = response.getHeaders("Date")[0].getValue(); log.info("Date recibido: " + aux1); message.add(response.getHeaders("Date")[0].getValue()); HttpEntity ent = response.getEntity(); if (ent != null) { EntityUtils.consume(ent); } } catch (ClientProtocolException ex) { log.error("Client protocol exception"); throw new OpenStackException("Client protocol exception " + ex.getMessage()); } catch (IOException ex) { log.error("I/O exception of some sort has occurred"); throw new OpenStackException("I/O exception of some sort has occurred " + ex.getMessage()); } return message; }

Target:
public ArrayList<Object> executePostRequest(HttpPost postRequest) throws OpenStackException { HttpResponse response; CloseableHttpClient httpClient = getHttpClient(); ArrayList<Object> message = new ArrayList(); String aux; try { response = httpClient.execute(postRequest); int statusCode = response.getStatusLine().getStatusCode(); if ((statusCode != 201) && (statusCode != 200)) { String errorMessage = "Failed : HTTP error code : " + statusCode; log.error(errorMessage); throw new RuntimeException(errorMessage); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String temp = ""; while ((aux = br.readLine()) != null) { temp += aux; } message.add(temp); String aux1 = response.getHeaders("Date")[0].getValue(); log.info("Date recibido: " + aux1); message.add(response.getHeaders("Date")[0].getValue()); HttpEntity ent = response.getEntity(); if (ent != null) { EntityUtils.consume(ent); } } catch (ClientProtocolException ex) { log.error("Client protocol exception"); throw new OpenStackException("Client protocol exception " + ex.getMessage()); } catch (IOException ex) { log.error("I/O exception of some sort has occurred"); throw new OpenStackException("I/O exception of some sort has occurred " + ex.getMessage()); } return message; }
Source:
private MyqBindingConfig parseBindingConfig(Item item, String bindingConfig) throws BindingConfigParseException { final MyqBindingConfig config = new MyqBindingConfig(); if (item instanceof SwitchItem) { config.type = ITEMTYPE.Switch; } else if (item instanceof RollershutterItem) { config.type = ITEMTYPE.Rollershutter; } else if (item instanceof ContactItem) { config.type = ITEMTYPE.ContactStatus; } else if (item instanceof StringItem) { config.type = ITEMTYPE.StringStatus; } config.deviceIndex = Integer.parseInt(bindingConfig); return config; }

Target:
private MyqBindingConfig parseBindingConfig(Item item, String bindingConfig) throws BindingConfigParseException { final MyqBindingConfig config = new MyqBindingConfig(); config.acceptedDataTypes = new ArrayList<Class<? extends State>>( item.getAcceptedDataTypes()); config.deviceIndex = Integer.parseInt(bindingConfig); return config; }
Source:
private void createServerStore(ClientDescriptor clientDescriptor, CreateServerStore createServerStore) throws ClusterException { validateClusteredTierManagerConfigured(clientDescriptor); if(createServerStore.getStoreConfiguration().getPoolAllocation() instanceof PoolAllocation.Unknown) { throw new LifecycleException("Clustered tier can't be created with an Unknown resource pool"); } boolean isDuplicate = isLifeCycleMessageDuplicate(createServerStore); final String name = createServerStore.getName(); ServerStoreImpl serverStore; if (!isDuplicate) { LOGGER.info("Client creating new clustered tier '{}'", clientDescriptor, name); ServerStoreConfiguration storeConfiguration = createServerStore.getStoreConfiguration(); serverStore = ehcacheStateService.createStore(name, storeConfiguration); management.serverStoreCreated(name); } else { serverStore = ehcacheStateService.getStore(name); } serverStore.setEvictionListener(key -> invalidateHashAfterEviction(name, key)); attachStore(clientDescriptor, name); try { entityMessenger.messageSelfAndDeferRetirement(createServerStore, new ClientIDTrackerMessage.ServerStoreLifeCycleReplicationMessage(createServerStore)); } catch (MessageCodecException e) { LOGGER.error("Codec Exception", e); } }

Target:
private void createServerStore(ClientDescriptor clientDescriptor, CreateServerStore createServerStore) throws ClusterException { validateClusteredTierManagerConfigured(clientDescriptor); if(createServerStore.getStoreConfiguration().getPoolAllocation() instanceof PoolAllocation.Unknown) { throw new LifecycleException("Clustered tier can't be created with an Unknown resource pool"); } boolean isDuplicate = isLifeCycleMessageDuplicate(createServerStore); final String name = createServerStore.getName(); ServerStoreImpl serverStore; if (!isDuplicate) { LOGGER.info("Client creating new clustered tier '{}'", clientDescriptor, name); ServerStoreConfiguration storeConfiguration = createServerStore.getStoreConfiguration(); serverStore = ehcacheStateService.createStore(name, storeConfiguration); management.serverStoreCreated(name); } else { serverStore = ehcacheStateService.getStore(name); } serverStore.setEvictionListener(key -> invalidateHashAfterEviction(name, key)); attachStore(clientDescriptor, name); try { entityMessenger.messageSelfAndDeferRetirement(createServerStore, new ClientIDTrackerMessage.ServerStoreLifeCycleReplicationMessage(createServerStore)); } catch (MessageCodecException e) { throw new AssertionError("Codec error", e); } }