auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static boolean exists(Object path) { if (path instanceof String) { return Files.exists(Paths.get((String) path)); } if (path instanceof Path) { return Files.exists(((Path) path)); } if (path instanceof File) { return ((File) path).exists(); } throw new IllegalStateException("Unsupported type: " + path.getClass().getName()); }

Target:
private static boolean exists(Object path) { if (path instanceof String) { return Files.exists(Paths.get((String) path)); } if (path instanceof Path) { return Files.exists((Path) path); } if (path instanceof File) { return ((File) path).exists(); } throw new IllegalArgumentException("Unsupported type for @FileExists: " + path.getClass().getName()); }
Source:
private Set<String> getMissingFields(GraphQLInputObjectType type, Map<String, ObjectField> objectFieldMap) { return type.getFields().parallelStream() .filter(field -> field.getType() instanceof GraphQLNonNull) .map(GraphQLInputObjectField::getName) .filter(((Predicate<String>) objectFieldMap::containsKey).negate()) .collect(Collectors.toSet()); }

Target:
private Set<String> getMissingFields(GraphQLInputObjectType type, Map<String, ObjectField> objectFieldMap) { return type.getFields().stream() .filter(field -> field.getType() instanceof GraphQLNonNull) .map(GraphQLInputObjectField::getName) .filter(((Predicate<String>) objectFieldMap::containsKey).negate()) .collect(Collectors.toSet()); }
Source:
void uninstall() { StyledText editorTextWidget = fEditorViewer.getTextWidget(); if (editorTextWidget.getContent() != null) { editorTextWidget.getContent().removeTextChangeListener(this); } if (fEditorViewer instanceof ITextViewerExtension4) { ((ITextViewerExtension4) fEditorViewer).removeTextPresentationListener(this); } fEditorViewer.removeViewportListener(this); editorTextWidget.removeControlListener(this); fScaledFonts.values().forEach(font -> font.dispose()); }

Target:
void uninstall() { StyledText editorTextWidget = fEditorViewer.getTextWidget(); if (editorTextWidget.getContent() != null) { editorTextWidget.getContent().removeTextChangeListener(this); } if (fEditorViewer instanceof ITextViewerExtension4) { ((ITextViewerExtension4) fEditorViewer).removeTextPresentationListener(this); } fEditorViewer.removeViewportListener(this); editorTextWidget.removeControlListener(this); fScaledFonts.values().forEach(Font::dispose); }
Source:
default List<T> padTo(int length, T element) { if(length == 0) { return this; } else { return appendAll(Stream.gen(() -> element).take(length)); } }

Target:
default List<T> padTo(int length, T element) { if(length <= length()) { return this; } else { return appendAll(Stream.gen(() -> element).take(length - length())); } }
Source:
private void checkImportBlacklist(String userData) throws Exception { mod tree = new AnalyzingParser(new ANTLRStringStream(userData), "", "ascii").parseModule(); Visitor vis = new Visitor() { @Override public Object visitImport(Import node) throws Exception { for (alias importName : node.getInternalNames()) { if (backList.contains(importName.getInternalName())) { throw ProcessingErrorCode.createInvalidPythonImportErrorException(new RuntimeException(), importName.getInternalName()); } } return node; } @Override public Object visitImportFrom(ImportFrom node) throws Exception { if (backList.contains(node.getInternalModule())) { throw ProcessingErrorCode.createInvalidPythonImportErrorException(new RuntimeException(), node.getInternalModule()); } for (alias importName : node.getInternalNames()) { if (backList.contains(node.getInternalModule() + "." + importName.getInternalName())) { throw ProcessingErrorCode.createInvalidPythonImportErrorException(new RuntimeException(), node.getInternalModule() + "." + importName.getInternalName()); } } return node; } }; for (PythonTree c : tree.getChildren()) { try { vis.visit(c); } catch (Exception e) { interpreter.close(); interpreter = null; throw e; } } }

Target:
private void checkImportBlacklist(String userData) throws Exception { mod tree = new AnalyzingParser(new ANTLRStringStream(userData), "", "ascii").parseModule(); Visitor vis = new Visitor() { @Override public Object visitImport(Import node) throws Exception { for (alias importName : node.getInternalNames()) { if (moduleBlacklist.contains(importName.getInternalName())) { throw ProcessingErrorCode.createInvalidPythonImportErrorException(importName.getInternalName()); } } return node; } @Override public Object visitImportFrom(ImportFrom node) throws Exception { if (moduleBlacklist.contains(node.getInternalModule())) { throw ProcessingErrorCode.createInvalidPythonImportErrorException(node.getInternalModule()); } for (alias importName : node.getInternalNames()) { if (moduleBlacklist.contains(node.getInternalModule() + "." + importName.getInternalName())) { throw ProcessingErrorCode.createInvalidPythonImportErrorException( node.getInternalModule() + "." + importName.getInternalName()); } } return node; } }; for (PythonTree c : tree.getChildren()) { try { vis.visit(c); } catch (Exception e) { interpreter.close(); interpreter = null; throw e; } } }
Source:
public Token getGithubUserTokens(@ApiParam(hidden = true) @Auth Token authToken, @ApiParam(value = "User to return") @PathParam("userId") long userId) { User user = userDAO.findById(authToken.getUserId()); if (!user.getIsAdmin() && user.getId() != userId) { throw new WebApplicationException(HttpStatus.SC_FORBIDDEN); } return tokenDAO.findGithubByUserId(userId); }

Target:
public Token getGithubUserTokens(@ApiParam(hidden = true) @Auth Token authToken, @ApiParam(value = "User to return") @PathParam("userId") long userId) { User user = userDAO.findById(authToken.getUserId()); Helper.checkUser(user, userId); return tokenDAO.findGithubByUserId(userId); }
Source:
public void refresh() { final View view = getView(); if (view == null) { return; } if (decorationService == null) { return; } if (ExampleUtils.isAllocatedTo((CallBehaviorAction) view.getElement(), ExampleUtils.NODE_A_STEREOTYPE) != nodeAMarked) { nodeAMarked = !nodeAMarked; if (nodeAMarked) { decorationService.addDecoration(getMarkerA(), getView()); } else { decorationService.removeDecoration(getMarkerA().toString()); } getHost().refresh(); } if (ExampleUtils.isAllocatedTo((CallBehaviorAction) view.getElement(), ExampleUtils.NODE_B_STEREOTYPE) != nodeBMarked) { nodeBMarked = !nodeBMarked; if (nodeBMarked) { decorationService.addDecoration( view.getElement().toString(), "NodeBDecoration", view.getElement(), org.eclipse.papyrus.infra.widgets.Activator.getDefault().getImageDescriptor(Activator.ID, "icons/NodeB.gif"), org.eclipse.papyrus.infra.widgets.Activator.getDefault().getImageDescriptor(Activator.ID, "icons/NodeB.gif"), PreferedPosition.SOUTH_WEST, "NodeB decoration Without marker", 0); } else { decorationService.removeDecoration(view.getElement().toString()); } getHost().refresh(); } }

