auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String toString() { Iterable<String> parameterIndexii = Iterables.transform(positionList, new Function<Integer, String>() { @Override public String apply(Integer input) { return String.format("+%d", input); } }); return "check " + type.getPrettyPrintableName() + "(" + Joiner.on(", ").join(parameterIndexii) + ")"; }

Target:
public String toString() { Iterable<String> parameterIndices = Iterables.transform(positionList, new Function<Integer, String>() { @Override public String apply(Integer input) { return String.format("+%d", input); } }); return "check " + type.getPrettyPrintableName() + "(" + Joiner.on(", ").join(parameterIndices) + ")"; }
Source:
public void setSanStorageModel(SanStorageModel sanStorageModel) { super.setSanStorageModel(sanStorageModel); sanStorageModel.getLunSelectionChangedEvent().getListeners().clear(); sanStorageModel.getLunSelectionChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { String description = getDescription().getEntity(); if (description == null || description.isEmpty() || (!description.isEmpty() && descriptionDerivedFromLunId)) { LunModel selectedLunModel = ((ValueEventArgs<LunModel>) args).getValue(); if (selectedLunModel.getLunId() != null) { String newDescription = selectedLunModel.getLunId().substring(selectedLunModel.getLunId().length() - 4); getDescription().setEntity(newDescription); descriptionDerivedFromLunId = true; } } } }); }

Target:
public void setSanStorageModel(SanStorageModel sanStorageModel) { super.setSanStorageModel(sanStorageModel); sanStorageModel.getLunSelectionChangedEvent().getListeners().clear(); sanStorageModel.getLunSelectionChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { String description = getDescription().getEntity(); if (description == null || description.isEmpty() || (!description.isEmpty() && descriptionDerivedFromLunId)) { LunModel selectedLunModel = ((ValueEventArgs<LunModel>) args).getValue(); if (selectedLunModel.getLunId() != null) { int numOfChars = (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.PopulateDirectLUNDiskDescriptionWithLUNId); if (numOfChars == 0) { return; } String newDescription; if (numOfChars <= -1 || numOfChars >= selectedLunModel.getLunId().length()) { newDescription = selectedLunModel.getLunId(); } else { newDescription = selectedLunModel.getLunId().substring(selectedLunModel.getLunId().length() - numOfChars); } getDescription().setEntity(newDescription); descriptionDerivedFromLunId = true; } } } }); }
Source:
private Boolean hasIdPermission(Collection<Permission> permissions, Long id) { for (Permission p : permissions) { if (p.id != null && p.id.longValue() == id) { return true; } } return false; }

Target:
private Boolean hasIdPermission(Collection<Permission> permissions, Long id) { boolean hasIdPermission = false; for (Permission p : permissions) { if (p.id != null && p.id.longValue() == id) { hasIdPermission = true; break; } } return hasIdPermission; }
Source:
public void set(long uuid, VKmer thisReadSequence, VKmer mateReadSequence) { value = uuid; if (thisReadSequence == null) { this.thisReadSequence = null; } else { this.thisReadSequence.setAsCopy(thisReadSequence); } if (mateReadSequence == null) { this.mateReadSequence = null; } else { this.mateReadSequence.setAsCopy(mateReadSequence); } }

Target:
public void set(long uuid, VKmer thisReadSequence, VKmer mateReadSequence) { value = uuid; if (thisReadSequence == null) { throw new IllegalArgumentException("thisReadSequence can not be null!"); } getThisReadSequence().setAsCopy(thisReadSequence); if (mateReadSequence == null) { this.mateReadSequence = null; } else { getMateReadSequence().setAsCopy(mateReadSequence); } }
Source:
private static <M> OperatorImpl<M, ?> createOperatorImpl(MessageStreamImpl<M> source, OperatorSpec operatorSpec, Config config, TaskContext context) { if (operatorSpec instanceof StreamOperatorSpec) { StreamOperatorSpec<M, ?> streamOpSpec = (StreamOperatorSpec<M, ?>) operatorSpec; return new StreamOperatorImpl<>(streamOpSpec, source, config, context); } else if (operatorSpec instanceof SinkOperatorSpec) { return new SinkOperatorImpl<>((SinkOperatorSpec<M>) operatorSpec, config, context); } else if (operatorSpec instanceof WindowOperatorSpec) { return new WindowOperatorImpl((WindowOperatorSpec<M, ?, ?>) operatorSpec); } else if (operatorSpec instanceof PartialJoinOperatorSpec) { return new PartialJoinOperatorImpl<>((PartialJoinOperatorSpec) operatorSpec, source, config, context); } throw new IllegalArgumentException( String.format("Unsupported OperatorSpec: %s", operatorSpec.getClass().getName())); }

Target:
private <M> OperatorImpl<M, ?> createOperatorImpl(MessageStreamImpl<M> source, OperatorSpec operatorSpec, Config config, TaskContext context) { if (operatorSpec instanceof StreamOperatorSpec) { StreamOperatorSpec<M, ?> streamOpSpec = (StreamOperatorSpec<M, ?>) operatorSpec; return new StreamOperatorImpl<>(streamOpSpec, source, config, context); } else if (operatorSpec instanceof SinkOperatorSpec) { return new SinkOperatorImpl<>((SinkOperatorSpec<M>) operatorSpec, config, context); } else if (operatorSpec instanceof WindowOperatorSpec) { return new WindowOperatorImpl((WindowOperatorSpec<M, ?, ?>) operatorSpec, clock); } else if (operatorSpec instanceof PartialJoinOperatorSpec) { return new PartialJoinOperatorImpl<>((PartialJoinOperatorSpec) operatorSpec, source, config, context); } throw new IllegalArgumentException( String.format("Unsupported OperatorSpec: %s", operatorSpec.getClass().getName())); }
Source:
public Object decode(Response response, Type type) throws IOException { if (response.status() == 404) return Util.emptyValueOf(type); if (response.body() == null) return null; if (!(type instanceof Class)) { throw new UnsupportedOperationException( "JAXB only supports decoding raw types. Found " + type); } try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setFeature("<LINK_1>", false); saxParserFactory.setFeature("<LINK_3>", false); saxParserFactory.setFeature("<LINK_0>", false); saxParserFactory.setFeature("<LINK_2>", false); Source source = new SAXSource(saxParserFactory.newSAXParser().getXMLReader(), new InputSource(response.body().asInputStream())); Unmarshaller unmarshaller = jaxbContextFactory.createUnmarshaller((Class) type); return unmarshaller.unmarshal(source); } catch (JAXBException e) { throw new DecodeException(e.toString(), e); } catch (ParserConfigurationException e) { throw new DecodeException(e.toString(), e); } catch (SAXNotRecognizedException e) { throw new DecodeException(e.toString(), e); } catch (SAXNotSupportedException e) { throw new DecodeException(e.toString(), e); } catch (SAXException e) { throw new DecodeException(e.toString(), e); } finally { if (response.body() != null) { response.body().close(); } } }

