auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testTextInputComp() { ComponentIdentifier identifier = OM_factories.TextField_pfr_txf; TextInputComponent textField = ConcreteComponents .createTextInputComponent(identifier); Assert.assertNotNull(textField); CAP cap1 = textField.checkEditability(true); Assert.assertNotNull(cap1); CAP cap2 = textField.checkText("test", Operator.equals); Assert.assertNotNull(cap2); CAP cap3 = textField.inputText("test"); Assert.assertNotNull(cap3); CAP cap4 = textField.insertTextAfterIndex("test", 1); Assert.assertNotNull(cap4); CAP cap5 = textField.insertTextBeforeAfterPattern( "test", "pattern", Operator.equals, true); Assert.assertNotNull(cap5); CAP cap6 = textField.replaceText("test"); Assert.assertNotNull(cap6); CAP cap7 = textField.selectAll(); Assert.assertNotNull(cap7); CAP cap8 = textField.selectPattern("test", Operator.equals); Assert.assertNotNull(cap8); Assert.assertTrue(textField instanceof org.eclipse.jubula.toolkit.base.components.TextComponent); Assert.assertTrue(textField instanceof org.eclipse.jubula.toolkit.base.components.GraphicsComponent); Assert.assertTrue(textField instanceof org.eclipse.jubula.toolkit.base.components.TextInputComponent); }

Target:
public void testTextInputComp() { ComponentIdentifier identifier = OM_factories.TextField_pfr_txf; TextInputComponent textField = ConcreteComponents .createTextInputComponent(identifier); Assert.assertNotNull(textField); CAP cap1 = textField.checkEditability(true); Assert.assertNotNull(cap1); CAP cap2 = textField.checkText(TEST, Operator.equals); Assert.assertNotNull(cap2); CAP cap3 = textField.inputText(TEST); Assert.assertNotNull(cap3); CAP cap4 = textField.insertTextAfterIndex(TEST, 1); Assert.assertNotNull(cap4); CAP cap5 = textField.insertTextBeforeAfterPattern( TEST, "pattern", Operator.equals, true); Assert.assertNotNull(cap5); CAP cap6 = textField.replaceText(TEST); Assert.assertNotNull(cap6); CAP cap7 = textField.selectAll(); Assert.assertNotNull(cap7); CAP cap8 = textField.selectPattern(TEST, Operator.equals); Assert.assertNotNull(cap8); Assert.assertTrue(textField instanceof org.eclipse.jubula.toolkit.base.components.TextComponent); Assert.assertTrue(textField instanceof org.eclipse.jubula.toolkit.base.components.GraphicsComponent); Assert.assertTrue(textField instanceof org.eclipse.jubula.toolkit.base.components.TextInputComponent); }
Source:
private static List<Throwable> runConcurrently(ConsumerWithCoreException<TaskDataStore>... consumers) throws Exception { TaskDataStore store = newTaskDataStore(); CyclicBarrier barrier = new CyclicBarrier(consumers.length + 1); List<Throwable> failures = new ArrayList<>(consumers.length); List<Thread> threads = Arrays.asList(consumers) .stream() .map(c -> thread(c, store, barrier, failures).get()) .collect(toList()); threads.stream().forEach(Thread::start); barrier.await(); for (Thread thread : threads) { thread.join(); } return failures; }

Target:
private static List<Throwable> runConcurrently(ConsumerWithCoreException<TaskDataStore>... consumers) throws Exception { TaskDataStore store = newTaskDataStore(); CyclicBarrier barrier = new CyclicBarrier(consumers.length + 1); List<Throwable> failures = new ArrayList<>(consumers.length); List<Thread> threads = Arrays.asList(consumers) .stream() .map(c -> thread(c, store, Optional.of(barrier), failures).get()) .collect(toList()); startThreadsSimultaneously(barrier, threads); return failures; }
Source:
public ApplicationModule getApplicationModule(String moduleId) throws AppCatalogException { ApplicationModuleRepository applicationModuleRepository = new ApplicationModuleRepository(); Map<String, Object> queryParameters = new HashMap<>(); queryParameters.put(DBConstants.ApplicationModule.APPLICATION_MODULE_ID, moduleId); ApplicationModule applicationModule = applicationModuleRepository.select(QueryConstants.FIND_APPLICATION_MODULE, -1, 0, queryParameters).get(0); return applicationModule; }

Target:
public ApplicationModule getApplicationModule(String moduleId) throws AppCatalogException { ApplicationModuleRepository applicationModuleRepository = new ApplicationModuleRepository(); return applicationModuleRepository.get(moduleId); }
Source:
public SubordinateTransaction getImportedTransaction (Xid xid) throws XAException { if (xid == null) throw new IllegalArgumentException(); AtomicReference<SubordinateTransaction> holder = _transactions.get(new SubordinateXidImple(xid)); SubordinateTransaction tx = holder == null ? null : holder.get(); if (tx == null) { return null; } try { if (tx.getStatus() == javax.transaction.Status.STATUS_ROLLEDBACK) { throw new XAException(XAException.XA_RBROLLBACK); } } catch (SystemException e) { e.printStackTrace(); throw new XAException(XAException.XA_RBROLLBACK); } if (tx.baseXid() == null) { tx.recover(); return tx; } else return tx; }

Target:
public SubordinateTransaction getImportedTransaction (Xid xid) throws XAException { if (xid == null) throw new IllegalArgumentException(); AtomicReference<SubordinateTransaction> holder = _transactions.get(new SubordinateXidImple(xid)); SubordinateTransaction tx = holder == null ? null : holder.get(); if (tx == null) { return null; } try { if (tx.getStatus() == javax.transaction.Status.STATUS_ROLLEDBACK) { throw new XAException(XAException.XA_RBROLLBACK); } } catch (SystemException e) { throw new XAException(XAException.XA_RBROLLBACK); } if (tx.baseXid() == null) { tx.recover(); return tx; } else return tx; }
Source:
public Response execute() { DatabaseAccessor db = null; Response response; try { db = initDB(); String hash = BCrypt.hashpw(password,BCrypt.gensalt()); db.addUser(username, hash, "SALT", privileges, name, email); response = new MinimalResponse(HttpStatusCode.OK); } catch (SQLException e) { response = new ErrorResponse(HttpStatusCode.BAD_REQUEST, "Creation of user '" + username + "' unsuccessful, user " + "already exists."); Debug.log("Reason: " + e.getMessage()); } catch (IOException e) { response = new ErrorResponse(HttpStatusCode.INTERNAL_SERVER_ERROR, "Creation of user '" + username + "' unsuccessful due to " + "temporary database problems."); } finally { if (db != null) db.close(); } return response; }

