auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testApplyBlockUpdatesToTrainingDataWhenEpochBegins() { final int numInitialInstances = MINI_BATCH_SIZE * 10; final int blockId = generateBlockIdNotInLocalStore().get(0); final Map<Long, Integer> dataSet = generateDataSetForBlock(blockId, MAX_BLOCK_SIZE); final MoveHandler moveHandler = (MoveHandler) memoryStore; createTrainingData(numInitialInstances); trainingDataProvider.prepareDataForEpoch(); moveHandler.putBlock(blockId, (Map) dataSet); operationRouter.updateOwnership(blockId, REMOTE_STORE_ID, LOCAL_STORE_ID); kvMapBackingMemoryStore.putAll(dataSet); testGetNextTrainingData(numInitialInstances + dataSet.size()); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); moveHandler.removeBlock(blockId); operationRouter.updateOwnership(blockId, LOCAL_STORE_ID, REMOTE_STORE_ID); for (final Long key : dataSet.keySet()) { kvMapBackingMemoryStore.remove(key); } testGetNextTrainingData(numInitialInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }

Target:
public void testApplyBlockUpdatesToTrainingDataWhenEpochBegins() { final int numMiniBatches = 10; final int numInitialInstances = MINI_BATCH_SIZE * numMiniBatches; final int blockId = generateBlockIdNotInLocalStore().get(0); final Map<Long, Integer> dataSet = generateDataSetForBlock(blockId, BLOCK_SIZE); createTrainingData(numInitialInstances); trainingDataProvider.prepareDataForEpoch(); putBlockToMemoryStore(blockId, dataSet); testGetNextTrainingData(numInitialInstances + dataSet.size()); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); trainingDataProvider.prepareDataForEpoch(); removeBlockFromMemoryStore(blockId); testGetNextTrainingData(numInitialInstances); assertTrue("Data should be exhausted", trainingDataProvider.getNextTrainingData().isEmpty()); }
Source:
private int readLastBlock(final byte[] b, final int off, final int len) throws IOException { int validation = validate(b, off, len); if (validation < 1) { return validation; } buffer = new byte[bufferSize]; bCursor = (int) (((contentLength < bufferSize) ? contentLength : bufferSize) - FOOTER_SIZE); long lastBlockStartPos = (contentLength < bufferSize) ? 0 : contentLength - bufferSize; int bytesRead = readInternal(lastBlockStartPos, buffer, 0, bufferSize, true); firstRead = false; if (bytesRead == -1) { return -1; } fCursorAfterLastRead = fCursor; limit = bytesRead; fCursor = lastBlockStartPos + bytesRead; return copyToUserBuffer(b, off, len); }

Target:
private int readLastBlock(final byte[] b, final int off, final int len) throws IOException { if (len == 0) { return 0; } if (!validate(b, off, len)) { return -1; } savePointerState(); long lastBlockStart = max(0, contentLength - bufferSize); bCursor = (int) (fCursor - lastBlockStart); long actualLenToRead = min(bufferSize, contentLength); return optimisedRead(b, off, len, lastBlockStart, actualLenToRead); }
Source:
public LabelType(String name, List<LabelValue> valueList) { this.name = checkName(name); canOverride = true; values = sortValues(valueList); defaultValue = new LabelValue((short) 0, "No Score"); abbreviation = defaultAbbreviation(name); functionName = "MaxWithBlock"; maxNegative = Short.MIN_VALUE; maxPositive = Short.MAX_VALUE; if (values.size() > 0) { if (values.get(0).getValue() < 0) { maxNegative = values.get(0).getValue(); } if (values.get(values.size() - 1).getValue() > 0) { maxPositive = values.get(values.size() - 1).getValue(); } } }

Target:
public LabelType(String name, List<LabelValue> valueList) { this.name = checkName(name); canOverride = true; values = sortValues(valueList); defaultValue = 0; abbreviation = defaultAbbreviation(name); functionName = "MaxWithBlock"; maxNegative = Short.MIN_VALUE; maxPositive = Short.MAX_VALUE; if (values.size() > 0) { if (values.get(0).getValue() < 0) { maxNegative = values.get(0).getValue(); } if (values.get(values.size() - 1).getValue() > 0) { maxPositive = values.get(values.size() - 1).getValue(); } } }
Source:
public static <A> Equal<Zipper<A>> zipperEqual(final Equal<A> ea) { Definition<A> eaDef = ea.def; return equalDef((a1, a2) -> { Zipper<A> x1 = a1; Zipper<A> x2 = a2; x1.move(0); x2.move(0); while (true) { if (!eaDef.equal(x1.focus(), x2.focus())) { return false; } if (x1.atEnd() || x2.atEnd()) { break; } x1 = x1.tryNext(); x2 = x2.tryNext(); } return x1.atEnd() && x2.atEnd(); }); }

Target:
public static <A> Equal<Zipper<A>> zipperEqual(final Equal<A> ea) { Equal<Stream<A>> se = Equal.streamEqual(ea); return equalDef((a1, a2) -> se.eq(a1.lefts(), a2.lefts()) && ea.eq(a1.focus(), a2.focus()) && se.eq(a1.rights(), a2.rights()) ); }
Source:
public void onItemFished(ItemFishedEvent event) { logger.info("Item fished"); List<ItemStack> stacks = event.getItemStacks(); stacks.clear(); stacks.add(new ItemStack(Items.SLIME_BALL, 2)); stacks.add(new ItemStack(Items.SNOWBALL, 3)); event.setRodDamage(50); }

Target:
public void onItemFished(ItemFishedEvent event) { EntityFishHook hook = event.getHookEntity(); BlockPos bobberPos = hook.getPosition(); Biome biomeFishedAt = hook.getEntityWorld().getBiome(bobberPos); logger.info("Item fished in Biome " + biomeFishedAt.getBiomeName()); if (biomeFishedAt.equals(Biomes.OCEAN)) { logger.info("Canceling the event because biome is ocean"); event.setCanceled(true); } event.damageRodBy(50); }
Source:
public void createBranch() throws RestApiException { gApi.projects() .name(project.get()) .branch("foo") .create(new BranchInput()); }