Target:
public void refresh() { final View view = getView(); if (null == view) { return; } if (null == decorationService) { return; } if (ExampleUtils.isAllocatedTo((CallBehaviorAction) view.getElement(), ExampleUtils.NODE_A_STEREOTYPE) != nodeAMarked) { nodeAMarked = !nodeAMarked; if (nodeAMarked) { decorationService.addDecoration(getMarkerA(), getView()); } else { decorationService.removeDecoration(getMarkerA().toString()); } getHost().refresh(); } if (ExampleUtils.isAllocatedTo((CallBehaviorAction) view.getElement(), ExampleUtils.NODE_B_STEREOTYPE) != nodeBMarked) { nodeBMarked = !nodeBMarked; if (nodeBMarked) { decorationService.addDecoration( view.getElement().toString(), "NodeBDecoration", view.getElement(), org.eclipse.papyrus.infra.widgets.Activator.getDefault().getImageDescriptor(Activator.ID, "icons/NodeB.gif"), org.eclipse.papyrus.infra.widgets.Activator.getDefault().getImageDescriptor(Activator.ID, "icons/NodeB.gif"), PreferedPosition.SOUTH_WEST, "NodeB decoration Without marker", 0); } else { decorationService.removeDecoration(view.getElement().toString()); } getHost().refresh(); } }
Source:
private JSONObject execute(final String command, final Object... args) { AXE.inject(this.driver, this.script, this.skipFrames); this.driver.manage().timeouts().setScriptTimeout(this.timeout, TimeUnit.SECONDS); JSONObject result= new JSONObject(); if (args.length > 0) for (Object arg: args) { Object response = ((JavascriptExecutor) this.driver).executeAsyncScript(command, arg); JSONObject oneResult = new JSONObject((Map)response); for (String key : oneResult.keySet()) { result.accumulate(key, oneResult.get(key)); } } else { Object response = ((JavascriptExecutor) this.driver).executeAsyncScript(command, args); result = new JSONObject((Map)response); } String error = result.getString("error"); if (error != null && !error.isEmpty()) { throw new AxeRuntimeException(error); } JSONObject results = result.getJSONObject("results"); return results; }

Target:
private JSONObject execute(final String command, final Object... args) { AXE.inject(this.driver, this.script, this.skipFrames); this.driver.manage().timeouts().setScriptTimeout(this.timeout, TimeUnit.SECONDS); Object response = ((JavascriptExecutor) this.driver).executeAsyncScript(command, args); JSONObject result = new JSONObject((Map) response); String error = result.getString("error"); if (error != null && !error.isEmpty()) { throw new AxeRuntimeException(error); } JSONObject results = result.getJSONObject("results"); return results; }
Source:
private boolean uncheckInactive(Object element) { int unchecked = 0; boolean isInactive = false; Object[] children = fContentProvider.getChildren(element); for (Object child : children) { if (uncheckInactive(child)) { unchecked++; } } if (fTree.getChecked(element)) { isInactive = element instanceof ITimeGraphEntry && !fActiveProvider.isActive((ITimeGraphEntry) element); if (isInactive && unchecked == children.length) { fTree.setChecked(element, false); } } return !fTree.getChecked(element); }

Target:
private boolean uncheckInactive(Object element) { boolean wasChildChecked = false; for (Object child : fContentProvider.getChildren(element)) { wasChildChecked |= uncheckInactive(child); } if (fTree.getChecked(element) && !wasChildChecked) { if (element instanceof ITimeGraphEntry && !fActiveProvider.isActive((ITimeGraphEntry) element)) { fTree.setChecked(element, false); } } return fTree.getChecked(element); }
Source:
protected void startScan() { logger.debug("Starting Astro discovery scan"); PointType location = locationProvider.getLocation(); if (location == null) { logger.debug("LocationProvider.getLocation() is not set -> Will not provide any discovery results"); return; } ThingTypeUID sunType = new ThingTypeUID(BINDING_ID, SUN); ThingTypeUID moonType = new ThingTypeUID(BINDING_ID, MOON); ThingUID sunThing = new ThingUID(sunType, LOCAL); ThingUID moonThing = new ThingUID(moonType, LOCAL); String propGeolocation = String.format("%s,%s", location.getLatitude(), location.getLongitude()); thingDiscovered(DiscoveryResultBuilder.create(sunThing).withLabel("Local Sun") .withProperty("geolocation", propGeolocation).build()); thingDiscovered(DiscoveryResultBuilder.create(moonThing).withLabel("Local Moon") .withProperty("geolocation", propGeolocation).build()); }

Target:
protected void startScan() { logger.debug("Starting Astro discovery scan"); PointType location = locationProvider.getLocation(); if (location == null) { logger.debug("LocationProvider.getLocation() is not set -> Will not provide any discovery results"); return; } ThingUID sunThing = new ThingUID(AstroBindingConstants.THING_TYPE_SUN, LOCAL); ThingUID moonThing = new ThingUID(AstroBindingConstants.THING_TYPE_MOON, LOCAL); String propGeolocation; if (location.getAltitude() != null) { propGeolocation = String.format("%s,%s,%s", location.getLatitude(), location.getLongitude(), location.getAltitude()); } else { propGeolocation = String.format("%s,%s", location.getLatitude(), location.getLongitude()); } thingDiscovered(DiscoveryResultBuilder.create(sunThing).withLabel("Local Sun") .withProperty("geolocation", propGeolocation).build()); thingDiscovered(DiscoveryResultBuilder.create(moonThing).withLabel("Local Moon") .withProperty("geolocation", propGeolocation).build()); }
Source:
private void resetData() { for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks = new TreeSet<>(); }