Target:
public Response execute() { DatabaseAccessor db = null; Response response; try { db = initDB(); String hash = BCrypt.hashpw(password,BCrypt.gensalt()); db.addUser(username, hash, "SALT", privileges, name, email); response = new MinimalResponse(HttpStatusCode.OK); } catch (SQLException e) { response = new ErrorResponse(HttpStatusCode.INTERNAL_SERVER_ERROR, "Creation of user '" + username + "' unsuccessful due " + "to temporary database problems."); Debug.log("Reason: " + e.getMessage()); } catch (IOException e) { response = new ErrorResponse(HttpStatusCode.BAD_REQUEST, "Creation of user '" + username + "' unsuccessful. " + e.getMessage()); } finally { if (db != null) db.close(); } return response; }
Source:
public UserDto addUser(UserDto user, Optional<String> overwriteUserConfirmationCode) { assert user.getPrivateData().getDevices().orElse(Collections.emptySet()).size() == 1; UserLookupService.assertValidUserFields(user, UserService.UserPurpose.USER); handleExistingUserForMobileNumber(user.getMobileNumber(), overwriteUserConfirmationCode); User userEntity = createUserEntity(user, UserSignUp.FREE); addDevicesToEntity(user, userEntity); Optional<ConfirmationCode> confirmationCode = createConfirmationCodeIfNeeded(overwriteUserConfirmationCode, userEntity); userEntity = userRepository.save(userEntity); UserDto userDto = userLookupService.createUserDtoWithPrivateData(userEntity); if (confirmationCode.isPresent()) { userUpdateService.sendConfirmationCodeTextMessage(userEntity.getMobileNumber(), confirmationCode.get(), SmsTemplate.ADD_USER_NUMBER_CONFIRMATION); } logger.info("Added new user with mobile number '{}' and ID '{}'", userDto.getMobileNumber(), userDto.getId()); return userDto; }

Target:
public UserDto addUser(UserDto user, Optional<String> overwriteUserConfirmationCode) { assert user.getPrivateData().getDevices().orElse(Collections.emptySet()).size() == 1; UserAssertionService.assertValidUserFields(user, UserService.UserPurpose.USER); handleExistingUserForMobileNumber(user.getMobileNumber(), overwriteUserConfirmationCode); User userEntity = createUserEntity(user, UserSignUp.FREE); addDevicesToEntity(user, userEntity); Optional<ConfirmationCode> confirmationCode = createConfirmationCodeIfNeeded(overwriteUserConfirmationCode, userEntity); userEntity = userRepository.save(userEntity); UserDto userDto = userLookupService.createUserDtoWithPrivateData(userEntity); if (confirmationCode.isPresent()) { userUpdateService.sendConfirmationCodeTextMessage(userEntity.getMobileNumber(), confirmationCode.get(), SmsTemplate.ADD_USER_NUMBER_CONFIRMATION); } logger.info("Added new user with mobile number '{}' and ID '{}'", userDto.getMobileNumber(), userDto.getId()); return userDto; }
Source:
private VirtualMachineTemplate registerKubernetesVersionIso(final Long zoneId, final String versionName, final String isoUrl, final String isoChecksum)throws IllegalAccessException, NoSuchFieldException, IllegalArgumentException, ResourceAllocationException { String isoName = String.format("%s-Kubernetes-Binaries-ISO", versionName); RegisterIsoCmd registerIsoCmd = new RegisterIsoCmd(); registerIsoCmd = ComponentContext.inject(registerIsoCmd); Field f = registerIsoCmd.getClass().getDeclaredField("isoName"); f.setAccessible(true); f.set(registerIsoCmd, isoName); if (zoneId != null) { f = registerIsoCmd.getClass().getDeclaredField("zoneId"); f.setAccessible(true); f.set(registerIsoCmd, zoneId); } f = registerIsoCmd.getClass().getDeclaredField("displayText"); f.setAccessible(true); f.set(registerIsoCmd, isoName); f = registerIsoCmd.getClass().getDeclaredField("bootable"); f.setAccessible(true); f.set(registerIsoCmd, false); f = registerIsoCmd.getClass().getDeclaredField("publicIso"); f.setAccessible(true); f.set(registerIsoCmd, true); f = registerIsoCmd.getClass().getDeclaredField("url"); f.setAccessible(true); f.set(registerIsoCmd, isoUrl); if (!Strings.isNullOrEmpty(isoChecksum)) { f = registerIsoCmd.getClass().getDeclaredField("checksum"); f.setAccessible(true); f.set(registerIsoCmd, isoChecksum); } f = registerIsoCmd.getClass().getDeclaredField("accountName"); f.setAccessible(true); f.set(registerIsoCmd, accountManager.getSystemAccount().getAccountName()); f = registerIsoCmd.getClass().getDeclaredField("domainId"); f.setAccessible(true); f.set(registerIsoCmd, accountManager.getSystemAccount().getDomainId()); return templateService.registerIso(registerIsoCmd); }

