auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static void runMemoryTest(Set<ITmfTrace> testTraces, String testName, int loop_count) { Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + MEMORY + '#' + testName); perf.tagAsSummary(pm, TEST_SUMMARY + MEMORY + ':' + testName, Dimension.CPU_TIME); for (int i = 0; i < loop_count; i++) { TmfNetworkEventMatching traceMatch = new TmfNetworkEventMatching(testTraces); System.gc(); pm.start(); traceMatch.matchEvents(); System.gc(); pm.stop(); } pm.commit(); }

Target:
private static void runMemoryTest(Set<ITmfTrace> testTraces, String testName, int loop_count) { Performance perf = Performance.getDefault(); PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID + MEMORY + '#' + testName); perf.tagAsSummary(pm, TEST_SUMMARY + MEMORY + ':' + testName, Dimension.USED_JAVA_HEAP); for (int i = 0; i < loop_count; i++) { TmfNetworkEventMatching traceMatch = new TmfNetworkEventMatching(testTraces); System.gc(); pm.start(); traceMatch.matchEvents(); System.gc(); pm.stop(); } pm.commit(); }
Source:
public Collection<String> findAllUsersWithRole(String roleName) { TypedQuery<String> query = entityManager.createNamedQuery("listUsersWithRole", String.class); query.setParameter("groupname", roleName); return query.getResultList(); }

Target:
public Collection<String> findAllUsersWithRole(String roleName) { JPAQuery query = new JPAQuery(entityManager); QRoleImpl role = QRoleImpl.roleImpl; QUserImpl user = QUserImpl.userImpl; return query.from(role) .where(role.name.eq(roleName)) .join(role.members, user) .list(user.username); }
Source:
public void test10_01_tagConfiguration() { driver.findElement(By.id("tagConfiguration_10_01")).click(); assertThat(driver.getPageSource().contains( "<div class=\"alert alert-success\"><ul><li></li></ul></div>"), is(true)); screenCapture.save(driver); }

Target:
public void test10_01_tagConfiguration() { driver.findElement(By.id("tagConfiguration_10_01")).click(); assertThat(driver.getPageSource().contains( "<div class=\"alert alert-success\"><ul><li></li></ul></div>"), is(true)); pageSource.save(driver); }
Source:
protected Guid getStoragePoolIdForDomain(Guid storageDomainId) { StorageDomainQueryParametersBase params = new StorageDomainQueryParametersBase(storageDomainId); params.setSessionId(getSessionHelper().getSessionId()); VdcQueryReturnValue returnValue = getBackend().RunQuery(VdcQueryType.GetStoragePoolsByStorageDomainId, params); @SuppressWarnings("unchecked") List<storage_pool> storagePools = (List<storage_pool>) returnValue.getReturnValue(); if (storagePools != null && !storagePools.isEmpty()) { return storagePools.get(0).getId(); } else { return Guid.Empty; } }

Target:
protected Guid getStoragePoolIdForDomain(Guid storageDomainId) { StorageDomainQueryParametersBase params = new StorageDomainQueryParametersBase(storageDomainId); List<storage_pool> storagePools = getBackendCollection(storage_pool.class, VdcQueryType.GetStoragePoolsByStorageDomainId, params); if (storagePools != null && !storagePools.isEmpty()) { return storagePools.get(0).getId(); } else { return Guid.Empty; } }
Source:
public MethodOutcome updateFHIRCondition(@ResourceParam Condition condition, @IdParam IdType uuid) { try { return MethodOutcomeBuilder.buildUpdate(conditionResource.updateFHIRCondition(condition, uuid.getIdPart())); } catch (Exception e) { throw new InvalidRequestException("Following exception occured: " + e.getMessage() + " " + ExceptionUtils.getStackTrace(e)); } }

Target:
public MethodOutcome updateFHIRCondition(@ResourceParam Condition condition, @IdParam IdType uuid) { return MethodOutcomeBuilder.buildUpdate(conditionResource.updateFHIRCondition(condition)); }
Source:
public void validate(String path) { if (path == null || path.isEmpty()) { return; } String[] folders = REGEX_FOLDER_SPLIT.split(path); if (folders == null || folders.length < 1) { return; } for (String folder : folders) { if (PARENT_FOLDER_IDENTIFIER.equals(folder)) { throw new IllegalArgumentException("Invalid URI path: '" + path + "'. Parent paths are not allowed."); } } }

Target:
public void validate(String path) { if (path == null || path.isEmpty()) { return; } String[] folders = REGEX_FOLDER_SPLIT.split(path); if (folders == null || folders.length < 1) { return; } for (String folder : folders) { if (PARENT_FOLDER_IDENTIFIER.equals(folder)) { throw new IllegalArgumentException("Invalid path: '" + path + "'. Parent paths are not allowed."); } } }
Source:
protected void createTestData() { LNPTestData testData = getTestData(); try { createJsonDataFile(testData); createCsvConfigDataFile(testData); } catch (IOException ex) { log.severe(TeammatesException.toStringWithStackTrace(ex)); } }