Target:
private void resetData() { for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks.clear(); }
Source:
public AlluxioHiveMetastore(TableMasterClient client) { requireNonNull(client, "client is null"); this.client = client; }

Target:
public AlluxioHiveMetastore(TableMasterClient client) { this.client = requireNonNull(client, "client is null"); }
Source:
public <R, X extends Exception> R inTransaction(Handle handle, TransactionCallback<R, X> callback) throws X { didTxnRollback.set(false); final R returnValue; try { handle.begin(); returnValue = callback.inTransaction(handle); if (!didTxnRollback.get()) { handle.commit(); } } catch (Exception e) { try { handle.rollback(); } catch (Exception rollback) { e.addSuppressed(rollback); } throw (X) e; } didTxnRollback.remove(); return returnValue; }

Target:
public <R, X extends Exception> R inTransaction(Handle handle, TransactionCallback<R, X> callback) throws X { if (isInTransaction(handle)) { throw new IllegalStateException("Already in transaction"); } didTxnRollback.set(false); final R returnValue; try { handle.begin(); returnValue = callback.inTransaction(handle); if (!didTxnRollback.get()) { handle.commit(); } } catch (Exception e) { try { handle.rollback(); } catch (Exception rollback) { e.addSuppressed(rollback); } throw (X) e; } didTxnRollback.remove(); return returnValue; }
Source:
public void testOneFail() throws IOException { final List<Pass> list = new ArrayList<Pass>(1); list.add(new PsFake(false)); final Opt<Identity> identity = new PsAll(list, 0).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(false) ); }

Target:
public void testOneFail() throws Exception { final List<Pass> list = new ArrayList<Pass>(1); list.add(new PsFake(false)); final Opt<Identity> identity = new PsAll(list, 0).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(false) ); }
Source:
Flux<BlobChangefeedEventWrapper> getEvents() { return validateChangefeed() .flatMap(ignore -> populateLastConsumable()) .flatMapMany(ignore -> listYears()) .concatMap(this::listSegmentsForYear) .concatMap(this::getEventsForSegment); }

Target:
Flux<BlobChangefeedEventWrapper> getEvents() { return validateChangefeed() .then(populateLastConsumable()) .thenMany(listYears()) .concatMap(this::listSegmentsForYear) .concatMap(this::getEventsForSegment); }
Source:
private void testJob(final String jobName, final Map<String, String[]> expectedResultSets) throws Exception { final InputStream resultInputStream = new ByteArrayInputStream(runJob(jobName).getBytes()); final InputStreamReader resultInputStreamReader = new InputStreamReader(resultInputStream); final BufferedReader resultReader = new BufferedReader(resultInputStreamReader); try { String resultLine; while ((resultLine = resultReader.readLine()) != null && !resultLine.equals("SUCCESS!")) { } while ((resultLine = resultReader.readLine()) != null) { final String resultKey = resultLine.trim(); if (!"".equals(resultKey)) { String[] expectedResultSet = expectedResultSets.get(resultKey); assertNotNull(expectedResultSet); for (String expectedResult : expectedResultSet) { assertThat(resultReader.readLine(), containsString(expectedResult)); } expectedResultSets.remove(resultKey); } } assertEquals(0, expectedResultSets.size()); } finally { resultReader.close(); resultInputStreamReader.close(); resultInputStream.close(); } }

Target:
private static void testJob(final String jobName, final Map<String, String[]> expectedResultSets) throws Exception { JobTestHelper.testJob(URLDecoder.decode(new File("src/main/resources/datacleaner-home/jobs/" + jobName + ".analysis.xml").getPath(), "UTF-8"), expectedResultSets); }
Source:
public void stopContainer() throws Exception { deployer.undeploy(APP_CONTEXT); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); final ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); LOGGER.info("*** reseting test configuration"); serverTearDown(managementClient); LOGGER.trace("*** stopping container"); containerController.stop(CONTAINER); }

Target:
public void stopContainer() throws Exception { deployer.undeploy(APP_CONTEXT); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); final ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); LOGGER.trace("*** reseting test configuration"); serverTearDown(managementClient); LOGGER.trace("*** stopping container"); containerController.stop(CONTAINER); }
Source:
private static long getMinimumTimeout(List<Map<String, String>> connectorData) { return connectorData.stream() .map(connectorDatum -> connectorDatum.get(IDLE_TIMEOUT)) .map(idleTimeout -> Duration.parse(idleTimeout).toMilliseconds()) .min(Long::compareTo) .orElse(DEFAULT_IDLE_TIMEOUT); }

Target:
private static long getMinimumTimeout(List<Map<String, String>> connectorData) { Optional<Long> minimum = connectorData.stream() .map(connectorDatum -> connectorDatum.get(IDLE_TIMEOUT)) .map(idleTimeout -> Duration.parse(idleTimeout).toMilliseconds()) .min(Long::compareTo); if (minimum.isPresent()) { return minimum.get(); } return logAndGetDefault(); }
Source:
public static InetSocketAddress retrieveAddress(AsynchronousSocketChannel channel) { SocketAddress a = null; try { a = channel.getRemoteAddress(); } catch (IOException e) { } if (a != null && (a instanceof InetSocketAddress)) { return ((InetSocketAddress) a); } return null; }

Target:
public static InetSocketAddress retrieveAddress(AsynchronousSocketChannel channel) { SocketAddress a = null; try { a = channel.getRemoteAddress(); } catch (IOException e) { logger.error("retrieveAddress channel exception: {}", e.getMessage()); } if (a != null && (a instanceof InetSocketAddress)) { return ((InetSocketAddress) a); } return null; }
Source:
public static DryRunFormatType dryRunFormatType() { return ConfigDefaults.getDryRunFormatType("DRYRUN_FORMAT_TYPE"); }

Target:
public static DryRunFormatType dryRunFormatType() { return ConfigDefaults.getDryRunFormatType("DRY_RUN_FORMAT_TYPE"); }
Source:
public AuthenticationInfo authenticate( @RequestBody AuthenticationCredentials authenticationCredentials) throws ApiException { ApiUtils.methodInvocationLog("authenticate", authenticationCredentials.getUsername()); restApiBusiness.getApiContext(httpServletRequest, false); try(Connection connection = PlatformConnection.getInstance().getConnection()) { return restApiBusiness .authenticate(authenticationCredentials, connection); } catch (SQLException ex) { throw new ApiException(ex); } }