Target:
public Object decode(Response response, Type type) throws IOException { if (response.status() == 404) return Util.emptyValueOf(type); if (response.body() == null) return null; if (!(type instanceof Class)) { throw new UnsupportedOperationException( "JAXB only supports decoding raw types. Found " + type); } try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setFeature("<LINK_1>", false); saxParserFactory.setFeature("<LINK_3>", false); saxParserFactory.setFeature("<LINK_0>", false); saxParserFactory.setFeature("<LINK_2>", false); Source source = new SAXSource(saxParserFactory.newSAXParser().getXMLReader(), new InputSource(response.body().asInputStream())); Unmarshaller unmarshaller = jaxbContextFactory.createUnmarshaller((Class) type); return unmarshaller.unmarshal(source); } catch (JAXBException e) { throw new DecodeException(e.toString(), e); } catch (ParserConfigurationException e) { throw new DecodeException(e.toString(), e); } catch (SAXException e) { throw new DecodeException(e.toString(), e); } finally { if (response.body() != null) { response.body().close(); } } }
Source:
public void endpointTest() throws Exception { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(URL); try { int statusCode = client.executeMethod(method); assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode); String response = method.getResponseBodyAsString(); assertTrue("Unexpected response body", response.contains("hello world")); assertTrue(checkLogMessage(2000, "SLF4J: Failed to load class")); } finally { method.releaseConnection(); } }

Target:
public void endpointTest() throws Exception { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(URL); try { int statusCode = client.executeMethod(method); assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode); String response = method.getResponseBodyAsString(); assertTrue("Unexpected response body", response.contains("hello world")); assertTrue(checkLogMessage(2000, "SLF4J: Failed to load class")); assertFalse(checkLogMessage(2000, "SLF4J Logger is ready for messages.")); } finally { method.releaseConnection(); } }
Source:
public void run() { try { jmsClientConnector.send(message, null, jmsProperties); } catch (ClientConnectorException e) { log.error("Error sending the JMS message: ", e); } }

Target:
public void run() { try { jmsClientConnector.send(message, null, jmsProperties); } catch (ClientConnectorException e) { log.error("Error sending JMS message: ", e); } }
Source:
public void testIterableSliceExpectedSingle() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); String data = "aaaaaaaaaabbbbbbbbbbccccc"; Payload payload = new InputStreamPayload(new ByteArrayInputStream(data.getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 25).iterator(); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(new String(ByteStreams.toByteArray(iter.next())), data); assertFalse(iter.hasNext()); }

Target:
public void testIterableSliceExpectedSingle() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); String contents = "aaaaaaaaaabbbbbbbbbbccccc"; Payload payload = new InputStreamPayload(new ByteArrayInputStream(contents.getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 25).iterator(); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(new String(ByteStreams.toByteArray(iter.next())), contents); assertFalse(iter.hasNext()); }
Source:
public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws CryptoException { setName(name); setIsSecure(isSecure); if (!isSecure && StringUtils.isNotEmpty(encryptedValue)) { errors().add(ENCRYPTEDVALUE, "You may specify encrypted value only when option 'secure' is true."); } if (StringUtils.isNotEmpty(value) && StringUtils.isNotEmpty(encryptedValue)) { addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError(ENCRYPTEDVALUE, "You may only specify `value` or `encrypted_value`, not both!"); } if (StringUtils.isNotEmpty(encryptedValue)) { setEncryptedValue(encryptedValue); } if (isSecure) { if (value != null) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } } else { setValue(new VariableValueConfig(value)); } }

Target:
public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws CryptoException { setName(name); setIsSecure(isSecure); if (!isSecure && StringUtils.isNotBlank(encryptedValue)) { errors().add(ENCRYPTEDVALUE, "You may specify encrypted value only when option 'secure' is true."); } if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(encryptedValue)) { addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError(ENCRYPTEDVALUE, "You may only specify `value` or `encrypted_value`, not both!"); } if (StringUtils.isNotBlank(encryptedValue)) { setEncryptedValue(encryptedValue); } if (isSecure) { if (value != null) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } } else { setValue(new VariableValueConfig(value)); } }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("_bytes", _bytes) .add("_scheduledFor", _scheduledFor) .add("_generatedAt", _generatedAt) .add("_format", _format) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("bytes", _bytes) .add("scheduledFor", _scheduledFor) .add("generatedAt", _generatedAt) .add("format", _format) .toString(); }
Source:
public void testIsConditionValidWhenHeaderIsValid() throws Exception { final ConditionCol52 conditionCol1 = fakeConditionCol52("header1"); final ConditionCol52 conditionCol2 = fakeConditionCol52("header2"); final Validator validator = new Validator(fakeCompositeColumn(conditionCol1, conditionCol2)); assertFalse(validator.isConditionValid(conditionCol2)); }

Target:
public void testIsConditionValidWhenHeaderIsValid() throws Exception { final ConditionCol52 conditionCol1 = fakeConditionCol52("header1"); final ConditionCol52 conditionCol2 = fakeConditionCol52("header2"); final Validator validator = new Validator(fakeCompositeColumn(conditionCol1, conditionCol2)); assertTrue(validator.isConditionValid(conditionCol2)); }
Source:
private void closeProducer(final long timeout, final TimeUnit timeUnit) { if (producer != null) { final Thread closeThread = new Log4jThread(new Runnable() { @Override public void run() { if (producer != null) { producer.close(); } } }, "KafkaManager-CloseThread"); closeThread.setDaemon(true); closeThread.start(); try { closeThread.join(timeUnit.toMillis(timeout)); } catch (final InterruptedException ignore) { } } }