Target:
private VirtualMachineTemplate registerKubernetesVersionIso(final Long zoneId, final String versionName, final String isoUrl, final String isoChecksum)throws IllegalAccessException, NoSuchFieldException, IllegalArgumentException, ResourceAllocationException { String isoName = String.format("%s-Kubernetes-Binaries-ISO", versionName); RegisterIsoCmd registerIsoCmd = new RegisterIsoCmd(); registerIsoCmd = ComponentContext.inject(registerIsoCmd); registerIsoCmd.setIsoName(isoName); registerIsoCmd.setPublic(true); if (zoneId != null) { registerIsoCmd.setZoneId(zoneId); } registerIsoCmd.setDisplayText(isoName); registerIsoCmd.setBootable(false); registerIsoCmd.setUrl(isoUrl); if (!Strings.isNullOrEmpty(isoChecksum)) { registerIsoCmd.setChecksum(isoChecksum); } registerIsoCmd.setAccountName(accountManager.getSystemAccount().getAccountName()); registerIsoCmd.setDomainId(accountManager.getSystemAccount().getDomainId()); return templateService.registerIso(registerIsoCmd); }
Source:
public void draw(final BoundingBox boundingBox, final byte zoomLevel, final Canvas canvas, final Point topLeftPoint) { if (destinationCoords == null || currentCoords == null) { return; } if (line == null) { line = AndroidGraphicFactory.INSTANCE.createPaint(); line.setStrokeWidth(width); line.setStyle(Style.STROKE); line.setColor(0xD0EB391E); } final long mapSize = MercatorProjection.getMapSize(zoomLevel, this.displayModel.getTileSize()); final Geopoint[] routingPoints = Routing.getTrack(currentCoords, destinationCoords); final ArrayList<Pair<Integer, Integer>> pixelPoints = new ArrayList<>(); for (final Geopoint geopoint : routingPoints) { pixelPoints.add(translateToPixels(mapSize, topLeftPoint, geopoint)); } for (int i = 1; i < pixelPoints.size(); i++) { final Pair<Integer, Integer> source = pixelPoints.get(i - 1); final Pair<Integer, Integer> destination = pixelPoints.get(i); canvas.drawLine(source.first, source.second, destination.first, destination.second, line); } }

Target:
public void draw(final BoundingBox boundingBox, final byte zoomLevel, final Canvas canvas, final Point topLeftPoint) { if (destinationCoords == null || currentCoords == null) { return; } if (line == null) { line = AndroidGraphicFactory.INSTANCE.createPaint(); line.setStrokeWidth(width); line.setStyle(Style.STROKE); line.setColor(0xD0EB391E); } final long mapSize = MercatorProjection.getMapSize(zoomLevel, this.displayModel.getTileSize()); final Geopoint[] routingPoints = Routing.getTrack(currentCoords, destinationCoords); final ArrayList<Pair<Integer, Integer>> pixelPoints = new ArrayList<>(routingPoints.length); for (final Geopoint geopoint : routingPoints) { pixelPoints.add(translateToPixels(mapSize, topLeftPoint, geopoint)); } for (int i = 1; i < pixelPoints.size(); i++) { final Pair<Integer, Integer> source = pixelPoints.get(i - 1); final Pair<Integer, Integer> destination = pixelPoints.get(i); canvas.drawLine(source.first, source.second, destination.first, destination.second, line); } }
Source:
public static void setupCluster() throws IOException { cluster = init(inst.builder() .withNodes(2) .withConfig(c -> c.with(Feature.NETWORK) .with(Feature.GOSSIP) .set("disk_failure_policy", "die")) .start()); }

Target:
public static void setupCluster() throws IOException { CLUSTER = init(Cluster.build() .withNodes(2) .withConfig(c -> c.with(Feature.NETWORK) .with(Feature.GOSSIP) .set("disk_failure_policy", "die")) .start()); }
Source:
private void handleBinaryExpression(BinaryExpression binaryExpression, SubscriptionContext ctx) { boolean shouldReport = false; if (binaryExpression.leftOperand().is(Tree.Kind.NAME, Tree.Kind.QUALIFIED_EXPR) && binaryExpression.rightOperand().is(Tree.Kind.STRING_LITERAL)) { shouldReport = checkBinaryExpression(binaryExpression.leftOperand()); } if (binaryExpression.rightOperand().is(Tree.Kind.NAME, Tree.Kind.QUALIFIED_EXPR) && binaryExpression.leftOperand().is(Tree.Kind.STRING_LITERAL)) { shouldReport = checkBinaryExpression(binaryExpression.rightOperand()); } if (shouldReport) { ctx.addIssue(binaryExpression, MESSAGE); } }

Target:
private void handleBinaryExpression(BinaryExpression binaryExpression, SubscriptionContext ctx) { boolean shouldReport = false; if (binaryExpression.leftOperand() instanceof HasSymbol && binaryExpression.rightOperand().is(Tree.Kind.STRING_LITERAL)) { shouldReport = isSymbolCredential(((HasSymbol) binaryExpression.leftOperand()).symbol()); } if (binaryExpression.rightOperand() instanceof HasSymbol && binaryExpression.leftOperand().is(Tree.Kind.STRING_LITERAL)) { shouldReport = isSymbolCredential(((HasSymbol) binaryExpression.rightOperand()).symbol()); } if (shouldReport) { ctx.addIssue(binaryExpression, MESSAGE); } }
Source:
void maybeHandleDelayedWriteBookieFailure() { synchronized (metadataLock) { if (delayedWriteFailedBookies.isEmpty()) { return; } Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(); toReplace.putAll(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); handleBookieFailure(toReplace); } }

Target:
void maybeHandleDelayedWriteBookieFailure() { synchronized (metadataLock) { if (delayedWriteFailedBookies.isEmpty()) { return; } Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); handleBookieFailure(toReplace); } }
Source:
private void abortTask(Task task, TaskStatus status) { log.warn("[{}] Task found in unexpected state, switching to ", task.getId(), task, status); task.setStatus(status); Task removed = null; try { removed = schedulingPool.removeTask(task); } catch (TaskStoreException e) { log.error("[{}] Failed during removal of Task from SchedulingPool: {}", task.getId(), task, e); } if (removed != null) { try { jmsQueueManager.reportTaskStatus(task.getId(), task.getStatus(), System.currentTimeMillis()); } catch (JMSException e) { log.error("[{}] Error trying to reportTaskStatus of to Dispatcher: {}", task.getId(), task, e); } } else { log.error("[{}] Stale Task was not removed and not reported to dispatcher.", task.getId(), task); log.warn(" - This is nonsense - why we abort the Task taken from AllTasks but we can remove it from it ??"); } }