Target:
public AuthenticationInfo authenticate( @RequestBody AuthenticationCredentials authenticationCredentials) throws ApiException { ApiUtils.methodInvocationLog("authenticate", authenticationCredentials.getUsername()); restApiBusiness.getApiContext(httpServletRequest, false); try(Connection connection = connectionSupplier.get()) { return restApiBusiness .authenticate(authenticationCredentials, connection); } catch (SQLException | SQLRuntimeException ex) { throw new ApiException(ex); } }
Source:
public void testBuilder() { String prefix = "rya_"; String auth = "U"; String visibility = "U"; String user = "user"; String password = "password"; String instance = "instance"; String zookeeper = "zookeeper"; boolean useMock = true; boolean useComposite = true; boolean usePrefixHash = true; boolean useInference = true; boolean displayPlan = false; AccumuloRdfConfiguration conf = new AccumuloRdfConfiguration().getBuilder() .auths(auth) .visibilities(visibility) .setRyaPrefix(prefix) .useInference(useInference) .useCompositeCardinality(useComposite) .displayQueryPlan(displayPlan) .setAccumuloInstance(instance) .setAccumuloPassword(password) .setAccumuloUser(user) .setAccumuloZooKeepers(zookeeper) .useMockAccumulo(useMock) .useAccumuloPrefixHashing(usePrefixHash) .build(); org.junit.Assert.assertEquals(conf.getTablePrefix(), prefix); org.junit.Assert.assertEquals(conf.getCv(), visibility); org.junit.Assert.assertEquals(conf.getAuthorizations(), new Authorizations(auth)); org.junit.Assert.assertEquals(conf.isInfer(), useInference); org.junit.Assert.assertEquals(conf.isUseCompositeCardinality(), useComposite); org.junit.Assert.assertEquals(conf.isDisplayQueryPlan(), displayPlan); org.junit.Assert.assertEquals(conf.getAccumuloInstance(), instance); org.junit.Assert.assertEquals(conf.getAccumuloPassword(), password); org.junit.Assert.assertEquals(conf.getAccumuloUser(), user); org.junit.Assert.assertEquals(conf.getAccumuloZookeepers(), zookeeper); org.junit.Assert.assertEquals(conf.getUseMockAccumulo(), useMock); org.junit.Assert.assertEquals(conf.isPrefixRowsWithHash(), usePrefixHash); }

Target:
public void testBuilder() { String prefix = "rya_"; String auth = "U"; String visibility = "U"; String user = "user"; String password = "password"; String instance = "instance"; String zookeeper = "zookeeper"; boolean useMock = false; boolean useComposite = true; boolean usePrefixHash = true; boolean useInference = true; boolean displayPlan = false; AccumuloRdfConfiguration conf = new AccumuloRdfConfiguration().getBuilder() .setAuths(auth) .setVisibilities(visibility) .setRyaPrefix(prefix) .setUseInference(useInference) .setUseCompositeCardinality(useComposite) .setDisplayQueryPlan(displayPlan) .setAccumuloInstance(instance) .setAccumuloPassword(password) .setAccumuloUser(user) .setAccumuloZooKeepers(zookeeper) .setUseMockAccumulo(useMock) .setUseAccumuloPrefixHashing(usePrefixHash) .build(); assertEquals(conf.getTablePrefix(), prefix); assertEquals(conf.getCv(), visibility); assertEquals(conf.getAuthorizations(), new Authorizations(auth)); assertEquals(conf.isInfer(), useInference); assertEquals(conf.isUseCompositeCardinality(), useComposite); assertEquals(conf.isDisplayQueryPlan(), displayPlan); assertEquals(conf.getAccumuloInstance(), instance); assertEquals(conf.getAccumuloPassword(), password); assertEquals(conf.getAccumuloUser(), user); assertEquals(conf.getAccumuloZookeepers(), zookeeper); assertEquals(conf.getUseMockAccumulo(), useMock); assertEquals(conf.isPrefixRowsWithHash(), usePrefixHash); }
Source:
private String filterPropertiesAndGetGithubPrimaryEmail(List<Map<String, String>> properties) { List<Map<String, String>> primaryPublicGithubEmails = properties .stream() .filter( map -> map.get("primary").equals("true") && map.get("visibility").equals("public")) .collect(toList()); return primaryPublicGithubEmails.get(0).get("email"); }

Target:
private String filterPropertiesAndGetGithubPrimaryEmail(List<Map<String, String>> properties) { List<Map<String, String>> primaryPublicGithubEmails = properties .stream() .filter( map -> map.get("primary").equals("true") && map.get("visibility").equals("public")) .collect(toList()); if (primaryPublicGithubEmails.isEmpty()) { throw new NoSuchElementException("The list with github primary, public emails is empty"); } return primaryPublicGithubEmails.get(0).get("email"); }
Source:
public static void main(String... args) throws Exception { String boltUrl = "%%BOLT_URL_PLACEHOLDER%%"; String user = "<Username for Neo4j Aura database>"; String password = "<Password for Neo4j Aura database>"; Config config = Config.builder().withEncryption().build(); try (DriverIntroductionExample app = new DriverIntroductionExample(boltUrl, user, password, config)) { app.createFriendship("Alice", "David"); app.findPerson("Alice"); } }

Target:
public static void main(String... args) throws Exception { String boltUrl = "%%BOLT_URL_PLACEHOLDER%%"; String user = "<Username for Neo4j Aura database>"; String password = "<Password for Neo4j Aura database>"; Config config = Config.builder().withEncryption().build(); try (DriverIntroductionExample app = new DriverIntroductionExample(boltUrl, user, password, Config.defaultConfig())) { app.createFriendship("Alice", "David"); app.findPerson("Alice"); } }
Source:
@Override public void getBindings(Map<String, Binding<?>> bindings) { for (Class<?> c = moduleClass; c != Object.class; c = c.getSuperclass()) { for (Method method : c.getDeclaredMethods()) { Provides provides = method.getAnnotation(Provides.class); if (provides != null) { Type genericReturnType = method.getGenericReturnType(); if (genericReturnType instanceof ParameterizedType) { Type rawType = ((ParameterizedType) genericReturnType).getRawType(); if (Provider.class.equals(rawType)) { throw new IllegalStateException("@Provides method must not return Provider directly: " + c.getName() + "." + method.getName()); } if (Lazy.class.equals(rawType)) { throw new IllegalStateException("@Provides method must not return Lazy directly: " + c.getName() + "." + method.getName()); } } String key = Keys.get(genericReturnType, method.getAnnotations(), method); switch (provides.type()) { case UNIQUE: handleBindings(bindings, method, key); break; case SET: handleSetBindings(bindings, method, key); break; default: throw new AssertionError("Unknown @Provides type " + provides.type()); } } } } }

