auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { String workspaceId = workspace.getId(); try { runtime.start(options); try (Unlocker ignored = lockService.writeLock(workspaceId)) { statuses.replace(workspaceId, RUNNING); } LOG.info( "Workspace '{}:{}' with id '{}' started by user '{}'", workspace.getNamespace(), workspace.getName(), workspaceId, sessionUserNameOr("undefined")); publishWorkspaceStatusEvent(workspaceId, RUNNING, STARTING, null, true); } catch (InfrastructureException e) { try (Unlocker ignored = lockService.writeLock(workspaceId)) { runtimes.remove(workspaceId); statuses.remove(workspaceId); } probeScheduler.cancel(workspaceId); String failureCause = "failed"; boolean isWorkspaceStartInterrupted = e instanceof RuntimeStartInterruptedException; if (isWorkspaceStartInterrupted) { failureCause = "interrupted"; } LOG.info( "Workspace '{}:{}' with id '{}' start {}", workspace.getNamespace(), workspace.getName(), workspaceId, failureCause); if (e instanceof InternalInfrastructureException) { LOG.error(e.getLocalizedMessage(), e); } publishWorkspaceStatusEvent( workspaceId, STOPPED, STARTING, e.getMessage(), isWorkspaceStartInterrupted, Collections.emptyMap()); throw new RuntimeException(e); } }

Target:
public void run() { String workspaceId = workspace.getId(); try { runtime.start(options); try (Unlocker ignored = lockService.writeLock(workspaceId)) { statuses.replace(workspaceId, RUNNING); } LOG.info( "Workspace '{}:{}' with id '{}' started by user '{}'", workspace.getNamespace(), workspace.getName(), workspaceId, sessionUserNameOr("undefined")); publishWorkspaceStatusEvent(workspaceId, RUNNING, STARTING, null, true); } catch (InfrastructureException e) { try (Unlocker ignored = lockService.writeLock(workspaceId)) { runtimes.remove(workspaceId); statuses.remove(workspaceId); } probeScheduler.cancel(workspaceId); String failureCause = "failed"; boolean isWorkspaceStartInterrupted = e instanceof RuntimeStartInterruptedException; if (isWorkspaceStartInterrupted) { failureCause = "interrupted"; } LOG.info( "Workspace '{}:{}' with id '{}' start {}", workspace.getNamespace(), workspace.getName(), workspaceId, failureCause); if (e instanceof InternalInfrastructureException) { LOG.error(e.getLocalizedMessage(), e); } publishWorkspaceStatusEvent( workspaceId, STOPPED, STARTING, e.getMessage(), isWorkspaceStartInterrupted); throw new RuntimeException(e); } }
Source:
XmlComponentConfigurations loadEncryptedSnapshotFileContent(long snapshotID) throws KuraException { File fSnapshot = getSnapshotFile(snapshotID); if (fSnapshot == null || !fSnapshot.exists()) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND, fSnapshot.getAbsolutePath()); } FileReader fr = null; BufferedReader br = null; StringBuilder entireFile = new StringBuilder(); try { fr = new FileReader(fSnapshot); br = new BufferedReader(fr); String line = ""; while ((line = br.readLine()) != null) { entireFile.append(line); } } catch (IOException e) { s_logger.error("Error loading file from disk", e); return null; } finally { try { if (br != null) { br.close(); } } catch (IOException e) { } try { if (fr != null) { fr.close(); } } catch (IOException e) { } } char[] decryptAes = this.m_cryptoService.decryptAes(entireFile.toString().toCharArray()); if (decryptAes == null) { throw new KuraException(KuraErrorCode.DECODER_ERROR); } String decryptedContent = new String(decryptAes); XmlComponentConfigurations xmlConfigs = null; try { xmlConfigs = XmlUtil.unmarshal(decryptedContent, XmlComponentConfigurations.class); } catch (XMLStreamException e) { s_logger.warn("Error parsing xml", e); } catch (FactoryConfigurationError e) { s_logger.warn("Error parsing xml", e); } return ConfigurationUpgrade.upgrade(xmlConfigs); }

Target:
XmlComponentConfigurations loadEncryptedSnapshotFileContent(long snapshotID) throws KuraException { File fSnapshot = getSnapshotFile(snapshotID); if (fSnapshot == null || !fSnapshot.exists()) { throw new KuraException(KuraErrorCode.CONFIGURATION_SNAPSHOT_NOT_FOUND, fSnapshot.getAbsolutePath()); } FileReader fr = null; BufferedReader br = null; StringBuilder entireFile = new StringBuilder(); try { fr = new FileReader(fSnapshot); br = new BufferedReader(fr); String line = ""; while ((line = br.readLine()) != null) { entireFile.append(line); } } catch (IOException e) { logger.error("Error loading file from disk", e); return null; } finally { try { if (br != null) { br.close(); } } catch (IOException e) { } try { if (fr != null) { fr.close(); } } catch (IOException e) { } } char[] decryptAes = this.cryptoService.decryptAes(entireFile.toString().toCharArray()); if (decryptAes == null) { throw new KuraException(KuraErrorCode.DECODER_ERROR); } String decryptedContent = new String(decryptAes); XmlComponentConfigurations xmlConfigs = null; try { xmlConfigs = XmlUtil.unmarshal(decryptedContent, XmlComponentConfigurations.class); } catch (XMLStreamException e) { logger.warn("Error parsing xml", e); } catch (FactoryConfigurationError e) { logger.warn("Error parsing xml", e); } return ConfigurationUpgrade.upgrade(xmlConfigs); }
Source:
private void invokeNoMoreSplitsIfNecessary() { taskExecutionLock.readLock().lock(); try { if (!partitions.isEmpty() || !fileIterators.isEmpty()) { return; } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); return; } finally { taskExecutionLock.readLock().unlock(); } taskExecutionLock.writeLock().lock(); try { if (partitions.isEmpty() && fileIterators.isEmpty()) { hiveSplitSource.noMoreSplits(); } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped); } finally { taskExecutionLock.writeLock().unlock(); } }