Target:
protected void createTestData() { LNPTestData testData = getTestData(); try { createJsonDataFile(testData); persistTestData(); createCsvConfigDataFile(testData); } catch (IOException | HttpRequestFailedException ex) { log.severe(TeammatesException.toStringWithStackTrace(ex)); } }
Source:
void createIMMenu (long imHandle) { boolean showInputMethod = false; long settings = OS.gtk_settings_get_default (); if (settings != 0) { int buffer = new int [1]; if (OS.GTK_VERSION < OS.VERSION (3, 10, 0)) { OS.g_object_get (settings, OS.gtk_show_input_method_menu, buffer, 0); showInputMethod = buffer[0] != 0; } } if (imHandle == 0 || !showInputMethod) { this.imHandle = 0; if (imItem != 0) { OS.gtk_widget_destroy (imItem); imItem = 0; } if (imSeparator != 0) { OS.gtk_widget_destroy (imSeparator); imSeparator = 0; } return; } if (this.imHandle == imHandle) return; this.imHandle = imHandle; if (imSeparator == 0) { imSeparator = OS.gtk_separator_menu_item_new (); OS.gtk_widget_show (imSeparator); OS.gtk_menu_shell_insert (handle, imSeparator, -1); } if (imItem == 0) { byte[] buffer = Converter.wcsToMbcs (null, SWT.getMessage("SWT_InputMethods"), true); imItem = OS.gtk_image_menu_item_new_with_label (buffer); OS.gtk_widget_show (imItem); OS.gtk_menu_shell_insert (handle, imItem, -1); } long imSubmenu = OS.gtk_menu_new (); OS.gtk_im_multicontext_append_menuitems (imHandle, imSubmenu); OS.gtk_menu_item_set_submenu (imItem, imSubmenu); }

Target:
void createIMMenu (long imHandle) { boolean showInputMethod = false; long settings = OS.gtk_settings_get_default (); if (settings != 0 && OS.GTK_VERSION < OS.VERSION (3, 10, 0)) { int buffer = new int [1]; OS.g_object_get (settings, OS.gtk_show_input_method_menu, buffer, 0); showInputMethod = buffer[0] != 0; } if (imHandle == 0 || !showInputMethod) { this.imHandle = 0; if (imItem != 0) { OS.gtk_widget_destroy (imItem); imItem = 0; } if (imSeparator != 0) { OS.gtk_widget_destroy (imSeparator); imSeparator = 0; } return; } if (this.imHandle == imHandle) return; this.imHandle = imHandle; if (imSeparator == 0) { imSeparator = OS.gtk_separator_menu_item_new (); OS.gtk_widget_show (imSeparator); OS.gtk_menu_shell_insert (handle, imSeparator, -1); } if (imItem == 0) { byte[] buffer = Converter.wcsToMbcs (null, SWT.getMessage("SWT_InputMethods"), true); imItem = OS.gtk_image_menu_item_new_with_label (buffer); OS.gtk_widget_show (imItem); OS.gtk_menu_shell_insert (handle, imItem, -1); } long imSubmenu = OS.gtk_menu_new (); OS.gtk_im_multicontext_append_menuitems (imHandle, imSubmenu); OS.gtk_menu_item_set_submenu (imItem, imSubmenu); }
Source:
private ASTValue evalRepeat(WordsEnvironment environment) throws WordsException { ASTValue times = children.get(0).eval(environment); AST statementList = children.get(1); if (times.type != ValueType.NUM) { throw new InvalidTypeException(this.lineNo, ValueType.NUM.toString(), times.type.toString()); } for (int i = 0; i < times.numValue; i++) { statementList.eval(environment); } return null; }

Target:
private ASTValue evalRepeat(WordsEnvironment environment) throws WordsRuntimeException { ASTValue times = children.get(0).eval(environment).tryCoerceTo(ValueType.NUM); AST statementList = children.get(1); if (times.type != ValueType.NUM) { throw new WordsInvalidTypeException(ValueType.NUM.toString(), times.type.toString()); } for (int i = 0; i < times.numValue; i++) { statementList.eval(environment); } return null; }
Source:
public static JSONObject getItemJsonObject(Context context, String name) { try { int stringId = context.getResources().getIdentifier(name, "string", context.getPackageName()); String item = context.getString(stringId); return new JSONObject(item); } catch (NullPointerException | JSONException e) { e.printStackTrace(); return DUMMY_OBJECT; } }

Target:
public static JSONObject getItemJsonObject(Context context, String name) { if(context != null && name != null) { try { name = MyApplication.toId(name); int stringId = context.getResources().getIdentifier(name, "string", context.getPackageName()); if (stringId != 0) { String item = context.getString(stringId); return new JSONObject(item); } } catch (JSONException e) { } } return DUMMY_JSON_ITEM; }
Source:
private Notifications getSwitches(SonyAudioClientSocket socket, Notifications notifications) throws IOException { SwitchNotifications switchNotifications = new SwitchNotifications(notifications.enabled, notifications.disabled); JsonElement switches = socket.callMethod(switchNotifications); Gson mapper = new Gson(); Type notificationListType = new TypeToken<List<Notification>>() { }.getType(); notifications.enabled = mapper.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("enabled"), notificationListType); notifications.disabled = mapper.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("disabled"), notificationListType); return notifications; }

Target:
private Notifications getSwitches(SonyAudioClientSocket socket, Notifications notifications) throws IOException { SwitchNotifications switchNotifications = new SwitchNotifications(notifications.enabled, notifications.disabled); JsonElement switches = socket.callMethod(switchNotifications); Type notificationListType = new TypeToken<List<Notification>>() { }.getType(); notifications.enabled = gson.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("enabled"), notificationListType); notifications.disabled = gson.fromJson(switches.getAsJsonArray().get(0).getAsJsonObject().get("disabled"), notificationListType); return notifications; }
Source:
public boolean isUsefulForIndex() { if("place".equals(tagKey) && "houses".equals(tagValue)) return false; if(houseNumber != null) return true; if(name.isEmpty()) return false; return linkedPlaceId <= 0; }

Target:
public boolean isUsefulForIndex() { if("place".equals(tagKey) && "houses".equals(tagValue)) return false; if(houseNumber != null) return true; if(name.isEmpty()) return false; if(linkedPlaceId > 0) return false; return true; }
Source:
public void onInitialization(FMLInitializationEvent e) { try { this.registry.init(); if (!this.game.getServiceManager().provide(PermissionService.class).isPresent()) { try { this.game.getServiceManager().setProvider(this, PermissionService.class, new SpongePermissionService()); } catch (ProviderExistsException e1) { } } } catch (Throwable t) { logger.error("On init", t); } }