Target:
@Override public void getBindings(Map<String, Binding<?>> bindings) { for (Class<?> c = moduleClass; c != Object.class; c = c.getSuperclass()) { for (Method method : c.getDeclaredMethods()) { Provides provides = method.getAnnotation(Provides.class); if (provides != null) { Type genericReturnType = method.getGenericReturnType(); Type typeToCheck = genericReturnType; if (genericReturnType instanceof ParameterizedType) { typeToCheck = ((ParameterizedType) genericReturnType).getRawType(); } if (Provider.class.equals(typeToCheck)) { throw new IllegalStateException("@Provides method must not return Provider directly: " + c.getName() + "." + method.getName()); } if (Lazy.class.equals(typeToCheck)) { throw new IllegalStateException("@Provides method must not return Lazy directly: " + c.getName() + "." + method.getName()); } String key = Keys.get(genericReturnType, method.getAnnotations(), method); switch (provides.type()) { case UNIQUE: handleBindings(bindings, method, key); break; case SET: handleSetBindings(bindings, method, key); break; default: throw new AssertionError("Unknown @Provides type " + provides.type()); } } } } }
Source:
public void nonVmWithSameMTUAddedToNic() { Network net = createNetwork("VLanVmMtu9000"); net.setvlan_id(100); net.setMtu(9000); Network newNet = createNetwork("nonVmMtu5000"); newNet.setVmNetwork(false); newNet.setMtu(9000); mockExistingNetworks(net, newNet); VdsNetworkInterface nic = createNic("nic0", null); VdsNetworkInterface nicWithVlan = createVlan(nic.getName(), net.getvlan_id(), net.getName()); nicWithVlan.setMtu(net.getMtu()); mockExistingIfaces(nic, nicWithVlan); nic.setNetworkName(newNet.getName()); SetupNetworksHelper helper = createHelper(createParametersForNics(nic, nicWithVlan)); validateAndExpectNoViolations(helper); }

Target:
public void nonVmWithSameMTUAddedToNic() { Network net = createNetwork("vlanVmMtu9000"); net.setvlan_id(100); net.setMtu(9000); Network newNet = createNetwork("nonVmMtu9000"); newNet.setVmNetwork(false); newNet.setMtu(9000); mockExistingNetworks(net, newNet); VdsNetworkInterface nic = createNic("nic0", null); VdsNetworkInterface nicWithVlan = createVlan(nic.getName(), net.getvlan_id(), net.getName()); nicWithVlan.setMtu(net.getMtu()); mockExistingIfaces(nic, nicWithVlan); nic.setNetworkName(newNet.getName()); SetupNetworksHelper helper = createHelper(createParametersForNics(nic, nicWithVlan)); validateAndExpectNoViolations(helper); }
Source:
protected void onInitUI() { super.onInitUI(); prev = new Hyperlink(Util.C.pagedChangeListPrev(), true, ""); prev.setVisible(false); next = new Hyperlink(Util.C.pagedChangeListNext(), true, ""); next.setVisible(false); table = new ChangeTable2() { { keysNavigation.add(new DoLinkCommand(0, 'p', Util.C .changeTablePagePrev(), prev)); keysNavigation.add(new DoLinkCommand(0, 'n', Util.C .changeTablePageNext(), next)); keysNavigation.add(new DoLinkCommand(0, '[', Util.C .changeTablePagePrev(), prev)); keysNavigation.add(new DoLinkCommand(0, ']', Util.C .changeTablePageNext(), next)); keysNavigation.add(new KeyCommand(0, 'R', Util.C.keyReloadSearch()) { @Override public void onKeyPress(final KeyPressEvent event) { Gerrit.display(getToken()); } }); } }; section = new ChangeTable2.Section(); table.addSection(section); table.setSavePointerId(anchorPrefix); HorizontalPanel copySearchResultPanel = new HorizontalPanel(); copySearchResultPanel.add(new Label(Util.C.pagedCopySearchResults())); copySearchResultPanel.add(copySearchResult = new CopyableLabel("", false)); setTitleFarEast(copySearchResultPanel); add(table); final HorizontalPanel buttons = new HorizontalPanel(); buttons.setStyleName(Gerrit.RESOURCES.css().changeTablePrevNextLinks()); buttons.add(prev); buttons.add(next); add(buttons); }

