auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testOverlappingGroupsFail() throws AccumuloSecurityException, AccumuloException, TableExistsException { Connector conn = getConnector(); String tableName = getUniqueNames(2)[0]; NewTableConfiguration ntc = new NewTableConfiguration(); Map<String,Set<Text>> lgroups = new HashMap<>(); lgroups.put("lg1", ImmutableSet.of(new Text("colFamA"), new Text("colFamB"))); lgroups.put("lg2", ImmutableSet.of(new Text("colFamC"), new Text("colFamB"))); ntc.setLocalityGroups(lgroups); conn.tableOperations().create(tableName, ntc); }

Target:
public void testOverlappingGroupsFail() throws AccumuloSecurityException, AccumuloException, TableExistsException { NewTableConfiguration ntc = new NewTableConfiguration(); Map<String,Set<Text>> lgroups = new HashMap<>(); lgroups.put("lg1", ImmutableSet.of(new Text("colFamA"), new Text("colFamB"))); lgroups.put("lg2", ImmutableSet.of(new Text("colFamC"), new Text("colFamB"))); ntc.setLocalityGroups(lgroups); }
Source:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .enable() .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class) .addProperty(SearchConfig.DIRECTORY_TYPE, SearchConfig.HEAP) .addProperty(SearchConfig.DIRECTORY_ROOT, indexDirectory) .addProperty(SearchConfig.THREAD_POOL_SIZE, "6") .addProperty(SearchConfig.QUEUE_COUNT, "6") .addProperty(SearchConfig.QUEUE_SIZE, "4096") .addProperty(SearchConfig.COMMIT_INTERVAL, "10000") .addProperty(SearchConfig.SHARDING_STRATEGY, SearchConfig.HASH) .addProperty(SearchConfig.NUMBER_OF_SHARDS, "6") ; enhanceConfig(cfg); return TestCacheManagerFactory.createCacheManager(cfg); }

Target:
protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder cfg = getDefaultStandaloneCacheConfig(true); cfg .indexing() .enable() .addIndexedEntity(Person.class) .addIndexedEntity(AnotherGrassEater.class) .addKeyTransformer(CustomKey3.class, CustomKey3Transformer.class) .addProperty(SearchConfig.DIRECTORY_TYPE, SearchConfig.HEAP) .addProperty(SearchConfig.DIRECTORY_ROOT, indexDirectory) .addProperty(SearchConfig.THREAD_POOL_SIZE, "6") .addProperty(SearchConfig.QUEUE_COUNT, "6") .addProperty(SearchConfig.QUEUE_SIZE, "4096") .addProperty(SearchConfig.COMMIT_INTERVAL, "10000") .addProperty(SearchConfig.SHARDING_STRATEGY, SearchConfig.HASH) .addProperty(SearchConfig.NUMBER_OF_SHARDS, "6") .addProperty(SearchConfig.ERROR_HANDLER, StaticTestingErrorHandler.class.getName()); enhanceConfig(cfg); return TestCacheManagerFactory.createCacheManager(cfg); }
Source:
public void testRequiresNew() throws Exception { service.inPropagationRequired(outer -> { final Handle h = JdbiUtil.getHandle(outer); h.insert("insert into something (id, name) values (7, 'ignored')"); try { service.inRequiresNewReadUncommitted(inner -> { final Handle h1 = JdbiUtil.getHandle(inner); int count = h1.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(1); h1.insert("insert into something (id, name) values (8, 'ignored again')"); throw new ForceRollback(); }); } catch (ForceRollback e) { assertThat(e).isNotNull(); } int count = h.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(1); }); }

Target:
public void testRequiresNew() throws Exception { service.inPropagationRequired(outer -> { final Handle h = JdbiUtil.getHandle(outer); h.insert("insert into something (id, name) values (7, 'ignored')"); assertThatExceptionOfType(ForceRollback.class).isThrownBy(() -> { service.inRequiresNewReadUncommitted(inner -> { final Handle h1 = JdbiUtil.getHandle(inner); int count = h1.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(1); h1.insert("insert into something (id, name) values (8, 'ignored again')"); throw new ForceRollback(); }); }); int count = h.createQuery("select count(*) from something").mapTo(Integer.class).findOnly(); assertThat(count).isEqualTo(1); }); }
Source:
private List<Integer> spreadBytesAsIntegerList() { if (spread == null) { return Collections.emptyList(); } List<Integer> integers = new ArrayList<>(spread.length); for (int i = 0; (i < spread.length); i++) { integers.set(i, (int) spread[i]); } return integers; }

Target:
private List<Integer> spreadBytesAsIntegerList() { assert spread.length == SPREAD_COUNT; List<Integer> integers = new ArrayList<>(spread.length); for (int i = 0; (i < spread.length); i++) { integers.set(i, (int) spread[i]); } return integers; }
Source:
private void visitUnionType(UnionType ut) { Collection<JSType> alts = Collections2.filter(ut.getAlternates(), new Predicate<JSType>() { @Override public boolean apply(JSType input) { return !input.isNullable() && !input.isVoidType() || input.isTemplateType(); } }); if (alts.size() == 1) { visitType(alts.iterator().next()); return; } emit("("); Iterator<JSType> it = alts.iterator(); while (it.hasNext()) { visitType(it.next()); if (it.hasNext()) { emit("|"); } } emit(")"); }

Target:
private void visitUnionType(UnionType ut) { Collection<JSType> alts = Collections2.filter(ut.getAlternates(), new Predicate<JSType>() { @Override public boolean apply(JSType input) { return !input.isNullType() && !input.isVoidType(); } }); if (alts.size() == 1) { visitType(alts.iterator().next()); return; } emit("("); Iterator<JSType> it = alts.iterator(); while (it.hasNext()) { visitType(it.next()); if (it.hasNext()) { emit("|"); } } emit(")"); }
Source:
public int hashCode() { int result = getClassName().hashCode(); result = 31 * result + getName().hashCode(); result = 31 * result + getReturnType().hashCode(); result = 31 * result + getExceptionType().hashCode(); result = 31 * result + getParametersType().hashCode(); return result; }

Target:
public int hashCode() { return Objects.hash(); }
Source:
public BitSet getCoveredBranches() { return coveredBranches; }

Target:
public int getCoveredBranches() { return coveredBranches.cardinality(); }
Source:
public void setAttribute(final String key, final String value) { super.setAttribute(key, value); if (key.equals(SORT_ORDER_TAG)) this.setSortOrder(SortOrder.valueOf(value)); else if (key.equals(GROUP_ORDER_TAG)) this.setGroupOrder(GroupOrder.valueOf(value)); else super.setAttribute(key, value); }