Target:
public void onInitialization(FMLInitializationEvent e) { try { this.registry.init(); if (!this.game.getServiceManager().provide(PermissionService.class).isPresent()) { try { this.game.getServiceManager().setProvider(this, PermissionService.class, new SpongePermissionService()); } catch (ProviderExistsException e1) { } } } catch (Throwable t) { this.controller.errorOccurred(this, t); } }
Source:
protected void setNextTableToSweep(TableReference tableRef) { Mockito.doReturn(Optional.of(tableRef)).when(nextTableToSweepProvider) .getNextTableToSweep(any(), Mockito.anyLong()); }

Target:
protected void setNextTableToSweep(TableReference tableRef) { doReturn(Optional.of(tableRef)).when(nextTableToSweepProvider) .getNextTableToSweep(any(), anyLong()); }
Source:
private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { String env = null; if (!SidecarToolingWorkspaceUtil.isSidecarBasedWorkspace(workspace.getConfig().getAttributes()) || envName != null || !workspace.getConfig().getEnvironments().isEmpty()) { if (envName != null && !workspace.getConfig().getEnvironments().containsKey(envName)) { throw new NotFoundException( format( "Workspace '%s:%s' doesn't contain environment '%s'", workspace.getNamespace(), workspace.getConfig().getName(), envName)); } env = firstNonNull(envName, workspace.getConfig().getDefaultEnv()); try { runtimes.validate(workspace.getConfig().getEnvironments().get(env)); } catch (InfrastructureException | ValidationException e) { throw new ServerException(e); } } workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, env, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace)) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace); } else { handleStartupError(workspace, ex.getCause()); } return null; }); }

Target:
private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { String env = getValidatedEnvironmentName(workspace, envName); workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, env, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace)) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace); } else { handleStartupError(workspace, ex.getCause()); } return null; }); }
Source:
public Response toResponse(JsonMappingException exception) { LOGGER.error(exception.getMessage()); ImmutableMap<String, String> entity = ImmutableMap.of("message", exception.getMessage()); return Response.status(400).entity(entity).type(APPLICATION_JSON).build(); }

Target:
public Response toResponse(JsonMappingException exception) { LOGGER.error(exception.getMessage()); Map<String, String> entity = Map.of("message", exception.getMessage()); return Response.status(400).entity(entity).type(APPLICATION_JSON).build(); }
Source:
public JSONObject createContent() { if (sessionsBySetting.size() == 0) { return null; } Map<Boolean, Set<String>> currentSessions; synchronized (sessionsBySetting) { currentSessions = new TreeMap<>(sessionsBySetting); sessionsBySetting.clear(); } JSONObject payload = new JSONObject(); for (Map.Entry<Boolean, Set<String>> entry : currentSessions.entrySet()) { payload.put(entry.getKey().toString(), entry.getValue().size()); } return payload; }

Target:
public JSONObject createContent() { int sessionsWithAutoRefreshCount, sessionsWithoutAutoRefreshCount; synchronized (sessionsWithAutoRefresh) { sessionsWithAutoRefreshCount = sessionsWithAutoRefresh.size(); sessionsWithAutoRefresh.clear(); } synchronized (sessionsWithoutAutoRefresh) { sessionsWithoutAutoRefreshCount = sessionsWithoutAutoRefresh.size(); sessionsWithoutAutoRefresh.clear(); } if (sessionsWithAutoRefreshCount == 0 && sessionsWithoutAutoRefreshCount == 0) { return null; } JSONObject payload = new JSONObject(); payload.put("enabled", sessionsWithAutoRefreshCount); payload.put("disabled", sessionsWithoutAutoRefreshCount); return payload; }
Source:
protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.newGuid()); newDiskImage = cloneDiskImage(getDestinationImageId()); newDiskImage.setId(Guid.newGuid()); Guid storagePoolID = newDiskImage.getStoragePoolId() != null ? newDiskImage .getStoragePoolId() : Guid.Empty; VDSReturnValue vdsReturnValue = null; Guid taskId = persistAsyncTaskPlaceHolder(VdcActionType.AddVmFromTemplate); try { vdsReturnValue = runVdsCommand(VDSCommandType.CopyImage, PostZeroHandler.fixParametersWithPostZero( new CopyImageVDSCommandParameters(storagePoolID, getParameters().getStorageDomainId(), getVmTemplateId(), getDiskImage().getId(), getImage().getImageId(), newDiskImage.getId(), getDestinationImageId(), "", getDestinationStorageDomainId(), CopyVolumeType.LeafVol, newDiskImage.getVolumeFormat(), newDiskImage.getVolumeType(), getDiskImage().isWipeAfterDelete(), false))); } catch (VdcBLLException e) { log.error("Failed creating snapshot from image id -'{}'", getImage().getImageId()); throw e; } if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalVdsmTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate, VdcObjectType.Storage, getParameters().getStorageDomainId(), getDestinationStorageDomainId())); } return vdsReturnValue; }