Target:
protected void onInitUI() { super.onInitUI(); prev = new Hyperlink(Util.C.pagedChangeListPrev(), true, ""); prev.setVisible(false); next = new Hyperlink(Util.C.pagedChangeListNext(), true, ""); next.setVisible(false); table = new ChangeTable2() { { keysNavigation.add( new DoLinkCommand(0, 'p', Util.C.changeTablePagePrev(), prev), new DoLinkCommand(0, 'n', Util.C.changeTablePageNext(), next)); keysNavigation.add( new DoLinkCommand(0, '[', Util.C.changeTablePagePrev(), prev), new DoLinkCommand(0, ']', Util.C.changeTablePageNext(), next)); keysNavigation.add(new KeyCommand(0, 'R', Util.C.keyReloadSearch()) { @Override public void onKeyPress(final KeyPressEvent event) { Gerrit.display(getToken()); } }); } }; section = new ChangeTable2.Section(); table.addSection(section); table.setSavePointerId(anchorPrefix); if (CopyableLabel.isFlashEnabled()) { HorizontalPanel copySearchResultPanel = new HorizontalPanel(); copySearchResultPanel.add(new Label(Util.C.pagedCopySearchResults())); copySearchResultPanel.add(copySearchResult = new CopyableLabel("", false)); setTitleFarEast(copySearchResultPanel); } add(table); final HorizontalPanel buttons = new HorizontalPanel(); buttons.setStyleName(Gerrit.RESOURCES.css().changeTablePrevNextLinks()); buttons.add(prev); buttons.add(next); add(buttons); }
Source:
private ProcessBatchResult processBatch(int batchSize) { Block[] blocks = new Block[outputCount]; int pageSize = 0; SelectedPositions positionsBatch = selectedPositions.subRange(0, batchSize); for (PageProjectionWithOutputs projection : projections) { if (yieldSignal.isSet()) { return ProcessBatchResult.processBatchYield(); } if (positionsBatch.size() > 1 && pageSize > MAX_PAGE_SIZE_IN_BYTES) { return ProcessBatchResult.processBatchTooLarge(); } int[] outputChannels = projection.getOutputChannels(); if (previouslyComputedResults[outputChannels[0]] != null && previouslyComputedResults[outputChannels[0]].getPositionCount() >= batchSize) { for (Integer channel : outputChannels) { blocks[channel] = previouslyComputedResults[channel].getRegion(0, batchSize); pageSize += blocks[channel].getSizeInBytes(); } } else { if (pageProjectWork == null) { expressionProfiler.start(); pageProjectWork = projection.project(session, yieldSignal, projection.getPageProjection().getInputChannels().getInputChannels(page), positionsBatch); expressionProfiler.stop(positionsBatch.size()); } if (!pageProjectWork.process()) { return ProcessBatchResult.processBatchYield(); } List<Block> projectionOutputs = pageProjectWork.getResult(); for (int j = 0; j < outputChannels.length; j++) { int channel = outputChannels[j]; previouslyComputedResults[channel] = projectionOutputs.get(j); blocks[channel] = previouslyComputedResults[channel]; pageSize += blocks[channel].getSizeInBytes(); } pageProjectWork = null; } } return ProcessBatchResult.processBatchSuccess(new Page(positionsBatch.size(), blocks)); }

Target:
private ProcessBatchResult processBatch(int batchSize) { Block[] blocks = new Block[outputCount]; int pageSize = 0; SelectedPositions positionsBatch = selectedPositions.subRange(0, batchSize); for (PageProjectionWithOutputs projection : projections) { if (yieldSignal.isSet()) { return ProcessBatchResult.processBatchYield(); } if (positionsBatch.size() > 1 && pageSize > MAX_PAGE_SIZE_IN_BYTES) { return ProcessBatchResult.processBatchTooLarge(); } int[] outputChannels = projection.getOutputChannels(); if (previouslyComputedResults[outputChannels[0]] != null && previouslyComputedResults[outputChannels[0]].getPositionCount() >= batchSize) { for (int channel : outputChannels) { blocks[channel] = previouslyComputedResults[channel].getRegion(0, batchSize); pageSize += blocks[channel].getSizeInBytes(); } } else { if (pageProjectWork == null) { expressionProfiler.start(); pageProjectWork = projection.project(properties, yieldSignal, projection.getPageProjection().getInputChannels().getInputChannels(page), positionsBatch); expressionProfiler.stop(positionsBatch.size()); } if (!pageProjectWork.process()) { return ProcessBatchResult.processBatchYield(); } List<Block> projectionOutputs = pageProjectWork.getResult(); for (int j = 0; j < outputChannels.length; j++) { int channel = outputChannels[j]; previouslyComputedResults[channel] = projectionOutputs.get(j); blocks[channel] = previouslyComputedResults[channel]; pageSize += blocks[channel].getSizeInBytes(); } pageProjectWork = null; } } return ProcessBatchResult.processBatchSuccess(new Page(positionsBatch.size(), blocks)); }
Source:
JavaFile brewJava(int sdk, boolean debuggable, boolean useAndroidX) { return JavaFile.builder(bindingClassName.packageName(), createType( sdk, debuggable, useAndroidX)) .addFileComment("Generated code from Butter Knife. Do not modify!") .build(); }

Target:
JavaFile brewJava(int sdk, boolean debuggable, boolean useAndroidX) { TypeSpec bindingConfiguration = createType(sdk, debuggable, useAndroidX); return JavaFile.builder(bindingClassName.packageName(), bindingConfiguration) .addFileComment("Generated code from Butter Knife. Do not modify!") .build(); }
Source:
public TaskInstance findTaskById(Long taskId, boolean withSLA) { if( config.isRest() ) { Map<String, Object> valuesMap = new HashMap<String, Object>(); valuesMap.put(TASK_INSTANCE_ID, taskId); String queryString = ""; if(withSLA) { queryString = "?includeSLA=true"; } return makeHttpGetRequestAndCreateCustomResponse( build(loadBalancer.getUrl(), QUERY_URI + "/" + TASK_GET_URI + queryString, valuesMap), TaskInstance.class); } else { CommandScript script =new CommandScript( Collections.singletonList( (KieServerCommand) new DescriptorCommand( "QueryService", "getTaskById", new Object[]{taskId, withSLA}) ) ); ServiceResponse<TaskInstance> response = (ServiceResponse<TaskInstance>) executeJmsCommand( script, DescriptorCommand.class.getName(), "BPM" ).getResponses().get(0); throwExceptionOnFailure(response); if (shouldReturnWithNullResponse(response)) { return null; } return response.getResult(); } }

Target:
public TaskInstance findTaskById(Long taskId, boolean withSLA) { if( config.isRest() ) { Map<String, Object> valuesMap = new HashMap<String, Object>(); valuesMap.put(TASK_INSTANCE_ID, taskId); return makeHttpGetRequestAndCreateCustomResponse( build(loadBalancer.getUrl(), QUERY_URI + "/" + TASK_GET_URI + "?withSLA=" + withSLA, valuesMap), TaskInstance.class); } else { CommandScript script = new CommandScript( Collections.singletonList( (KieServerCommand) new DescriptorCommand( "QueryService", "getTaskById", new Object[]{taskId, withSLA}) ) ); ServiceResponse<TaskInstance> response = (ServiceResponse<TaskInstance>) executeJmsCommand( script, DescriptorCommand.class.getName(), "BPM" ).getResponses().get(0); throwExceptionOnFailure(response); if (shouldReturnWithNullResponse(response)) { return null; } return response.getResult(); } }
Source:
private static Credential refreshToken(Credential credential) throws IOException { try { credential.refreshToken(); return credential; } catch (NullPointerException e) { throw new IllegalStateException( "Couldn't refresh the OAuth token. Are you using a different client secrets file? If you " + "want to use a different file, first clear your stored credentials: http://google-g" + "enomics.readthedocs.org/en/latest/api-client-java/resetting_auth.html", e); } }