Target:
private void abortTask(Task task, TaskStatus status) { log.warn("[{}] Task found in unexpected state, switching to ", task.getId(), task, status); task.setStatus(status); Task removed = null; try { removed = schedulingPool.removeTask(task); } catch (TaskStoreException e) { log.error("[{}] Failed during removal of Task from SchedulingPool: {}", task.getId(), task, e); } if (removed != null) { try { jmsQueueManager.reportTaskStatus(task.getId(), task.getStatus(), System.currentTimeMillis()); } catch (JMSException e) { log.error("[{}] Error trying to reportTaskStatus of to Dispatcher: {}", task.getId(), task, e); } } else { log.error("[{}] Stale Task was not removed and not reported to dispatcher.", task.getId(), task); log.error(" - This is nonsense - why we abort the Task taken from AllTasks but we can remove it from it ??"); } }
Source:
private boolean elementHasJUnit4Annotations(AnnotatedElement element) { Annotation[] annotations = element.getAnnotations(); if (annotations != null) { for (Annotation a : annotations) { final String annotationName = a.annotationType() .getName(); if (annotationName.startsWith("org.junit.") && !annotationName.contains(".jupiter.")) { return true; } } } return false; }

Target:
private boolean elementHasJUnit4Annotations(AnnotatedElement element) { Annotation[] annotations = element.getAnnotations(); if (annotations == null) { return false; } return Stream.of(annotations) .map(Annotation::annotationType) .map(Class::getName) .anyMatch(JUNIT4_ANNOTATIONS::contains); }
Source:
public void setUp() { if (CASE_DIRECTORY_PATH.toFile().exists()) { try { FileUtils.deleteDirectory(CASE_DIRECTORY_PATH.toFile()); } catch (IOException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } } assertFalse("Unable to delete existing test directory", CASE_DIRECTORY_PATH.toFile().exists()); CASE_DIRECTORY_PATH.toFile().mkdirs(); assertTrue("Unable to create test directory", CASE_DIRECTORY_PATH.toFile().exists()); try { Case.createAsCurrentCase(Case.CaseType.SINGLE_USER_CASE, CASE_DIRECTORY_PATH.toString(), new CaseDetails("EmbeddedFileTest")); } catch (CaseActionException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } assertTrue(CASE_DIR.exists()); ImageDSProcessor dataSourceProcessor = new ImageDSProcessor(); try { DataSourceProcessorRunner.ProcessorCallback callBack = DataSourceProcessorRunner.runDataSourceProcessor(dataSourceProcessor, IMAGE_PATH); List<Content> dataSourceContent = callBack.getDataSourceContent(); assertEquals(1, dataSourceContent.size()); List<String> errorMessages = callBack.getErrorMessages(); assertEquals(0, errorMessages.size()); } catch (AutoIngestDataSourceProcessor.AutoIngestDataSourceProcessorException | InterruptedException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } try { openCase = Case.getOpenCase(); runIngestJob(openCase.getDataSources()); } catch (NoCurrentCaseException | TskCoreException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } }

Target:
public void setUp() { CaseUtils.createCase(CASE_DIRECTORY_PATH); ImageDSProcessor dataSourceProcessor = new ImageDSProcessor(); IngestUtils.addDataSource(dataSourceProcessor, IMAGE_PATH); try { openCase = Case.getOpenCase(); } catch (NoCurrentCaseException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } IngestModuleTemplate embeddedTemplate = IngestUtils.getIngestModuleTemplate(new EmbeddedFileExtractorModuleFactory()); IngestModuleTemplate hashLookupTemplate = IngestUtils.getIngestModuleTemplate(new HashLookupModuleFactory()); ArrayList<IngestModuleTemplate> templates = new ArrayList<>(); templates.add(embeddedTemplate); templates.add(hashLookupTemplate); IngestJobSettings ingestJobSettings = new IngestJobSettings(EmbeddedFileTest.class.getCanonicalName(), IngestType.FILES_ONLY, templates); try { IngestUtils.runIngestJob(openCase.getDataSources(), ingestJobSettings); } catch (TskCoreException ex) { Exceptions.printStackTrace(ex); Assert.fail(ex); } }
Source:
public void handleEvent(Event event) { Object element = event.getProperty(IEventBroker.DATA); if (!(element instanceof MApplication)) { return; } List<Object> unusedResources = new ArrayList<Object>(); Set<IResourcesRegistry> processedRegistries = new HashSet<IResourcesRegistry>(); for (MWindow window : ((MApplication) element).getChildren()) { CSSEngine engine = getEngine(window); if (engine != null) { IResourcesRegistry registry = engine.getResourcesRegistry(); if (!processedRegistries.contains(registry)) { unusedResources.addAll(removeResources(registry)); processedRegistries.add(registry); } engine.reapply(); } } for (Object resource : unusedResources) { disposeResource(resource); } }

Target:
public void handleEvent(Event event) { Object element = event.getProperty(IEventBroker.DATA); if (!(element instanceof MApplication)) { return; } List<Object> unusedResources = new ArrayList<Object>(); Set<CSSEngine> engines = new HashSet<CSSEngine>(); for (MWindow window : ((MApplication) element).getChildren()) { CSSEngine engine = getEngine(window); if (engine != null) { engines.add(engine); } } for (CSSEngine engine : engines) { unusedResources.addAll(removeResources(engine .getResourcesRegistry())); engine.reapply(); } for (Object resource : unusedResources) { disposeResource(resource); } }
Source:
private String updateRecorderToDefaultOption() { final String envVar = System.getenv("RECORDER"); final String recorder = System.getProperty("RECORDER"); if ((envVar != null && !"".equals(envVar)) || (recorder != null && !"".equals(recorder))) { System.setProperty("RECORDER", TestRecorderRule.FAILURES); return recorder; } return null; }

Target:
private String updateRecorderToDefaultOption() { final String envVar = System.getenv("RECORDER"); final String recorder = System.getProperty("RECORDER"); if ((envVar != null && !envVar.isEmpty()) || (recorder != null && !recorder.isEmpty())) { System.setProperty("RECORDER", TestRecorderRule.FAILURES); return recorder; } return null; }
Source:
private AjaxLink<String> trucateAllLink(String id) { AjaxLink<String> trunkAlllink = new AjaxLink<String>(id) { @Override public void onClick(AjaxRequestTarget target) { dialog.setTitle( new ParamResourceModel( "confirmGwcTruncateTitle", CachedLayersPage.this)); dialog.setDefaultModel(getDefaultModel()); dialog.showOkCancel( target, new GeoServerDialog.DialogDelegate() { private static final long serialVersionUID = 1L; private TruncateAllRequest truncateAllRequest; @Override protected Component getContents(final String id) { Label confirmLabel = new Label( id, "You are about to wipe GWC cache clean, Do you want to continue?"); confirmLabel.setEscapeModelStrings( false); return confirmLabel; } @Override protected boolean onSubmit( final AjaxRequestTarget target, final Component contents) { GWC facade = GWC.get(); try { truncateAllRequest = facade.truncateAll(); } catch (Exception e) { error(e.getMessage()); log.error("An Error while clearing GWC cache", e); return false; } return true; } @Override public void onClose(final AjaxRequestTarget target) { target.add(table); if (truncateAllRequest != null) if (truncateAllRequest.getTrucatedLayers().length() == 0) warn("GWC Cache already empty"); else info( "Cleared GWC cache for " + truncateAllRequest .getTrucatedLayersList()); else error("There was a problem, check logs"); setResponsePage(getPage()); } }); } }; return trunkAlllink; }