Target:
protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.newGuid()); newDiskImage = cloneDiskImage(getDestinationImageId()); newDiskImage.setId(Guid.newGuid()); Guid storagePoolID = newDiskImage.getStoragePoolId() != null ? newDiskImage .getStoragePoolId() : Guid.Empty; VDSReturnValue vdsReturnValue = null; Guid taskId = persistAsyncTaskPlaceHolder(VdcActionType.AddVmFromTemplate); try { vdsReturnValue = runVdsCommand(VDSCommandType.CopyImage, PostZeroHandler.fixParametersWithPostZero( new CopyImageVDSCommandParameters(storagePoolID, getParameters().getStorageDomainId(), getVmTemplateId(), getDiskImage().getId(), getImage().getImageId(), newDiskImage.getId(), getDestinationImageId(), "", getDestinationStorageDomainId(), CopyVolumeType.LeafVol, newDiskImage.getVolumeFormat(), newDiskImage.getVolumeType(), getDiskImage().isWipeAfterDelete(), false))); } catch (VdcBLLException e) { log.error("Failed creating snapshot from image id '{}'", getImage().getImageId()); throw e; } if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalVdsmTaskIdList().add( createTask(taskId, vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate, VdcObjectType.Storage, getParameters().getStorageDomainId(), getDestinationStorageDomainId())); } return vdsReturnValue; }
Source:
public HazelcastEntityInformation(PersistentEntity<T, ?> entity) { super(entity); if (!entity.hasIdProperty()) { throw new MappingException( String.format("Entity %s requires a field annotated with %s", entity.getName(), Id.class.getName())); } }

Target:
HazelcastEntityInformation(PersistentEntity<T, ?> entity) { super(entity); if (!entity.hasIdProperty()) { throw new MappingException( String.format("Entity %s requires a field annotated with %s", entity.getName(), Id.class.getName())); } }
Source:
public Object newInstance(Class[] argumentTypes, Object[] arguments, Callback[] callbacks) { setThreadCallbacks(callbacks); try { if (!Arrays.equals(primaryConstructorArgTypes, argumentTypes)) { return ReflectUtils.newInstance(generatedClass, argumentTypes, arguments); } try { return primaryConstructor.newInstance(arguments); } catch (InstantiationException e) { throw new CodeGenerationException(e); } catch (IllegalAccessException e) { throw new CodeGenerationException(e); } catch (InvocationTargetException e) { throw new CodeGenerationException(e.getTargetException()); } } finally { setThreadCallbacks(null); } }

Target:
public Object newInstance(Class[] argumentTypes, Object[] arguments, Callback[] callbacks) { setThreadCallbacks(callbacks); try { if (primaryConstructorArgTypes == argumentTypes || Arrays.equals(primaryConstructorArgTypes, argumentTypes)) { return ReflectUtils.newInstance(primaryConstructor, arguments); } return ReflectUtils.newInstance(generatedClass, argumentTypes, arguments); } finally { setThreadCallbacks(null); } }
Source:
public void testCreateTeamWithRepoAccess() throws IOException { String REPO_NAME = "github-api"; String TEAM_NAME = "create-team-test"; GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHRepository repo = org.getRepository(REPO_NAME); GHTeam existingTeam = org.getTeamByName(TEAM_NAME); if (existingTeam != null) { existingTeam.delete(); } GHTeam team = org.createTeam(TEAM_NAME, GHOrganization.Permission.PUSH, repo); Assert.assertTrue(team.getRepositories().containsKey(REPO_NAME)); }

Target:
public void testCreateTeamWithRepoAccess() throws IOException { String REPO_NAME = "github-api"; GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); GHRepository repo = org.getRepository(REPO_NAME); GHTeam team = org.createTeam(TEAM_NAME_CREATE, GHOrganization.Permission.PUSH, repo); Assert.assertTrue(team.getRepositories().containsKey(REPO_NAME)); }
Source:
public static boolean isDemoUser() { try { User u = CommCareApplication._().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { return true; } }

Target:
public static boolean isDemoUser() { try { User u = CommCareApplication._().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { return false; } }
Source:
public void withExtensibleChannelTypeIds_shouldSetUnmodifiableExtensibleChannelTypeIds() { @SuppressWarnings("null") ThingType thingType = builder .withExtensibleChannelTypeIds(Arrays.asList(new String[] { "channelTypeId1", "channelTypeId2" })) .build(); assertThat(thingType.getExtensibleChannelTypeIds(), is(hasSize(2))); try { thingType.getExtensibleChannelTypeIds().add("channelTypeId"); fail(); } catch (UnsupportedOperationException e) { } }

Target:
public void withExtensibleChannelTypeIds_shouldSetUnmodifiableExtensibleChannelTypeIds() { ThingType thingType = builder .withExtensibleChannelTypeIds(Arrays.asList(new String[] { "channelTypeId1", "channelTypeId2" })) .build(); assertThat(thingType.getExtensibleChannelTypeIds(), is(hasSize(2))); try { thingType.getExtensibleChannelTypeIds().add("channelTypeId"); fail(); } catch (UnsupportedOperationException e) { } }
Source:
private void startDeleteBlobAuthorizationFailTest(final OperationChain opChain) { Callback<Void> callback = new TestCallback<>(opChain, false); BlobId originalId, fraudId; try { originalId = new BlobId(opChain.blobId, clusterMap); fraudId = BlobId.craft(originalId, originalId.getVersion(), (short) (originalId.getAccountId() + 1), (short) (originalId.getContainerId() + 1)); } catch (IOException e) { FutureResult<Void> future = new FutureResult<>(); future.done(null, null); callback.onCompletion(null, null); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { throw e; } }; opChain.testFutures.add(testFuture); return; } Future<Void> future = router.deleteBlob(fraudId.getID(), null, callback); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { checkExpectedRouterErrorCode(RouterErrorCode.BlobAuthorizationFailure); } }; opChain.testFutures.add(testFuture); }