Target:
public void createBranch() throws GitAPIException, IOException, RestApiException { gApi.projects() .name(project.get()) .branch("foo") .create(new BranchInput()); }
Source:
public void testDeadWriterNotification() throws Exception { final OutputStream os = new RemoteOutputStream(new OutputStream() { @Override public void write(int b) throws IOException { System.gc(); throw (IOException) new IOException(MESSAGE, (Exception) DummyClassLoader.apply(TestCallable.class)); } }); channel.call(new DeadWriterCallable(os)); }

Target:
public void testDeadWriterNotification() throws Exception { final OutputStream os = new RemoteOutputStream(new OutputStream() { @Override public void write(int b) throws IOException { System.gc(); throw new IOException(MESSAGE, (Exception) DummyClassLoader.apply(TestCallable.class)); } }); channel.call(new DeadWriterCallable(os)); }
Source:
private Callable<Void> getConnectorStartingCallable(final String connectorName) { return new Callable<Void>() { @Override public Void call() throws Exception { try { startConnector(connectorName, (error, result) -> { }); } catch (Throwable t) { log.error("Couldn't instantiate connector " + connectorName + " because it has an invalid connector " + "configuration. This connector will not execute until reconfigured.", t); onFailure(connectorName, t); } return null; } }; }

Target:
private Callable<Void> getConnectorStartingCallable(final String connectorName) { return new Callable<Void>() { @Override public Void call() throws Exception { try { startConnector(connectorName, (error, result) -> { if (error != null) { log.error("Failed to start connector '" + connectorName + "'", error); } }); } catch (Throwable t) { log.error("Unexpected error while trying to start connector " + connectorName, t); onFailure(connectorName, t); } return null; } }; }
Source:
private void putImageInRegistry() throws InterruptedException { client.pullImageCmd("alpine:latest") .exec(new PullImageResultCallback()) .awaitCompletion(1, TimeUnit.MINUTES); final String id = client.listImagesCmd() .withImageNameFilter("alpine:latest") .exec() .get(0) .getId(); client.tagImageCmd(id, testImageName, "latest").exec(); client.pushImageCmd(testImageNameWithTag) .exec(new PushImageResultCallback()) .awaitCompletion(1, TimeUnit.MINUTES); client.removeImageCmd(testImageNameWithTag).withForce(true).exec(); }

Target:
private void putImageInRegistry() throws InterruptedException { final String dummySourceImage = TestcontainersConfiguration.getInstance().getRyukImage(); client.pullImageCmd(dummySourceImage) .exec(new PullImageResultCallback()) .awaitCompletion(1, TimeUnit.MINUTES); final String id = client.inspectImageCmd(dummySourceImage) .exec() .getId(); client.tagImageCmd(id, testImageName, "latest").exec(); client.pushImageCmd(testImageNameWithTag) .exec(new PushImageResultCallback()) .awaitCompletion(1, TimeUnit.MINUTES); client.removeImageCmd(testImageNameWithTag).withForce(true).exec(); }
Source:
public synchronized String format(long value) { long date = value / 1000000; long sec = value / 1000000000; long ms = Math.abs(value) % 1000000000 / 1000000; long cs = Math.abs(value) % 1000000 / 1000; long ns = Math.abs(value) % 1000; if (value < 0 && ms + cs + ns > 0 && !fPattern.contains("T")) { date -= 1; ms = (1000000000 - (1000000 * ms + 1000 * cs + ns)) / 1000000; cs = (1000000000 - (1000000 * ms + 1000 * cs + ns)) % 1000000 / 1000; ns = (1000000000 - (1000000 * ms + 1000 * cs + ns)) % 1000; } StringBuffer result = new StringBuffer(super.format(date)); int loc = result.indexOf(fCloseBracket + "'" + fOpenBracket); while (loc != -1) { result.deleteCharAt(loc + fCloseBracket.length()); loc = result.indexOf(fCloseBracket + "'" + fOpenBracket); } for (String pattern : fSupplPatterns) { int length = pattern.length(); StringBuffer fmt = new StringBuffer(length); for (int i = 0; i < length; i++) { fmt.append("0"); } DecimalFormat dfmt = new DecimalFormat(fmt.toString()); String fmtVal = ""; switch (pattern.charAt(0)) { case 'T': if (value < 0 && sec == 0) { result.insert(0, '-'); } fmtVal = dfmt.format(sec); break; case 'S': fmtVal = dfmt.format(ms); break; case 'C': fmtVal = dfmt.format(cs); break; case 'N': fmtVal = dfmt.format(ns); break; default: break; } String ph = new StringBuffer(fOpenBracket + pattern + fCloseBracket).toString(); loc = result.indexOf(ph); result.replace(loc, loc + length + fOpenBracket.length() + fCloseBracket.length(), fmtVal); } return result.toString(); }

Target:
public synchronized String format(long value) { long sec = value / 1000000000; long ms = value % 1000000000 / 1000000; long cs = value % 1000000 / 1000; long ns = value % 1000; StringBuffer result = new StringBuffer(super.format(sec * 1000 + ms)); int loc = result.indexOf(fCloseBracket + "'" + fOpenBracket); while (loc != -1) { result.deleteCharAt(loc + fCloseBracket.length()); loc = result.indexOf(fCloseBracket + "'" + fOpenBracket); } for (String pattern : fSupplPatterns) { int length = pattern.length(); StringBuffer fmt = new StringBuffer(length); for (int i = 0; i < length; i++) { fmt.append("0"); } DecimalFormat dfmt = new DecimalFormat(fmt.toString()); String fmtVal = ""; switch (pattern.charAt(0)) { case 'T': fmtVal = dfmt.format(sec); break; case 'S': fmtVal = dfmt.format(ms); break; case 'C': fmtVal = dfmt.format(cs); break; case 'N': fmtVal = dfmt.format(ns); break; default: break; } String ph = new StringBuffer(fOpenBracket + pattern + fCloseBracket).toString(); loc = result.indexOf(ph); result.replace(loc, loc + length + fOpenBracket.length() + fCloseBracket.length(), fmtVal); } return result.toString(); }
Source:
private Map<@NonNull String, @NonNull OutputElementStyle> getStyles() { if (fStylesMap == null) { fStylesMap = new HashMap<>(); synchronized (fProviders) { for (ITimeGraphDataProvider<?> provider : fProviders) { if (provider instanceof IOutputStyleProvider) { TmfModelResponse<@NonNull OutputStyleModel> styleResponse = ((IOutputStyleProvider) provider).fetchStyle(getStyleParameters(), null); OutputStyleModel styleModel = styleResponse.getModel(); if (styleModel != null) { Map<@NonNull String, @NonNull OutputElementStyle> currentStyleMap = styleModel.getStyles(); fStylesMap.putAll(currentStyleMap); } } } } } return fStylesMap; }