Target:
private void invokeNoMoreSplitsIfNecessary() { taskExecutionLock.readLock().lock(); try { if (!partitions.isEmpty() || !fileIterators.isEmpty()) { return; } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped, "Task is not marked as stopped even though it failed"); return; } finally { taskExecutionLock.readLock().unlock(); } taskExecutionLock.writeLock().lock(); try { if (partitions.isEmpty() && fileIterators.isEmpty()) { hiveSplitSource.noMoreSplits(); } } catch (Exception e) { hiveSplitSource.fail(e); checkState(stopped, "Task is not marked as stopped even though it failed"); } finally { taskExecutionLock.writeLock().unlock(); } }
Source:
protected void cleanup() throws Exception { delete(item); }

Target:
protected void cleanup() throws Exception { delete(workspaceItem); }
Source:
public static void testGetAllActivities() throws MambuApiException { System.out.println("\nIn testGetAllActivities"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 5; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate); if (jsonActivities == null) { System.out.println("Error - API returned NULL for" + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total activities returned=" + jsonActivities.size() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); System.out.println(activity.getType() + "\tID =" + activity.getTransactionId() + " Client Key=" + activity.getClientKey() + "\tLoanAccount Key=" + activity.getLoanAccountKey() + "\tSavingsAccount Key=" + activity.getSavingsAccountKey()); } return; }

Target:
public static void testGetAllActivities() throws MambuApiException { System.out.println("\nIn testGetAllActivities"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 5; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate); if (jsonActivities == null) { System.out.println("Error - API returned NULL for" + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total activities returned=" + jsonActivities.size() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); ActivityType activityType = activity.getType(); System.out.println(activityType + "\tID =" + activity.getTransactionId() + " Client Key=" + activity.getClientKey() + "\tLoanAccount Key=" + activity.getLoanAccountKey() + "\tSavingsAccount Key=" + activity.getSavingsAccountKey()); final String activityTypePrefix = "CLIENT_"; if (clientKeyWithActivities == null && activityType != null && activityType.name().startsWith(activityTypePrefix)) { clientKeyWithActivities = activity.getClientKey(); } } }
Source:
public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); if (NullHandling.sqlCompatible() && (leftVal.value() == null || rightVal.value() == null)) { return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { if (NullHandling.sqlCompatible() && (leftVal.isNull() || rightVal.isNull())) { return ExprEval.of(null); } return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { if (NullHandling.sqlCompatible() && (leftVal.isNull() || rightVal.isNull())) { return ExprEval.of(null); } return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }

Target:
public ExprEval eval(ObjectBinding bindings) { ExprEval leftVal = left.eval(bindings); ExprEval rightVal = right.eval(bindings); if (NullHandling.sqlCompatible() && (leftVal.value() == null || rightVal.value() == null)) { return ExprEval.of(null); } if (leftVal.type() == ExprType.STRING && rightVal.type() == ExprType.STRING) { return evalString(leftVal.asString(), rightVal.asString()); } else if (leftVal.type() == ExprType.LONG && rightVal.type() == ExprType.LONG) { if (NullHandling.sqlCompatible() && (leftVal.isNumericNull() || rightVal.isNumericNull())) { return ExprEval.of(null); } return ExprEval.of(evalLong(leftVal.asLong(), rightVal.asLong())); } else { if (NullHandling.sqlCompatible() && (leftVal.isNumericNull() || rightVal.isNumericNull())) { return ExprEval.of(null); } return ExprEval.of(evalDouble(leftVal.asDouble(), rightVal.asDouble())); } }
Source:
public void testFindAllIterationOperation() throws Exception { assertEquals(0, testCollection.count()); pumpDataIntoTestCollection(); int numToSkip = 0; final int limit = 100; for (int i = 0; i < 10; i++) { Map<String, Object> headers = new HashMap<String, Object>(); headers.put(MongoDbConstants.NUM_TO_SKIP, numToSkip); headers.put(MongoDbConstants.LIMIT, 100); Object result = template.requestBodyAndHeaders("direct:findAll", (Object) null, headers); System.out.println(result.getClass()); assertTrue("Result is not of type List", result instanceof List); @SuppressWarnings("unchecked") List<DBObject> resultList = (List<DBObject>) result; assertListSize("Result does not contain 100 elements", resultList, 100); assertEquals("Id of first record is not as expected", numToSkip + 1, Integer.parseInt((String) resultList.get(0).get("_id"))); for (DBObject dbObject : resultList) { assertNotNull("DBObject in returned list should contain all fields", dbObject.get("_id")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("scientist")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("fixedField")); } numToSkip = numToSkip + limit; } for (Exchange resultExchange : getMockEndpoint("mock:resultFindAll").getReceivedExchanges()) { assertEquals("Result page size header should equal 100", 100, resultExchange.getIn().getHeader(MongoDbConstants.RESULT_PAGE_SIZE)); } }

Target:
public void testFindAllIterationOperation() throws Exception { assertEquals(0, testCollection.count()); pumpDataIntoTestCollection(); int numToSkip = 0; final int limit = 100; for (int i = 0; i < 10; i++) { Map<String, Object> headers = new HashMap<String, Object>(); headers.put(MongoDbConstants.NUM_TO_SKIP, numToSkip); headers.put(MongoDbConstants.LIMIT, 100); Object result = template.requestBodyAndHeaders("direct:findAll", (Object) null, headers); assertTrue("Result is not of type List", result instanceof List); @SuppressWarnings("unchecked") List<DBObject> resultList = (List<DBObject>) result; assertListSize("Result does not contain 100 elements", resultList, 100); assertEquals("Id of first record is not as expected", numToSkip + 1, Integer.parseInt((String) resultList.get(0).get("_id"))); for (DBObject dbObject : resultList) { assertNotNull("DBObject in returned list should contain all fields", dbObject.get("_id")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("scientist")); assertNotNull("DBObject in returned list should contain all fields", dbObject.get("fixedField")); } numToSkip = numToSkip + limit; } for (Exchange resultExchange : getMockEndpoint("mock:resultFindAll").getReceivedExchanges()) { assertEquals("Result page size header should equal 100", 100, resultExchange.getIn().getHeader(MongoDbConstants.RESULT_PAGE_SIZE)); } }
Source:
public void testResynchronize_success() { this.client.getApplicationDelegate().resynchronize( this.app.getName() ); }

Target:
public void testResynchronize_success() throws ApplicationException { final Collection<Instance> rootInstances = this.app.getRootInstances(); for(Instance i : rootInstances) i.setStatus( InstanceStatus.DEPLOYED_STARTED ); this.client.getApplicationDelegate().resynchronize( this.app.getName() ); final List<Message> sentMessages = this.msgClient.sentMessages; Assert.assertEquals( rootInstances.size(), sentMessages.size() ); for (Iterator<Message> i = sentMessages.iterator(); i.hasNext();) Assert.assertTrue( i.next() instanceof MsgCmdResynchronize ); }
Source:
public final String toString() { return this.joinpoint.toString(); }

Target:
public String toString() { return this.joinpoint.toString(); }
Source:
public Future<Long> write(ByteBuffer src, Callback<Long> callback) { return writeInternal(() -> { ByteBuf copy = src.isDirect() ? ByteBufAllocator.DEFAULT.directBuffer(src.remaining()) : PooledByteBufAllocator.DEFAULT.heapBuffer(src.remaining()); copy.writeBytes(src); return copy; }, callback); }

Target:
public Future<Long> write(ByteBuffer src, Callback<Long> callback) { return writeInternal(() -> { ByteBuf copy = src.isDirect() ? ByteBufAllocator.DEFAULT.directBuffer(src.remaining()) : PooledByteBufAllocator.DEFAULT.heapBuffer(src.remaining()); copy.writeBytes(src); src.position(src.limit()); return copy; }, callback); }
Source:
public Criterion convert(final String value) { final Criterion.Builder criterionBuilder = new Criterion.Builder(); final Matcher multiComponentMatcher = MULTI_CRITERION_PATTERN.matcher(value); final Matcher singleComponentMatcher = SINGLE_CRITERION_PATTERN.matcher(value); final Matcher matchingMatcher; if (multiComponentMatcher.matches()) { matchingMatcher = multiComponentMatcher; } else if (singleComponentMatcher.matches()) { matchingMatcher = singleComponentMatcher; } else { throw new ParameterException("Invalid criterion: " + value); } final String id = matchingMatcher.group("id"); final String name = matchingMatcher.group("name"); final String status = matchingMatcher.group("status"); final String tags = matchingMatcher.group("tags"); final Set<String> splitTags = tags == null ? null : Sets.newHashSet(tags.split(",")); criterionBuilder .withId(id) .withName(name) .withStatus(status) .withTags(splitTags); try { return criterionBuilder.build(); } catch (final GeniePreconditionException e) { throw new ParameterException("Invalid criterion: " + value, e); } }

Target:
public Criterion convert(final String value) { final Criterion.Builder criterionBuilder = new Criterion.Builder(); final Matcher multiComponentMatcher = MULTI_CRITERION_PATTERN.matcher(value); final Matcher singleComponentMatcher = SINGLE_CRITERION_PATTERN.matcher(value); final Matcher matchingMatcher; if (multiComponentMatcher.matches()) { matchingMatcher = multiComponentMatcher; } else if (singleComponentMatcher.matches()) { matchingMatcher = singleComponentMatcher; } else { throw new ParameterException("Invalid criterion: " + value); } final String id = matchingMatcher.group(ID_CAPTURE_GROUP); final String name = matchingMatcher.group(NAME_CAPTURE_GROUP); final String status = matchingMatcher.group(STATUS_CAPTURE_GROUP); final String tags = matchingMatcher.group(TAGS_CAPTURE_GROUP); final Set<String> splitTags = tags == null ? null : Sets.newHashSet(tags.split(",")); criterionBuilder .withId(id) .withName(name) .withStatus(status) .withTags(splitTags); try { return criterionBuilder.build(); } catch (final GeniePreconditionException e) { throw new ParameterException("Invalid criterion: " + value, e); } }
Source:
protected IFigure createNodeShape() { final EObject eObj = resolveSemanticElement(); ViewNodeContainerFigureDesc shapeFigure = null; if (eObj instanceof DDiagramElementContainer) { final DDiagramElementContainer container = (DDiagramElementContainer) eObj; ContainerStyle ownedStyle = container.getOwnedStyle(); if (ownedStyle instanceof ShapeContainerStyle) { shapeFigure = new ViewNodeContainerParallelogram(); } else if (ownedStyle instanceof WorkspaceImage) { shapeFigure = new ViewNodeContainerRectangleFigureDesc(); } } else { deactivate(); } if (shapeFigure == null) { shapeFigure = new GradientRoundedRectangle(DiagramContainerEditPartOperation.getCornerDimension(this), DiagramContainerEditPartOperation.getBackgroundStyle(this)); } shapeFigure.getLabelFigure().setVisible(false); return shapeFigure; }

Target:
protected IFigure createNodeShape() { final EObject eObj = resolveSemanticElement(); ViewNodeContainerFigureDesc shapeFigure = null; if (eObj instanceof DDiagramElementContainer) { final DDiagramElementContainer container = (DDiagramElementContainer) eObj; ContainerStyle ownedStyle = container.getOwnedStyle(); if (ownedStyle instanceof ShapeContainerStyle) { shapeFigure = new ViewNodeContainerParallelogram(); } else if (ownedStyle instanceof WorkspaceImage) { shapeFigure = new ViewNodeContainerRectangleFigureDesc(); } } else { deactivate(); } if (shapeFigure == null) { shapeFigure = new GradientRoundedRectangle(DiagramContainerEditPartOperation.getCornerDimension(this), DiagramContainerEditPartOperation.getBackgroundStyle(this)); } if (eObj instanceof DDiagramElement && new DDiagramElementQuery((DDiagramElement) eObj).isLabelHidden()) { shapeFigure.getLabelFigure().setVisible(false); } else { shapeFigure.getLabelFigure().setVisible(true); } return shapeFigure; }
Source:
public Batch firstBatch() throws RetryableException { setUpTopicPartitions(); Map<TopicPartition, OffsetAndTimestamp> kafkaOffsets = getOffsets(); consumer.assign(kafkaOffsets.keySet()); log.info("Subscribed to topics", kafkaOffsets.size()); kafkaOffsets.forEach( (topic, offset) -> { if (offset == null) { log.info("No offset for {}, starting at the end", topic); consumer.seekToEnd(Collections.singletonList(topic)); return; } consumer.seek(topic, offset.offset()); log.info("Set topic to {}", topic, offset); } ); return fetch(firstStartTime); }

Target:
public Batch firstBatch() throws RetryableException { setUpTopicPartitions(); Map<TopicPartition, OffsetAndTimestamp> kafkaOffsets = fetchOffsets(); consumer.assign(kafkaOffsets.keySet()); log.info("Subscribed to topics", kafkaOffsets.size()); kafkaOffsets.forEach( (topic, offset) -> { if (offset == null) { log.info("No offset for {}, starting at the end", topic); consumer.seekToEnd(Collections.singletonList(topic)); return; } consumer.seek(topic, offset.offset()); log.info("Set topic to {}", topic, offset); } ); return fetch(firstStartTime); }
Source:
private void refreshLocks() { try { Set<LockToken> toRefresh = ImmutableSet.copyOf(tokensToRefresh); if (toRefresh.isEmpty()) { return; } Set<LockToken> successfullyRefreshedTokens = timelockService.refreshLockLeases(toRefresh); Set<LockToken> refreshFailures = Sets.difference(toRefresh, successfullyRefreshedTokens); tokensToRefresh.removeAll(refreshFailures); if (!refreshFailures.isEmpty()) { log.info("Failed to refresh lock tokens, most likely because they were lost on the server." + " The first (up to) 20 of these were {}.", SafeArg.of("successfullyRefreshed", successfullyRefreshedTokens.size()), SafeArg.of("numLockTokens", refreshFailures.size()), SafeArg.of("firstFailures", Iterables.transform(Iterables.limit(refreshFailures, 20), LockToken::getRequestId))); } } catch (Throwable error) { log.warn("Error while refreshing locks. Trying again on next iteration", error); } }

Target:
private void refreshLocks() { try { Set<LockToken> toRefresh = ImmutableSet.copyOf(tokensToRefresh); if (toRefresh.isEmpty()) { return; } Set<LockToken> successfullyRefreshedTokens = timelockService.refreshLockLeases(toRefresh); Set<LockToken> refreshFailures = Sets.difference(toRefresh, successfullyRefreshedTokens); tokensToRefresh.removeAll(refreshFailures); if (!refreshFailures.isEmpty()) { log.info("Successfully refreshed {}, but failed to refresh lock tokens, " + "most likely because they were lost on the server." + " The first (up to) 20 of these were {}.", SafeArg.of("successfullyRefreshed", successfullyRefreshedTokens.size()), SafeArg.of("numLockTokens", refreshFailures.size()), SafeArg.of("firstFailures", Iterables.transform(Iterables.limit(refreshFailures, 20), LockToken::getRequestId))); } } catch (Throwable error) { log.warn("Error while refreshing locks. Trying again on next iteration", error); } }
Source:
public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { DocumentCursor<BaseDocument> cursor = null; try { String aqlQuery = String.format( "FOR target IN %s FILTER target._key >= @key SORT target._key ASC LIMIT %d RETURN %s ", table, recordcount, constructReturnForAQL(fields, "target")); Map<String, Object> bindVars = new MapBuilder().put("key", startkey).get(); cursor = arangoDriver.executeDocumentQuery(aqlQuery, bindVars, null, BaseDocument.class); Iterator<BaseDocument> iterator = cursor.entityIterator(); while (iterator.hasNext()) { BaseDocument aDocument = iterator.next(); HashMap<String, ByteIterator> aMap = new HashMap<String, ByteIterator>(aDocument.getProperties().size()); this.fillMap(aMap, aDocument.getProperties()); result.add(aMap); } return Status.OK; } catch (Exception e) { logger.error("Exception while trying scan " + table + " " + startkey + " " + recordcount, e); } finally { if (cursor != null) { try { cursor.close(); } catch (ArangoException e) { logger.error("Fail to close cursor", e); } } } return Status.ERROR; }

Target:
public Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { DocumentCursor<BaseDocument> cursor = null; try { String aqlQuery = String.format( "FOR target IN %s FILTER target._key >= @key SORT target._key ASC LIMIT %d RETURN %s ", table, recordcount, constructReturnForAQL(fields, "target")); Map<String, Object> bindVars = new MapBuilder().put("key", startkey).get(); cursor = arangoDriver.executeDocumentQuery(aqlQuery, bindVars, null, BaseDocument.class); Iterator<BaseDocument> iterator = cursor.entityIterator(); while (iterator.hasNext()) { BaseDocument aDocument = iterator.next(); HashMap<String, ByteIterator> aMap = new HashMap<String, ByteIterator>(aDocument.getProperties().size()); if (!this.fillMap(aMap, aDocument.getProperties())) { return Status.ERROR; } result.add(aMap); } return Status.OK; } catch (Exception e) { logger.error("Exception while trying scan with ex {}", table, startkey, recordcount, e.toString()); } finally { if (cursor != null) { try { cursor.close(); } catch (ArangoException e) { logger.error("Fail to close cursor", e); } } } return Status.ERROR; }
Source:
public void onTestContextInitialized() { execute( "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest.address(street text)", "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest.user(name text PRIMARY KEY, address address)", "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest2.address(street text)", "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest2.user(name text PRIMARY KEY, address address)" ); }

Target:
public void onTestContextInitialized() { execute( "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest.address(street text)", "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest.user(name text PRIMARY KEY, address frozen<address>)", "CREATE KEYSPACE IF NOT EXISTS MapperKeyspaceTest2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", "CREATE TYPE IF NOT EXISTS MapperKeyspaceTest2.address(street text)", "CREATE TABLE IF NOT EXISTS MapperKeyspaceTest2.user(name text PRIMARY KEY, address frozen<address>)" ); }
Source:
public void passesValidXmlWithNetworkProblems() throws Exception { final Validator validator = Mockito.mock(Validator.class); final AtomicInteger counter = new AtomicInteger(0); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final int attempt = counter.incrementAndGet(); if (attempt == 1 || attempt == 2) { throw new SocketException( String.format("Attempt #%s failed", attempt) ); } else { return null; } } }).when(validator).validate(Mockito.any(Source.class)); new StrictXML( new XMLDocument( "<root>passesValidXmlWithNetworkProblems</root>" ), validator ); }

Target:
public void passesValidXmlWithNetworkProblems() throws Exception { final Validator validator = Mockito.mock(Validator.class); final AtomicInteger counter = new AtomicInteger(0); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { final int attempt = counter.incrementAndGet(); if (attempt == 1 || attempt == 2) { throw new SocketException( String.format("Attempt #%s failed", attempt) ); } return null; } } ).when(validator).validate(Mockito.any(Source.class)); new StrictXML( new XMLDocument( "<root>passesValidXmlWithNetworkProblems</root>" ), validator ); }
Source:
private void playOutExplosion(GlowPlayer player, Iterable<Block> blocks) { Collection<Record> records = new ArrayList<>(); for (Block block : blocks) { byte x = (byte) (block.getLocation().getBlockX() - (int) location.getX()); byte y = (byte) (block.getLocation().getBlockY() - (int) location.getY()); byte z = (byte) (block.getLocation().getBlockZ() - (int) location.getZ()); records.add(new Record(x, y, z)); } Vector velocity = player.getVelocity(); ExplosionMessage message = new ExplosionMessage((float) location.getX(), (float) location.getY(), (float) location.getZ(), power, (float) velocity.getX(), (float) velocity.getY(), (float) velocity.getZ(), records); player.getSession().send(message); }

Target:
private void playOutExplosion(GlowPlayer player, Iterable<Block> blocks) { Collection<Record> records = new ArrayList<>(); for (Block block : blocks) { Location blockLocation = block.getLocation(); byte x = (byte) (blockLocation.getBlockX() - (int) this.location.getX()); byte y = (byte) (blockLocation.getBlockY() - (int) this.location.getY()); byte z = (byte) (blockLocation.getBlockZ() - (int) this.location.getZ()); records.add(new Record(x, y, z)); } Vector velocity = player.getVelocity(); ExplosionMessage message = new ExplosionMessage((float) location.getX(), (float) location.getY(), (float) location.getZ(), power, (float) velocity.getX(), (float) velocity.getY(), (float) velocity.getZ(), records); player.getSession().send(message); }
Source:
public void testWindowDataManager() throws Exception { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); KinesisStringInputOperator inputOperator = dag.addOperator("KinesisInput", new KinesisStringInputOperator() { @Override public void deactivate() { } @Override public void teardown() { } }); testMeta.operator = inputOperator; Assert.assertFalse("Default behaviour of WindowDataManager changed", (inputOperator.getWindowDataManager() instanceof WindowDataManager.NoopWindowDataManager)); }

Target:
public void testWindowDataManager() throws Exception { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); KinesisStringInputOperator inputOperator = dag.addOperator("KinesisInput", new KinesisStringInputOperator() { @Override public void deactivate() { } @Override public void teardown() { } }); testMeta.operator = inputOperator; Assert.assertTrue("Default behaviour of WindowDataManager changed", (inputOperator.getWindowDataManager() instanceof WindowDataManager.NoopWindowDataManager)); }
Source:
public void doLaunch(Context context, View v) { if (v == null) { if (togglesHandler == null) { togglesHandler = new TogglesHandler(context); } String msg = context.getResources().getString(togglesHandler.getState(togglePojo) ? R.string.toggles_off : R.string.toggles_on); togglesHandler.setState(togglePojo, !togglesHandler.getState(togglePojo)); Toast.makeText(context, String.format(msg + " " + this.pojo.displayName, Locale.getDefault()), Toast.LENGTH_SHORT).show(); } else { final CompoundButton toggleButton = (CompoundButton) v .findViewById(R.id.item_toggle_action_toggle); if (toggleButton.isEnabled()) { toggleButton.performClick(); } } }