Target:
private AjaxLink<String> trucateAllLink(String id) { AjaxLink<String> trunkAlllink = new AjaxLink<String>(id) { @Override public void onClick(AjaxRequestTarget target) { dialog.setTitle( new ParamResourceModel( "confirmGwcTruncateTitle", CachedLayersPage.this)); dialog.setDefaultModel(getDefaultModel()); dialog.showOkCancel( target, new GeoServerDialog.DialogDelegate() { private static final long serialVersionUID = 1L; private TruncateAllRequest truncateAllRequest; @Override protected Component getContents(final String id) { Label confirmLabel = new Label( id, new ParamResourceModel( "confirmGWCClean", CachedLayersPage.this)); confirmLabel.setEscapeModelStrings( false); return confirmLabel; } @Override protected boolean onSubmit( final AjaxRequestTarget target, final Component contents) { GWC facade = GWC.get(); try { truncateAllRequest = facade.truncateAll(); } catch (Exception e) { error( new ParamResourceModel( "confirmGWCClean", CachedLayersPage.this) .getString()); log.error("An Error while clearing GWC cache", e); return false; } return true; } @Override public void onClose(final AjaxRequestTarget target) { target.add(table); if (truncateAllRequest != null) if (truncateAllRequest.getTrucatedLayers().length() == 0) warn( new ParamResourceModel( "warnGWCClean", CachedLayersPage.this) .getString()); else info( new ParamResourceModel( "confirmGWCCleanInfo", CachedLayersPage.this) .getString()); else error( new ParamResourceModel( "errorGWCClean2", CachedLayersPage.this) .getString()); setResponsePage(getPage()); } }); } }; return trunkAlllink; }
Source:
public Dataset find(Object pk) { return chooseEM(session.getUser()).find(Dataset.class, pk); }

Target:
public Dataset find(Object pk) { return emBean.getEntityManager().find(Dataset.class, pk); }
Source:
public ArrayList<String> getAliases() { try { return Collections.list(keyStore.aliases()); } catch (KeyStoreException e) { System.out.println("Keystore not initialized"); return null; } }

Target:
public Collection<String> getAliases() throws ScriptSignatureException{ try { return Collections.list(fKeyStore.aliases()); } catch (KeyStoreException e) { throw new ScriptSignatureException("Keystore not initialized properly. Exiting...", e.getCause(), true); } }
Source:
T toObject(ProtobufCodec<T> codec, Provider<T> provider) { if (codec == null) { return null; } if (data instanceof byte[]) { this.codec = codec; if (provider == null) { data = codec.decode((byte[]) data); } else { T tmp = provider.get(); codec.mergeFrom((byte[]) data, tmp); data = tmp; } } return (T) data; }

Target:
T toObject(ProtobufCodec<T> codec, Provider<T> provider) { if (codec == null) { return null; } Object d = data; if (d instanceof byte[]) { this.codec = codec; if (provider == null) { d = codec.decode((byte[]) data); } else { T tmp = provider.get(); codec.mergeFrom((byte[]) data, tmp); d = tmp; } } data = d; return (T) data; }
Source:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { boolean toggled = false; boolean enabled = true; for (Plugin playerparticles : TotalFreedomMod.server.getPluginManager().getPlugins()) { if (playerparticles.getName().equalsIgnoreCase("playerparticles")) { if (playerparticles.isEnabled()) { playerparticles.getPluginLoader().disablePlugin(playerparticles); enabled = false; } else { playerparticles.getPluginLoader().enablePlugin(playerparticles); enabled = true; } toggled = true; } } if (toggled) { if (!enabled) { TFM_Util.adminAction(sender.getName(), "Disabling PlayerParticles", true); } else { TFM_Util.adminAction(sender.getName(), "Enabling PlayerParticles", false); } } return true; }

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { for (Plugin p : TotalFreedomMod.server.getPluginManager().getPlugins()) { if (p.getName().equalsIgnoreCase("PlayerParticles")) { if (p.isEnabled()) { p.getPluginLoader().disablePlugin(p); TFM_Util.adminAction(sender.getName(), "Disabled PlayerParticles", false); } else { p.getPluginLoader().enablePlugin(p); TFM_Util.adminAction(sender.getName(), "Enabled PlayerParticles", false); } } } return true; }
Source:
public void testEndBytes() { byte[] expectedEndBytes = new byte[] {0, 0, (byte) 0xF3}; byte[] endBytes = fileGenerator.getFileEndBytes(); boolean fileBytesEquality = Arrays.equals(expectedEndBytes, endBytes); assertTrue(fileBytesEquality); }

Target:
public void testEndBytes() { final byte[] expectedEndBytes = new byte[] {0, 0, (byte) 0xF3}; byte[] endBytes = fileGenerator.getFileEndBytes(); assertArrayEquals(expectedEndBytes, endBytes); }
Source:
public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) { int adjustments = 0; this.numAdjustments = 0; this.numContainers = currentPackingPlan.getContainers().size(); this.containerId = 1; int additionalContainers = computeNumAdditionalContainers(componentChanges, currentPackingPlan); increaseNumContainers(additionalContainers); LOG.info(String.format("Allocated " + "%s additional containers for repack bring the number of containers to %s.", additionalContainers, this.numContainers)); Optional<Map<Integer, List<InstanceId>>> resourceCompliantRRAllocation = getResourceCompliantRRAllocation(currentPackingPlan, componentChanges); while (!resourceCompliantRRAllocation.isPresent()) { if (this.numAdjustments > adjustments) { adjustments++; resourceCompliantRRAllocation = getResourceCompliantRRAllocation(currentPackingPlan, componentChanges); } else { return null; } } Map<String, Long> ramMap = TopologyUtils.getComponentRamMapConfig(topology); Set<PackingPlan.ContainerPlan> containerPlans = PackingUtils.buildContainerPlans( resourceCompliantRRAllocation.get(), ramMap, defaultInstanceResources, paddingPercentage); return new PackingPlan(topology.getId(), containerPlans); }