Target:
private void startDeleteBlobAuthorizationFailTest(final OperationChain opChain) { Callback<Void> callback = new TestCallback<>(opChain, false); BlobId originalId, fraudId; try { originalId = new BlobId(opChain.blobId, clusterMap); fraudId = BlobId.craft(originalId, originalId.getVersion(), (short) (originalId.getAccountId() + 1), (short) (originalId.getContainerId() + 1)); } catch (IOException e) { FutureResult<Void> future = new FutureResult<>(); future.done(null, e); callback.onCompletion(null, e); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { throw e; } }; opChain.testFutures.add(testFuture); return; } Future<Void> future = router.deleteBlob(fraudId.getID(), null, callback); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { checkExpectedRouterErrorCode(RouterErrorCode.BlobAuthorizationFailure); } }; opChain.testFutures.add(testFuture); }
Source:
public void testOneway() throws Exception { latch = new CountDownLatch(1); Client client = ResteasyClientBuilder.newClient(); WebTarget target = client.target("http://localhost:" + TestPortProvider.getPort() + "?oneway=true"); long start = System.currentTimeMillis(); Response response = target.request().put(Entity.entity("content", "text/plain")); long end = System.currentTimeMillis() - start; Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); Assert.assertTrue(end < 1000); Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); response.close(); }

Target:
public void testOneway() throws Exception { latch = new CountDownLatch(1); WebTarget target = client.target("http://localhost:" + TestPortProvider.getPort() + "?oneway=true"); long start = System.currentTimeMillis(); Response response = target.request().put(Entity.entity("content", "text/plain")); long end = System.currentTimeMillis() - start; Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); Assert.assertTrue(end < 1000); Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); response.close(); }
Source:
public MessageGroup getMessageGroup(Object groupId) { List<Object> allMessages = new LinkedList<Object>(); List<String> list = sortedKeys((String) groupId); for (String key : list) { List<?> messages = this.getRedisTemplate().boundListOps(key).range(0, -1); allMessages.addAll(messages); } return new SimpleMessageGroup((Collection<? extends Message<?>>) allMessages, groupId); }

Target:
public MessageGroup getMessageGroup(Object groupId) { Assert.isInstanceOf(String.class, groupId); List<Message<?>> allMessages = new LinkedList<Message<?>>(); List<String> list = sortedKeys((String) groupId); for (String key : list) { List<Message<?>> messages = this.getRedisTemplate().boundListOps(key).range(0, -1); allMessages.addAll(messages); } return new SimpleMessageGroup(allMessages, groupId); }
Source:
public void testInvalidCondition() throws Exception { final String query = "and if(length(user())>0,sleep(10),2)"; final String s = SQLUtil.sanitizeParameter( query ); assertNotNull(s); assertEquals(StringPool.BLANK, s); }

Target:
public void testInvalidCondition() throws Exception { final String query = "and if(length(user())>0,sleep(10),2)"; final String s = SQLUtil.sanitizeCondition( query ); assertNotNull(s); assertEquals(StringPool.BLANK, s); }
Source:
public CompareWidget(final CompareConfig compareConfig, final String themeId, LoaderFactory loaderFactory) { this.compareConfig = compareConfig; this.frame = new Frame(GWT.getModuleBaseURL() + "/Compare.html"); initWidget(frame); setSize("100%", "100%"); final MessageLoader loader = loaderFactory.newLoader(); loader.show(); frame.getElement().getStyle().setBorderStyle(Style.BorderStyle.NONE); AsyncPromiseHelper.RequestCall<Window> call = new AsyncPromiseHelper.RequestCall<Window>() { @Override public void makeCall(final AsyncCallback<Window> callback) { frame.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { frame.getElement().cast(); final JsIFrameElement iFrame = frame.getElement().cast(); callback.onSuccess(iFrame.getContentWindow()); loader.hide(); } }); } }; framePromise = PromiseHelper.newPromise(call); framePromise.then(new Operation<Window>() { @Override public void apply(Window arg) throws OperationException { sendThemeId(arg, themeId); } }); framePromise.then(new Operation<Window>() { @Override public void apply(Window arg) throws OperationException { sendConfig(arg, compareConfig); } }); }

Target:
public CompareWidget(final CompareConfig compareConfig, final String themeId, LoaderFactory loaderFactory) { this.compareConfig = compareConfig; this.frame = new Frame(GWT.getModuleBaseURL() + "/Compare.html"); initWidget(frame); setSize("100%", "100%"); final MessageLoader loader = loaderFactory.newLoader(); loader.show(); frame.getElement().getStyle().setBorderStyle(Style.BorderStyle.NONE); AsyncPromiseHelper.RequestCall<Window> call = new AsyncPromiseHelper.RequestCall<Window>() { @Override public void makeCall(final AsyncCallback<Window> callback) { frame.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { frame.getElement().cast(); final JsIFrameElement iFrame = frame.getElement().cast(); callback.onSuccess(iFrame.getContentWindow()); loader.hide(); } }); } }; framePromise = PromiseHelper.newPromise(call); framePromise.then(new Operation<Window>() { @Override public void apply(Window arg) throws OperationException { sendThemeId(arg, themeId); } }); framePromise.then(new Operation<Window>() { @Override public void apply(final Window arg) throws OperationException { arg.getDocument().addEventListener("onThemeLoaded", new EventListener() { @Override public void handleEvent(Event evt) { sendConfig(arg, compareConfig); loader.hide(); } }, false); } }); }
Source:
protected void checkRightFileType(ResourceInterface resourcePrototype, String fileName) { boolean isRight = false; if (fileName.length() > 0) { String docType = fileName.substring(fileName.lastIndexOf('.') + 1).trim(); String[] types = resourcePrototype.getAllowedFileTypes(); isRight = isValidType(docType, types); } else { isRight = true; } if (!isRight) { this.addFieldError("upload", this.getText("error.resource.file.wrongFormat")); } }

Target:
protected void checkRightFileType(ResourceInterface resourcePrototype, String fileName) { boolean isRight = false; if (fileName.length() > 0) { logger.debug("Check uploaded file type for ", fileName); String docType = fileName.substring(fileName.lastIndexOf('.') + 1).trim(); String[] types = resourcePrototype.getAllowedFileTypes(); isRight = isValidType(docType, types); } else { logger.debug("Check uploaded file type: file format is right for ", fileName); isRight = true; } if (!isRight) { logger.debug("Check uploaded file type: wrong file format for ", fileName); this.addFieldError("upload", this.getText("error.resource.file.wrongFormat")); } }
Source:
public synchronized long skip(long n) throws IOException { throw new IOException("skip not supported"); }