Target:
private Credential refreshToken(Credential credential) throws IOException { try { credential.refreshToken(); return credential; } catch (NullPointerException e) { throw new IllegalStateException( "Couldn't refresh the OAuth token. Are you using different client secrets? If so, you " + "need to first clear the stored credentials by removing the file at " + userDir.getPath(), e); } }
Source:
public DestroyImageVDSCommandParameters createDestroyImageParameters() { StorageDomain storageDomain = storageDomainDao.get(getParameters().getStorageDomainId()); return new DestroyImageVDSCommandParameters(getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupID(), Collections.singletonList(getParameters().getImageId()), getDiskImage().isWipeAfterDelete(), storageDomain.getSupportsDiscard(), true); }

Target:
public DestroyImageVDSCommandParameters createDestroyImageParameters() { StorageDomain storageDomain = storageDomainDao.get(getParameters().getStorageDomainId()); return new DestroyImageVDSCommandParameters(getStoragePoolId(), getParameters().getStorageDomainId(), getParameters().getImageGroupID(), Collections.singletonList(getParameters().getImageId()), getDiskImage().isWipeAfterDelete(), storageDomain.getDiscardAfterDelete(), true); }
Source:
public StreamAppenderMetrics(String prefix, MetricsRegistry registry) { super(prefix + "-", registry); bufferFillPct = newGauge("buffer-fill-percent", 0); recursiveCalls = newCounter("recursive-calls"); logMessagesDropped = newCounter("log-messages-dropped"); logMessagesBytes = newCounter("log-messages-bytes"); logMessagesCount = newCounter("log-messages-count"); logMessagesErrors = newCounter("log-messages-errors"); }

Target:
public StreamAppenderMetrics(String prefix, MetricsRegistry registry) { super(prefix + "-", registry); bufferFillPct = newGauge("buffer-fill-percent", 0); recursiveCalls = newCounter("recursive-calls"); logMessagesDropped = newCounter("log-messages-dropped"); logMessagesErrors = newCounter("log-messages-errors"); logMessagesBytesSent = newCounter("log-messages-bytes-sent"); logMessagesCountSent = newCounter("log-messages-count-sent"); }
Source:
private void onAckMessage( AffinityTopologyVersion topVer, ClusterNode node, DistributedMetaStorageUpdateAckMessage msg ) { GridFutureAdapter<Boolean> fut; updateFutsStopLock.readLock().lock(); try { fut = updateFuts.remove(msg.requestId()); } finally { updateFutsStopLock.readLock().unlock(); } if (fut != null) { String errorMsg = msg.errorMessage(); if (errorMsg == null) { Boolean res = msg instanceof DistributedMetaStorageCasAckMessage ? ((DistributedMetaStorageCasAckMessage)msg).updated() : null; fut.onDone(res); } else fut.onDone(new IllegalStateException(errorMsg)); } }

Target:
private void onAckMessage( AffinityTopologyVersion topVer, ClusterNode node, DistributedMetaStorageUpdateAckMessage msg ) { GridFutureAdapter<Boolean> fut = updateFuts.remove(msg.requestId()); if (fut != null) { String errorMsg = msg.errorMessage(); if (errorMsg == null) { Boolean res = msg instanceof DistributedMetaStorageCasAckMessage ? ((DistributedMetaStorageCasAckMessage)msg).updated() : null; fut.onDone(res); } else fut.onDone(new IllegalStateException(errorMsg)); } }
Source:
public String getDisplayName() { return "SetEnvBuildWrapper"; }

Target:
public String getDisplayName() { return ""; }
Source:
private void saveCommandCooldowns() { List<Object> serialized = new ArrayList<>(); for (Entry<Pattern, Long> entry : this.commandCooldowns.entrySet()) { if (entry.getValue() < System.currentTimeMillis()) { continue; } HashMap<Object, Object> map = new HashMap<>(); map.put("pattern", entry.getKey().pattern()); map.put("expiry", entry.getValue()); serialized.add(map); } config.setProperty("timestamps.command-cooldowns", serialized); save(); }

Target:
private void saveCommandCooldowns() { List<Object> serialized = new ArrayList<>(); for (Entry<Pattern, Long> entry : this.commandCooldowns.entrySet()) { if (entry.getValue() < System.currentTimeMillis()) { continue; } Map<?, ?> map = ImmutableMap.builder() .put("pattern", entry.getKey().pattern()) .put("expiry", entry.getValue()) .build(); serialized.add(map); } config.setProperty("timestamps.command-cooldowns", serialized); save(); }
Source:
private void zipFolder(String srcFolder, String destZipFile) { try { FileOutputStream fileWriter = new FileOutputStream(destZipFile); ZipOutputStream zip = new ZipOutputStream(fileWriter); addFolderContentsToZip(srcFolder, zip); zip.flush(); zip.close(); } catch (Exception ex) { getLog().error("Error occurred while creating CAR file. " + ex); } }

Target:
private void zipFolder(String srcFolder, String destZipFile) throws ArchiveException { try (FileOutputStream fileWriter = new FileOutputStream(destZipFile); ZipOutputStream zip = new ZipOutputStream(fileWriter)) { addFolderContentsToZip(srcFolder, zip); zip.flush(); } catch (IOException ex) { throw new ArchiveException(Constants.ARCHIVE_EXCEPTION_MSG, ex); } }
Source:
private void printStats(final int threadId, final long elapsedTime) { final Statistics pullStat = pullStats[threadId]; final Statistics pushStat = pushStats[threadId]; final Statistics requestStat = requestStats[threadId]; final Statistics pushWaitStat = pushWaitStats[threadId]; final Statistics pullWaitStat = pullWaitStats[threadId]; LOG.log(Level.INFO, "PS Elapsed Time: {0}, PS Sum Pull: {1}, PS Avg Pull: {2}, PS Pull Count: {3}, " + "PS Sum Push: {4}, PS Avg Push: {5}, PS Push Count: {6}, " + "PS Avg Request: {7}, PS Sum Request: {8}, PS Request Count: {9}, " + "PS Avg Push Wait: {10}, PS Sum Push Wait: {11}, " + "PS Avg Pull Wait: {12}, PS Sum Pull Wait: {13}", new Object[]{elapsedTime / 1e9D, Double.toString(pullStat.sum()), Double.toString(pullStat.avg()), pullStat.count(), Double.toString(pushStat.sum()), Double.toString(pushStat.avg()), pushStat.count(), Double.toString(requestStat.avg()), Double.toString(requestStat.sum()), requestStat.count(), Double.toString(pushWaitStat.avg()), Double.toString(pushWaitStat.sum()), Double.toString(pullWaitStat.avg()), Double.toString(pullWaitStat.sum())}); pushStat.reset(); pullStat.reset(); requestStat.reset(); pushWaitStat.reset(); pullWaitStat.reset(); startTimes[threadId] = ticker.read(); }