Target:
private Map<@NonNull String, @NonNull OutputElementStyle> getStyles() { if (fStylesMap == null) { fStylesMap = new LinkedHashMap<>(); synchronized (fProviders) { for (ITimeGraphDataProvider<?> provider : fProviders) { if (provider instanceof IOutputStyleProvider) { TmfModelResponse<@NonNull OutputStyleModel> styleResponse = ((IOutputStyleProvider) provider).fetchStyle(getStyleParameters(), null); OutputStyleModel styleModel = styleResponse.getModel(); if (styleModel != null) { Map<@NonNull String, @NonNull OutputElementStyle> currentStyleMap = styleModel.getStyles(); fStylesMap.putAll(currentStyleMap); } } } } } return fStylesMap; }
Source:
public List<Patient> getDuplicatePatientsByAttributes(List<String> attributes) throws APIException { if (attributes == null || !attributes.isEmpty()) { throw new APIException("Patient.no.attribute", (Object[]) null); } return dao.getDuplicatePatientsByAttributes(attributes); }

Target:
public List<Patient> getDuplicatePatientsByAttributes(List<String> attributes) throws APIException { if (attributes == null || attributes.isEmpty()) { throw new APIException("Patient.no.attribute", (Object[]) null); } return dao.getDuplicatePatientsByAttributes(attributes); }
Source:
public void testEnvironmentVars() { Map<String, String> vars = new HashMap<>(); vars.put("RABBITMQ_TEST_ADMIN_PASSWORD", "FOO"); vars.put("RABBITMQ_TEST_ADMIN_URI", "http://foo/bar"); vars.put("RABBITMQ_TEST_ADMIN_USER", "BAR"); vars.put("RABBITMQ_TEST_HOSTNAME", "BAZ"); vars.put("RABBITMQ_TEST_PASSWORD", "QUX"); vars.put("RABBITMQ_TEST_PORT", "2345"); vars.put("RABBITMQ_TEST_USER", "FIZ"); BrokerRunning.setEnvironmentVariables(vars); BrokerRunning brokerRunning = BrokerRunning.isBrokerAndManagementRunning(); assertEquals("http://foo/bar", brokerRunning.getAdminUri()); ConnectionFactory connectionFactory = brokerRunning.getConnectionFactory(); assertEquals("BAZ", connectionFactory.getHost()); assertEquals(2345, connectionFactory.getPort()); assertEquals("FIZ", connectionFactory.getUsername()); assertEquals("QUX", connectionFactory.getPassword()); DirectFieldAccessor dfa = new DirectFieldAccessor(brokerRunning); assertEquals("BAR", dfa.getPropertyValue("adminUser")); assertEquals("FOO", dfa.getPropertyValue("adminPassword")); }

Target:
public void testEnvironmentVars() { Map<String, String> vars = new HashMap<>(); vars.put("RABBITMQ_TEST_ADMIN_PASSWORD", "FOO"); vars.put("RABBITMQ_TEST_ADMIN_URI", "http://foo/bar"); vars.put("RABBITMQ_TEST_ADMIN_USER", "BAR"); vars.put("RABBITMQ_TEST_HOSTNAME", "BAZ"); vars.put("RABBITMQ_TEST_PASSWORD", "QUX"); vars.put("RABBITMQ_TEST_PORT", "2345"); vars.put("RABBITMQ_TEST_USER", "FIZ"); BrokerRunning.setEnvironmentVariableOverrides(vars); BrokerRunning brokerRunning = BrokerRunning.isBrokerAndManagementRunning(); assertEquals("http://foo/bar", brokerRunning.getAdminUri()); ConnectionFactory connectionFactory = brokerRunning.getConnectionFactory(); assertEquals("BAZ", connectionFactory.getHost()); assertEquals(2345, connectionFactory.getPort()); assertEquals("FIZ", connectionFactory.getUsername()); assertEquals("QUX", connectionFactory.getPassword()); DirectFieldAccessor dfa = new DirectFieldAccessor(brokerRunning); assertEquals("BAR", dfa.getPropertyValue("adminUser")); assertEquals("FOO", dfa.getPropertyValue("adminPassword")); BrokerRunning.clearEnvironmentVariableOverrides(); }
Source:
public void testInspectVolume() throws Exception { requireDockerApiVersionAtLeast("1.21", "volumes"); final Volume volume = sut.createVolume(); assertEquals(volume, sut.inspectVolume(volume.name())); final String badVolumeName = "this-is-a-very-unlikely-volume-name"; try { sut.inspectVolume(badVolumeName); fail("We should not have found a volume with name " + badVolumeName); } catch (VolumeNotFoundException e) { assertEquals(badVolumeName, e.getVolumeName()); } sut.removeVolume(volume); }

Target:
public void testInspectVolume() throws Exception { requireDockerApiVersionAtLeast("1.21", "volumes"); final Volume volume = sut.createVolume(); assertEquals(volume, sut.inspectVolume(volume.name())); sut.removeVolume(volume); final String badVolumeName = "this-is-a-very-unlikely-volume-name"; exception.expect(VolumeNotFoundException.class); exception.expect(volumeNotFoundExceptionWithName(badVolumeName)); sut.inspectVolume(badVolumeName); }
Source:
public static void saveModuleToFile(Module module, File toFile) throws IOException { String moduleInfoJson = moduleToJsonString(module); if (!toFile.getParentFile().exists()) { toFile.getParentFile().mkdirs(); } if (!toFile.exists()) { toFile.createNewFile(); } Files.write(moduleInfoJson, toFile, Charsets.UTF_8); }