Target:
public void setAttribute(final String key, final String value) { if (key.equals(SORT_ORDER_TAG)) { this.sortOrder = null; } else if (key.equals(GROUP_ORDER_TAG)) { this.groupOrder = null; } super.setAttribute(key, value); }
Source:
private String updateOperator(byte[] byteContent) { String result = null; if (byteContent != null) { boolean modified = false; try { Document document = getSchemaDocument(byteContent); NodeList appinfoTags = document.getElementsByTagName("xsd:appinfo"); int len = appinfoTags.getLength(); for (int i = 0; i < len; i++) { Node appItem = appinfoTags.item(i); Node sourceAttr = appItem.getAttributes().getNamedItem("source"); if (sourceAttr.getNodeValue().equals("X_ForeignKey_Filter")) { String content = appItem.getTextContent(); if (content.contains("Strict Contains") || content.contains("Contains Text Of")) { content = content.replaceAll("Contains Text Of", "Contains"); content = content.replaceAll("Strict Contains", "Contains"); appItem.setTextContent(content); modified = true; } } } if (modified) { result = Util.nodeToString(document); } } catch (Exception e) { log.error(e.getMessage(), e); } } return result; }

Target:
private String updateOperator(byte[] byteContent) { String result = null; if (byteContent != null) { boolean modified = false; try { Document document = getSchemaDocument(byteContent); NodeList appinfoTags = document.getElementsByTagName("xsd:appinfo"); int len = appinfoTags.getLength(); for (int i = 0; i < len; i++) { Node appItem = appinfoTags.item(i); Node sourceAttr = appItem.getAttributes().getNamedItem("source"); if (sourceAttr.getNodeValue().equals("X_ForeignKey_Filter")) { String content = appItem.getTextContent(); if (content.contains("Strict Contains") || content.contains("Contains Text Of")) { content = content.replaceAll("Contains Text Of", "Contains"); content = content.replaceAll("Strict Contains", "Contains"); appItem.setTextContent(content); modified = true; } } } if (modified) { result = Util.nodeToString(document); } } catch (Exception e) { LOG.error("Failed to update data model condition operator.", e); } } return result; }
Source:
public void aboutToBeShown() { super.aboutToBeShown(); String onClickExpression = Optional.ofNullable(this.description.getOnClickExpression()).orElse(""); if (!onClickExpression.isEmpty()) { this.hyperlinkListener = new EEFHyperlinkListener(this, this.text, this.container, this.controller); text.addMouseListener(hyperlinkListener); } }

Target:
public void aboutToBeShown() { super.aboutToBeShown(); String onClickExpression = Optional.ofNullable(this.description.getOnClickExpression()).orElse(""); if (!onClickExpression.isEmpty()) { this.hyperlinkListener = new EEFHyperlinkListener(this, this.hyperlink, this.container, this.controller); hyperlink.addMouseListener(hyperlinkListener); } }
Source:
void onMode(@SuppressWarnings("unused") ChangeEvent e) { final String mode = getSelectedMode(); prefs.syntaxHighlighting(true); syntaxHighlighting.setValue(true, false); new ModeInjector().add(mode).inject(new GerritCallback<Void>() { @Override public void onSuccess(Void result) { if (prefs.syntaxHighlighting() && eq(mode, getSelectedMode()) && view.isAttached()) { view.operation(new Runnable() { @Override public void run() { view.getCmFromSide(DisplaySide.A).setOption("mode", mode); view.getCmFromSide(DisplaySide.B).setOption("mode", mode); } }); } } }); }

Target:
void onMode(@SuppressWarnings("unused") ChangeEvent e) { final String mode = getSelectedMode(); prefs.syntaxHighlighting(true); syntaxHighlighting.setValue(true, false); new ModeInjector().add(mode).inject(new GerritCallback<Void>() { @Override public void onSuccess(Void result) { if (prefs.syntaxHighlighting() && Objects.equals(mode, getSelectedMode()) && view.isAttached()) { view.operation(new Runnable() { @Override public void run() { view.getCmFromSide(DisplaySide.A).setOption("mode", mode); view.getCmFromSide(DisplaySide.B).setOption("mode", mode); } }); } } }); }
Source:
private String createHtmlEmailBody(JobExecutionContext jobContext) { JobDataMap jdm = jobContext.getMergedJobDataMap(); String reasonForStatusChange = jdm.getString("reason"); if (StringUtils.isEmpty(reasonForStatusChange)) { reasonForStatusChange = "<strong>ONC-ACB provided reason for status change:</strong> This field is blank"; } else { reasonForStatusChange = "<strong>ONC-ACB provided reason for status change:</strong> \"" + reasonForStatusChange + "\""; } String reasonForListingChange = jdm.getString("reasonForChange"); if (StringUtils.isEmpty(reasonForListingChange)) { reasonForListingChange = "<strong>ONC-ACB provided reason for listing change:</strong> This field is blank"; } else { reasonForListingChange = "<strong>ONC-ACB provided reason for listing change:</strong> \"" + reasonForListingChange + "\""; } int openNcs = jdm.getInt("openNcs"); int closedNcs = jdm.getInt("closedNcs"); String htmlMessage = String.format(env.getProperty("developerBanEmailBody"), env.getProperty("chplUrlBegin"), env.getProperty("developerBanEmailUrl"), jdm.getLong("dbId"), jdm.getString("chplId"), jdm.getString("developer"), jdm.getString("acb"), Util.getDateFormatter().format(new Date(jdm.getLong("changeDate"))), jdm.getString("fullName"), jdm.getString("status"), Util.getDateFormatter().format(new Date(jdm.getLong("effectiveDate"))), reasonForStatusChange, reasonForListingChange, (openNcs != 1 ? "were" : "was"), openNcs, (openNcs != 1 ? "ies" : "y"), closedNcs, (closedNcs != 1 ? "ies" : "y")); return htmlMessage; }