Target:
public void doLaunch(Context context, View v) { if (v == null) { if (togglesHandler == null) { togglesHandler = new TogglesHandler(context); } String msg = context.getResources().getString(togglesHandler.getState(togglePojo) ? R.string.toggles_off : R.string.toggles_on); togglesHandler.setState(togglePojo, !togglesHandler.getState(togglePojo)); Toast.makeText(context, String.format(msg, " " + this.pojo.displayName), Toast.LENGTH_SHORT).show(); } else { final CompoundButton toggleButton = (CompoundButton) v .findViewById(R.id.item_toggle_action_toggle); if (toggleButton.isEnabled()) { toggleButton.performClick(); } } }
Source:
public void log(RequestLogLine requestLogLine) throws IOException { IOException exception = null; for (RequestLogger logger : loggers) { try { logger.log(requestLogLine); } catch (IOException e) { if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } if (exception != null) { throw exception; } }

Target:
public void log(RequestLogLine requestLogLine) throws IOException { Exception exception = null; for (RequestLogger logger : loggers) { try { logger.log(requestLogLine); } catch (Exception e) { if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } if (exception != null) { Throwables.propagateIfInstanceOf(exception, IOException.class); throw Throwables.propagate(exception); } }
Source:
public List<IndexedVector> sendReduceData(final int iteration) { final List<IndexedVector> columnsOfResultMatrix = new LinkedList<>(); for (final Integer column : elementsOfLargeMatrix.keySet()) { final Vector columnVectorOfLargeMatrix = getColumnVector(elementsOfLargeMatrix.get(column)); final Vector columnVectorOfResultMatrix = getColumnOfResultMatrix(columnVectorOfLargeMatrix); columnsOfResultMatrix.add(new IndexedVector(column, columnVectorOfResultMatrix)); } return columnsOfResultMatrix; }

Target:
public List<IndexedVector> sendReduceData(final int iteration) { return columnsOfResultMatrix; }
Source:
public HMSShim(IMetaStoreClient client) { while (Proxy.isProxyClass(client.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(client); if (handler.getClass().isAssignableFrom(RetryingMetaStoreClient.class)) { client = getField(handler, "base"); continue; } throw new RuntimeException("Unknown InvocationHandler " + handler.getClass()); } mClient = getField(client, "client"); }

Target:
public HMSShim(IMetaStoreClient client) { while (Proxy.isProxyClass(client.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(client); if (handler.getClass().isAssignableFrom(RetryingMetaStoreClient.class)) { client = getField(handler, "base"); continue; } throw new RuntimeException("Unknown proxy handler for IMetaStoreClient"); } mClient = getField(client, "client"); }
Source:
private void reloadRecentRepositories() { new ProgressDialogTask<Void>(this) { @Override protected Void run(Account account) throws IOException { List<User> orgs = accountDataManager.getOrgs(false); for (User org: orgs) { RecentRepositories cache = new RecentRepositories(SettingsActivity.this, org); cache.clearAll(); cache.saveAsync(); } return null; } @Override public void execute() { showIndeterminate(getString(R.string .updating_recent_repositories)); super.execute(); } @Override protected void onSuccess(Void result) throws Exception { super.onSuccess(result); ToastUtils.show(SettingsActivity.this, R.string. success_clearing_recent_repositories); } }.execute(); }

Target:
private void reloadRecentRepositories() { new AuthenticatedUserTask<Void>(this) { @Override protected Void run(Account account) throws IOException { List<User> orgs = accountDataManager.getOrgs(false); for (User org: orgs) { RecentRepositories cache = new RecentRepositories(SettingsActivity.this, org); cache.clearAll(); cache.saveAsync(); } return null; } @Override public void execute() { super.execute(); } @Override protected void onSuccess(Void result) throws Exception { super.onSuccess(result); ToastUtils.show(SettingsActivity.this, R.string. success_clearing_recent_repositories); } }.execute(); }
Source:
public Map<Document, List<ValidationError>> validate(List<Document> documents) { Map<Document, List<ValidationError>> docErrorsMap = new HashMap<>(); documents.forEach(e -> docErrorsMap.put(e, new ArrayList<>())); runDocumentValidators(documents, docErrorsMap); runSectionValidators(documents, docErrorsMap); runSentenceValidators(documents, docErrorsMap); applyPreprocessorRules(documents, docErrorsMap); return docErrorsMap; }

Target:
public Map<Document, List<ValidationError>> validate(List<Document> documents) { Map<Document, List<ValidationError>> docErrorsMap = new HashMap<>(); documents.forEach(e -> docErrorsMap.put(e, new ArrayList<>())); initializeValidators(); runDocumentValidators(documents, docErrorsMap); runSectionValidators(documents, docErrorsMap); runSentenceValidators(documents, docErrorsMap); applyPreprocessorRules(documents, docErrorsMap); return docErrorsMap; }
Source:
private boolean hostHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return false; } ArchitectureType archType = cluster.getArchitecture(); return (archType == ArchitectureType.ppc64) || (archType == ArchitectureType.ppc64le) || (archType == ArchitectureType.ppcle); }

Target:
private boolean hostHasPpcArchitecture() { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return false; } ArchitectureType archType = cluster.getArchitecture(); return ArchitectureType.ppc64.equals(archType) || ArchitectureType.ppc64le.equals(archType) || ArchitectureType.ppcle.equals(archType); }
Source:
private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { if (entry.enabled) { activatedEntries.put(entry.getName(), entry); createExtension(entry, loadModule(entry.getConfig().getProperty(MODULE))); List<ExtensionEntry> entries = providesEntries.get(entry.getProvides()); if (entries == null) { entries = new ArrayList<>(); providesEntries.put(entry.getProvides(), entries); } entries.add(entry); } } }