Target:
public static void saveModuleToFile(Module module, File toFile) throws IOException { String moduleInfoJson = moduleToJsonString(module); if (!toFile.getParentFile().exists()) { toFile.getParentFile().mkdirs(); } if (!toFile.exists()) { toFile.createNewFile(); } Files.asCharSink(toFile, Charsets.UTF_8).write(moduleInfoJson); }
Source:
void setup() { MockitoAnnotations.initMocks(this); when(message.getLockToken()).thenReturn(LOCK_TOKEN); when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH); when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1)); client = new ServiceBusReceiverClient(asyncClient, OPERATION_TIMEOUT); }

Target:
void setup() { MockitoAnnotations.initMocks(this); when(asyncClient.getEntityPath()).thenReturn(ENTITY_PATH); when(asyncClient.getFullyQualifiedNamespace()).thenReturn(NAMESPACE); when(asyncClient.getReceiverOptions()).thenReturn(new ReceiverOptions(ReceiveMode.PEEK_LOCK, 1)); client = new ServiceBusReceiverClient(asyncClient, OPERATION_TIMEOUT); }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } final SAMSequenceRecord that = (SAMSequenceRecord) o; if (mSequenceIndex != that.mSequenceIndex) return false; if (mSequenceLength != that.mSequenceLength) return false; if (!attributesEqual(that)) return false; if (mSequenceName != that.mSequenceName) return false; return true; }

Target:
public boolean equals(final Object o) { if (this == o) return true; if (o == null) return false; if (this.getClass() != o.getClass()) return false; final SAMSequenceRecord that = (SAMSequenceRecord) o; if (mSequenceIndex != that.mSequenceIndex) return false; if (mSequenceLength != that.mSequenceLength) return false; if (!attributesEqual(that)) return false; if (mSequenceName != that.mSequenceName) return false; return true; }
Source:
public void testRehashes() throws PersistenceException { MagicKey k = new MagicKey("k", c1); c1.put(k, "v"); Cache<Object, String>[] owners = getOwners(k); log.infof("Initial owners list for key %s: %s", k, Arrays.asList(owners)); for (Cache<Object, String> c: Arrays.asList(c1, c2, c3)) { DummyInMemoryStore dims = TestingUtil.getFirstStore(c); assert dims.contains(k) : format("CacheStore on %s should contain key %s", c, k); } Cache<Object, String> primaryOwner = owners[0]; if (getCacheStoreStats(primaryOwner, "write") == 0) primaryOwner = owners[1]; for (Cache<Object, String> c: owners) { int numWrites = getCacheStoreStats(c, "write"); assert numWrites == 1 : "store() should have been invoked on the cache store once. Was " + numWrites; } log.infof("Stopping node %s", primaryOwner); caches.remove(primaryOwner); primaryOwner.stop(); primaryOwner.getCacheManager().stop(); TestingUtil.blockUntilViewsReceived(60000, false, caches); TestingUtil.waitForNoRebalance(caches); owners = getOwners(k); log.infof("After shutting one node down, owners list for key %s: %s", k, Arrays.asList(owners)); assert owners.length == numOwners; for (Cache<Object, String> o : owners) { int numWrites = getCacheStoreStats(o, "write"); assert numWrites == 1 : "store() should have been invoked on the cache store once. Was " + numWrites; assert "v".equals(o.get(k)) : "Should be able to see key on new owner"; } }

Target:
public void testRehashes() throws PersistenceException { MagicKey k = new MagicKey("k", c1); c1.put(k, "v"); Cache<Object, String>[] owners = getOwners(k); log.infof("Initial owners list for key %s: %s", k, Arrays.asList(owners)); for (Cache<Object, String> c: Arrays.asList(c1, c2, c3)) { DummyInMemoryStore dims = TestingUtil.getFirstStore(c); assertTrue("CacheStore on " + c + " should contain key " + k, dims.contains(k)); } Cache<Object, String> primaryOwner = owners[0]; if (getCacheStoreStats(primaryOwner, "write") == 0) primaryOwner = owners[1]; for (Cache<Object, String> c: owners) { int numWrites = getCacheStoreStats(c, "write"); assertEquals(1, numWrites); } log.infof("Stopping node %s", primaryOwner); caches.remove(primaryOwner); primaryOwner.stop(); primaryOwner.getCacheManager().stop(); TestingUtil.blockUntilViewsReceived(60000, false, caches); TestingUtil.waitForNoRebalance(caches); owners = getOwners(k); log.infof("After shutting one node down, owners list for key %s: %s", k, Arrays.asList(owners)); assertEquals(numOwners, owners.length); for (Cache<Object, String> o : owners) { int numWrites = getCacheStoreStats(o, "write"); assertEquals(1, numWrites); assertEquals("v", o.get(k)); } }
Source:
public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.UNTAP_STEP_PRE) { reset(); return; } if (game.getPhase() != null && event.getType() == GameEvent.EventType.DREW_CARD) { UUID playerId = event.getPlayerId(); if (playerId != null) { amountOfCardsDrawnThisTurn.putIfAbsent(playerId, 0); amountOfCardsDrawnThisTurn.compute(playerId, (p, amount) -> amount + 1); if (amountOfCardsDrawnThisTurn.get(playerId) == 1) { checkMiracleAbility(event, game); } } } }