Target:
public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) { int adjustments = 0; this.numContainers = currentPackingPlan.getContainers().size(); resetState(); int additionalContainers = computeNumAdditionalContainers(componentChanges, currentPackingPlan); increaseNumContainers(additionalContainers); LOG.info(String.format("Allocated " + "%s additional containers for repack bring the number of containers to %s.", additionalContainers, this.numContainers)); Optional<Map<Integer, List<InstanceId>>> resourceCompliantRRAllocation = getResourceCompliantRRAllocation(currentPackingPlan, componentChanges); while (!resourceCompliantRRAllocation.isPresent()) { if (this.numAdjustments > adjustments) { adjustments++; resourceCompliantRRAllocation = getResourceCompliantRRAllocation(currentPackingPlan, componentChanges); } else { return null; } } Map<String, Long> ramMap = TopologyUtils.getComponentRamMapConfig(topology); Set<PackingPlan.ContainerPlan> containerPlans = PackingUtils.buildContainerPlans( resourceCompliantRRAllocation.get(), ramMap, defaultInstanceResources, paddingPercentage); return new PackingPlan(topology.getId(), containerPlans); }
Source:
public void refresh(IResource[] resources, int depth, IProgressMonitor monitor) throws TeamException { for (IResource resource : resources) { if (resource.getType() == IResource.ROOT) { GitSyncCache newCache = GitSyncCache.getAllData(gsds, monitor); cache.merge(newCache, null); super.refresh(resources, depth, monitor); return; } } Map<GitSynchronizeData, Collection<String>> updateRequests = new HashMap<GitSynchronizeData, Collection<String>>(); Collection<String> allUpdateRequestPaths = new LinkedHashSet<String>(); for (IResource resource : resources) { IProject project = resource.getProject(); GitSynchronizeData data = gsds.getData(project.getName()); if (data != null) { RepositoryMapping mapping = RepositoryMapping .getMapping(project); if (mapping != null) { Collection<String> paths = updateRequests.get(data); if (paths == null) { paths = new ArrayList<String>(); updateRequests.put(data, paths); } String path = mapping.getRepoRelativePath(resource); if (path == null) path = ""; paths.add(path); allUpdateRequestPaths.add(path); } } } if (!updateRequests.isEmpty()) { GitSyncCache newCache = GitSyncCache.getAllData(updateRequests, monitor); cache.merge(newCache, allUpdateRequestPaths); } super.refresh(resources, depth, monitor); }

Target:
public void refresh(IResource[] resources, int depth, IProgressMonitor monitor) throws TeamException { for (IResource resource : resources) { if (resource.getType() == IResource.ROOT) { cache = GitSyncCache.getAllData(gsds, monitor); super.refresh(resources, depth, monitor); return; } } Map<GitSynchronizeData, Collection<String>> updateRequests = new HashMap<GitSynchronizeData, Collection<String>>(); for (IResource resource : resources) { IProject project = resource.getProject(); GitSynchronizeData data = gsds.getData(project.getName()); if (data != null) { RepositoryMapping mapping = RepositoryMapping .getMapping(project); if (mapping != null) { Collection<String> paths = updateRequests.get(data); if (paths == null) { paths = new ArrayList<String>(); updateRequests.put(data, paths); } String path = mapping.getRepoRelativePath(resource); if (path == null) path = ""; paths.add(path); } } } if (!updateRequests.isEmpty()) { GitSyncCache.mergeAllDataIntoCache(updateRequests, monitor, cache); } super.refresh(resources, depth, monitor); }
Source:
public static Properties defaultProperties() { Properties properties = ProfitBricksApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_REGIONS, "DE,US"); properties.setProperty(PROPERTY_REGION + ".DE.FKB." + ISO3166_CODES, "DE-FKB"); properties.setProperty(PROPERTY_REGION + ".DE.FRA." + ISO3166_CODES, "DE-FRA"); properties.setProperty(PROPERTY_REGION + ".US.LAS." + ISO3166_CODES, "US-LAS"); properties.setProperty(PROPERTY_REGION + ".US.LASDEV." + ISO3166_CODES, "US-LASDEV"); return properties; }

Target:
public static Properties defaultProperties() { Properties properties = ProfitBricksApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_ISO3166_CODES, "US-NV,DE-HE,DE-BW"); properties.setProperty(PROPERTY_REGIONS, "DE,US"); properties.setProperty(PROPERTY_REGION + ".DE.zones", "FKB,FRA"); properties.setProperty(PROPERTY_REGION + ".US.zones", "LAS,LASDEV"); properties.setProperty(PROPERTY_ZONES, "FKB,FRA,LAS,LASDEV"); properties.setProperty(PROPERTY_ZONE + ".FKB." + ISO3166_CODES, "DE-BW"); properties.setProperty(PROPERTY_ZONE + ".FRA." + ISO3166_CODES, "DE-HE"); properties.setProperty(PROPERTY_ZONE + ".LAS." + ISO3166_CODES, "US-NV"); properties.setProperty(PROPERTY_ZONE + ".LASDEV." + ISO3166_CODES, "US-NV"); return properties; }
Source:
public void testDesktopDestroy() { F85_ZK_1148FileDealer.writeMsg("", false); DesktopAgent da = connect(); da.destroy(); Assert.assertEquals("DestroyD is called!DestroyC is called!IncludeVM is called!", F85_ZK_1148FileDealer.readMsg()); F85_ZK_1148FileDealer.close(); }