Target:
private void closeProducer(final long timeout, final TimeUnit timeUnit) { if (producer != null) { final Thread closeThread = new Log4jThread(new Runnable() { @Override public void run() { if (producer != null) { producer.close(); } } }, "KafkaManager-CloseThread"); closeThread.setDaemon(true); closeThread.start(); try { closeThread.join(timeUnit.toMillis(timeout)); } catch (final InterruptedException ignore) { Thread.currentThread().interrupt(); } } }
Source:
public void testGetCustomPeriod404() throws InterruptedException, ParseException { server.enqueue( new MockResponse().setResponseCode(404)); GenericDateQueryOptions options = new GenericDateQueryOptions(); String startStr = "11-11-2012"; String endStr = "11-11-2013"; DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date end = dateFormat.parse(endStr); Date start = dateFormat.parse(startStr); options.CustomPeriod(start, end); MonitoringCenter result = monitoringCenterApi().get("serverId", options); assertEquals(result, null); assertEquals(server.getRequestCount(), 1); assertSent(server, "GET", "/monitoring_center/serverId?period=CUSTOM&start_date=" + URLEncoder.encode(FormatDateToISO8601(start)) + "&end_date=" + URLEncoder.encode(FormatDateToISO8601(end))); }

Target:
public void testGetCustomPeriod404() throws InterruptedException, ParseException { server.enqueue( new MockResponse().setResponseCode(404)); GenericDateQueryOptions options = new GenericDateQueryOptions(); String startStr = "11-11-2012"; String endStr = "11-11-2013"; DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date end = dateFormat.parse(endStr); Date start = dateFormat.parse(startStr); options.customPeriod(start, end); MonitoringCenter result = monitoringCenterApi().get("serverId", options); assertEquals(result, null); assertEquals(server.getRequestCount(), 1); assertSent(server, "GET", "/monitoring_center/serverId?period=CUSTOM&start_date=2012-11-11T00%3A00%3A00Z&end_date=2013-11-11T00%3A00%3A00Z"); }
Source:
private Sets.SetView<VariableReferenceExpression> extractInliningTargets(ProjectNode parent, ProjectNode child, Context context) { Set<VariableReferenceExpression> childOutputSet = ImmutableSet.copyOf(child.getOutputVariables()); Map<VariableReferenceExpression, Long> dependencies = parent.getAssignments() .getExpressions().stream() .flatMap(expression -> SymbolsExtractor.extractAllVariable(expression, context.getSymbolAllocator().getTypes()).stream()) .filter(childOutputSet::contains) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); Set<VariableReferenceExpression> constants = dependencies.keySet().stream() .filter(input -> child.getAssignments().get(input) instanceof Literal) .collect(toSet()); Set<VariableReferenceExpression> tryArguments = parent.getAssignments() .getExpressions().stream() .flatMap(expression -> extractTryArguments(expression, context.getSymbolAllocator().getTypes()).stream()) .collect(toSet()); Set<VariableReferenceExpression> singletons = dependencies.entrySet().stream() .filter(entry -> entry.getValue() == 1) .filter(entry -> !tryArguments.contains(entry.getKey())) .filter(entry -> !isIdentity(child.getAssignments(), entry.getKey())) .map(Map.Entry::getKey) .collect(toSet()); return Sets.union(singletons, constants); }

Target:
private Sets.SetView<VariableReferenceExpression> extractInliningTargets(ProjectNode parent, ProjectNode child, Context context) { Set<VariableReferenceExpression> childOutputSet = ImmutableSet.copyOf(child.getOutputVariables()); Map<VariableReferenceExpression, Long> dependencies = parent.getAssignments() .getExpressions() .stream() .map(OriginalExpressionUtils::castToExpression) .flatMap(expression -> SymbolsExtractor.extractAll(expression).stream()) .map(symbol -> variable(symbol.getName(), context.getSymbolAllocator().getTypes().get(symbol))) .filter(childOutputSet::contains) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); Set<VariableReferenceExpression> constants = dependencies.keySet().stream() .filter(input -> castToExpression(child.getAssignments().get(input)) instanceof Literal) .collect(toSet()); Set<VariableReferenceExpression> tryArguments = parent.getAssignments() .getExpressions().stream() .flatMap(expression -> extractTryArguments(castToExpression(expression), context.getSymbolAllocator().getTypes()).stream()) .collect(toSet()); Set<VariableReferenceExpression> singletons = dependencies.entrySet().stream() .filter(entry -> entry.getValue() == 1) .filter(entry -> !tryArguments.contains(entry.getKey())) .filter(entry -> !isIdentity(child.getAssignments(), entry.getKey())) .map(Map.Entry::getKey) .collect(toSet()); return Sets.union(singletons, constants); }
Source:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { JdbcSchema jdbc = (JdbcSchema) db; SystemConfig sc = db.systemConfig().get(new SystemConfig.Key()); Statement s = jdbc.getConnection().createStatement(); try { ResultSet r; r = s.executeQuery("SELECT name FROM projects WHERE project_id = 0"); try { if (!r.next()) { throw new OrmException("Cannot read old wild project"); } sc.wildProjectName = new Project.NameKey(r.getString(1)); } finally { r.close(); } if (jdbc.getDialect() instanceof DialectMySQL) { try { s.execute("DROP FUNCTION nextval_project_id"); } catch (SQLException se) { ui.message("Warning: could not delete function nextval_project_id"); } } else if (jdbc.getDialect() instanceof DialectH2) { s.execute("ALTER TABLE projects DROP CONSTRAINT" + " IF EXISTS CONSTRAINT_F3"); } } finally { s.close(); } db.systemConfig().update(Collections.singleton(sc)); }