Target:
public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.UNTAP_STEP_PRE) { reset(); return; } if (game.getPhase() != null && event.getType() == GameEvent.EventType.DREW_CARD) { UUID playerId = event.getPlayerId(); if (playerId != null) { Integer amount = 1 + amountOfCardsDrawnThisTurn.getOrDefault(playerId, 0); amountOfCardsDrawnThisTurn.put(playerId, amount); if (amount == 1) { checkMiracleAbility(event, game); } } } }
Source:
protected boolean checkIfLunDiskCanBeAdded(DiskValidator diskValidator) { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections() == null || lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } for (StorageServerConnections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } break; } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } if (getVm() != null && !(isVmNotLocked() && isVmNotInPreviewSnapshot())) { return false; } if (!validate(diskValidator.isVirtIoScsiValid(getVm()))) { return false; } if (!validate(diskValidator.isDiskInterfaceSupported(getVm()))) { return false; } if (getVds() != null && !validate(diskValidator.isLunDiskVisible(lun, getVds()))) { return false; } LunDisk lunDisk = ((LunDisk) getParameters().getDiskInfo()); if (lunDisk.isUsingScsiReservation() && !lunDisk.isScsiPassthrough()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_PASSTHROUGH_IS_DISABLED); } return true; }

Target:
protected boolean checkIfLunDiskCanBeAdded(DiskValidator diskValidator) { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections() == null || lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } for (StorageServerConnections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } break; } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } if (getVm() != null && !(isVmNotLocked() && isVmNotInPreviewSnapshot())) { return false; } if (!validate(diskValidator.isVirtIoScsiValid(getVm()))) { return false; } if (!validate(diskValidator.isDiskInterfaceSupported(getVm()))) { return false; } if (getVds() != null && !validate(diskValidator.isLunDiskVisible(lun, getVds()))) { return false; } LunDisk lunDisk = ((LunDisk) getParameters().getDiskInfo()); ValidationResult validationResult = diskValidator.isUsingScsiReservationValid(lunDisk); if (!validate(validationResult)) { return failCanDoAction(validationResult.getMessage()); } return true; }
Source:
public CtfTmfEvent getCurrentEvent() { final StreamInputReader top = super.getPrio().peek(); if (top != null) { if (hashCode() != previousHashCode) { previousHashCode = hashCode(); previousCurrentEvent = CtfTmfEventFactory.createEvent(top.getCurrentEvent(), top.getFilename(), fTrace); } return previousCurrentEvent; } return null; }