Target:
private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { try { if (entry.enabled) { entry.setExtension(createExtension(entry, loadModule(entry.getConfig().getProperty(MODULE)))); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } } catch (ConfigurationException ex) { log.error(String.format("Error in activating extension %1$s. Exception message is " + entry.getName()), ex.getMessage()); if (log.isDebugEnabled()) { log.error("", ex); } } } }
Source:
private void sendEvent(Address subscriber, EventEnvelope eventEnvelope, int orderKey) { String serviceName = eventEnvelope.getServiceName(); EventServiceSegment segment = getSegment(serviceName, true); boolean sync = segment.incrementPublish() % eventSyncFrequency == 0; if (sync) { SendEventOperation op = new SendEventOperation(eventEnvelope, orderKey); Future f = nodeEngine.getOperationService() .createInvocationBuilder(serviceName, op, subscriber) .setTryCount(SEND_RETRY_COUNT).invoke(); try { f.get(sendEventSyncTimeoutMillis, MILLISECONDS); } catch (Exception e) { syncDeliveryFailureCount.inc(); if (logger.isFinestEnabled()) { logger.finest("Sync event delivery failed. Event: " + eventEnvelope, e); } } } else { Packet packet = new Packet(serializationService.toBytes(eventEnvelope), orderKey) .setPacketType(Packet.Type.EVENT) .raiseFlags(Packet.FLAG_4_0); EndpointManager em = nodeEngine.getNode().getNetworkingService().getEndpointManager(MEMBER); if (!em.transmit(packet, subscriber)) { if (nodeEngine.isRunning()) { logFailure("Failed to send event packet to: %s, connection might not be alive.", subscriber); } } } }