Target:
private void printStats(final int threadId, final long elapsedTime) { final Statistics pullStat = pullStats[threadId]; final Statistics pushStat = pushStats[threadId]; final Statistics requestStat = requestStats[threadId]; final Statistics pushWaitStat = pushWaitStats[threadId]; final Statistics pullWaitStat = pullWaitStats[threadId]; LOG.log(Level.INFO, "PS Elapsed Time (sec): {0}, PS Sum Pull (sec): {1}, PS Avg Pull (sec): {2}, " + "PS Pull Count: {3}, PS Sum Push (sec): {4}, PS Avg Push (sec): {5}, PS Push Count: {6}, " + "PS Avg Request (sec): {7}, PS Sum Request (sec): {8}, PS Request Count: {9}, " + "PS Avg Push Wait (sec): {10}, PS Sum Push Wait (sec): {11}, " + "PS Avg Pull Wait (sec): {12}, PS Sum Pull Wait (sec): {13}", new Object[]{elapsedTime / 1e9D, Double.toString(pullStat.sum()), Double.toString(pullStat.avg()), pullStat.count(), Double.toString(pushStat.sum()), Double.toString(pushStat.avg()), pushStat.count(), Double.toString(requestStat.avg()), Double.toString(requestStat.sum()), requestStat.count(), Double.toString(pushWaitStat.avg()), Double.toString(pushWaitStat.sum()), Double.toString(pullWaitStat.avg()), Double.toString(pullWaitStat.sum())}); pushStat.reset(); pullStat.reset(); requestStat.reset(); pushWaitStat.reset(); pullWaitStat.reset(); startTimes[threadId] = ticker.read(); }
Source:
private void initialize() { graphLoadService = new GraphLoadService(); newickLoadService = new NewickLoadService(); graphLoadService.setOnFailed(e -> new ExceptionDialog(root, graphLoadService.getException(), "Error loading file!")); graphLoadService.setOnRunning(e -> progressDialog.show()); graphLoadService.setOnSucceeded(e -> progressDialog.close()); graphLoadService.setOnCancelled(e -> Neo4jSingleton.getInstance().deleteDatabase()); }

Target:
private void initialize() { graphLoadService = new GraphLoadService(); graphLoadService.setOnFailed(e -> new ExceptionDialog(root, graphLoadService.getException(), "Error loading graph files!")); graphLoadService.setOnRunning(e -> progressDialog.show()); graphLoadService.setOnSucceeded(e -> progressDialog.close()); newickLoadService = new NewickLoadService(); newickLoadService.setOnFailed(e -> new ExceptionDialog(root, newickLoadService.getException(), "Error loading newick file!")); }
Source:
public Resource syncAsset(Resource resource) { try { this.session.refresh(true); Resource localRes = this.resourceResolver.getResource(resource.getPath()); Node node = localRes.adaptTo(Node.class); Asset asset = localRes.getParent().adaptTo(Asset.class); URI pathUi = new URI(null, null, asset.getPath(), null); String baseUrl = this.remoteAssetsConfig.getServer().concat(pathUi.toString()).concat("/_jcr_content/renditions/"); Iterator<? extends Rendition> renditions = asset.listRenditions(); while (renditions.hasNext()) { Rendition assetRendition = renditions.next(); if (StringUtils.isEmpty(assetRendition.getMimeType())) { continue; } String renditionName = assetRendition.getName(); URL url = new URL(String.format("%s%s", baseUrl, renditionName)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", String.format("Basic %s", RemoteAssets.encodeForBasicAuth(this.remoteAssetsConfig))); if (LOG.isDebugEnabled()) { LOG.debug("syncing from remote asset url {}", url); } setRenditionOnAsset(connection, assetRendition, asset, renditionName); } node.setProperty("isRemoteAsset", (Value)null); node.setProperty("remoteSyncFailed", (Value)null); this.session.save(); return localRes; } catch (Exception e) { LOG.error("Error transferring remote asset '{}' to local server {}", resource.getPath(), e); try { this.session.refresh(false); } catch (RepositoryException re) { LOG.error("Failed to rollback asset changes", re); } return flagAssetAsFailedSync(resource); } }

Target:
public boolean syncAsset(Resource resource) { ResourceResolver remoteAssetsResolver = null; try { remoteAssetsResolver = this.remoteAssetsConfig.getResourceResolver(); Resource localRes = remoteAssetsResolver.getResource(resource.getPath()); Asset asset = DamUtil.resolveToAsset(localRes); URI pathUri = new URI(null, null, asset.getPath(), null); String baseUrl = this.remoteAssetsConfig.getServer().concat(pathUri.toString()).concat("/_jcr_content/renditions/"); Iterator<? extends Rendition> renditions = asset.listRenditions(); while (renditions.hasNext()) { Rendition assetRendition = renditions.next(); if (StringUtils.isEmpty(assetRendition.getMimeType())) { continue; } String renditionName = assetRendition.getName(); String remoteUrl = String.format("%s%s", baseUrl, renditionName); setRenditionOnAsset(remoteUrl, assetRendition, asset, renditionName); } ModifiableValueMap localResProps = localRes.adaptTo(ModifiableValueMap.class); localResProps.remove(RemoteAssets.IS_REMOTE_ASSET); localResProps.remove(RemoteAssets.REMOTE_SYNC_FAILED); remoteAssetsResolver.commit(); return true; } catch (Exception e) { LOG.error("Error transferring remote asset '{}' to local server", resource.getPath(), e); try { remoteAssetsResolver.revert(); } catch (Exception re) { LOG.error("Failed to rollback asset changes", re); } flagAssetAsFailedSync(remoteAssetsResolver, resource); } finally { this.remoteAssetsConfig.closeResourceResolver(remoteAssetsResolver); } return false; }