Target:
public synchronized long skip(long n) { if (n < 0) { return 0; } long totalSkippedBytes = min(n, remainingBytes); n = totalSkippedBytes; while (n > 0) { if (currentBufferPosition >= currentBuffer.length) { advanceCurrentBuffer(); } int skippedBytes = (int) min(n, currentBuffer.length - currentBufferPosition); n -= skippedBytes; currentBufferPosition += skippedBytes; } remainingBytes -= totalSkippedBytes; return totalSkippedBytes; }
Source:
public void testAppendPath() { assertEquals("services/data/v28.0/chatter/foo", new ConnectUriBuilder().appendPath("foo").toString()); assertEquals("services/data/v28.0/chatter/foo/bar", new ConnectUriBuilder().appendPath("foo").appendPath("bar") .toString()); assertEquals("services/data/v28.0/chatter/foo/bar", new ConnectUriBuilder().appendPath("foo/bar").toString()); }

Target:
public void testAppendPath() { assertEquals(connectPath + "foo", new ConnectUriBuilder().appendPath("foo").toString()); assertEquals(connectPath + "foo/bar", new ConnectUriBuilder().appendPath("foo").appendPath("bar") .toString()); assertEquals(connectPath + "foo/bar", new ConnectUriBuilder().appendPath("foo/bar").toString()); }
Source:
public static <T> EventStep<AttributesImpl, T, byte[], String> binary() { return BinaryMarshaller.<AttributesImpl, T, byte[], String>builder() .map(AttributesImpl::marshal) .map(Accessor::extensionsOf) .map(ExtensionFormat::marshal) .map(HeaderMapper::map) .map(Json::binaryMarshal) .builder(Wire::new); }

Target:
public static <T> EventStep<AttributesImpl, T, byte[], String> binary() { return binary(Json::binaryMarshal); }
Source:
public void exportData(Configuration config, SessionManagementMethod sessionMethod) { if (!(sessionMethod instanceof ScriptBasedSessionManagementMethod)) { throw new UnsupportedSessionManagementMethodException( "Script based session management type only supports: " + ScriptBasedSessionManagementMethod.class.getName()); } ScriptBasedSessionManagementMethod method = (ScriptBasedSessionManagementMethod) sessionMethod; config.setProperty(CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_NAME, method.script.getName()); config.setProperty( CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_PARAMS, EncodingUtils.mapToString(method.paramValues)); }

Target:
public void exportData(Configuration config, SessionManagementMethod sessionMethod) { if (!(sessionMethod instanceof ScriptBasedSessionManagementMethod)) { throw new UnsupportedSessionManagementMethodException( "Script based session management type only supports: " + ScriptBasedSessionManagementMethod.class.getName()); } ScriptBasedSessionManagementMethod method = (ScriptBasedSessionManagementMethod) sessionMethod; if (method.script != null) { config.setProperty(CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_NAME, method.script.getName()); } config.setProperty( CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_PARAMS, EncodingUtils.mapToString(method.paramValues)); }
Source:
public void setRadius(Long radius) { if (geolocationType.toString().equalsIgnoreCase("Notification")) { this.radius = radius; } else { this.radius = null; } }

Target:
public void setRadius(Long radius) { if (geolocationType.toString().equals(GeolocationType.Notification)) { this.radius = radius; } else { this.radius = null; } }
Source:
public PhoenixRemoteUserExtractor(Configuration conf) { this.requestRemoteUserExtractor = new HttpRequestRemoteUserExtractor(); this.doAsParam = conf.get(QueryServices.QUERY_SERVER_DOAS_PARAM, QueryServicesOptions.DEFAULT_QUERY_SERVER_DOAS_PARAM); this.paramRemoteUserExtractor = new HttpQueryStringParameterRemoteUserExtractor(doAsParam); this.enableDoAs = conf.getBoolean(QueryServices.QUERY_SERVER_DOAS_ENABLED_ATTRIB, QueryServicesOptions.DEFAULT_QUERY_SERVER_DOAS_ENABLED); }

Target:
public PhoenixRemoteUserExtractor(Configuration conf) { this.requestRemoteUserExtractor = new HttpRequestRemoteUserExtractor(); this.userExtractParam = conf.get(QueryServices.QUERY_SERVER_REMOTEUSEREXTRACTOR_PARAM, QueryServicesOptions.DEFAULT_QUERY_SERVER_REMOTEUSEREXTRACTOR_PARAM); this.paramRemoteUserExtractor = new HttpQueryStringParameterRemoteUserExtractor(userExtractParam); }
Source:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().setSoftLimit(DateUtils.addMinutes(new Date(), Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval))); int maxSessionInterval = Config.<Integer> getValue(ConfigValues.MaxSessionTimeoutInterval); Date validTo = maxSessionInterval != 0 ? DateUtils.addMinutes(new Date(), maxSessionInterval) : null; try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }

Target:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().refresh(); int userSessionHardLimit = Config.<Integer> getValue(ConfigValues.UserSessionHardLimit); Date validTo = userSessionHardLimit != 0 ? DateUtils.addMinutes(new Date(), userSessionHardLimit) : null; try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } else { validTo = fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }
Source:
private String getName(ITestResult iTestResult) { String suitePrefix = getCurrentSuitePrefix(iTestResult); StringBuilder sb = new StringBuilder(suitePrefix); sb.append(iTestResult.getName()); if (!AllureConfig.newInstance().areTestNgParametersDisabled()) { Object[] parameters = iTestResult.getParameters(); if (parameters != null && parameters.length > 0) { sb.append("["); for (Object parameter : parameters) { sb.append(parameter).append(","); } sb.replace(sb.length() - 1, sb.length(), "]"); } } return sb.toString(); }