Target:
private void sendEvent(Address subscriber, EventEnvelope eventEnvelope, int orderKey) { String serviceName = eventEnvelope.getServiceName(); EventServiceSegment segment = getSegment(serviceName, true); boolean sync = segment.incrementPublish() % eventSyncFrequency == 0; if (sync) { SendEventOperation op = new SendEventOperation(eventEnvelope, orderKey); Future f = nodeEngine.getOperationService() .createInvocationBuilder(serviceName, op, subscriber) .setTryCount(SEND_RETRY_COUNT).invoke(); try { f.get(sendEventSyncTimeoutMillis, MILLISECONDS); } catch (Exception e) { syncDeliveryFailureCount.inc(); if (logger.isFinestEnabled()) { logger.finest("Sync event delivery failed. Event: " + eventEnvelope, e); } } } else { Packet packet = new Packet(serializationService.toBytes(eventEnvelope), orderKey) .setPacketType(Packet.Type.EVENT); EndpointManager em = nodeEngine.getNode().getNetworkingService().getEndpointManager(MEMBER); if (!em.transmit(packet, subscriber)) { if (nodeEngine.isRunning()) { logFailure("Failed to send event packet to: %s, connection might not be alive.", subscriber); } } } }
Source:
private String createPatch(RevCommit commit) { Repository repository = input.getRepository(); CreatePatchOperation operation = new CreatePatchOperation( repository, commit); operation.useGitFormat(true); try { operation.execute(null); } catch (CoreException e) { Activator.logError(NLS.bind( UIText.CommitGraphTable_UnableToCreatePatch, commit .getId().name()), e); } String patchContent = operation.getPatchContent(); return patchContent; }