Target:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { JdbcSchema jdbc = (JdbcSchema) db; SystemConfig sc = db.systemConfig().get(new SystemConfig.Key()); Statement s = jdbc.getConnection().createStatement(); try { ResultSet r; r = s.executeQuery("SELECT name FROM projects WHERE project_id = 0"); try { if (!r.next()) { throw new OrmException("Cannot read old wild project"); } sc.wildProjectName = new Project.NameKey(r.getString(1)); } finally { r.close(); } if (jdbc.getDialect() instanceof DialectMySQL) { try { s.execute("DROP FUNCTION nextval_project_id"); } catch (SQLException se) { ui.message("warning: could not delete function nextval_project_id"); } } else if (jdbc.getDialect() instanceof DialectH2) { s.execute("ALTER TABLE projects DROP CONSTRAINT" + " IF EXISTS CONSTRAINT_F3"); } } finally { s.close(); } db.systemConfig().update(Collections.singleton(sc)); }
Source:
protected Map<Locator, List<IMetric>> generateEnumForTenants() throws Exception { Map<Locator, List<IMetric>> locatorToMetrics = new HashMap<Locator, List<IMetric>>(); long startTime = System.currentTimeMillis(); final Locator locator1 = Locator.createLocatorFromPathComponents(TENANT1, "my", "enum", "values"); final Locator locator2 = Locator.createLocatorFromPathComponents(TENANT2, "my", "enum", "values"); List<IMetric> metrics = new ArrayList<IMetric>(); PreaggregatedMetric metric = getEnumMetric(locator1, startTime - DELTA_MS); metrics.add(metric); locatorToMetrics.put(locator1, metrics); metric = getEnumMetric(locator2, startTime); metrics = new ArrayList<IMetric>(); metrics.add(metric); locatorToMetrics.put(locator2, metrics); MetadataCache.getInstance().put(locator1, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator1, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); MetadataCache.getInstance().put(locator2, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator2, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); return locatorToMetrics; }

Target:
protected Map<Locator, List<IMetric>> generateEnumForTenants() throws Exception { Map<Locator, List<IMetric>> locatorToMetrics = new HashMap<Locator, List<IMetric>>(); long startTime = System.currentTimeMillis(); final Locator locator1 = Locator.createLocatorFromPathComponents(TENANT1, getClass().getSimpleName(), "my", "enum", "values"); final Locator locator2 = Locator.createLocatorFromPathComponents(TENANT2, getClass().getSimpleName(), "my", "enum", "values"); List<IMetric> metrics = new ArrayList<IMetric>(); PreaggregatedMetric metric = getEnumMetric(locator1, startTime - DELTA_MS); metrics.add(metric); locatorToMetrics.put(locator1, metrics); metric = getEnumMetric(locator2, startTime); metrics = new ArrayList<IMetric>(); metrics.add(metric); locatorToMetrics.put(locator2, metrics); MetadataCache.getInstance().put(locator1, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator1, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); MetadataCache.getInstance().put(locator2, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator2, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); return locatorToMetrics; }
Source:
private String getCrlFilePath() { String filePath = config.getString(ConfigProperties.CRL_FILE_PATH); if (filePath == null) { throw new IseException("CRL file path not defined in config file"); } return filePath; }

Target:
private String getCrlFilePath() throws ConfigurationException { String filePath = config.getString(ConfigProperties.CRL_FILE_PATH); if (filePath == null) { throw new ConfigurationException("CRL file path not defined in config file"); } return filePath; }
Source:
public PapyrusEditorFixture openTable(IMultiDiagramEditor editor, final String name) { activate(editor); try { ModelSet modelSet = ServiceUtils.getInstance().getModelSet(editor.getServicesRegistry()); PapyrusNattableModel notation = (PapyrusNattableModel) modelSet.getModel(PapyrusNattableModel.MODEL_ID); Table table = notation.getTable(name); ServiceUtils.getInstance().getIPageManager(editor.getServicesRegistry()).openPage(table); flushDisplayEvents(); activateDiagram(editor, name); } catch (Exception e) { throw new IllegalStateException("Cannot initialize test", e); } return this; }

Target:
public PapyrusEditorFixture openTable(IMultiDiagramEditor editor, final String name) { activate(editor); try { ModelSet modelSet = ServiceUtils.getInstance().getModelSet(editor.getServicesRegistry()); PapyrusNattableModel notation = (PapyrusNattableModel) modelSet.getModel(PapyrusNattableModel.MODEL_ID); Table table = notation.getTable(name); ServiceUtils.getInstance().getIPageManager(editor.getServicesRegistry()).openPage(table); flushDisplayEvents(); activateTable(editor, name); } catch (Exception e) { throw new IllegalStateException("Cannot initialize test", e); } return this; }
Source:
private void analyzeReplStatus(ASTNode ast) throws SemanticException { initReplStatus(ast); String dbNameOrPattern = replScope.getDbName(); String replLastId = getReplStatus(dbNameOrPattern); prepareReturnValues(Collections.singletonList(replLastId), "last_repl_id#string"); setFetchTask(createFetchTask("last_repl_id#string")); LOG.debug("ReplicationSemanticAnalyzer.analyzeReplStatus: writing repl.last.id={} out to {}", replLastId, ctx.getResFile(), conf); }

Target:
private void analyzeReplStatus(ASTNode ast) throws SemanticException { initReplStatus(ast); String dbNameOrPattern = replScope.getDbName(); String replLastId = getReplStatus(dbNameOrPattern); prepareReturnValues(Collections.singletonList(replLastId), "last_repl_id#string"); setFetchTask(createFetchTask("last_repl_id#string")); LOG.debug("ReplicationSemanticAnalyzer.analyzeReplStatus: writing repl.last.id={} out to using configuration {}", replLastId, ctx.getResFile(), conf); }
Source:
protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, KeyManagerFactory kmf, String keyStore) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf, keyStore); }

Target:
static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, KeyManagerFactory kmf, String keyStore) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf, keyStore); }
Source:
public CqlResult execute_cql3_query(ByteBuffer query, Compression compression, ConsistencyLevel consistency) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException { return checkLimitAndCall(() -> super.execute_cql3_query(query, compression, consistency)); }