Target:
private String createHtmlEmailBody(JobExecutionContext jobContext) { JobDataMap jdm = jobContext.getMergedJobDataMap(); String reasonForStatusChange = jdm.getString("reason"); if (StringUtils.isEmpty(reasonForStatusChange)) { reasonForStatusChange = "<strong>ONC-ACB provided reason for status change:</strong> This field is blank"; } else { reasonForStatusChange = "<strong>ONC-ACB provided reason for status change:</strong> \"" + reasonForStatusChange + "\""; } String reasonForListingChange = jdm.getString("reasonForChange"); if (StringUtils.isEmpty(reasonForListingChange)) { reasonForListingChange = "<strong>ONC-ACB provided reason for listing change:</strong> This field is blank"; } else { reasonForListingChange = "<strong>ONC-ACB provided reason for listing change:</strong> \"" + reasonForListingChange + "\""; } int openNcs = jdm.getInt("openNcs"); int closedNcs = jdm.getInt("closedNcs"); String htmlMessage = String.format(env.getProperty("developerBanEmailBody"), env.getProperty("chplUrlBegin"), env.getProperty("listingDetailsUrl"), jdm.getLong("dbId"), jdm.getString("chplId"), jdm.getString("developer"), jdm.getString("acb"), Util.getDateFormatter().format(new Date(jdm.getLong("changeDate"))), jdm.getString("fullName"), jdm.getString("status"), Util.getDateFormatter().format(new Date(jdm.getLong("effectiveDate"))), reasonForStatusChange, reasonForListingChange, (openNcs != 1 ? "were" : "was"), openNcs, (openNcs != 1 ? "ies" : "y"), closedNcs, (closedNcs != 1 ? "ies" : "y")); return htmlMessage; }
Source:
public PluginsZip(SystemEnvironment systemEnvironment, ZipUtil zipUtil) { pluginsEnabled = systemEnvironment.get(SystemEnvironment.PLUGIN_FRAMEWORK_ENABLED); destZipFile = new File(systemEnvironment.get(SystemEnvironment.ALL_PLUGINS_ZIP_PATH)); bundledPlugins = new File(systemEnvironment.get(SystemEnvironment.PLUGIN_GO_PROVIDED_PATH)); externalPlugins = new File(systemEnvironment.get(SystemEnvironment.PLUGIN_EXTERNAL_PROVIDED_PATH)); this.zipUtil = zipUtil; checkFilesAccessibility(bundledPlugins, externalPlugins); }

Target:
public PluginsZip(SystemEnvironment systemEnvironment, ZipUtil zipUtil) { pluginsEnabled = systemEnvironment.get(SystemEnvironment.PLUGIN_FRAMEWORK_ENABLED); destZipFile = new File(systemEnvironment.get(SystemEnvironment.ALL_PLUGINS_ZIP_PATH)); bundledPlugins = new File(systemEnvironment.get(SystemEnvironment.PLUGIN_GO_PROVIDED_PATH)); externalPlugins = new File(systemEnvironment.get(SystemEnvironment.PLUGIN_EXTERNAL_PROVIDED_PATH)); this.zipUtil = zipUtil; }
Source:
private void createIndex() { try ( Transaction tx = db.beginTx() ) { db.execute( "CREATE INDEX ON " + indexDefinition ); tx.success(); } try ( Transaction tx = db.beginTx() ) { db.schema().awaitIndexesOnline( 1, TimeUnit.SECONDS ); tx.success(); } }