Target:
private String getName(ITestResult iTestResult) { String suitePrefix = getCurrentSuitePrefix(iTestResult); StringBuilder sb = new StringBuilder(suitePrefix); sb.append(iTestResult.getName()); if (AllureConfig.newInstance().areTestNgParametersEnabled()) { Object[] parameters = iTestResult.getParameters(); if (parameters != null && parameters.length > 0) { sb.append("["); for (Object parameter : parameters) { sb.append(parameter).append(","); } sb.replace(sb.length() - 1, sb.length(), "]"); } } return sb.toString(); }
Source:
private void verifyCourseArchivedInDatastore(String instructorId, CourseAttributes course) { ThreadHelper.waitFor(500); assertEquals(getArchivedCourse(instructorId, course.getId()), course); }

Target:
private void verifyCourseArchivedInDatastore(String instructorId, CourseAttributes course) { int retryLimit = 5; CourseAttributes actual = getArchivedCourse(instructorId, course.getId()); while (actual == null && retryLimit > 0) { retryLimit--; ThreadHelper.waitFor(1000); actual = getArchivedCourse(instructorId, course.getId()); } assertEquals(actual, course); }
Source:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ActivityCalendar other = (ActivityCalendar) obj; if (this.calendarName == null) { if (other.calendarName != null) { return false; } } else if (!this.calendarName.equals(other.calendarName)) { return false; } if (this.activatePassiveCalendarTime == null) { if (other.activatePassiveCalendarTime != null) { return false; } } else if (!this.activatePassiveCalendarTime.equals(other.activatePassiveCalendarTime)) { return false; } if (this.seasonProfileList == null) { if (other.seasonProfileList != null) { return false; } } else if (!this.seasonProfileList.equals(other.seasonProfileList)) { return false; } return true; }

Target:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ActivityCalendar other = (ActivityCalendar) obj; if (!this.calendarName.equals(other.calendarName)) { return false; } if (!this.activatePassiveCalendarTime.equals(other.activatePassiveCalendarTime)) { return false; } if (!this.seasonProfileList.equals(other.seasonProfileList)) { return false; } return true; }
Source:
public Profile getCurrentProfile() { if(cachedProfile != null) { return cachedProfile; } return (Profile)storageManager.getStorage(Profile.STORAGE_KEY).read(profile); }

Target:
public Profile getCurrentProfile() { if (cachedProfile == null) { this.cachedProfile = (Profile)storageManager.getStorage(Profile.STORAGE_KEY).read(profile); } return cachedProfile; }
Source:
private String replaceQueriesWithVariables(String eval) { if (null == queryVars) { queryVars = new HashMap<>(); } queryVars.clear(); List<String> queries = new ArrayList<String>(); Matcher m = Pattern.compile("q\\(.*?\\)").matcher(eval); while (m.find()) { queries.add(m.group()); } int varNum = 0; for (String q : queries) { String var = null; QueryFunc qf = new QueryFunc(q); if (queryVars.containsValue(qf)) { for (Map.Entry<String, QueryFunc> e : queryVars.entrySet()) { if (e.getValue().equals(qf)) { var = e.getKey(); break; } } } else { var = "q" + varNum++; queryVars.put(var, qf); } eval = eval.replaceFirst("q\\(.*?\\)", var); } return eval; }

Target:
private String replaceQueriesWithVariables(String eval) { if (null == queryVars) { queryVars = new HashMap<>(); } queryVars.clear(); List<String> queries = new ArrayList<String>(); Matcher m = PATTERN_QUERY_VAR.matcher(eval); while (m.find()) { queries.add(m.group()); } int varNum = 0; for (String q : queries) { String var = null; QueryFunc qf = new QueryFunc(q); if (queryVars.containsValue(qf)) { for (Map.Entry<String, QueryFunc> e : queryVars.entrySet()) { if (e.getValue().equals(qf)) { var = e.getKey(); break; } } } else { var = "q" + varNum++; queryVars.put(var, qf); } eval = eval.replaceFirst("q\\(.*?\\)", var); } return eval; }
Source:
public int score() { switch(this.yachtCategory) { case ONES: return Arrays.stream(dice) .filter(n -> n==1) .sum(); case TWOS: return Arrays.stream(dice) .filter(n -> n==2) .sum(); case THREES: return Arrays.stream(dice) .filter(n -> n==3) .sum(); case FOURS: return Arrays.stream(dice) .filter(n -> n==4) .sum(); case FIVES: return Arrays.stream(dice) .filter(n -> n==5) .sum(); case SIXES: return Arrays.stream(dice) .filter(n -> n==6) .sum(); case FULL_HOUSE: Collection<Long> occurrences = Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .values(); return occurrences.contains(2L) && occurrences.contains(3L) ? Arrays.stream(dice).sum() : 0; case FOUR_OF_A_KIND: return Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(x -> x.getValue() >= 4) .map(Map.Entry::getKey) .findFirst() .orElse(0) * 4; case LITTLE_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 1, 2, 3, 4, 5 }) ? 30 : 0; case BIG_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 2, 3, 4, 5, 6 }) ? 30 : 0; case CHOICE: return Arrays.stream(dice).sum(); case YACHT: return (Arrays.stream(dice).distinct().count() == 1) ? 50 : 0; default: return 0; } }