Target:
public CqlResult execute_cql3_query(ByteBuffer query, Compression compression, ConsistencyLevel consistency) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException { qosClient.checkLimit(); CqlResult cqlResult = delegate.execute_cql3_query(query, compression, consistency); recordBytesRead(ThriftObjectSizeUtils.getCqlResultSize(cqlResult)); return cqlResult; }
Source:
public void updateAvailableUserActions(GameBean game) throws GameException { boolean isMandatory = false; List<String> actionsList = new ArrayList<String>(); List<GameUserActions> actionCode = new ArrayList<GameUserActions>(); switch (game.getStage()) { case PREPARATION: List<List<String>> initialBuildingsSet = getInitialBuildingsSetFromJson(game.getInitialBuildingsSet()); for (GameUserBean gameUser : game.getGameUsers()) { if (gameUser.getMoveOrder() == game.getCurrentMove()) { actionCode = getActionCodeInPreparationStage(game, initialBuildingsSet); } if (!actionCode.isEmpty()) { actionsList.add("{\"code\": \"" + actionCode.get(0).toString() + "\", \"params\": {}}"); gameUser.setAvailableActions("{\"list\": [" + actionsList.get(0) + "], \"isMandatory\": true}"); } else { gameUser.setAvailableActions("{\"list\": [], \"isMandatory\": false}"); } actionCode.clear(); actionsList.clear(); } break; case MAIN: for (GameUserBean gameUser : game.getGameUsers()) { if (gameUser.getMoveOrder() == game.getCurrentMove()) { gameUser.setAvailableActions("{\"list\": [], \"isMandatory\": false}"); } else { gameUser.setAvailableActions("{\"list\": [], \"isMandatory\": false}"); } } break; default: log.debug("Cannot recognize current game stage: {}", game.getStage()); throw new GameException(ERROR_CODE_ERROR); } }

Target:
public void updateAvailableUserActions(GameBean game) throws GameException { switch (game.getStage()) { case PREPARATION: preparationStageUtil.updateAvailableUserActions(game); break; case MAIN: break; default: log.debug("Cannot recognize current game stage: {}", game.getStage()); throw new GameException(ERROR_CODE_ERROR); } }
Source:
public void testSimpleJoin() throws InterruptedException { m_rejoinLog.info("testSimpleJoin"); long[] seeds = new long[] {0L, 0L, 0L, 0L, 0L}; final int clusterSize = 5; final int killSize = 2; constructCluster(clusterSize, seeds); while (!getNodesInState(NodeState.START).isEmpty()) { Thread.sleep(50); } FuzzTestState state = new FuzzTestState(0L, m_nodes.keySet()); int nextid = clusterSize; for (int i = 0; i < 8; ++i) { for (int k = 0; k < killSize; ++k){ if ((k % 2) == 1) { state.killRandomLink(); } else { state.killRandomNode(); } } state.setUpExpectations(); state.expect(); state.pruneDeadNodes(); int nodes2join = clusterSize - m_nodes.size(); for (int j = 0; j < nodes2join; j++) { int rejoinHostId = nextid++; state.joinNode(rejoinHostId, 0L); } state.settleMesh(); } }

Target:
public void testSimpleJoin() throws InterruptedException { m_rejoinLog.info("testSimpleJoin"); long[] seeds = new long[] {0L, 0L, 0L, 0L, 0L}; final int clusterSize = 5; final int killSize = 2; constructCluster(clusterSize, seeds); while (!getNodesInState(NodeState.START).isEmpty()) { Thread.sleep(50); } long seed = System.currentTimeMillis(); System.out.println("Fuzz State Seed: " + seed); FuzzTestState state = new FuzzTestState(seed, m_nodes.keySet()); int nextid = clusterSize; for (int i = 0; i < 8; ++i) { for (int k = 0; k < killSize; ++k){ if ((k % 2) == 1) { state.killRandomLink(); } else { state.killRandomNode(); } } state.setUpExpectations(); state.expect(); state.pruneDeadNodes(); int nodes2join = clusterSize - m_nodes.size(); for (int j = 0; j < nodes2join; j++) { int rejoinHostId = nextid++; state.joinNode(rejoinHostId, 0L); } state.settleMesh(); } }
Source:
public void handleMessage(Message msg) { try { if (msg.arg2 > INTERNALLY_RESERVED_COMMAND_MAX_USED && msg.arg2 <= INTERNALLY_RESERVED_COMMAND_MAX) { throw new RuntimeException("ReplicationService received an EXTRA_COMMAND " + "using an id in the range reserved for internal use. Custom commands " + "must" + " use an id above " + INTERNALLY_RESERVED_COMMAND_MAX); } switch (msg.arg2) { case COMMAND_START_REPLICATION: startReplications(); break; case COMMAND_STOP_REPLICATION: stopReplications(); break; default: break; } } finally { Intent intent = msg.getData().getParcelable(EXTRA_INTENT); WakefulBroadcastReceiver.completeWakefulIntent(intent); notifyOperationStarted(msg.arg2); } }

Target:
public void handleMessage(Message msg) { try { if (msg.arg2 > INTERNALLY_RESERVED_COMMAND_MAX_USED && msg.arg2 <= INTERNALLY_RESERVED_COMMAND_MAX) { throw new RuntimeException("ReplicationService received an EXTRA_COMMAND " + "using an id in the range reserved for internal use. Custom commands " + "must use an id above " + INTERNALLY_RESERVED_COMMAND_MAX); } switch (msg.arg2) { case COMMAND_START_REPLICATION: startReplications(); break; case COMMAND_STOP_REPLICATION: stopReplications(); break; default: break; } } finally { Intent intent = msg.getData().getParcelable(EXTRA_INTENT); WakefulBroadcastReceiver.completeWakefulIntent(intent); notifyOperationStarted(msg.arg2); } }
Source:
public static void checkpoint() { if(null == databaseInstance){ throw new IllegalStateException("database is not initialized"); } Cursor c = databaseInstance.query("pragma wal_checkpoint(full)", null); if(c.moveToFirst() && c.getInt(0) == 1) { throw new RuntimeException("Checkpoint was blocked from completing"); } }