Target:
private String createPatch(RevCommit commit) { Repository repository = input.getRepository(); CreatePatchOperation operation = new CreatePatchOperation( repository, commit); operation.useGitFormat(true); operation.setContextLines(CreatePatchOperation.DEFAULT_CONTEXT_LINES); try { operation.execute(null); } catch (CoreException e) { Activator.logError(NLS.bind( UIText.CommitGraphTable_UnableToCreatePatch, commit .getId().name()), e); } String patchContent = operation.getPatchContent(); return patchContent; }
Source:
public void reloadConfig() { new GetRequest(mContext, mUrl, GetRequest.URI_CONFIG, mApiKey, null, result -> onReloadConfigComplete(result)); }

Target:
public void reloadConfig() { new GetRequest(mContext, mUrl, GetRequest.URI_CONFIG, mApiKey, null, this::onReloadConfigComplete); }
Source:
private void createSnapshotsForDisks() { for (DiskImage image : getDisksList()) { VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction( VdcActionType.CreateSnapshot, buildCreateSnapshotParameters(image), cloneContextAndDetachFromParent()); if (vdcReturnValue.getSucceeded()) { getTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); } else { throw new VdcBLLException(vdcReturnValue.getFault().getError(), "Failed to create snapshot!"); } } }

Target:
private void createSnapshotsForDisks() { for (DiskImage image : getDisksList()) { VdcReturnValueBase vdcReturnValue = Backend.getInstance().runInternalAction( VdcActionType.CreateSnapshot, buildCreateSnapshotParameters(image), ExecutionHandler.createDefaultContextForTasks(getContext())); if (vdcReturnValue.getSucceeded()) { getTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList()); } else { throw new VdcBLLException(vdcReturnValue.getFault().getError(), "Failed to create snapshot!"); } } }
Source:
public boolean matches(long ssrc) { if (primarySSRC != ssrc && rtxSSRC != ssrc) { return false; } return true; }