Target:
private void createIndex() { try ( Transaction tx = db.beginTx() ) { db.execute( "CREATE INDEX ON " + indexDefinition ); tx.success(); } try ( Transaction tx = db.beginTx() ) { db.schema().awaitIndexesOnline( 5, TimeUnit.SECONDS ); tx.success(); } }
Source:
public List<FirmwareCountInfo> getSeenFirmwareByTime(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("range_start") final Long rangeStart, @QueryParam("range_end") final Long rangeEnd) { if(rangeStart == null) { LOGGER.error("Missing range_start parameter"); throw new WebApplicationException(Response.Status.BAD_REQUEST); } if(rangeEnd == null) { LOGGER.error("Missing range_end parameter"); throw new WebApplicationException(Response.Status.BAD_REQUEST); } final Jedis jedis = jedisPool.getResource(); final List<FirmwareCountInfo> firmwareCounts = new ArrayList<>(); try { final Set<Tuple> seenFirmwares = jedis.zrangeByScoreWithScores(REDIS_SEEN_FIRMWARE_KEY, rangeStart, rangeEnd); for (final Tuple fwInfo:seenFirmwares) { final long lastSeen = (long) fwInfo.getScore(); final long fwCount = jedis.zcard(fwInfo.getElement()); if (fwCount > 0) { firmwareCounts.add(new FirmwareCountInfo(fwInfo.getElement(), fwCount, lastSeen)); } } } catch (Exception e) { LOGGER.error("Failed retrieving all seen firmware by time.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } return firmwareCounts; }

Target:
public List<FirmwareCountInfo> getSeenFirmwareByTime(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("range_start") final Long rangeStart, @QueryParam("range_end") final Long rangeEnd) { if(rangeStart == null) { LOGGER.error("Missing range_start parameter"); throw new WebApplicationException(Response.Status.BAD_REQUEST); } if(rangeEnd == null) { LOGGER.error("Missing range_end parameter"); throw new WebApplicationException(Response.Status.BAD_REQUEST); } final Jedis jedis = jedisPool.getResource(); final List<FirmwareCountInfo> firmwareCounts = Lists.newArrayList(); try { final Set<Tuple> seenFirmwares = jedis.zrangeByScoreWithScores(REDIS_SEEN_FIRMWARE_KEY, rangeStart, rangeEnd); final Pipeline pipe = jedis.pipelined(); final Map<String, redis.clients.jedis.Response<Long>> responseMap = Maps.newHashMap(); for (final Tuple fwInfo:seenFirmwares) { responseMap.put(fwInfo.getElement(), pipe.zcard(fwInfo.getElement())); } pipe.sync(); for (final Tuple fwInfo:seenFirmwares) { final String fwVersion = fwInfo.getElement(); final long fwCount = responseMap.get(fwVersion).get(); final long lastSeen = (long) fwInfo.getScore(); if (fwCount > 0) { firmwareCounts.add(new FirmwareCountInfo(fwInfo.getElement(), fwCount, lastSeen)); } } } catch (Exception e) { LOGGER.error("Failed retrieving all seen firmware by time.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } return firmwareCounts; }
Source:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { TilequeryActivity.this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { addClickLayer(); addResultLayer(); displayDeviceLocation(); mapboxMap.addOnMapClickListener(TilequeryActivity.this); Toast.makeText(TilequeryActivity.this, R.string.click_on_map_instruction, Toast.LENGTH_SHORT).show(); } }); }

Target:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { TilequeryActivity.this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { addClickLayer(style); addResultLayer(style); displayDeviceLocation(style); mapboxMap.addOnMapClickListener(TilequeryActivity.this); Toast.makeText(TilequeryActivity.this, R.string.click_on_map_instruction, Toast.LENGTH_SHORT).show(); } }); }
Source:
public void run() { while (true) { if (persistQueue.peek() != null) { try { StreamsDatum entry = persistQueue.remove(); write(entry); } catch (Exception ex) { ex.printStackTrace(); } } try { Thread.sleep(new Random().nextInt(1)); } catch (InterruptedException interrupt) { LOGGER.trace("Interrupt", interrupt); } } }

Target:
public void run() { while (true) { if (persistQueue.peek() != null) { try { StreamsDatum entry = persistQueue.remove(); write(entry); } catch (Exception ex) { LOGGER.warn("Failure writing entry from Queue: {}", ex.getMessage()); } } try { Thread.sleep(new Random().nextInt(1)); } catch (InterruptedException interrupt) { LOGGER.trace("Interrupt", interrupt); } } }
Source:
public void run() { synchronized (isActive) { if (isActive.getAndSet(true)) throw new IllegalStateException("already running"); } while (shouldBeActive.get()) { long startTime = System.currentTimeMillis(); try { if (preAttempt()) { int code = HttpTestUtils.getHttpStatusCode(url); lastTime.set(System.currentTimeMillis()-startTime); if (code!=200) { lastStatus.set(code); lastFailure.set(code); failures.incrementAndGet(); onFailure("return code "+code); } else { lastStatus.set(null); successes.incrementAndGet(); } } } catch (Exception e) { lastTime.set(System.currentTimeMillis()-startTime); lastStatus.set(e); lastFailure.set(e); failures.incrementAndGet(); onFailure(e); } try { if (delayMillis > 0) { Thread.sleep(delayMillis); } } catch (InterruptedException e) { onFailure(e); shouldBeActive.set(false); } } synchronized (isActive) { if (!isActive.getAndSet(false)) throw new IllegalStateException("shouldn't be possible!"); isActive.notifyAll(); } }

Target:
public void run() { synchronized (isActive) { if (isActive.getAndSet(true)) throw new IllegalStateException("already running"); } while (shouldBeActive.get()) { long startTime = System.currentTimeMillis(); try { if (preAttempt()) { int code = HttpTestUtils.getHttpStatusCode(url); lastTime.set(System.currentTimeMillis()-startTime); lastStatus.set(code); if (isResponseOkay(code)) { lastFailure.set(code); failures.incrementAndGet(); onFailure("return code "+code); } else { successes.incrementAndGet(); } } } catch (Exception e) { lastTime.set(System.currentTimeMillis()-startTime); lastStatus.set(e); lastFailure.set(e); failures.incrementAndGet(); onFailure(e); } try { if (delayMillis > 0) { Thread.sleep(delayMillis); } } catch (InterruptedException e) { onFailure(e); shouldBeActive.set(false); } } synchronized (isActive) { if (!isActive.getAndSet(false)) throw new IllegalStateException("shouldn't be possible!"); isActive.notifyAll(); } }
Source:
private static void writeParameter(final Object param, final ByteBuffer b) { if (param instanceof SPromise) { b.put((byte) 0x04); b.putLong(((SPromise) param).getPromiseId()); } else if (param instanceof SResolver) { b.put((byte) 0x05); b.putLong(((SResolver) param).getPromise().getPromiseId()); } else if (param instanceof SAbstractObject) { b.put((byte) 0x06); b.putShort(((SAbstractObject) param).getSOMClass().getName().getSymbolId()); } else { if (param instanceof Long) { b.put((byte) 0x02); b.putLong((Long) param); } else if (param instanceof Double) { b.put((byte) 0x03); b.putDouble((Double) param); } else if (param instanceof Boolean) { if ((Boolean) param) { b.put((byte) 0x01); } else { b.put((byte) 0x00); } } else if (param instanceof String) { b.put((byte) 0x07); } else { throw new RuntimeException("unexpected parameter type"); } } }

Target:
private static void writeParameter(final Object param, final ByteBuffer b) { if (param instanceof SPromise) { b.put(ParamTypes.Promise.id()); b.putLong(((SPromise) param).getPromiseId()); } else if (param instanceof SResolver) { b.put(ParamTypes.Resolver.id()); b.putLong(((SResolver) param).getPromise().getPromiseId()); } else if (param instanceof SAbstractObject) { b.put(ParamTypes.Object.id()); b.putShort(((SAbstractObject) param).getSOMClass().getName().getSymbolId()); } else { if (param instanceof Long) { b.put(ParamTypes.Long.id()); b.putLong((Long) param); } else if (param instanceof Double) { b.put(ParamTypes.Double.id()); b.putDouble((Double) param); } else if (param instanceof Boolean) { if ((Boolean) param) { b.put(ParamTypes.True.id()); } else { b.put(ParamTypes.False.id()); } } else if (param instanceof String) { b.put(ParamTypes.String.id()); } else { throw new RuntimeException("unexpected parameter type"); } } }
Source:
public static SWTBotTreeItem createProject(SWTWorkbenchBot bot, String projectName) { SWTBotUtils.createProject(projectName); SWTBotView projectExplorerBot = bot.viewByTitle("Project Explorer"); projectExplorerBot.show(); SWTBotTreeItem treeItem = projectExplorerBot.bot().tree().getTreeItem(projectName); treeItem.select(); treeItem.expand(); SWTBotTreeItem treeNode = null; for (String node : treeItem.getNodes()) { if (node.startsWith("Trace")) { treeNode = treeItem.getNode(node); break; } } assertNotNull(treeNode); return treeNode; }

Target:
public static SWTBotTreeItem createProject(SWTWorkbenchBot bot, String projectName) { SWTBotUtils.createProject(projectName); SWTBotView projectExplorerBot = bot.viewByTitle("Project Explorer"); projectExplorerBot.show(); SWTBotTreeItem treeItem = projectExplorerBot.bot().tree().getTreeItem(projectName); treeItem.select(); treeItem.expand(); SWTBotTreeItem treeNode = null; for (String node : treeItem.getNodes()) { if (node.matches("Traces\\s\\[(\\d)*\\]")) { treeNode = treeItem.getNode(node); break; } } assertNotNull(treeNode); return treeNode; }
Source:
protected boolean consumeNextMessage() { Message rawMessage = null; try { boolean hasNext = mMessageReader.hasNext(); if (!hasNext) { return false; } rawMessage = mMessageReader.read(); } catch (ConsumerTimeoutException e) { LOG.trace("Consumer timed out", e); } if (rawMessage != null) { try { mMessageWriter.adjustOffset(rawMessage); } catch (IOException e) { throw new RuntimeException("Failed to adjust offset.", e); } Message transformedMessage = mMessageTransformer.transform(rawMessage); if(transformedMessage == null) { return true; } ParsedMessage parsedMessage = null; try { parsedMessage = mMessageParser.parse(transformedMessage); final double DECAY = 0.999; mUnparsableMessages *= DECAY; } catch (Throwable e) { mMetricCollector.increment("consumer.message_errors.count", rawMessage.getTopic()); mUnparsableMessages++; final double MAX_UNPARSABLE_MESSAGES = 1000.; if (mUnparsableMessages > MAX_UNPARSABLE_MESSAGES) { throw new RuntimeException("Failed to parse message " + rawMessage, e); } LOG.warn("Failed to parse message {}", rawMessage, e); } if (parsedMessage != null) { try { mMessageWriter.write(parsedMessage); mMetricCollector.metric("consumer.message_size_bytes", rawMessage.getPayload().length, rawMessage.getTopic()); mMetricCollector.increment("consumer.throughput_bytes", rawMessage.getPayload().length, rawMessage.getTopic()); } catch (Exception e) { throw new RuntimeException("Failed to write message " + parsedMessage, e); } } } return true; }

Target:
protected boolean consumeNextMessage() { Message rawMessage = null; try { boolean hasNext = mMessageReader.hasNext(); if (!hasNext) { return false; } rawMessage = mMessageReader.read(); } catch (ConsumerTimeoutException e) { LOG.trace("Consumer timed out", e); } if (rawMessage != null) { try { mMessageWriter.adjustOffset(rawMessage); } catch (IOException e) { throw new RuntimeException("Failed to adjust offset.", e); } ParsedMessage parsedMessage = null; try { Message transformedMessage = mMessageTransformer.transform(rawMessage); if (transformedMessage == null) { return true; } parsedMessage = mMessageParser.parse(transformedMessage); final double DECAY = 0.999; mUnparsableMessages *= DECAY; } catch (Throwable e) { mMetricCollector.increment("consumer.message_errors.count", rawMessage.getTopic()); mUnparsableMessages++; final double MAX_UNPARSABLE_MESSAGES = 1000.; if (mUnparsableMessages > MAX_UNPARSABLE_MESSAGES) { throw new RuntimeException("Failed to parse message " + rawMessage, e); } LOG.warn("Failed to parse message {}", rawMessage, e); } if (parsedMessage != null) { try { mMessageWriter.write(parsedMessage); mMetricCollector.metric("consumer.message_size_bytes", rawMessage.getPayload().length, rawMessage.getTopic()); mMetricCollector.increment("consumer.throughput_bytes", rawMessage.getPayload().length, rawMessage.getTopic()); } catch (Exception e) { throw new RuntimeException("Failed to write message " + parsedMessage, e); } } } return true; }
Source:
public void testActivateDeActivate() throws GridClientException { GridClientClusterState state = client.state(); assertTrue(state.toString(), state.state().active()); state.state(INACTIVE, true); IgniteEx ig1 = grid(0); IgniteEx ig2 = grid(1); assertFalse(ig1.active()); assertFalse(ig2.active()); assertEquals(INACTIVE, state.state()); state.state(ACTIVE, false); assertTrue(ig1.active()); assertTrue(ig2.active()); assertEquals(ACTIVE, state.state()); }

Target:
public void testActivateDeActivate() throws GridClientException { GridClientClusterState state = client.state(); assertTrue(state.state().toString(), state.state().active()); state.state(INACTIVE, true); IgniteEx ig1 = grid(0); IgniteEx ig2 = grid(1); assertFalse(ig1.active()); assertFalse(ig2.active()); assertEquals(INACTIVE, state.state()); state.state(ACTIVE, false); assertTrue(ig1.active()); assertTrue(ig2.active()); assertEquals(ACTIVE, state.state()); }
Source:
public void subscribeToDataStoreInternal(@NonNull CompositeSubscription compositeSubscription) { Log.v(TAG, "subscribeToDataStoreInternal"); ConnectableObservable<DataStreamNotification<GitHubRepositorySearch>> repositorySearchSource = searchString .filter(string -> string.length() > 2) .debounce(SEARCH_INPUT_DELAY, TimeUnit.MILLISECONDS) .distinctUntilChanged() .doOnNext(string -> Log.d(TAG, "Searching with: " + string)) .switchMap(getGitHubRepositorySearch::call) .publish(); compositeSubscription.add(repositorySearchSource .doOnNext(notification -> Log.d(TAG, "status: " + notification)) .map(toProgressStatus()) .doOnNext(progressStatus -> Log.d(TAG, "Progress status: " + progressStatus.name())) .subscribe(this::setNetworkStatusText)); compositeSubscription.add(repositorySearchSource .filter(DataStreamNotification::isOnNext) .doOnNext(notification -> Log.d(TAG, "Processing search results")) .map(DataStreamNotification::getValue) .map(GitHubRepositorySearch::getItems) .flatMap(toGitHubRepositoryList()) .doOnNext(list -> Log.d(TAG, "Publishing " + list.size() + " repositories from the ViewModel")) .subscribe(RepositoriesViewModel.this.repositories::onNext)); compositeSubscription.add(repositorySearchSource.connect()); }

Target:
public void subscribeToDataStoreInternal(@NonNull CompositeSubscription compositeSubscription) { Log.v(TAG, "subscribeToDataStoreInternal"); ConnectableObservable<DataStreamNotification<GitHubRepositorySearch>> repositorySearchSource = searchString .filter(string -> string.length() > 2) .debounce(SEARCH_INPUT_DELAY, TimeUnit.MILLISECONDS) .distinctUntilChanged() .doOnNext(string -> Log.d(TAG, "Searching with: " + string)) .switchMap(getGitHubRepositorySearch::call) .publish(); compositeSubscription.add(repositorySearchSource .map(toProgressStatus()) .doOnNext(progressStatus -> Log.d(TAG, "Progress status: " + progressStatus.name())) .subscribe(this::setNetworkStatusText)); compositeSubscription.add(repositorySearchSource .filter(DataStreamNotification::isOnNext) .map(DataStreamNotification::getValue) .map(GitHubRepositorySearch::getItems) .flatMap(toGitHubRepositoryList()) .doOnNext(list -> Log.d(TAG, "Publishing " + list.size() + " repositories from the ViewModel")) .subscribe(RepositoriesViewModel.this.repositories::onNext)); compositeSubscription.add(repositorySearchSource.connect()); }
Source:
private Map<String, ?> transform(String payload) { Map<String, Object> map = new LinkedHashMap<String, Object>(); Matcher matcher = pattern.matcher(payload); if (matcher.matches()) { try { String facilityString = matcher.group(1); int facility = Integer.parseInt(facilityString); int severity = facility & 0x7; facility = facility >> 3; map.put(FACILITY, facility); map.put(SEVERITY, severity); String timestamp = matcher.group(2); Date date; try { date = this.dateFormat.parse(timestamp); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); calendar.setTime(date); if (month == 11 && calendar.get(Calendar.MONTH) == 0) { calendar.set(Calendar.YEAR, year + 1); } else if (month == 0 && calendar.get(Calendar.MONTH) == 1) { calendar.set(Calendar.YEAR, year - 1); } else { calendar.set(Calendar.YEAR, year); } map.put(TIMESTAMP, calendar.getTime()); } catch (Exception e) { map.put(TIMESTAMP, timestamp); } map.put(HOST, matcher.group(3)); map.put(TAG, matcher.group(4)); map.put(MESSAGE, matcher.group(5)); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Could not decode:" + payload, e); } map.clear(); map.put(UNDECODED, payload); } } else { if (logger.isDebugEnabled()) { logger.debug("Could not decode:" + payload); } map.put(UNDECODED, payload); } return map; }

Target:
private Map<String, ?> transform(String payload) { Map<String, Object> map = new LinkedHashMap<String, Object>(); Matcher matcher = pattern.matcher(payload); if (matcher.matches()) { try { String facilityString = matcher.group(1); int facility = Integer.parseInt(facilityString); int severity = facility & 0x7; facility = facility >> 3; map.put(FACILITY, facility); map.put(SEVERITY, severity); String timestamp = matcher.group(2); Date date; try { date = this.dateFormat.parse(timestamp); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); calendar.setTime(date); if (month == 11 && calendar.get(Calendar.MONTH) == 0) { calendar.set(Calendar.YEAR, year + 1); } else if (month == 0 && calendar.get(Calendar.MONTH) == 1) { calendar.set(Calendar.YEAR, year - 1); } else { calendar.set(Calendar.YEAR, year); } map.put(TIMESTAMP, calendar.getTime()); } catch (Exception e) { map.put(TIMESTAMP, timestamp); } map.put(HOST, matcher.group(3)); if (matcher.group(4) != null) { map.put(TAG, matcher.group(4)); } map.put(MESSAGE, matcher.group(5)); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Could not decode:" + payload, e); } map.clear(); map.put(UNDECODED, payload); } } else { if (logger.isDebugEnabled()) { logger.debug("Could not decode:" + payload); } map.put(UNDECODED, payload); } return map; }
Source:
void create() { statusTransitioner.checkMaintenance(); try { if (!getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent()) { destroy(); } PersistenceSpaceIdentifier space = localPersistenceService.getOrCreatePersistenceSpace(id); throw new UnsupportedOperationException("How do I get the space reference in to the service config list?"); } catch (CachePersistenceException e) { throw new RuntimeException("Unable to create persistence context for user managed cache " + id, e); } }

Target:
void create() { statusTransitioner.checkMaintenance(); try { if (!getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent()) { destroy(); } localPersistenceService.getOrCreatePersistenceSpace(id); } catch (CachePersistenceException e) { throw new RuntimeException("Unable to create persistence space for user managed cache " + id, e); } }
Source:
public static void setup() throws Exception { esSetup = new EsSetup(); elasticIO = new ElasticIO(); elasticIO.insertDiscovery(createTestMetrics(TENANT_A)); elasticIO.insertDiscovery(createTestMetrics(TENANT_B)); elasticIO.insertDiscovery(createTestMetricsFromInterface(TENANT_C)); Thread.sleep(3*1000); }

Target:
public void setup() throws Exception { helper = ElasticsearchRestHelper.getInstance(); tearDown(); elasticIO = new ElasticIO(); elasticIO.insertDiscovery(createTestMetrics(TENANT_A)); elasticIO.insertDiscovery(createTestMetrics(TENANT_B)); elasticIO.insertDiscovery(createTestMetricsFromInterface(TENANT_C)); String TOKEN_INDEX_NAME_OLD = ElasticTokensIO.ELASTICSEARCH_TOKEN_INDEX_NAME_WRITE + "_v1"; elasticTokensIO = new ElasticTokensIO() { @Override protected String[] getIndexesToSearch() { return new String[] {ElasticTokensIO.ELASTICSEARCH_TOKEN_INDEX_NAME_READ, TOKEN_INDEX_NAME_OLD}; } }; elasticTokensIO.insertDiscovery(createTestTokens(TENANT_A)); elasticTokensIO.insertDiscovery(createTestTokens(TENANT_B)); List<Token> tokens = createTestTokens(TENANT_C); for(Token token : tokens){ elasticTokensIO.insertDiscovery(token); } this.insertTokenDiscovery(createTestTokens(TENANT_A), TOKEN_INDEX_NAME_OLD, elasticTokensIO.elasticsearchRestHelper); this.insertTokenDiscovery(createTestTokens(TENANT_B), TOKEN_INDEX_NAME_OLD, elasticTokensIO.elasticsearchRestHelper); this.insertTokenDiscovery(createTestTokens(TENANT_C), TOKEN_INDEX_NAME_OLD, elasticTokensIO.elasticsearchRestHelper); helper.refreshIndex("metric_metadata"); helper.refreshIndex("metric_tokens"); }
Source:
protected void addUserAgentHeader(HttpRequest request) { if (USER_AGENT_VALUE == null) { USER_AGENT_VALUE = "bazel/" + StringUtils.defaultIfEmpty(BlazeVersionInfo.instance().getVersion(), "dev"); } request.headers().set(HttpHeaderNames.USER_AGENT, USER_AGENT_VALUE); }

Target:
protected void addUserAgentHeader(HttpRequest request) { request.headers().set(HttpHeaderNames.USER_AGENT, USER_AGENT_VALUE); }
Source:
public Set<String> getGenres(final Record record) { String leaderStr = record.getLeader().marshal(); char leaderChar07 = leaderStr.charAt(7); Set<String> resultSet = new HashSet<String>(); if (!record.getVariableFields("502").isEmpty()) resultSet.add(Genre.THESIS.toString()); List<DataField> dfList = (List<DataField>) record.getDataFields(); for (DataField df : dfList) { if (df.getTag().startsWith("6")) { List<String> subList = MarcUtils.getSubfieldStrings(df, 'x'); subList.addAll(MarcUtils.getSubfieldStrings(df, 'v')); for (String s : subList) { if (s.toLowerCase().contains("congresses")) { resultSet.add(Genre.CONFERENCE_PROCEEDINGS.toString()); } } } } if (leaderChar07 == 'm' || leaderChar07 == 's') { char c29 = '\u0000'; if (cf008 != null && cf008.getData().length() >= 30) { c29 = ((ControlField) cf008).getData().charAt(29); if (c29 == '1') resultSet.add(Genre.CONFERENCE_PROCEEDINGS.toString()); } } if (cf008 != null && cf008.getData().length() >= 29) { if (!main_formats.contains(Format.MUSIC_SCORE.toString()) && !main_formats.contains(Format.MUSIC_RECORDING.toString()) && !main_formats.contains(Format.MANUSCRIPT_ARCHIVE.toString()) && cf008.find("^.{28}[a-z]")) { resultSet.add(Genre.GOVERNMENT_DOCUMENTS.toString()); } } return resultSet; }

Target:
public Set<String> getGenres(final Record record) { String leaderStr = record.getLeader().marshal(); char leaderChar07 = leaderStr.charAt(7); Set<String> resultSet = new HashSet<String>(); if (!record.getVariableFields("502").isEmpty()) resultSet.add(Genre.THESIS.toString()); List<DataField> dfList = (List<DataField>) record.getDataFields(); for (DataField df : dfList) { if (df.getTag().startsWith("6")) { List<String> subList = MarcUtils.getSubfieldStrings(df, 'x'); subList.addAll(MarcUtils.getSubfieldStrings(df, 'v')); for (String s : subList) { if (s.toLowerCase().contains("congresses")) { resultSet.add(Genre.CONFERENCE_PROCEEDINGS.toString()); } } } } if (leaderChar07 == 'm' || leaderChar07 == 's') { char c29 = '\u0000'; if (cf008 != null && cf008.getData().length() >= 30) { c29 = ((ControlField) cf008).getData().charAt(29); if (c29 == '1') resultSet.add(Genre.CONFERENCE_PROCEEDINGS.toString()); } } if (cf008 != null && cf008.getData().length() >= 29) { if (!main_formats.contains(Format.MUSIC_SCORE.toString()) && !main_formats.contains(Format.MUSIC_RECORDING.toString()) && !main_formats.contains(Format.MANUSCRIPT_ARCHIVE.toString()) && cf008.find("^.{28}[a-z]")) { resultSet.add(Genre.GOVERNMENT_DOCUMENT.toString()); } } return resultSet; }
Source:
public static CodeSystem b2iExtension(String extensionPath) { return CodeSystem.builder() .name("Systematized Nomenclature of Medicine Clinical Terms, B2i extension") .shortName(SNOMED_B2I_SHORT_NAME) .oid(SNOMED_B2I_OID) .primaryLanguage(SNOMED_INT_LANGUAGE) .organizationLink("<LINK_0>") .citation(SNOMED_INT_CITATION) .branchPath(extensionPath) .iconPath(SNOMED_INT_ICON_PATH) .repositoryUuid(REPOSITORY_UUID) .terminologyId(TERMINOLOGY_ID) .extensionOf(SNOMED_SHORT_NAME) .build(); }

Target:
public static CodeSystem b2iExtension(String extensionPath) { return CodeSystem.builder() .name(SNOMED_B2I_NAME) .shortName(SNOMED_B2I_SHORT_NAME) .oid(SNOMED_B2I_OID) .primaryLanguage(SNOMED_INT_LANGUAGE) .organizationLink(SNOMED_B2I_LINK) .citation(SNOMED_INT_CITATION) .branchPath(extensionPath) .iconPath(SNOMED_INT_ICON_PATH) .repositoryUuid(REPOSITORY_UUID) .terminologyId(TERMINOLOGY_ID) .extensionOf(SNOMED_SHORT_NAME) .build(); }
Source:
public boolean deleteTasks(String taskId) throws MambuApiException { String urlString = new String(mambuAPIService.createUrl(TASKS + "/" + taskId)); String jsonResponse = mambuAPIService.executeRequest(urlString, Method.DELETE); boolean deletionStatus = false; MambuApiResponseMessage response = new MambuApiResponseMessage(jsonResponse); if (response.getReturnCode() == 0) deletionStatus = true; return deletionStatus; }

Target:
public boolean deleteTasks(String taskId) throws MambuApiException { String urlString = new String(mambuAPIService.createUrl(TASKS + "/" + taskId)); String jsonResponse = mambuAPIService.executeRequest(urlString, Method.DELETE); boolean deletionStatus = false; MambuApiResponseMessage response = new MambuApiResponseMessage(jsonResponse); if (response.getReturnCode() == 0) { deletionStatus = true; } return deletionStatus; }
Source:
private void assertAccountMapEquals(Collection<Account> expectedAccounts, Map<String, String> accountMap) throws Exception { Set<Account> expectedAccountSet = new HashSet<>(expectedAccounts); for (String accountJsonString : accountMap.values()) { JSONObject accountJson = new JSONObject(accountJsonString); Account account = Account.fromJson(accountJson); assertTrue("unexpected account in map: " + accountJson.toString(), expectedAccountSet.contains(account)); } }

Target:
private void assertAccountMapEquals(Collection<Account> expectedAccounts, Map<String, String> accountMap) throws Exception { Set<Account> expectedAccountSet = new HashSet<>(expectedAccounts); assertEquals("Number of accounts mismatch", expectedAccountSet.size(), accountMap.size()); for (String accountJsonString : accountMap.values()) { JSONObject accountJson = new JSONObject(accountJsonString); Account account = Account.fromJson(accountJson); assertTrue("unexpected account in map: " + accountJson.toString(), expectedAccountSet.contains(account)); } }
Source:
public static void loadDimensionDataMap(@Nullable NBTTagCompound compound) { usedDimensionIds.clear(); lastUsedDimensionId = 0; if (compound == null) { dimensionTypeByDimensionId.keySet().stream().filter(dimensionId -> dimensionId >= 0).forEach(usedDimensionIds::add); } else { for (int id : compound.getIntArray("UsedIDs")) { usedDimensionIds.add(id); } int[] intArray = compound.getIntArray("DimensionArray"); for (int i = 0; i < intArray.length; i++) { int data = intArray[i]; if (data == 0) continue; for (int j = 0; j < Integer.SIZE; j++) { if ((data & (1 << j)) != 0) usedDimensionIds.add(i * Integer.SIZE + j); } } } }

Target:
public static void loadDimensionDataMap(@Nullable NBTTagCompound compound) { usedDimensionIds.clear(); lastUsedDimensionId = 0; if (compound == null) { dimensionTypeByDimensionId.keySet().stream().filter(dimensionId -> dimensionId >= 0).forEach(usedDimensionIds::add); } else { for (int id : compound.getIntArray(NbtDataUtil.USED_DIMENSION_IDS)) { usedDimensionIds.add(id); } int[] intArray = compound.getIntArray(NbtDataUtil.LEGACY_DIMENSION_ARRAY); for (int i = 0; i < intArray.length; i++) { int data = intArray[i]; if (data == 0) continue; for (int j = 0; j < Integer.SIZE; j++) { if ((data & (1 << j)) != 0) usedDimensionIds.add(i * Integer.SIZE + j); } } } }
Source:
public static ActiveMQQueue createQueue(final String address) { if (ArtemisSystemProperties.getInstance().is1XPrefix()) { return new ActiveMQQueue(PacketImpl.OLD_QUEUE_PREFIX + address); } else { return new ActiveMQQueue(address); } }

Target:
public static ActiveMQQueue createQueue(final String address) { return new ActiveMQQueue(address); }
Source:
public String getHelp() { return new TextComponentTranslation("commands.bloodmagic.bind.help").getFormattedText(); }

Target:
public String getHelp() { return "commands.bloodmagic.bind.help"; }
Source:
static KeyspaceMetadata ensureExists(String keyspace, boolean searchEnabled, Session session) { session.getCluster().getMetadata().getAllHosts().forEach((host) -> { Preconditions.checkState( 0 < VersionNumber.parse("3.11.2").compareTo(host.getCassandraVersion()), "All Cassandra nodes must be running 3.11.3+"); }); KeyspaceMetadata result = session.getCluster().getMetadata().getKeyspace(keyspace); if (result == null || result.getTable(Schema.TABLE_SPAN) == null) { LOG.info("Installing schema for keyspace {}", SCHEMA_RESOURCE, keyspace); applyCqlFile(keyspace, session, SCHEMA_RESOURCE); if (searchEnabled) { LOG.info("Installing indexes for keyspace {}", INDEX_RESOURCE, keyspace); applyCqlFile(keyspace, session, INDEX_RESOURCE); } result = session.getCluster().getMetadata().getKeyspace(keyspace); } return result; }

Target:
static KeyspaceMetadata ensureExists(String keyspace, boolean searchEnabled, Session session) { session.getCluster().getMetadata().getAllHosts().forEach((host) -> { Preconditions.checkState( 0 < VersionNumber.parse("3.11.3").compareTo(host.getCassandraVersion()), "All Cassandra nodes must be running 3.11.3+"); }); KeyspaceMetadata result = session.getCluster().getMetadata().getKeyspace(keyspace); if (result == null || result.getTable(Schema.TABLE_SPAN) == null) { LOG.info("Installing schema for keyspace {}", SCHEMA_RESOURCE, keyspace); applyCqlFile(keyspace, session, SCHEMA_RESOURCE); if (searchEnabled) { LOG.info("Installing indexes for keyspace {}", INDEX_RESOURCE, keyspace); applyCqlFile(keyspace, session, INDEX_RESOURCE); } result = session.getCluster().getMetadata().getKeyspace(keyspace); } return result; }
Source:
public void setValueForField(Table table, int fieldIndex, int lineNumber, Field field, String string, boolean postgresText, String[] transformedStrings) { if (string.isEmpty()) { if (field.isRequired() && !field.isEmptyValuePermitted() && errorStorage != null) { errorStorage.storeError(NewGTFSError.forLine(table, lineNumber, MISSING_FIELD, field.name)); } setFieldToNull(postgresText, transformedStrings, fieldIndex, field); } else { try { Set<NewGTFSError> errors; if (postgresText) { ValidateFieldResult<String> result = field.validateAndConvert(string); if (result.clean == null) setFieldToNull(postgresText, transformedStrings, fieldIndex, field); else transformedStrings[fieldIndex + 1] = result.clean; errors = result.errors; } else errors = field.setParameter(insertStatement, fieldIndex + 2, string); for (NewGTFSError error : errors) { error.entityType = table.getEntityClass(); error.lineNumber = lineNumber; if (errorStorage != null) errorStorage.storeError(error); } } catch (StorageException ex) { if (errorStorage != null) { errorStorage.storeError(NewGTFSError.forLine(table, lineNumber, ex.errorType, ex.badValue)); } setFieldToNull(postgresText, transformedStrings, fieldIndex, field); } } }

Target:
public void setValueForField(Table table, int fieldIndex, int lineNumber, Field field, String string, boolean postgresText, String[] transformedStrings) { if (string.isEmpty()) { if (field.isRequired() && !field.isEmptyValuePermitted() && errorStorage != null) { errorStorage.storeError(NewGTFSError.forLine(table, lineNumber, MISSING_FIELD, field.name)); } setFieldToNull(postgresText, transformedStrings, fieldIndex, field); } else { try { Set<NewGTFSError> errors; if (postgresText) { ValidateFieldResult<String> result = field.validateAndConvert(string); if (result.clean == null) setFieldToNull(postgresText, transformedStrings, fieldIndex, field); else transformedStrings[fieldIndex + 1] = result.clean; errors = result.errors; } else { errors = field.setParameter(insertStatement, fieldIndex + 2, string); } for (NewGTFSError error : errors) { error.entityType = table.getEntityClass(); error.lineNumber = lineNumber; if (errorStorage != null) errorStorage.storeError(error); } } catch (StorageException ex) { if (errorStorage != null) { errorStorage.storeError(NewGTFSError.forLine(table, lineNumber, ex.errorType, ex.badValue)); } setFieldToNull(postgresText, transformedStrings, fieldIndex, field); } } }
Source:
private void initUnregisteredTemplate() { if (vmTemplateFromConfiguration == null) { List<OvfEntityData> ovfEntityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(getParameters().getVmTemplateId(), getParameters().getStorageDomainId()); if (!ovfEntityList.isEmpty()) { ovfEntityData = ovfEntityList.get(0); try { FullEntityOvfData fullEntityOvfData = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()); vmTemplateFromConfiguration = fullEntityOvfData.getVmTemplate(); setVmTemplate(vmTemplateFromConfiguration); images = fullEntityOvfData.getDiskImages(); } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: {}:\n{}", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception", e); } } } }

Target:
private void initUnregisteredTemplate() { if (vmTemplateFromConfiguration == null) { List<OvfEntityData> ovfEntityList = unregisteredOVFDataDao.getByEntityIdAndStorageDomain(getParameters().getVmTemplateId(), getParameters().getStorageDomainId()); if (!ovfEntityList.isEmpty()) { ovfEntityData = ovfEntityList.get(0); try { FullEntityOvfData fullEntityOvfData = ovfHelper.readVmTemplateFromOvf(ovfEntityData.getOvfData()); vmTemplateFromConfiguration = fullEntityOvfData.getVmTemplate(); setVmTemplate(vmTemplateFromConfiguration); images = fullEntityOvfData.getDiskImages(); } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: {}:\n{}", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception: ", e); } } } }