Target:
public static void checkpoint() { if (databaseInstance == null) { throw new IllegalStateException("database is not initialized"); } Cursor c = databaseInstance.query("pragma wal_checkpoint(full)", null); if (c.moveToFirst() && c.getInt(0) == 1) { throw new RuntimeException("Checkpoint was blocked from completing"); } }
Source:
public void testAdminConfigsClientOverridesWithAllPolicy() { Map<String, String> props = new HashMap<>(workerProps); props.put("admin.client.id", "testid"); props.put("admin.metadata.max.age.ms", "5000"); WorkerConfig configWithOverrides = new StandaloneConfig(props); Map<String, Object> connConfig = new HashMap<String, Object>(); connConfig.put("metadata.max.age.ms", "10000"); Map<String, String> expectedConfigs = new HashMap<>(); expectedConfigs.putAll(props); expectedConfigs.put("bootstrap.servers", "localhost:9092"); expectedConfigs.put("client.id", "testid"); expectedConfigs.put("metadata.max.age.ms", "10000"); EasyMock.expect(connectorConfig.originalsWithPrefix(ConnectorConfig.CONNECTOR_CLIENT_ADMIN_OVERRIDES_PREFIX)) .andReturn(connConfig); PowerMock.replayAll(); assertEquals(expectedConfigs, Worker.adminConfigs(new ConnectorTaskId("test", 1), configWithOverrides, connectorConfig, null, allConnectorClientConfigOverridePolicy)); }

Target:
public void testAdminConfigsClientOverridesWithAllPolicy() { Map<String, String> props = new HashMap<>(workerProps); props.put("admin.client.id", "testid"); props.put("admin.metadata.max.age.ms", "5000"); props.put("producer.bootstrap.servers", "cbeauho.com"); props.put("consumer.bootstrap.servers", "localhost:4761"); WorkerConfig configWithOverrides = new StandaloneConfig(props); Map<String, Object> connConfig = new HashMap<String, Object>(); connConfig.put("metadata.max.age.ms", "10000"); Map<String, String> expectedConfigs = new HashMap<>(workerProps); expectedConfigs.put("bootstrap.servers", "localhost:9092"); expectedConfigs.put("client.id", "testid"); expectedConfigs.put("metadata.max.age.ms", "10000"); EasyMock.expect(connectorConfig.originalsWithPrefix(ConnectorConfig.CONNECTOR_CLIENT_ADMIN_OVERRIDES_PREFIX)) .andReturn(connConfig); PowerMock.replayAll(); assertEquals(expectedConfigs, Worker.adminConfigs(new ConnectorTaskId("test", 1), configWithOverrides, connectorConfig, null, allConnectorClientConfigOverridePolicy)); }
Source:
public void onNext(final TaskStart taskStart) { LOG.log(Level.FINE, "Sends a msg to register itself to start subscribing updates in routing table"); sender.sendWorkerRegisterMsg(); }

Target:
public void onNext(final TaskStart taskStart) { LOG.log(Level.FINE, "Task {0} sends a msg to register itself to start subscribing updates in routing table", taskStart.getId()); sender.sendWorkerRegisterMsg(); }
Source:
private void addUGI(FileStatus remoteStatus, AclStatus remoteAcl) { if (remoteAcl != null) { addUser(remoteAcl.getOwner()); addGroup(remoteAcl.getGroup()); for (AclEntry entry : remoteAcl.getEntries()) { if (entry.getName() != null) { if (entry.getType() == AclEntryType.USER) { addUser(entry.getName()); } else if (entry.getType() == AclEntryType.GROUP) { addGroup(entry.getName()); } } } } else { addUser(remoteStatus.getOwner()); addGroup(remoteStatus.getGroup()); } }

Target:
private void addUGI(FileStatus remoteStatus, AclStatus remoteAcl) { if (remoteAcl != null) { addUser(remoteAcl.getOwner()); addGroup(remoteAcl.getGroup()); for (AclEntry entry : remoteAcl.getEntries()) { String name = entry.getName(); if (name != null) { if (entry.getType() == AclEntryType.USER) { addUser(name); } else if (entry.getType() == AclEntryType.GROUP) { addGroup(name); } } } } else { addUser(remoteStatus.getOwner()); addGroup(remoteStatus.getGroup()); } }
Source:
public void putAttributes( final RepositoryItemUid uid, Attributes attributes ) { final RepositoryItemUidLock uidLock = uid.getAttributeLock(); uidLock.lock( Action.create ); try { if ( getLogger().isDebugEnabled() ) { getLogger().debug( "Storing attributes on UID=" + uid.toString() ); } try { Attributes onDisk = doGetAttributes( uid ); if ( onDisk != null && ( onDisk.getGeneration() > attributes.getGeneration() ) ) { onDisk.overlayAttributes( attributes ); onDisk.setRepositoryId( uid.getRepository().getId() ); onDisk.setPath( uid.getPath() ); onDisk.setReadable( attributes.isReadable() ); onDisk.setWritable( attributes.isWritable() ); attributes = onDisk; } File target = getFileFromBase( uid ); target.getParentFile().mkdirs(); if ( target.getParentFile().exists() && target.getParentFile().isDirectory() ) { FileOutputStream fos = null; try { fos = new FileOutputStream( target ); attributes.incrementGeneration(); marshaller.marshal( attributes, fos ); } catch ( IOException ex ) { target.delete(); throw ex; } finally { Closeables.closeQuietly( fos ); } } else { getLogger().error( "Could not store attributes on UID=" + uid.toString() + ", parent exists but is not a directory!" ); } } catch ( IOException ex ) { getLogger().error( "Got IOException during store of UID=" + uid.toString(), ex ); } } finally { uidLock.unlock(); } }