Target:
public boolean matches(long ssrc) { return primarySSRC == ssrc || rtxSSRC == ssrc; }
Source:
protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) { ILaunchConfiguration configuration = null; ILaunchConfigurationType configType = getLaunchConfigType(); List<ILaunchConfiguration> candidateConfigs = Collections.emptyList(); try { ILaunchConfiguration[] configs = DebugPlugin.getDefault() .getLaunchManager().getLaunchConfigurations(configType); candidateConfigs = new ArrayList<>(configs.length); for (ILaunchConfiguration config : configs) { IPath programPath = CDebugUtils.getProgramPath(config); String projectName = CDebugUtils.getProjectName(config); IPath binPath = bin.getResource().getProjectRelativePath(); if (programPath != null && programPath.equals(binPath)) { if (projectName != null && projectName.equals(bin.getCProject() .getProject().getName())) { candidateConfigs.add(config); } } } } catch (CoreException e) { e.printStackTrace(); } int candidateCount = candidateConfigs.size(); if (candidateCount < 1) { configuration = createConfiguration(bin, mode, true); } else if (candidateCount == 1) { configuration = candidateConfigs.get(0); } else { configuration = chooseConfiguration(candidateConfigs, mode); } return configuration; }

Target:
protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) { ILaunchConfiguration configuration = null; ILaunchConfigurationType configType = getLaunchConfigType(); List<ILaunchConfiguration> candidateConfigs = Collections.emptyList(); try { ILaunchConfiguration[] configs = DebugPlugin.getDefault() .getLaunchManager().getLaunchConfigurations(configType); candidateConfigs = new ArrayList<>(configs.length); for (ILaunchConfiguration config : configs) { IPath programPath = CDebugUtils.getProgramPath(config); String projectName = CDebugUtils.getProjectName(config); IPath binPath = bin.getResource().getProjectRelativePath(); if (programPath != null && programPath.equals(binPath)) { if (projectName != null && projectName.equals(bin.getCProject() .getProject().getName())) { candidateConfigs.add(config); } } } } catch (CoreException e) { DockerLaunchUIPlugin.log(e); } int candidateCount = candidateConfigs.size(); if (candidateCount < 1) { configuration = createConfiguration(bin, mode, true); } else if (candidateCount == 1) { configuration = candidateConfigs.get(0); } else { configuration = chooseConfiguration(candidateConfigs, mode); } return configuration; }
Source:
List<MediaWikiDumpFile> findDumpsLocally(DumpContentType dumpContentType) { String directoryPrefix = dumpContentType.toString().toLowerCase() + "-"; List<String> dumpFileDirectories; try { dumpFileDirectories = this.dumpfileDirectoryManager .getSubdirectories(directoryPrefix + "*"); } catch (IOException e) { logger.error("Unable to access dump directory: " + e.toString()); return Collections.<MediaWikiDumpFile> emptyList(); } List<MediaWikiDumpFile> result = new ArrayList<MediaWikiDumpFile>(); for (String directory : dumpFileDirectories) { String dateStamp = directory.substring(directoryPrefix.length()); if (dateStamp.matches("\\d\\d\\d\\d\\d\\d\\d\\d")) { WmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp, this.projectName, dumpfileDirectoryManager, dumpContentType); if (dumpFile.isAvailable()) { result.add(dumpFile); } else { logger.error("Incomplete local dump file data. Maybe delete " + dumpFile.getDumpfileDirectory() + " to attempt fresh download."); } } } Collections.sort(result, Collections .reverseOrder(new MediaWikiDumpFile.DateComparator())); return result; }