Target:
public synchronized CtfTmfEvent getCurrentEvent() { final StreamInputReader top = super.getPrio().peek(); if (top != null) { if (fCurLocation.hashCode() != fPreviousHashCode) { fPreviousHashCode = fCurLocation.hashCode(); fPreviousCurEvent = CtfTmfEventFactory.createEvent(top.getCurrentEvent(), top.getFilename(), fTrace); } return fPreviousCurEvent; } return null; }
Source:
public InetSocketAddress next(long spinDelay) { if (!connectedSinceNext) { InetSocketAddress curAddr = serverAddresses.get(currentIndex); if (!curAddr.getHostString().equals(curAddr.getAddress().getHostAddress())) { try { int thePort = curAddr.getPort(); InetAddress resolvedAddresses[] = InetAddress.getAllByName(getHostString(curAddr)); if (resolvedAddresses.length == 1) { serverAddresses.set(currentIndex, new InetSocketAddress(resolvedAddresses[0], thePort)); } else { serverAddresses.remove(currentIndex); for (InetAddress resolvedAddress : resolvedAddresses) { InetSocketAddress newAddr = new InetSocketAddress(resolvedAddress, thePort); if (!serverAddresses.contains(newAddr)) { serverAddresses.add(newAddr); } } } } catch (UnknownHostException e) { LOG.warn("Cannot re-resolve server: " + curAddr + " UnknownHostException: " + e); } } } ++currentIndex; connectedSinceNext = false; if (currentIndex == serverAddresses.size()) { currentIndex = 0; } if (currentIndex == lastIndex && spinDelay > 0) { try { Thread.sleep(spinDelay); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } else if (lastIndex == -1) { lastIndex = 0; } return serverAddresses.get(currentIndex); }

Target:
public InetSocketAddress next(long spinDelay) { if (!connectedSinceNext) { InetSocketAddress curAddr = serverAddresses.get(currentIndex); String curHostString = getHostString(curAddr); if (!curHostString.equals(curAddr.getAddress().getHostAddress())) { LOG.info("Resolving again hostname: {}", getHostString(curAddr)); try { int thePort = curAddr.getPort(); InetAddress resolvedAddresses[] = InetAddress.getAllByName(curHostString); nextAdded = 0; nextRemoved = 0; if (resolvedAddresses.length == 1) { serverAddresses.set(currentIndex, new InetSocketAddress(resolvedAddresses[0], thePort)); nextAdded = nextRemoved = 1; LOG.debug("Newly resolved address: {}", resolvedAddresses[0]); } else { int i = 0; while (i < serverAddresses.size()) { if (getHostString(serverAddresses.get(i)).equals(curHostString) && serverAddresses.get(i).getPort() == curAddr.getPort()) { LOG.debug("Removing address: {}", serverAddresses.get(i)); serverAddresses.remove(i); nextRemoved++; } else { i++; } } for (InetAddress resolvedAddress : resolvedAddresses) { InetSocketAddress newAddr = new InetSocketAddress(resolvedAddress, thePort); if (!serverAddresses.contains(newAddr)) { LOG.debug("Adding address: {}", newAddr); serverAddresses.add(newAddr); nextAdded++; } } } } catch (UnknownHostException e) { LOG.warn("Cannot re-resolve server: {}", curAddr, e); } } } connectedSinceNext = false; currentIndex = ++currentIndex % serverAddresses.size(); if (currentIndex == lastIndex && spinDelay > 0) { try { Thread.sleep(spinDelay); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } else if (lastIndex == -1) { lastIndex = 0; } return serverAddresses.get(currentIndex); }
Source:
public List<Pipeline> getPipelinesSync() throws TimeoutException { return getPipelinesSync(TimeUnit.SECONDS.toMillis(pollingIntervalSeconds)); }

Target:
public List<Pipeline> getPipelinesSync() throws TimeoutException { return getPipelinesSync(pollingIntervalMs); }
Source:
protected Optional<Optional<org.spongepowered.api.entity.Entity>> getVal(Entity dataHolder) { if (!(dataHolder instanceof IEntityTargetingEntity)) return Optional.empty(); return Optional.of(Optional.ofNullable((org.spongepowered.api.entity.Entity) ((IEntityTargetingEntity) dataHolder).getTargetedEntity())); }

Target:
protected Optional<org.spongepowered.api.entity.EntitySnapshot> getVal(Entity dataHolder) { Entity entity = ((IEntityTargetingEntity) dataHolder).getTargetedEntity(); if (entity == null) { return Optional.empty(); } return Optional.of(((org.spongepowered.api.entity.Entity) entity).createSnapshot()); }
Source:
private void deleteWithRetries(final String s3Bucket, final String s3Path) throws Exception { RetryUtils.retry( (Callable<Void>) () -> { try { s3Client.deleteObject(s3Bucket, s3Path); if (s3Client.isObjectInBucket(s3Bucket, s3Path)) { throw new IOException(StringUtils.format( "After delete reported as successful the deleted file [s3://%s/%s] still exists", s3Bucket, s3Path )); } return null; } catch (Exception e) { log.info(e, "Error while trying to delete [s3://%s/%s]", s3Bucket, s3Path); throw e; } }, S3Utils.S3RETRY, 3 ); }

Target:
private void deleteWithRetries(final String s3Bucket, final String s3Path) throws Exception { RetryUtils.retry( (Callable<Void>) () -> { try { s3Client.deleteObject(s3Bucket, s3Path); return null; } catch (Exception e) { log.info(e, "Error while trying to delete [s3://%s/%s]", s3Bucket, s3Path); throw e; } }, S3Utils.S3RETRY, 3 ); }
Source:
public static void deleteHistoryLogging() { File folderLogs = new File(mFolder + File.separator); if(folderLogs.isDirectory()){ String[] myFiles = folderLogs.list(); for (String myFile1 : myFiles) { File myFile = new File(folderLogs, myFile1); Log_OC.d("delete file", myFile.getAbsoluteFile() + " " + myFile.delete()); } } }

Target:
public static void deleteHistoryLogging() { File folderLogs = new File(mFolder + File.separator); if (folderLogs.isDirectory()) { String[] myFiles = folderLogs.list(); for (String fileName : myFiles) { File fileInFolder = new File(folderLogs, fileName); Log_OC.d("delete file", fileInFolder.getAbsoluteFile() + " " + fileInFolder.delete()); } } }
Source:
public static void main(String[] args) throws ConfigurationException, FileNotFoundException { logger.info("Starting the Microservice with Metrics"); URL resource = Application.class.getClassLoader().getResource("metrics.yaml"); if (resource == null) { throw new FileNotFoundException("Metrics configuration resource not found"); } Path configPath = new File(resource.getFile()).toPath(); ConfigProvider configProvider = ConfigProviderFactory.getConfigProvider(configPath, null); org.wso2.msf4j.analytics.internal.DataHolder.getInstance().setConfigProvider(configProvider); new MicroservicesRunner() .addInterceptor(new MetricsInterceptor()) .deploy(new DemoService()) .start(); }

Target:
public static void main(String[] args) { logger.info("Starting the Microservice with Metrics"); new MicroservicesRunner() .addInterceptor(new MetricsInterceptor()) .deploy(new DemoService()) .start(); }
Source:
public void rollOver() { File file; if (qw != null) { long size = ((CountingQuietWriter)qw).getCount(); LogLog.debug("rolling over count=" + size); } LogLog.debug("maxBackupIndex=" + maxBackupIndex); boolean deleteSucceeded = true; int nextFileIndex = (currentFileIndex + 1) % maxBackupIndex; String nextFileName = fileName + '.' + nextFileIndex; if (maxBackupIndex > 0) { file = new File(nextFileName); if (file.exists()) { deleteSucceeded = file.delete(); } if (deleteSucceeded) { this.closeFile(); } else { try { this.setFile(fileName, true, bufferedIO, bufferSize); } catch (IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("setFile(" + fileName + ", true) call failed.", e); } } } currentFileIndex = nextFileIndex; if (deleteSucceeded) { try { this.setFile(fileName, false, bufferedIO, bufferSize); } catch (IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("setFile(" + fileName + ", false) call failed.", e); } } }

Target:
public void rollOver() { if (qw != null) { long size = ((CountingQuietWriter)qw).getCount(); LogLog.debug("rolling over count=" + size); } LogLog.debug("maxBackupIndex=" + maxBackupIndex); boolean deleteSucceeded = true; int nextFileIndex = (currentFileIndex + 1) % maxBackupIndex; String nextFileName = fileName + '.' + nextFileIndex; if (maxBackupIndex > 0) { File file = new File(nextFileName); if (file.exists()) { deleteSucceeded = file.delete(); } if (deleteSucceeded) { this.closeFile(); } else { try { this.setFile(fileName, true, bufferedIO, bufferSize); } catch (IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("setFile(" + fileName + ", true) call failed.", e); } } } currentFileIndex = nextFileIndex; if (deleteSucceeded) { try { this.setFile(fileName, false, bufferedIO, bufferSize); } catch (IOException e) { if (e instanceof InterruptedIOException) { Thread.currentThread().interrupt(); } LogLog.error("setFile(" + fileName + ", false) call failed.", e); } } }
Source:
public void decorateHeaderCell() { HeaderCell cell = m_headerCell; decorateHeaderCellInternal(cell); try { execDecorateHeaderCell(cell); getTable().getColumnSet().updateColumn(this); } catch (ProcessingException e) { LOG.warn(null, e); } catch (Throwable t) { LOG.warn(null, t); } }

Target:
public void decorateHeaderCell() { HeaderCell cell = m_headerCell; decorateHeaderCellInternal(cell); try { execDecorateHeaderCell(cell); if (getTable() != null && getTable().getColumnSet() != null) { getTable().getColumnSet().updateColumn(this); } } catch (ProcessingException e) { LOG.warn(null, e); } catch (Throwable t) { LOG.warn(null, t); } }
Source:
public boolean connectorExists(String id) { try { List<ConnectorConfiguration> list = configPersistence.load(ImmutableMap.of(Constants.CONNECTOR_PERSISTENT_ID, id)); if (list.isEmpty()) { return false; } return true; } catch (PersistenceException e) { throw new RuntimeException(e); } }

Target:
public Boolean connectorExists(String id) { try { List<ConnectorConfiguration> list = configPersistence.load(ImmutableMap.of(Constants.CONNECTOR_PERSISTENT_ID, id)); return !list.isEmpty(); } catch (PersistenceException e) { throw new RuntimeException(e); } }
Source:
private void captureScreenshot(ITestResult result, SeleniumWebDriver webDriver) { String testName = result.getTestClass().getName() + "." + result.getMethod().getMethodName(); String filename = NameGenerator.generate(testName + "_", 8) + ".png"; try { String pageSource = webDriver.getPageSource(); Path dmpDirectory = Paths.get("target/htmldump", filename + ".html"); Files.createDirectories(dmpDirectory.getParent()); Files.write(dmpDirectory, pageSource.getBytes(), StandardOpenOption.CREATE); byte[] data = webDriver.getScreenshotAs(OutputType.BYTES); Path screenshot = Paths.get(screenshotDir, filename); Files.createDirectories(screenshot.getParent()); Files.copy(new ByteArrayInputStream(data), screenshot); } catch (WebDriverException | IOException e) { LOG.error(format("Can't capture screenshot for test %s", testName), e); } }

Target:
private void captureScreenshot(ITestResult result, SeleniumWebDriver webDriver) { String testName = result.getTestClass().getName() + "." + result.getMethod().getMethodName(); String filename = NameGenerator.generate(testName + "_", 8) + ".png"; try { byte[] data = webDriver.getScreenshotAs(OutputType.BYTES); Path screenshot = Paths.get(screenshotDir, filename); Files.createDirectories(screenshot.getParent()); Files.copy(new ByteArrayInputStream(data), screenshot); } catch (WebDriverException | IOException e) { LOG.error(format("Can't capture screenshot for test %s", testName), e); } }
Source:
public void testInitialization() throws Exception { try (IgniteLock lock = createReentrantLock(0, "lock1", false)) { } try (IgniteLock lock = createReentrantLock(0, "lock2", true)) { } }

Target:
public void testInitialization() { try (IgniteLock ignore = createReentrantLock(0, "unfair lock", false)) { } try (IgniteLock ignore = createReentrantLock(0, "fair lock", true)) { } }
Source:
private List<VMImage> listImagesByLocation(String location) { final List<VMImage> osImages = Lists.newArrayList(); final List<Publisher> publisherList = api.getOSImageApi(location).listPublishers(); Iterable<String> publishers = Splitter.on(',').trimResults().omitEmptyStrings().split(this.azureComputeConstants.azureImagePublishers()); for (String publisher : publishers) { getImagesFromPublisher(publisher, osImages, location); } return osImages; }

Target:
private List<VMImage> listImagesByLocation(String location) { final List<VMImage> osImages = Lists.newArrayList(); Iterable<String> publishers = Splitter.on(',').trimResults().omitEmptyStrings().split(this.azureComputeConstants.azureImagePublishers()); for (String publisher : publishers) { getImagesFromPublisher(publisher, osImages, location); } return osImages; }
Source:
private void validatePort() { boolean inUse = serverHelper.isPortInUse(port); do { if (inUse) { String message = String.format("Port %s is already in use. Can we use %s? Otherwise the run will fail.", port, port + 1); boolean promptToChange = wizard.promptYesNo(message); if (promptToChange) { ++port; wizard.showMessage(String.format("Testing port %s", port)); inUse = serverHelper.isPortInUse(port); } else { break; } } } while (inUse); }

Target:
private void validatePort() { boolean inUse = false; int tmpPort = port; inUse = serverHelper.checkPortUsage(tmpPort); if (inUse) { tmpPort = serverHelper.findNearestPort(tmpPort); } else { return; } String message = String.format("Port %s is already in use. Would you like to use %s instead?", port, tmpPort); boolean promptToChange = wizard.promptYesNo(message); if (promptToChange) { port = tmpPort; return; } this.validatePort(); }
Source:
public void testTableSinkWithMissingKeyField() { Schema inputSchema = Schema.recordOf( "purchase", Schema.Field.of("uniqueId", Schema.of(Schema.Type.STRING)), Schema.Field.of("user", Schema.of(Schema.Type.STRING)) ); KVTableSink.KVTableConfig kvTableConfig = new KVTableSink.KVTableConfig("purchases", "rowKey", "user"); KVTableSink kvTableSink = new KVTableSink(kvTableConfig); MockPipelineConfigurer mockPipelineConfigurer = new MockPipelineConfigurer(inputSchema, Collections.<String, Object>emptyMap()); kvTableSink.configurePipeline(mockPipelineConfigurer); }

Target:
public void testTableSinkWithMissingKeyField() { Schema inputSchema = Schema.recordOf( "purchase", Schema.Field.of("uniqueId", Schema.of(Schema.Type.STRING)), Schema.Field.of("user", Schema.of(Schema.Type.STRING)) ); KVTableSink.KVTableConfig kvTableConfig = new KVTableSink.KVTableConfig("purchases", "rowKey", "user"); KVTableSink kvTableSink = new KVTableSink(kvTableConfig); MockPipelineConfigurer mockPipelineConfigurer = new MockPipelineConfigurer(inputSchema); kvTableSink.configurePipeline(mockPipelineConfigurer); }
Source:
public String getRyaInstanceName() { return get(MONGO_DB_NAME, "rya"); }

Target:
public String getRyaInstanceName() { return get(RYA_INSTANCE_NAME, "rya"); }
Source:
public void shouldPurgeAnAutoGenerationOption() throws Exception { MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService .getAutoGenerationOption(Context.getPatientService().getPatientIdentifierTypeByUuid(getUuid()))); }

Target:
public void shouldPurgeAnAutoGenerationOption() throws Exception { assertNotNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); }
Source:
public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(final String group, final String name, final Template template) { VirtualDatacenter vdc = cloudService.getVirtualDatacenter(Integer.valueOf(template.getHardware().getLocation() .getId())); VirtualAppliance vapp = find(vdc.listVirtualAppliances(), new Predicate<VirtualAppliance>() { @Override public boolean apply(VirtualAppliance input) { return input.getName().equals(group); } }); return createNodeWithGroupEncodedIntoName(vdc, vapp, name, template); }