Target:
public void putAttributes( final RepositoryItemUid uid, Attributes attributes ) { final RepositoryItemUidLock uidLock = uid.getAttributeLock(); uidLock.lock( Action.create ); try { if ( getLogger().isDebugEnabled() ) { getLogger().debug( "Storing attributes on UID=" + uid.toString() ); } try { Attributes onDisk = doGetAttributes( uid ); if ( onDisk != null && ( onDisk.getGeneration() > attributes.getGeneration() ) ) { onDisk.overlayAttributes( attributes ); onDisk.setRepositoryId( uid.getRepository().getId() ); onDisk.setPath( uid.getPath() ); onDisk.setReadable( attributes.isReadable() ); onDisk.setWritable( attributes.isWritable() ); attributes = onDisk; } File target = getFileFromBase( uid ); target.getParentFile().mkdirs(); if ( target.getParentFile().exists() && target.getParentFile().isDirectory() ) { FileOutputStream fos = null; try { fos = new FileOutputStream( target ); attributes.incrementGeneration(); marshaller.marshal( attributes, fos ); } catch ( IOException ex ) { if ( target.length() == 0 ) { target.delete(); } throw ex; } finally { Closeables.closeQuietly( fos ); } } else { getLogger().error( "Could not store attributes on UID=" + uid.toString() + ", parent exists but is not a directory!" ); } } catch ( IOException ex ) { getLogger().error( "Got IOException during store of UID=" + uid.toString(), ex ); } } finally { uidLock.unlock(); } }
Source:
protected Startpoint() { this.createdTimestamp = Instant.now().toEpochMilli(); }

Target:
Startpoint() { this(Instant.now().toEpochMilli()); }
Source:
public void testParametrizedUriEmitterConfig() { final Properties props = new Properties(); props.setProperty("druid.emitter", "parametrized"); props.setProperty("druid.emitter.parametrized.recipientBaseUrlPattern", "<LINK_0>{feed}"); props.setProperty("druid.emitter.parametrized.httpEmitting.flushMillis", "1"); props.setProperty("druid.emitter.parametrized.httpEmitting.flushCount", "2"); props.setProperty("druid.emitter.parametrized.httpEmitting.basicAuthentication", "a:b"); props.setProperty("druid.emitter.parametrized.httpEmitting.batchingStrategy", "NEWLINES"); props.setProperty("druid.emitter.parametrized.httpEmitting.maxBatchSize", "4"); props.setProperty("druid.emitter.parametrized.httpEmitting.maxBufferSize", "8"); props.setProperty("druid.emitter.parametrized.httpEmitting.flushTimeOut", "1000"); final Emitter emitter = makeInjectorWithProperties(props).getInstance(Emitter.class); System.out.println(emitter); }

Target:
public void testParametrizedUriEmitterConfig() { final Properties props = new Properties(); props.setProperty("druid.emitter", "parametrized"); props.setProperty("druid.emitter.parametrized.recipientBaseUrlPattern", "<LINK_0>{feed}"); props.setProperty("druid.emitter.parametrized.httpEmitting.flushMillis", "1"); props.setProperty("druid.emitter.parametrized.httpEmitting.flushCount", "2"); props.setProperty("druid.emitter.parametrized.httpEmitting.basicAuthentication", "a:b"); props.setProperty("druid.emitter.parametrized.httpEmitting.batchingStrategy", "NEWLINES"); props.setProperty("druid.emitter.parametrized.httpEmitting.maxBatchSize", "4"); props.setProperty("druid.emitter.parametrized.httpEmitting.maxBufferSize", "8"); props.setProperty("druid.emitter.parametrized.httpEmitting.flushTimeOut", "1000"); final Emitter emitter = makeInjectorWithProperties(props).getInstance(Emitter.class); Assert.assertTrue(emitter instanceof ParametrizedUriEmitter); }
Source:
public SnapshotInitiationInfo(Object[] params) throws Exception { m_path = null; m_nonce = null; m_blocking = true; m_format = SnapshotFormat.NATIVE; m_data = null; m_truncationRequest = false; boolean checkNonceValidity = true; switch (params.length) { case 3: parseLegacyParams(params); break; case 1: parseJsonParams(params); break; default: m_nonce = MAGIC_NONCE_PREFIX + System.currentTimeMillis(); m_stype = SnapshotPathType.SNAP_AUTO; m_path = VoltDB.instance().getSnapshotPath(); break; } if (checkNonceValidity && m_nonce != null && (m_nonce.contains("-") || m_nonce.contains(",")) && m_nonce.startsWith(MAGIC_NONCE_PREFIX)) { throw new Exception("Provided nonce " + m_nonce + " contains a prohibited character (- or ,) or starts with " + MAGIC_NONCE_PREFIX); } }

Target:
public SnapshotInitiationInfo(Object[] params) throws Exception { m_path = null; m_nonce = null; m_blocking = true; m_format = SnapshotFormat.NATIVE; m_data = null; m_truncationRequest = false; boolean checkNonceValidity = true; switch (params.length) { case 3: parseLegacyParams(params); break; case 1: checkNonceValidity = parseJsonParams(params); break; default: m_nonce = MAGIC_NONCE_PREFIX + System.currentTimeMillis(); m_stype = SnapshotPathType.SNAP_AUTO; m_path = VoltDB.instance().getSnapshotPath(); checkNonceValidity = false; break; } if (checkNonceValidity && m_nonce != null && (m_nonce.contains("-") || m_nonce.contains(",") || m_nonce.startsWith(MAGIC_NONCE_PREFIX))) { throw new IllegalArgumentException("Provided nonce " + m_nonce + " contains a prohibited character (- or ,) or start with " + MAGIC_NONCE_PREFIX); } }
Source:
private int getLatestPacketFailRate() { int failure = 0; int sent = 0; int received = 0; for (Map.Entry<Long, TcpStat> pair : mTcpStats.entrySet()) { failure += (pair.getValue().lost + pair.getValue().retransmit); sent += pair.getValue().sent; received += pair.getValue().received; } updateSentSinceLastRecv(sent, received); if (mSentSinceLastRecv < getMinPacketsThreshold()) return 0; log("getLatestPacketFailRate:" + ((sent != 0) ? (failure * 100 / sent) : 0)); return ((sent != 0) ? (failure * 100 / sent) : 0); }