Target:
List<MediaWikiDumpFile> findDumpsLocally(DumpContentType dumpContentType) { String directoryPattern = WmfDumpFile.getDumpFileDirectoryName( dumpContentType, "*"); List<String> dumpFileDirectories; try { dumpFileDirectories = this.dumpfileDirectoryManager .getSubdirectories(directoryPattern); } catch (IOException e) { logger.error("Unable to access dump directory: " + e.toString()); return Collections.<MediaWikiDumpFile> emptyList(); } List<MediaWikiDumpFile> result = new ArrayList<MediaWikiDumpFile>(); for (String directory : dumpFileDirectories) { String dateStamp = WmfDumpFile .getDateStampFromDumpFileDirectoryName(dumpContentType, directory); if (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) { WmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp, this.projectName, dumpfileDirectoryManager, dumpContentType); if (dumpFile.isAvailable()) { result.add(dumpFile); } else { logger.error("Incomplete local dump file data. Maybe delete " + dumpFile.getDumpfileDirectory() + " to attempt fresh download."); } } } Collections.sort(result, Collections .reverseOrder(new MediaWikiDumpFile.DateComparator())); return result; }
Source:
private void setModuleDefinitions(CuratorFramework client, StreamDefinition definition) { String streamName = definition.getName(); String path = Paths.build(Paths.STREAMS, streamName); try { byte[] bytes = client.getData().forPath(path); if (bytes != null) { Map<String, String> map = ZooKeeperUtils.bytesToMap(bytes); if (map.get(MODULE_DEFINITIONS_KEY) == null) { List<ModuleDescriptor> moduleDescriptors = this.parser.parse(streamName, definition.getDefinition(), definitionKind); List<ModuleDefinition> moduleDefinitions = createModuleDefinitions(moduleDescriptors); if (!moduleDefinitions.isEmpty()) { map.put(DEFINITION_KEY, definition.getDefinition()); try { map.put(MODULE_DEFINITIONS_KEY, objectWriter.writeValueAsString(moduleDefinitions)); byte[] binary = ZooKeeperUtils.mapToBytes(map); BackgroundPathAndBytesable<?> op = client.checkExists().forPath(path) == null ? client.create() : client.setData(); op.forPath(path, binary); } catch (JsonProcessingException jpe) { logger.error("Exception writing module definitions " + moduleDefinitions + " for the stream " + streamName + " : " + jpe); } } } } } catch (Exception e) { logger.error("Exception when updating module definitions for the stream " + streamName + " : " + e); } }

Target:
private void setModuleDefinitions(CuratorFramework client, StreamDefinition definition) { String streamName = definition.getName(); String path = Paths.build(Paths.STREAMS, streamName); try { byte[] bytes = client.getData().forPath(path); if (bytes != null) { Map<String, String> map = ZooKeeperUtils.bytesToMap(bytes); if (map.get(MODULE_DEFINITIONS_KEY) == null) { List<ModuleDescriptor> moduleDescriptors = this.parser.parse(streamName, definition.getDefinition(), definitionKind); List<ModuleDefinition> moduleDefinitions = createModuleDefinitions(moduleDescriptors); if (!moduleDefinitions.isEmpty()) { map.put(DEFINITION_KEY, definition.getDefinition()); try { map.put(MODULE_DEFINITIONS_KEY, objectWriter.writeValueAsString(moduleDefinitions)); byte[] binary = ZooKeeperUtils.mapToBytes(map); BackgroundPathAndBytesable<?> op = client.checkExists().forPath(path) == null ? client.create() : client.setData(); op.forPath(path, binary); } catch (JsonProcessingException jpe) { logger.error("Exception writing module definitions " + moduleDefinitions + " for the stream " + streamName, jpe); } } } } } catch (Exception e) { logger.error("Exception when updating module definitions for the stream " + streamName, e); } }