Target:
public void testDesktopDestroy() { F85_ZK_1148FileDealer.writeMsg("", false); DesktopAgent da = connect(); da.destroy(); try { Assert.assertEquals("DestroyD is called!DestroyC is called!IncludeVM is called!", F85_ZK_1148FileDealer.readMsg()); } finally { F85_ZK_1148FileDealer.close(); } }
Source:
public static org.ovirt.engine.core.common.businessentities.FencingPolicy map(FencingPolicy model, org.ovirt.engine.core.common.businessentities.FencingPolicy template) { org.ovirt.engine.core.common.businessentities.FencingPolicy entity = template != null ? template : new org.ovirt.engine.core.common.businessentities.FencingPolicy(); entity.setFencingEnabled(model.isEnabled()); if (model.isSetSkipIfSdActive()) { entity.setSkipFencingIfSDActive(model.getSkipIfSdActive().isEnabled()); } if (model.isSetSkipIfConnectivityBroken()) { entity.setSkipFencingIfConnectivityBroken(model.getSkipIfConnectivityBroken().isEnabled()); if (model.getSkipIfConnectivityBroken().getThreshold() != null) { entity.setHostsWithBrokenConnectivityThreshold(model.getSkipIfConnectivityBroken().getThreshold()); } else { entity.setHostsWithBrokenConnectivityThreshold(50); } } entity.setSkipFencingIfGlusterBricksUp(model.isSkipIfGlusterBricksUp()); entity.setSkipFencingIfGlusterQuorumNotMet(model.isSkipIfGlusterQuorumNotMet().isEnabled()); return entity; }

Target:
public static org.ovirt.engine.core.common.businessentities.FencingPolicy map(FencingPolicy model, org.ovirt.engine.core.common.businessentities.FencingPolicy template) { org.ovirt.engine.core.common.businessentities.FencingPolicy entity = template != null ? template : new org.ovirt.engine.core.common.businessentities.FencingPolicy(); entity.setFencingEnabled(model.isEnabled()); if (model.isSetSkipIfSdActive()) { entity.setSkipFencingIfSDActive(model.getSkipIfSdActive().isEnabled()); } if (model.isSetSkipIfConnectivityBroken()) { entity.setSkipFencingIfConnectivityBroken(model.getSkipIfConnectivityBroken().isEnabled()); if (model.getSkipIfConnectivityBroken().getThreshold() != null) { entity.setHostsWithBrokenConnectivityThreshold(model.getSkipIfConnectivityBroken().getThreshold()); } else { entity.setHostsWithBrokenConnectivityThreshold(50); } } if (model.isSetSkipIfGlusterBricksUp()) { entity.setSkipFencingIfGlusterBricksUp(model.isSkipIfGlusterBricksUp()); } if (model.isSetSkipIfGlusterQuorumNotMet()) { entity.setSkipFencingIfGlusterQuorumNotMet(model.isSkipIfGlusterQuorumNotMet()); } return entity; }
Source:
public static int[] unsignedByteToIntArray(Object array) { if (array instanceof int[]) return (int[])array; else if (array instanceof byte[]) return unsignedByteToIntArray((byte[])array); else return new int[0]; }

Target:
public static int[] unsignedByteToIntArray(Object array) { if (array instanceof int[]) { return (int[]) array; } else if (array instanceof byte[]) { return unsignedByteToIntArray((byte[])array); } else { return new int[0]; } }
Source:
public void stop() { synchronized (lock) { if (stopped) { return; } stopped = true; for (SegmentHolder holder : segmentsToDrop.values()) { holder.requestCompleted(false, null); } for (SegmentHolder holder : segmentsToLoad.values()) { holder.requestCompleted(false, null); } segmentsToDrop.clear(); segmentsToLoad.clear(); queuedSize.set(0L); failedAssignCount.set(0); } }

Target:
public void stop() { synchronized (lock) { if (stopped) { return; } stopped = true; for (SegmentHolder holder : segmentsToDrop.values()) { holder.requestSucceeded(); } for (SegmentHolder holder : segmentsToLoad.values()) { holder.requestSucceeded(); } segmentsToDrop.clear(); segmentsToLoad.clear(); queuedSize.set(0L); failedAssignCount.set(0); } }
Source:
private byte[] serialize(String topic, GenericRecord avroRecord) { if (avroRecord == null) { return null; } topic = "kipling" + topic + "-value"; Schema schema = avroRecord.getSchema(); try { int schemaId = s_schemaRegistryClient.register(topic, schema); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(0); out.write(ByteBuffer.allocate(4).putInt(schemaId).array()); BinaryEncoder encoder = s_encoderFactory.directBinaryEncoder(out, null); DatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); writer.write(avroRecord, encoder); encoder.flush(); byte[] bytes = out.toByteArray(); out.close(); return bytes; } catch (IOException e) { throw new SerializationException("Error serializing Avro message", e); } catch (RestClientException e) { throw new SerializationException("Error registering Avro schema: " + schema, e); } }

Target:
private byte[] serialize(String topic, GenericRecord avroRecord) { if (avroRecord == null) { return null; } String schemaName = "kipling-" + topic + "-value"; Schema schema = avroRecord.getSchema(); try { int schemaId = m_schemaRegistryClient.register(schemaName, schema); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(0); out.write(ByteBuffer.allocate(4).putInt(schemaId).array()); BinaryEncoder encoder = m_encoderFactory.directBinaryEncoder(out, null); DatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); writer.write(avroRecord, encoder); encoder.flush(); byte[] bytes = out.toByteArray(); out.close(); return bytes; } catch (IOException e) { throw new SerializationException("Error serializing Avro message", e); } catch (RestClientException e) { throw new SerializationException("Error registering Avro schema: " + schema, e); } }
Source:
public void testNoOpConfigurationFailsFilterInit() throws ServletException { final RequestParameterPolicyEnforcementFilter filter = new RequestParameterPolicyEnforcementFilter(); final Set<String> initParameterNames = new HashSet<String>(); initParameterNames.add(RequestParameterPolicyEnforcementFilter.ALLOW_MULTI_VALUED_PARAMETERS); initParameterNames.add(RequestParameterPolicyEnforcementFilter.CHARACTERS_TO_FORBID); final Enumeration parameterNamesEnumeration = Collections.enumeration(initParameterNames); final FilterConfig filterConfig = Mockito.mock(FilterConfig.class); Mockito.when(filterConfig.getInitParameterNames()).thenReturn(parameterNamesEnumeration); Mockito.when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.ALLOW_MULTI_VALUED_PARAMETERS)) .thenReturn("true"); Mockito.when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.CHARACTERS_TO_FORBID)) .thenReturn("none"); Mockito.when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.PARAMETERS_TO_CHECK)) .thenReturn(null); filter.init(filterConfig); }