Target:
public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(final String group, final String name, final Template template) { checkArgument(template instanceof VirtualApplianceCachingTemplate, "A VirtualApplianceCachingTemplate is required"); return createNodeWithGroupEncodedIntoName(name, VirtualApplianceCachingTemplate.class.cast(template)); }
Source:
private CompletableFuture<Void> nonBlockingClose() { if (this.isClosed) throw new IllegalStateException("Writer is already closed"); this.isClosed = true; return CompletableFuture.supplyAsync(() -> { try { this.blockingClose(); return null; } catch (Exception e) { throw new RuntimeException("Caught exception while closing PooledWriter.", e); } }, AsyncWriterPool.this.executor); }

Target:
private CompletableFuture<Void> nonBlockingClose() { return CompletableFuture.supplyAsync(() -> { try { this.close(); return null; } catch (Exception e) { throw new RuntimeException("Caught exception while closing PooledWriter.", e); } }, AsyncWriterPool.this.executor); }
Source:
public void execute() { final PatchSetContent content = new PatchSetContent(baseSet, targetSet); final IReviewItemSet compareSet = IReviewsFactory.INSTANCE.createReviewItemSet(); String basePatchSetLabel = content.getBase() != null ? content.getBase().getPatchSetId() + "" : "Base"; compareSet.setName(NLS.bind("Compare Patch Set {0} and {1}", content.getTarget().getPatchSetId(), basePatchSetLabel)); getGerritFactoryProvider().getReviewItemSetContentFactory().consume("Compare Items", compareSet, content, "", new RemoteEmfConsumer.IObserver<List<IReviewItem>>() { public void responded(boolean modified) { GerritToGitMapping mapper = getGitRepository(); Repository gitRepository = null; if (mapper != null) { try { gitRepository = mapper.find(); } catch (IOException e) { } } CompareConfiguration configuration = new CompareConfiguration(); CompareUI.openCompareEditor(new ReviewItemSetCompareEditorInput(configuration, compareSet, null, new GerritReviewBehavior(getTask(), gitRepository))); } public void failed(IStatus status) { StatusHandler.log(new Status(IStatus.ERROR, GerritUiPlugin.PLUGIN_ID, "Couldn't load task content for review", status.getException())); } public void created(List<IReviewItem> object) { } }); }