Target:
protected int getLatestPacketFailRate() { int failure = 0; int sent = 0; int received = 0; int size = mTcpStats.size(); for (int i = 0; i < size; i++) { long key = mTcpStats.keyAt(i); failure += (mTcpStats.get(key).nLost + mTcpStats.get(key).nRetransmit); sent += mTcpStats.get(key).nSent; received += mTcpStats.get(key).nReceived; } updateSentSinceLastRecv(sent, received); if (getSentSinceLastRecv() < getMinPacketsThreshold()) return 0; int rate = ((sent != 0) ? (failure * 100 / sent) : 0); log("getLatestPacketFailRate:" + rate); return rate; }
Source:
public void start() { cacheName = ByteString.fromString(cache.getName()); hasLoader = cache.getCacheConfiguration().persistence().usingStores(); ClusteringConfiguration clusteringConfiguration = cache.getCacheConfiguration().clustering(); this.maxSegment = clusteringConfiguration.hash().numSegments(); localAddress = rpc.getAddress(); requiresListener = !clusteringConfiguration.cacheMode().isReplicated(); if (requiresListener) { cache.addListener(this); } }

Target:
public void start() { cacheName = ByteString.fromString(cache.getName()); hasLoader = cache.getCacheConfiguration().persistence().usingStores(); ClusteringConfiguration clusteringConfiguration = cache.getCacheConfiguration().clustering(); this.maxSegment = clusteringConfiguration.hash().numSegments(); localAddress = rpc.getAddress(); isReplicated = clusteringConfiguration.cacheMode().isReplicated(); if (isReplicated) { cache.addListener(this); } }
Source:
public static List<String> getComputerNames() { final ArrayList<String> names = new ArrayList<String>(); for (Computer c : Jenkins.getActiveInstance().getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); } } return names; }

Target:
public static List<String> getComputerNames() { final ArrayList<String> names = new ArrayList<String>(); for (Computer c : Jenkins.getInstance().getComputers()) { if (!c.getName().isEmpty()) { names.add(c.getName()); } } return names; }
Source:
private void addSiblingNode(int indexOfNode) { synchronized (latestBranch) { final long splitTime = treeEnd; assert (indexOfNode < latestBranch.size()); if (indexOfNode == 0) { addNewRootNode(); return; } if (((CoreNode) latestBranch.get(indexOfNode - 1)).getNbChildren() == config.getMaxChildren()) { addSiblingNode(indexOfNode - 1); return; } for (int i = indexOfNode; i < latestBranch.size(); i++) { latestBranch.get(i).closeThisNode(splitTime); treeIO.writeNode(latestBranch.get(i)); CoreNode prevNode = (CoreNode) latestBranch.get(i - 1); HTNode newNode; if (latestBranch.get(i).getNodeType() == HTConfig.LEAFNODE_TYPE) { newNode = initNewLeafNode(prevNode.getSequenceNumber(), splitTime + 1); } else { newNode = initNewCoreNode(prevNode.getSequenceNumber(), splitTime + 1); } prevNode.linkNewChild(newNode); latestBranch.set(i, newNode); } } }

Target:
private void addSiblingNode(int indexOfNode) { synchronized (latestBranch) { final long splitTime = treeEnd; assert (indexOfNode < latestBranch.size()); if (indexOfNode == 0) { addNewRootNode(); return; } if (((CoreNode) latestBranch.get(indexOfNode - 1)).getNbChildren() == config.getMaxChildren()) { addSiblingNode(indexOfNode - 1); return; } for (int i = indexOfNode; i < latestBranch.size(); i++) { latestBranch.get(i).closeThisNode(splitTime); treeIO.writeNode(latestBranch.get(i)); CoreNode prevNode = (CoreNode) latestBranch.get(i - 1); HTNode newNode; if (latestBranch.get(i).getNodeType() == HTNode.LEAFNODE_TYPE) { newNode = initNewLeafNode(prevNode.getSequenceNumber(), splitTime + 1); } else { newNode = initNewCoreNode(prevNode.getSequenceNumber(), splitTime + 1); } prevNode.linkNewChild(newNode); latestBranch.set(i, newNode); } } }
Source:
public static Map<String, Object> convertMap(Schema schema, Map<String, Object> value) { Map<String, Schema.Type> fieldToType = schema.getFields().stream() .collect(toMap(Schema.Field::getName, Schema.Field::getType)); boolean fieldNotFound = (schema.getFields().size() != value.keySet().size()) || value.keySet().stream().anyMatch(f -> !(fieldToType.containsKey(f))); if (fieldNotFound) { throw new IllegalArgumentException("Field list doesn't match to output schema."); } return value.entrySet().stream() .collect(toMap(Map.Entry::getKey, e -> convert(fieldToType.get(e.getKey()), e.getValue()))); }

Target:
public static Map<String, Object> convertMap(Schema schema, Map<String, Object> value) { Map<String, Schema.Type> fieldToType = schema.getFields().stream() .collect(toMap(Schema.Field::getName, Schema.Field::getType)); List<Schema.Field> requiredFields = schema.getFields().stream() .filter(field -> !field.isOptional()).collect(toList()); List<String> fieldsNotFoundInSchema = value.keySet().stream() .filter(f -> !(fieldToType.containsKey(f))).collect(toList()); List<Schema.Field> requiredFieldsNotFoundInValue = requiredFields.stream() .filter(f -> !(value.containsKey(f.getName()))).collect(toList()); if (!fieldsNotFoundInSchema.isEmpty()) { throw new IllegalArgumentException("The value has fields which are not defined in schema: " + fieldsNotFoundInSchema); } if (!requiredFieldsNotFoundInValue.isEmpty()) { throw new IllegalArgumentException("The value doesn't have required fields: " + requiredFieldsNotFoundInValue); } return value.entrySet().stream() .collect(toMap(Map.Entry::getKey, e -> convert(fieldToType.get(e.getKey()), e.getValue()))); }
Source:
protected void process( Void batch, BatchSender sender ) throws Throwable { System.out.println( Thread.currentThread().getName() + " process" ); latch.await(); }

Target:
protected void process( Void batch, BatchSender sender ) throws Throwable { latch.await(); }