Target:
int score() { switch(this.yachtCategory) { case ONES: return Arrays.stream(dice) .filter(n -> n == 1) .sum(); case TWOS: return Arrays.stream(dice) .filter(n -> n == 2) .sum(); case THREES: return Arrays.stream(dice) .filter(n -> n == 3) .sum(); case FOURS: return Arrays.stream(dice) .filter(n -> n == 4) .sum(); case FIVES: return Arrays.stream(dice) .filter(n -> n == 5) .sum(); case SIXES: return Arrays.stream(dice) .filter(n -> n == 6) .sum(); case FULL_HOUSE: Collection<Long> occurrences = Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .values(); return occurrences.contains(2L) && occurrences.contains(3L) ? Arrays.stream(dice).sum() : 0; case FOUR_OF_A_KIND: return Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(x -> x.getValue() >= 4) .map(Map.Entry::getKey) .findFirst() .orElse(0) * 4; case LITTLE_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 1, 2, 3, 4, 5 }) ? 30 : 0; case BIG_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 2, 3, 4, 5, 6 }) ? 30 : 0; case CHOICE: return Arrays.stream(dice).sum(); case YACHT: return (Arrays.stream(dice).distinct().count() == 1) ? 50 : 0; default: return 0; } }
Source:
public MatchPredicateBuilder<ElasticsearchSearchPredicateBuilder> match(String absoluteFieldPath) { ElasticsearchScopedIndexFieldComponent<ElasticsearchFieldPredicateBuilderFactory> fieldComponent = scopeModel.getSchemaNodeComponent( absoluteFieldPath, PREDICATE_BUILDER_FACTORY_RETRIEVAL_STRATEGY, DslConverter.DISABLED ); return fieldComponent.getComponent().createMatchPredicateBuilder( searchContext, absoluteFieldPath, fieldComponent.getCompatibilityChecker() ); }

Target:
public MatchPredicateBuilder<ElasticsearchSearchPredicateBuilder> match(String absoluteFieldPath) { ElasticsearchScopedIndexFieldComponent<ElasticsearchFieldPredicateBuilderFactory> fieldComponent = scopeModel.getSchemaNodeComponent( absoluteFieldPath, PREDICATE_BUILDER_FACTORY_RETRIEVAL_STRATEGY, DslConverter.DISABLED ); return fieldComponent.getComponent().createMatchPredicateBuilder( searchContext, absoluteFieldPath, fieldComponent.getConverterCompatibilityChecker() ); }
Source:
private void addError(final SAMValidationError error) { if (this.errorsToIgnore.contains(error.getType())) return; if ( error.getType().severity == SAMValidationError.Severity.WARNING) { if ( this.ignoreWarnings ) { return; } this.numWarnings++; } else { this.numErrors++; } this.errorsByType.increment(error.getType()); if (verbose) { out.println(error); out.flush(); if (this.errorsByType.getCount() >= maxVerboseOutput) { throw new MaxOutputExceededException(); } } }

Target:
private void addError(final SAMValidationError error) { if (this.errorsToIgnore.contains(error.getType())) return; switch (error.getType().severity) { case WARNING: if ( this.ignoreWarnings ) { return; } this.numWarnings++; break; case ERROR: this.numErrors++; break; default: throw new SAMException("Unknown SAM validation error severity: " + error.getType().severity); } this.errorsByType.increment(error.getType()); if (verbose) { out.println(error); out.flush(); if (this.errorsByType.getCount() >= maxVerboseOutput) { throw new MaxOutputExceededException(); } } }
Source:
public T createHosted(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "The Docker registry (Tools only)") @QueryParam("registry") String registry, @ApiParam(value = "The repository name", required = true) @QueryParam("name") String name, @ApiParam(value = "The descriptor type (Workflows only)") @QueryParam("descriptorType") String descriptorType, @ApiParam(value = "The Docker namespace (Tools only)") @QueryParam("namespace") String namespace, @ApiParam(value = "Optional entry name (Tools only)") @QueryParam("entryName") String entryName) { final long currentCount = getEntryDAO().countAllHosted(user.getId()); User updatedUser = userDAO.findById(user.getId()); final int limit = updatedUser.getHostedEntryCountLimit() != null ? updatedUser.getHostedEntryCountLimit() : calculatedEntryLimit; if (currentCount >= limit) { throw new CustomWebApplicationException("You have " + currentCount + " workflows which is at the current limit of " + limit, HttpStatus.SC_PAYMENT_REQUIRED); } DescriptorLanguage convertedDescriptorType = checkType(descriptorType); Registry convertedRegistry = checkRegistry(registry); T entry = getEntry(user, convertedRegistry, name, convertedDescriptorType, namespace, entryName); checkForDuplicatePath(entry); long l = getEntryDAO().create(entry); T byId = getEntryDAO().findById(l); elasticManager.handleIndexUpdate(byId, ElasticMode.UPDATE); return byId; }

Target:
public T createHosted(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "The Docker registry (Tools only)") @QueryParam("registry") String registry, @ApiParam(value = "The repository name", required = true) @QueryParam("name") String name, @ApiParam(value = "The descriptor type (Workflows only)") @QueryParam("descriptorType") String descriptorType, @ApiParam(value = "The Docker namespace (Tools only)") @QueryParam("namespace") String namespace, @ApiParam(value = "Optional entry name (Tools only)") @QueryParam("entryName") String entryName) { final long currentCount = getEntryDAO().countAllHosted(user.getId()); final int limit = user.getHostedEntryCountLimit() != null ? user.getHostedEntryCountLimit() : calculatedEntryLimit; if (currentCount >= limit) { throw new CustomWebApplicationException("You have " + currentCount + " workflows which is at the current limit of " + limit, HttpStatus.SC_PAYMENT_REQUIRED); } DescriptorLanguage convertedDescriptorType = checkType(descriptorType); Registry convertedRegistry = checkRegistry(registry); T entry = getEntry(user, convertedRegistry, name, convertedDescriptorType, namespace, entryName); checkForDuplicatePath(entry); long l = getEntryDAO().create(entry); T byId = getEntryDAO().findById(l); elasticManager.handleIndexUpdate(byId, ElasticMode.UPDATE); return byId; }