Target:
public void execute() { final PatchSetContent content = new PatchSetContent(baseSet, targetSet); final IReviewItemSet compareSet = IReviewsFactory.INSTANCE.createReviewItemSet(); String basePatchSetLabel = content.getBase() != null ? content.getBase().getPatchSetId() + "" : "Base"; compareSet.setName(NLS.bind("Compare Patch Set {0} and {1}", content.getTarget().getPatchSetId(), basePatchSetLabel)); RemoteEmfConsumer<IReviewItemSet, List<IReviewItem>, PatchSetContent, PatchSetContent, String> consumer = getGerritFactoryProvider().getReviewItemSetContentFactory() .consume("Compare Items", compareSet, content, "", new RemoteEmfConsumer.IObserver<List<IReviewItem>>() { public void responded(boolean modified) { CompareConfiguration configuration = new CompareConfiguration(); CompareUI.openCompareEditor(new ReviewItemSetCompareEditorInput(configuration, compareSet, null, new GerritReviewBehavior(getTask(), resolveGitRepository()))); } public void failed(IStatus status) { StatusHandler.log(new Status(IStatus.ERROR, GerritUiPlugin.PLUGIN_ID, "Couldn't load task content for review", status.getException())); } public void created(List<IReviewItem> object) { } }); consumer.request(); }
Source:
static X509Certificate selfSignedCertificate() throws CertificateException { return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate( new ByteArrayInputStream(CERT.getBytes()) ); }

Target:
static X509Certificate selfSignedCertificate() throws CertificateException { return (X509Certificate) SslContext.X509_CERT_FACTORY.generateCertificate( new ByteArrayInputStream(CERT.getBytes(CharsetUtil.US_ASCII)) ); }
Source:
private void notifySelect(boolean ctrl) { int stateMask1 = (ctrl) ? (SWT.BUTTON1 | SWT.CTRL) : SWT.BUTTON1; int stateMask2 = (ctrl) ? (SWT.NONE | SWT.CTRL) : SWT.NONE; notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseDown, createMouseEvent(0, 0, 1, stateMask2, 1)); notify(SWT.Selection, selectionEvent(stateMask1)); notify(SWT.MouseUp, createMouseEvent(0, 0, 1, stateMask1, 1)); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); }

Target:
private void notifySelect(boolean ctrl) { int stateMask1 = (ctrl) ? (SWT.NONE | SWT.CTRL) : SWT.NONE; int stateMask2 = (ctrl) ? (SWT.BUTTON1 | SWT.CTRL) : SWT.BUTTON1; notify(SWT.MouseEnter); notify(SWT.MouseMove); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseDown, createMouseEvent(0, 0, 1, stateMask1, 1)); notify(SWT.Selection, selectionEvent(stateMask2)); notify(SWT.MouseUp, createMouseEvent(0, 0, 1, stateMask2, 1)); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); }
Source:
public int parseArguments(Parameters params) throws CmdLineException { String timestamp = params.getParameter(0); try { DateFormat fmt = new SimpleDateFormat(DATE_FORMAT); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); setter.addValue(new Timestamp(fmt.parse(timestamp).getTime())); return 1; } catch (ParseException e) { throw new CmdLineException(owner, String.format("Invalid timestamp: %s; expected format: %s", timestamp, DATE_FORMAT), e); } }

Target:
public int parseArguments(Parameters params) throws CmdLineException { String timestamp = params.getParameter(0); try { DateFormat fmt = new SimpleDateFormat(TIMESTAMP_FORMAT); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); setter.addValue(new Timestamp(fmt.parse(timestamp).getTime())); return 1; } catch (ParseException e) { throw new CmdLineException(owner, String.format("Invalid timestamp: %s; expected format: %s", timestamp, TIMESTAMP_FORMAT), e); } }