Target:
public void testNoOpConfigurationFailsFilterInit() throws ServletException { final RequestParameterPolicyEnforcementFilter filter = new RequestParameterPolicyEnforcementFilter(); final Set<String> initParameterNames = new HashSet<String>(); initParameterNames.add(RequestParameterPolicyEnforcementFilter.ALLOW_MULTI_VALUED_PARAMETERS); initParameterNames.add(RequestParameterPolicyEnforcementFilter.CHARACTERS_TO_FORBID); final Enumeration parameterNamesEnumeration = Collections.enumeration(initParameterNames); final FilterConfig filterConfig = mock(FilterConfig.class); when(filterConfig.getInitParameterNames()).thenReturn(parameterNamesEnumeration); when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.ALLOW_MULTI_VALUED_PARAMETERS)) .thenReturn("true"); when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.CHARACTERS_TO_FORBID)) .thenReturn("none"); when(filterConfig.getInitParameter(RequestParameterPolicyEnforcementFilter.PARAMETERS_TO_CHECK)) .thenReturn(null); filter.init(filterConfig); }
Source:
public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType) throws IOException { SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); Socket socket = channel.socket(); socket.setKeepAlive(true); socket.setSendBufferSize(sendBufferSize); socket.setReceiveBufferSize(receiveBufferSize); socket.setTcpNoDelay(true); try { channel.connect(address); } catch (UnresolvedAddressException e) { channel.close(); throw new IOException("Can't resolve address: " + address, e); } catch (IOException e) { channel.close(); throw e; } String connectionId = generateConnectionId(channel); SelectionKey key = channel.register(this.nioSelector, SelectionKey.OP_CONNECT); Transmission transmission = TransmissionFactory .getChannelWrapper(connectionId, channel, key, address.getHostName(), address.getPort(), time, metrics, logger, portType, sslFactory, SSLFactory.Mode.CLIENT); key.attach(transmission); this.keyMap.put(connectionId, key); activeConnections.set(this.keyMap.size()); return connectionId; }

Target:
public String connect(InetSocketAddress address, int sendBufferSize, int receiveBufferSize, PortType portType) throws IOException { SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); Socket socket = channel.socket(); socket.setKeepAlive(true); socket.setSendBufferSize(sendBufferSize); socket.setReceiveBufferSize(receiveBufferSize); socket.setTcpNoDelay(true); try { channel.connect(address); } catch (UnresolvedAddressException e) { channel.close(); throw new IOException("Can't resolve address: " + address, e); } catch (IOException e) { channel.close(); throw e; } String connectionId = generateConnectionId(channel); SelectionKey key = channel.register(this.nioSelector, SelectionKey.OP_CONNECT); Transmission transmission = TransmissionFactory .getTransmission(connectionId, channel, key, address.getHostName(), address.getPort(), time, metrics, portType, sslFactory, SSLFactory.Mode.CLIENT); key.attach(transmission); this.keyMap.put(connectionId, key); activeConnections.set(this.keyMap.size()); return connectionId; }
Source:
public Long createDispoSet(ArtifactReadable author, BranchId branch, DispoSet descriptor) { TransactionBuilder tx = getTxFactory().createTransaction(branch, author, "Create Dispo Set"); ArtifactId creatdArtId = tx.createArtifact(DispoConstants.DispoSet, descriptor.getName()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.ImportPath, descriptor.getImportPath()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.ImportState, descriptor.getImportState()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoType, descriptor.getDispoType()); try { String notes = JsonUtil.getMapper().writer().writeValueAsString(descriptor.getNotesList()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoNotesJson, notes); } catch (Exception ex) { throw new OseeCoreException("Could not parse Notes Json", ex); } tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoCiSet, descriptor.getCiSet()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoRerunList, descriptor.getRerunList()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoTime, descriptor.getTime()); tx.commit(); return creatdArtId.getUuid(); }

Target:
public Long createDispoSet(ArtifactReadable author, BranchId branch, DispoSet descriptor) { TransactionBuilder tx = getTxFactory().createTransaction(branch, author, "Create Dispo Set"); ArtifactId creatdArtId = tx.createArtifact(DispoConstants.DispoSet, descriptor.getName()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.ImportPath, descriptor.getImportPath()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.ImportState, descriptor.getImportState()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoType, descriptor.getDispoType()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoNotesJson, JsonUtil.toJson(descriptor.getNotesList())); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoCiSet, descriptor.getCiSet()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoRerunList, descriptor.getRerunList()); tx.setSoleAttributeValue(creatdArtId, DispoConstants.DispoTime, descriptor.getTime()); tx.commit(); return creatdArtId.getUuid(); }
Source:
public void writeObject(ObjectOutput output, T collection) throws IOException { Optional<Object> found = Optional.empty(); for (Object o : collection) { found = Optional.of(o); break; } output.writeObject(found.get()); }

Target:
public void writeObject(ObjectOutput output, T collection) throws IOException { output.writeObject(collection.iterator().next()); }
Source:
public static void main(String[] args) { if (args.length != 3) printUsage(); try { Version version = parseVersionString(args[0]); if (version == null) { System.err.println( "Invalid version number format, must be \"x.y.z(-.*)?\""); System.exit(1); } String rev = args[1]; if (rev == null || rev.trim().isEmpty()) { rev = "-1"; } generateFile(new File("."), version, rev, args[2]); } catch (NumberFormatException e) { System.err.println( "All version-related parameters must be valid integers!"); throw e; } }

Target:
public static void main(String[] args) { if (args.length != 3) printUsage(); try { Version version = parseVersionString(args[0]); if (version == null) { System.err.println( "Invalid version number format, must be \"x.y.z(-.*)?\""); System.exit(1); } String rev = args[1]; if (rev == null || rev.trim().isEmpty()) { rev = "-1"; } else { rev = rev.trim(); } generateFile(new File("."), version, rev, args[2]); } catch (NumberFormatException e) { System.err.println( "All version-related parameters must be valid integers!"); throw e; } }