auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private WorkspaceImpl doCreateWorkspace(WorkspaceConfig config, Account account, Map<String, String> attributes, boolean isTemporary) throws NotFoundException, ServerException, ConflictException { final WorkspaceImpl workspace = WorkspaceImpl.builder() .generateId() .setConfig(config) .setAccount(account) .setAttributes(attributes) .setTemporary(isTemporary) .build(); SshPairImpl sshPair = this.sshManager.generatePair(EnvironmentContext.getCurrent().getSubject().getUserId(), "workspace", workspace.getId()); workspace.getAttributes().put(CREATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.create(workspace); LOG.info("Workspace '{}:{}' with id '{}' created by user '{}'", account.getName(), workspace.getConfig().getName(), workspace.getId(), sessionUserNameOr("undefined")); eventService.publish(new WorkspaceCreatedEvent(workspace)); return workspace; }

Target:
private WorkspaceImpl doCreateWorkspace(WorkspaceConfig config, Account account, Map<String, String> attributes, boolean isTemporary) throws NotFoundException, ServerException, ConflictException { final WorkspaceImpl workspace = WorkspaceImpl.builder() .generateId() .setConfig(config) .setAccount(account) .setAttributes(attributes) .setTemporary(isTemporary) .build(); workspace.getAttributes().put(CREATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.create(workspace); LOG.info("Workspace '{}:{}' with id '{}' created by user '{}'", account.getName(), workspace.getConfig().getName(), workspace.getId(), sessionUserNameOr("undefined")); eventService.publish(new WorkspaceCreatedEvent(workspace)); return workspace; }
Source:
protected void okPressed() { IStructuredSelection selection = (IStructuredSelection) listViewer .getSelection(); setResult(selection.toList()); super.okPressed(); }

Target:
protected void okPressed() { IStructuredSelection selection = listViewer.getStructuredSelection(); setResult(selection.toList()); super.okPressed(); }
Source:
public static synchronized BlockCacheManager getClientInstance(AccumuloConfiguration conf) throws Exception { if (null == manager) { String impl = conf.get(Property.TSERV_CACHE_FACTORY_IMPL); Class<? extends BlockCacheManager> clazz = Class.forName(impl).asSubclass(BlockCacheManager.class); manager = (BlockCacheManager) clazz.newInstance(); LOG.info("Created new block cache factory of type: {}", clazz.getSimpleName()); } return manager; }

Target:
public static synchronized BlockCacheManager getClientInstance(AccumuloConfiguration conf) throws Exception { String impl = conf.get(Property.TSERV_CACHE_MANAGER_IMPL); Class<? extends BlockCacheManager> clazz = Class.forName(impl).asSubclass(BlockCacheManager.class); LOG.info("Created new block cache factory of type: {}", clazz.getSimpleName()); return (BlockCacheManager) clazz.newInstance(); }
Source:
private static void writeDataToFile(String data, String filePath) throws IOException { File f = new File(filePath); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileWriter fstream = new FileWriter(filePath); try (BufferedWriter out = new BufferedWriter(fstream)) { out.write(data); } }

Target:
private static void writeDataToFile(String data, String filePath) throws IOException { File f = new File(filePath); if (!f.exists()) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try (BufferedWriter out = new BufferedWriter(new FileWriter(filePath))) { out.write(data); } }
Source:
private <T> CompletableFuture<T> executeCommandAsyncWithInjectedTx(InvocationContext ctx, VisitableCommand command) { CompletableFuture<T> cf; final Transaction implicitTransaction; try { implicitTransaction = transactionManager.suspend(); assert implicitTransaction != null; cf = doInvokeAsync(ctx, command); } catch (SystemException e) { throw new CacheException("Cannot suspend implicit transaction", e); } catch (Throwable e) { tryRollback(); throw e; } return CompletionStages.continueOnExecutor(cf.handleAsync((result, throwable) -> { if (throwable != null) { try { implicitTransaction.rollback(); } catch (SystemException e) { log.trace("Could not rollback", e); throwable.addSuppressed(e); } throw CompletableFutures.asCompletionException(throwable); } try { implicitTransaction.commit(); } catch (Exception e) { log.couldNotCompleteInjectedTransaction(e); throw CompletableFutures.asCompletionException(e); } return result; }, blockingExecutor), nonBlockingExecutor, ctx).toCompletableFuture(); }

Target:
private <T> CompletableFuture<T> executeCommandAsyncWithInjectedTx(InvocationContext ctx, VisitableCommand command) { CompletableFuture<T> cf; final Transaction implicitTransaction; try { implicitTransaction = transactionManager.suspend(); assert implicitTransaction != null; cf = doInvokeAsync(ctx, command); } catch (SystemException e) { throw new CacheException("Cannot suspend implicit transaction", e); } catch (Throwable e) { tryRollback(); throw e; } return CompletionStages.continueOnExecutor(cf.handleAsync((result, throwable) -> { if (throwable != null) { try { implicitTransaction.rollback(); } catch (SystemException e) { log.trace("Could not rollback", e); throwable.addSuppressed(e); } throw CompletableFutures.asCompletionException(throwable); } try { implicitTransaction.commit(); } catch (Exception e) { log.couldNotCompleteInjectedTransaction(e); throw CompletableFutures.asCompletionException(e); } return result; }, blockingExecutor), nonBlockingExecutor, ctx.getLockOwner()).toCompletableFuture(); }
Source:
private boolean isSelfSigned(X509Certificate[] chain) { if(chain[0].getIssuerX500Principal().getName().equals(chain[0].getSubjectX500Principal().getName())){ return true; } else { return false; } }

Target:
private boolean isSelfSigned(X509Certificate[] chain) { return chain[0].getIssuerX500Principal().getName().equals(chain[0].getSubjectX500Principal().getName()) && chain.length == 1; }
Source:
private void updateModifiedInterfaces() { List<VdsNetworkInterface> nicsForUpdate = prepareNicsForUpdate(); List<Guid> updateNicsIds = Entities.getIds(nicsForUpdate); if (!nicsForUpdate.isEmpty()) { interfaceDao.massClearNetworkFromNics(updateNicsIds); interfaceDao.massUpdateInterfacesForVds(getNicsForUpdate()); } }

Target:
private void updateModifiedInterfaces() { List<VdsNetworkInterface> nicsForUpdate = getNicsForUpdate(); List<Guid> updateNicsIds = Entities.getIds(nicsForUpdate); if (!nicsForUpdate.isEmpty()) { interfaceDao.massClearNetworkFromNics(updateNicsIds); interfaceDao.massUpdateInterfacesForVds(nicsForUpdate); } }
Source:
public String getName() { return name; }

Target:
public String getName() { return "kudu"; }
Source:
public List<? extends Module> getJacksonModules() { return Arrays.<Module> asList( new SimpleModule("ArrayOfDoublesSketchModule").registerSubtypes( new NamedType(ArrayOfDoublesSketchAggregatorFactory.class, ARRAY_OF_DOUBLES_SKETCH), new NamedType(ArrayOfDoublesSketchToEstimatePostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_TO_ESTIMATE_POST_AGG), new NamedType(ArrayOfDoublesSketchToEstimateAndBoundsPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_TO_ESTIMATE_AND_BOUNDS_POST_AGG), new NamedType(ArrayOfDoublesSketchToNumEntriesPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_TO_NUM_ENTRIES_POST_AGG), new NamedType(ArrayOfDoublesSketchToMeansPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_TO_MEANS_POST_AGG), new NamedType(ArrayOfDoublesSketchToVariancesPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_TO_VARIANCES_POST_AGG), new NamedType(ArrayOfDoublesSketchToQuantilesSketchPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_TO_QUANTILES_SKETCH_POST_AGG), new NamedType(ArrayOfDoublesSketchSetOpPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_SET_OP_POST_AGG), new NamedType(ArrayOfDoublesSketchTTestPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_T_TEST_POST_AGG), new NamedType(ArrayOfDoublesSketchToStringPostAggregator.class, ARRAY_OF_DOUBLES_SKETCH_TO_STRING_POST_AGG)) .addSerializer(ArrayOfDoublesSketch.class, new ArrayOfDoublesSketchJsonSerializer())); }

Target:
public List<? extends Module> getJacksonModules() { return Arrays.<Module>asList( new SimpleModule("ArrayOfDoublesSketchModule").registerSubtypes( new NamedType( ArrayOfDoublesSketchAggregatorFactory.class, ARRAY_OF_DOUBLES_SKETCH ), new NamedType( ArrayOfDoublesSketchToEstimatePostAggregator.class, "arrayOfDoublesSketchToEstimate" ), new NamedType( ArrayOfDoublesSketchToEstimateAndBoundsPostAggregator.class, "arrayOfDoublesSketchToEstimateAndBounds" ), new NamedType( ArrayOfDoublesSketchToNumEntriesPostAggregator.class, "arrayOfDoublesSketchToNumEntries" ), new NamedType( ArrayOfDoublesSketchToMeansPostAggregator.class, "arrayOfDoublesSketchToMeans" ), new NamedType( ArrayOfDoublesSketchToVariancesPostAggregator.class, "arrayOfDoublesSketchToVariances" ), new NamedType( ArrayOfDoublesSketchToQuantilesSketchPostAggregator.class, "arrayOfDoublesSketchToQuantilesSketch" ), new NamedType( ArrayOfDoublesSketchSetOpPostAggregator.class, "arrayOfDoublesSketchSetOp" ), new NamedType( ArrayOfDoublesSketchTTestPostAggregator.class, "arrayOfDoublesSketchTTest" ), new NamedType( ArrayOfDoublesSketchToStringPostAggregator.class, "arrayOfDoublesSketchToString" ) ).addSerializer(ArrayOfDoublesSketch.class, new ArrayOfDoublesSketchJsonSerializer()) ); }
Source:
public void shouldMarkPatientDeadSuccessfully() { MarkPatientDeadPageController markPatientDeadPageController = new MarkPatientDeadPageController(); markPatientDeadPageController.post(concept.getUuid(), true, date, patient.getUuid().toString()); Assert.assertEquals(patient.getDead(), true); Assert.assertEquals(patient.getCauseOfDeath(), concept); }

Target:
public void shouldMarkPatientDeadSuccessfully() { MarkPatientDeadPageController markPatientDeadPageController = new MarkPatientDeadPageController(); markPatientDeadPageController.post(concept.getUuid(), true, dateOfDeath, patient.getUuid()); Assert.assertEquals(patient.getDead(), true); Assert.assertEquals(patient.getCauseOfDeath(), concept); }
Source:
public void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = ServiceAccountCredentialsTest .writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); File serviceAccountFile = File.createTempFile("service_account", ".json"); serviceAccountFile.deleteOnExit(); String serviceAccountPath = serviceAccountFile.getPath(); testProvider.addFile(serviceAccountPath, serviceAccountStream); testProvider.setEnv( DefaultCredentialsProvider.CREDENTIAL_ENV_VAR, serviceAccountPath); GoogleCredentials defaultCredentials = testProvider.getDefaultCredentials(transportFactory); assertNotNull(defaultCredentials); defaultCredentials = defaultCredentials.createScoped(SCOPES); Map<String, List<String>> metadata = defaultCredentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); }

Target:
public void getDefaultCredentials_envServiceAccount_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = ServiceAccountCredentialsTest .writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); TestDefaultCredentialsProvider testProvider = new TestDefaultCredentialsProvider(); String serviceAccountPath = tempFilePath("service_account.json"); testProvider.addFile(serviceAccountPath, serviceAccountStream); testProvider.setEnv( DefaultCredentialsProvider.CREDENTIAL_ENV_VAR, serviceAccountPath); GoogleCredentials defaultCredentials = testProvider.getDefaultCredentials(transportFactory); assertNotNull(defaultCredentials); defaultCredentials = defaultCredentials.createScoped(SCOPES); Map<String, List<String>> metadata = defaultCredentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); }
Source:
default Tuple2<Seq<K>, Seq<V>> unzip() { return this.unzip(Function.identity()); }

Target:
default Tuple2<Seq<K>, Seq<V>> unzip() { return unzip(Function.identity()); }
Source:
public FormValidation doCheckTargetLogIntakeURL(@QueryParameter("targetLogIntakeURL") final String targetLogIntakeURL) { if (StringUtils.isNotBlank(targetApiURL) && !DatadogHttpClient.validateTargetURL(targetLogIntakeURL) && collectBuildLogs) { return FormValidation.error("The field must be configured in the form <http|https>://<url>/"); } return FormValidation.ok("Valid URL"); }

Target:
public FormValidation doCheckTargetLogIntakeURL(@QueryParameter("targetLogIntakeURL") final String targetLogIntakeURL) { if (!validateURL(targetLogIntakeURL) && collectBuildLogs) { return FormValidation.error("The field must be configured in the form <http|https>://<url>/"); } return FormValidation.ok("Valid URL"); }
Source:
protected SChannelOutput(final SynchronousQueue<Object> cell, final SChannel channel) { this.cell = cell; this.channel = channel; if (VmSettings.ACTOR_TRACING | VmSettings.REPLAY) { numWrites = new AtomicInteger(0); } else { numWrites = null; } }

Target:
protected SChannelOutput(final SynchronousQueue<Object> cell, final SChannel channel) { this.cell = cell; this.channel = channel; }
Source:
Evaluator( final ObjectMapper mapper, final AsyncTaskExecutor asyncTaskExecutor, final long timeoutLength) { this.mapper = mapper; this.asyncTaskExecutor = asyncTaskExecutor; this.timeoutLength = timeoutLength; }

Target:
protected Evaluator( final ObjectMapper mapper, final AsyncTaskExecutor asyncTaskExecutor, final long timeoutLength ) { this.mapper = mapper; this.asyncTaskExecutor = asyncTaskExecutor; this.timeoutLength = timeoutLength; }
Source:
public Set<java.util.Map.Entry<String, Object>> entrySet() { return new AbstractSet<Map.Entry<String,Object>>() { @Override public Iterator<Entry<String, Object>> iterator() { Iterator<Entry<String,Object>> iterator = vars.entrySet().iterator(); return new Iterator<Entry<String,Object>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<String, Object> next() { Entry<String,Object> entry = iterator.next(); return new Entry<String,Object>() { @Override public String getKey() { return entry.getKey(); } @Override public Object getValue() { return resolve(entry.getValue()); } @Override public Object setValue(Object value) { Object previous = entry.setValue(value); return resolve(previous); } }; } }; } @Override public int size() { return vars.size(); } }; }

Target:
public Set<Map.Entry<String, Object>> entrySet() { return new AbstractSet<Map.Entry<String,Object>>() { @Override public Iterator<Entry<String, Object>> iterator() { Iterator<Entry<String,Object>> iterator = vars.entrySet().iterator(); return new Iterator<Entry<String,Object>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<String, Object> next() { Entry<String,Object> entry = iterator.next(); return new Entry<String,Object>() { @Override public String getKey() { return entry.getKey(); } @Override public Object getValue() { return resolve(entry.getValue()); } @Override public Object setValue(Object value) { Object previous = entry.setValue(value); return resolve(previous); } }; } }; } @Override public int size() { return vars.size(); } }; }
Source:
public static boolean writeRecoveryJob(final RecoveryJob job) { try { final File file; if(job.getJobType() == BulkJobType.GET_BULK) { file = createGetFile(job.getId().toString()); } else { file = createPutFile(job.getId().toString()); } try (BufferedWriter writer = com.google.common.io.Files.newWriter(file, Charset.forName("utf-8"))) { writer.write(JsonMapper.toJson(job)); } catch (final Exception inner) { throw inner; } return true; } catch (final IOException e) { LOG.error("Could not create recovery file", e); return false; } }

Target:
public static boolean writeRecoveryJob(final RecoveryJob job) { try { final File file; if(job.getJobType() == BulkJobType.GET_BULK) { file = createGetFile(job.getId().toString()); } else { file = createPutFile(job.getId().toString()); } try (final BufferedWriter writer = com.google.common.io.Files.newWriter(file, Charset.forName("utf-8"))) { writer.write(JsonMapper.toJson(job)); } catch (final Exception inner) { throw inner; } return true; } catch (final IOException e) { LOG.error("Could not create recovery file", e); return false; } }
Source:
public int compare(Team team1, Team team2) { if(team1==null || team2 == null) { return -1; } int skillCompare = compare(team1.getTeamSkillLevel(), team2.getTeamSkillLevel()); return skillCompare !=0 ? skillCompare : 0; }

Target:
public int compare(Team team1, Team team2) { if(team1 == null && team2==null) { return 0; } if(team1==null) { return -1; } if(team2==null) { return 1; } int skillCompare = compare(team1.getTeamSkillLevel(), team2.getTeamSkillLevel()); return skillCompare; }
Source:
public CompletableFuture<Boolean> thenMutate(RowMutations mutation) { preCheck(); return RawAsyncTableImpl.this.<Boolean> newCaller(row, mutation.getMaxPriority(), rpcTimeoutNs) .action((controller, loc, stub) -> RawAsyncTableImpl.this.mutateRow(controller, loc, stub, mutation, (rn, rm) -> RequestConverter.buildMutateRequest(rn, row, family, qualifier, op, value, null, timeRange, rm), resp -> ((CheckAndMutateResult) resp).isSuccess())) .call(); }

Target:
public CompletableFuture<Boolean> thenMutate(RowMutations mutation) { preCheck(); return RawAsyncTableImpl.this.<Boolean> newCaller(row, mutation.getMaxPriority(), rpcTimeoutNs) .action((controller, loc, stub) -> RawAsyncTableImpl.this.mutateRow(controller, loc, stub, mutation, (rn, rm) -> RequestConverter.buildMutateRequest(rn, row, family, qualifier, op, value, null, timeRange, rm), CheckAndMutateResult::isSuccess)) .call(); }
Source:
public int hashCode() { if (value.hasArray()) { return Binary.hashCode(value.array(), value.arrayOffset() + offset, length); } byte[] bytes = getBytes(); return Binary.hashCode(bytes, 0, bytes.length); }

Target:
public int hashCode() { if (value.hasArray()) { return Binary.hashCode(value.array(), value.arrayOffset() + offset, length); } else { return Binary.hashCode(value, offset, length); } }
Source:
public List<RichMember> getSponsoredMembers(PerunSession sess, Vo vo) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); Utils.notNull(vo, "vo"); if(!(AuthzResolver.isAuthorized(sess, Role.REGISTRAR)||AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo))) { throw new PrivilegeException(sess, "getSponsoredMembers must be called by REGISTRAR or VOADMIN"); } return membersManagerBl.convertMembersToRichMembers(sess, membersManagerBl.getSponsoredMembers(sess, vo)); }

Target:
public List<RichMember> getSponsoredMembers(PerunSession sess, Vo vo) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); Utils.notNull(vo, "vo"); if(!(AuthzResolver.isAuthorized(sess, Role.REGISTRAR)||AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo))) { throw new PrivilegeException(sess, "getSponsoredMembers"); } return membersManagerBl.convertMembersToRichMembers(sess, membersManagerBl.getSponsoredMembers(sess, vo)); }
Source:
public QueryResult convert(final ResponseBody value) throws IOException { try (InputStream is = value.byteStream()) { MessagePackTraverser traverser = new MessagePackTraverser(); for (QueryResult queryResult : traverser.traverse(is)) { return queryResult; } return null; } }

Target:
public QueryResult convert(final ResponseBody value) throws IOException { try (InputStream is = value.byteStream()) { MessagePackTraverser traverser = new MessagePackTraverser(); return traverser.parse(is); } }
Source:
public void testGetAllLoadBalancers() throws Exception { MockWebServer server = mockWebServer(); server.enqueue(new MockResponse().setBody(payloadFromResource("/loadbalancer/loadbalancers.xml"))); ProfitBricksApi pbApi = api(server.getUrl(rootUrl)); LoadBalancerApi api = pbApi.loadBalancerApi(); try { List<LoadBalancer> loadBalancerList = api.getAllLoadBalancers(); assertRequestHasCommonProperties(server.takeRequest()); assertNotNull(loadBalancerList); assertTrue(loadBalancerList.size() == 2); } finally { pbApi.close(); server.shutdown(); } }

Target:
public void testGetAllLoadBalancers() throws Exception { MockWebServer server = mockWebServer(); server.enqueue(new MockResponse().setBody(payloadFromResource("/loadbalancer/loadbalancers.xml"))); ProfitBricksApi pbApi = api(server.getUrl(rootUrl)); LoadBalancerApi api = pbApi.loadBalancerApi(); try { List<LoadBalancer> loadBalancerList = api.getAllLoadBalancers(); assertRequestHasCommonProperties(server.takeRequest(), "<ws:getAllLoadBalancers/>"); assertNotNull(loadBalancerList); assertTrue(loadBalancerList.size() == 2); } finally { pbApi.close(); server.shutdown(); } }
Source:
public void scikitLearnExample() { Map<Integer, double[]> data = new HashMap<>(); double one = 1.; double two = 2.; data.put(0, new double[] {one, -1, 1}); data.put(2, new double[] {one, -2, -1}); data.put(3, new double[] {one, -3, -2}); data.put(4, new double[] {two, 1, 1}); data.put(5, new double[] {two, 2, 1}); data.put(6, new double[] {two, 3, 2}); GaussianNaiveBayesTrainer trainer = new GaussianNaiveBayesTrainer(); GaussianNaiveBayesModel model = trainer.fit( new LocalDatasetBuilder<>(data, 2), (k, v) -> VectorUtils.of(Arrays.copyOfRange(v, 1, v.length)), (k, v) -> v[0] ); Vector observation = new DenseVector(new double[] {-0.8, -1}); Assert.assertEquals(one, model.apply(observation), PRECISION); }

Target:
public void scikitLearnExample() { Map<Integer, double[]> data = new HashMap<>(); double one = 1.; double two = 2.; data.put(0, new double[] {one, -1, 1}); data.put(2, new double[] {one, -2, -1}); data.put(3, new double[] {one, -3, -2}); data.put(4, new double[] {two, 1, 1}); data.put(5, new double[] {two, 2, 1}); data.put(6, new double[] {two, 3, 2}); GaussianNaiveBayesTrainer trainer = new GaussianNaiveBayesTrainer(); GaussianNaiveBayesModel model = trainer.fit( new LocalDatasetBuilder<>(data, 2), (k, v) -> VectorUtils.of(Arrays.copyOfRange(v, 1, v.length)), (k, v) -> v[0] ); Vector observation = VectorUtils.of(-0.8, -1); Assert.assertEquals(one, model.apply(observation), PRECISION); }
Source:
public AccountService getAccountService() { logger.info("Starting an InMemoryUnknownAccountService."); long startTime = System.currentTimeMillis(); AccountService res = new InMemoryUnknownAccountService(); logger.info("InMemoryUnknownAccountService started, took ms", System.currentTimeMillis() - startTime); return res; }

Target:
public AccountService getAccountService() { logger.info("Starting an InMemoryUnknownAccountService."); return new InMemoryUnknownAccountService(); }
Source:
public static IsolationMethod getIsolationMethod(String prfx) { IsolationMethod rc = null; for (IsolationMethod method: registeredIsolationMethods) { if (method.provider.equals(prfx)) { rc = method; if(! rc.getProvider().equals(UNKNOWN_PROVIDER)) { break; } } } return rc; }

Target:
public static IsolationMethod getIsolationMethod(String prfx) throws IsolationMethodNotRegistered { IsolationMethod rc = null; for (IsolationMethod method: registeredIsolationMethods) { if (method.methodPrefix.equals(prfx)) { rc = method; if(! rc.getProvider().equals(UNKNOWN_PROVIDER)) { break; } } } if (rc == null) { throw new IsolationMethodNotRegistered("No registration of prefix '" + prfx + "' found."); } return rc; }
Source:
private void setShareIntent() { if (mShareActionProvider != null) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, mlogs); mShareActionProvider.setShareIntent(shareIntent); } }

Target:
private void setShareIntent() { if (mShareActionProvider != null) { Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_STREAM, DataChangeLogger.getLogFilesUri()); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.commcare_logs)); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); mShareActionProvider.setShareIntent(shareIntent); } }
Source:
public boolean allowedRequest(ReconnectRequest req) { boolean allowed = false; if (req instanceof ReconnectRequest) { ReconnectRequest reconnectRequest = (ReconnectRequest) req; Object element = ((View) reconnectRequest.getConnectionEditPart().getModel()).getElement(); if (element instanceof Message) { MessageEnd oppositeMessageEnd = null; Message messageElement = (Message) element; MessageEnd sendEvent = messageElement.getSendEvent(); MessageEnd recvEvent = messageElement.getReceiveEvent(); if (RECONNECTION_TARGET_TYPE.equals(reconnectRequest.getType())) { oppositeMessageEnd = sendEvent; } else if (RECONNECTION_SOURCE_TYPE.equals(reconnectRequest.getType())) { oppositeMessageEnd = recvEvent; } InteractionFragment targetContainer = SequenceUtil.findInteractionFragmentContainerAt(reconnectRequest.getLocation(), getHost().getParent()); if (null != oppositeMessageEnd) { allowed = (targetContainer == oppositeMessageEnd.eContainer()); } } } return allowed; }

Target:
public boolean allowedRequest(ReconnectRequest req) { boolean allowed = false; if (req instanceof ReconnectRequest) { ReconnectRequest reconnectRequest = (ReconnectRequest) req; Object element = null; if (null != reconnectRequest.getConnectionEditPart() && reconnectRequest.getConnectionEditPart().getModel() instanceof View) { element = ((View) reconnectRequest.getConnectionEditPart().getModel()).getElement(); } if (element instanceof Message) { MessageEnd oppositeMessageEnd = null; Message messageElement = (Message) element; MessageEnd sendEvent = messageElement.getSendEvent(); MessageEnd recvEvent = messageElement.getReceiveEvent(); if (RECONNECTION_TARGET_TYPE.equals(reconnectRequest.getType())) { oppositeMessageEnd = sendEvent; } else if (RECONNECTION_SOURCE_TYPE.equals(reconnectRequest.getType())) { oppositeMessageEnd = recvEvent; } InteractionFragment targetContainer = SequenceUtil.findInteractionFragmentContainerAt(reconnectRequest.getLocation(), getHost().getParent()); if (null != oppositeMessageEnd) { allowed = (targetContainer == oppositeMessageEnd.eContainer()); } } } return allowed; }
Source:
public CifsWinRmConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assertNotOldStyleWindowsDomain(username, CIFS_PROTOCOL, cifsConnectionType); }

Target:
public CifsWinRmConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper); }
Source:
public List<String> getNames() { List<String> names = Lists.newArrayList(name); names.addAll(alternativeNames); return names; }

Target:
public List<String> getNames() { List<String> names = Lists.newArrayListWithCapacity(alternativeNames.size() +1); names.add(name); names.addAll(alternativeNames); return names; }
Source:
private void visitParameterDef(DetailAST parameterDef) { final DetailAST grandParentAST = parameterDef.getParent().getParent(); if (grandParentAST.getType() == TokenTypes.METHOD_DEF && isCheckedMethod(grandParentAST) && isVerifiable(grandParentAST) && !AnnotationUtil.containsAnnotation(grandParentAST, "Override")) { checkClassName(parameterDef); } }

Target:
private void visitParameterDef(DetailAST parameterDef) { final DetailAST grandParentAST = parameterDef.getParent().getParent(); if (grandParentAST.getType() == TokenTypes.METHOD_DEF && isCheckedMethod(grandParentAST)) { checkClassName(parameterDef); } }
Source:
private Object createObjectFromMap(String name) { final String packageName = SHORT_TO_FULL_MODULE_NAMES.get(name); Object instance = null; if (packageName == null) { final String nameCheck = name + CHECK_SUFFIX; final String packageNameWithSuffix = SHORT_TO_FULL_MODULE_NAMES.get(nameCheck); if (packageNameWithSuffix != null) { instance = createObject(packageNameWithSuffix); } } else { instance = createObject(packageName); } return instance; }

Target:
private Object createObjectFromMap(String name) { final String fullModuleName = NAME_TO_FULL_MODULE_NAME.get(name); Object instance = null; if (fullModuleName == null) { final String fullCheckModuleName = NAME_TO_FULL_MODULE_NAME.get(name + CHECK_SUFFIX); if (fullCheckModuleName != null) { instance = createObject(fullCheckModuleName); } } else { instance = createObject(fullModuleName); } return instance; }
Source:
private SelectionListener downloadButtonListener(Composite parent) { return new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { MenuManager mgr = new MenuManager(); mgr.add(new CherryPickRevision(fChangeInfo.getUserSelectedRevision(), fGerritClient)); mgr.add(new CheckoutRevision(fChangeInfo.getUserSelectedRevision(), fGerritClient)); mgr.createContextMenu(parent).setVisible(true); ActiveWorkspaceRevision.getInstance().enableQuickDiff(getSite(), fGerritClient, fChangeInfo); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; }

Target:
private SelectionListener downloadButtonListener(Composite parent) { return new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { MenuManager mgr = new MenuManager(); mgr.add(new CherryPickRevision(fChangeInfo.getUserSelectedRevision(), fGerritClient)); mgr.add(new CheckoutRevision(fChangeInfo.getUserSelectedRevision(), fGerritClient)); mgr.createContextMenu(parent).setVisible(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; }
Source:
private static boolean isJavaIdentifier(String s) { if (s.length() == 0) { return false; } int start = s.codePointAt(0); if (!Character.isJavaIdentifierStart(start)) { return false; } int charCount = Character.charCount(start); for (int i = charCount; i < s.length(); i += charCount) { int codePoint = s.codePointAt(i); if (!Character.isJavaIdentifierPart(codePoint)) { return false; } } return true; }

Target:
private static boolean isJavaIdentifier(String s) { if (s.isEmpty()) { return false; } int start = s.codePointAt(0); if (!Character.isJavaIdentifierStart(start)) { return false; } int charCount = Character.charCount(start); for (int i = charCount; i < s.length(); i += charCount) { int codePoint = s.codePointAt(i); if (!Character.isJavaIdentifierPart(codePoint)) { return false; } } return true; }
Source:
public void testSerDes() throws Exception { if (version == BLOB_ID_V3) { return; } BlobId blobId = new BlobId(version, referenceType, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, referenceIsEncrypted); deserializeBlobIdAndAssert(version, blobId.getID(), referenceIsEncrypted); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertTrue(blobId.equals(blobIdSerDed)); assertTrue(blobIdSerDed.equals(blobId)); assertEquals(blobId.hashCode(), blobIdSerDed.hashCode()); assertEquals(0, blobId.compareTo(blobIdSerDed)); assertEquals(0, blobIdSerDed.compareTo(blobId)); }

Target:
public void testSerDes() throws Exception { BlobId blobId = new BlobId(version, referenceType, referenceDatacenterId, referenceAccountId, referenceContainerId, referencePartitionId, referenceIsEncrypted); deserializeBlobIdAndAssert(version, blobId.getID()); BlobId blobIdSerDed = new BlobId(new DataInputStream(new ByteArrayInputStream(blobId.toBytes())), referenceClusterMap); assertTrue(blobId.equals(blobIdSerDed)); assertTrue(blobIdSerDed.equals(blobId)); assertEquals(blobId.hashCode(), blobIdSerDed.hashCode()); assertEquals(0, blobId.compareTo(blobIdSerDed)); assertEquals(0, blobIdSerDed.compareTo(blobId)); }
Source:
private GlusterGeoRepSession getGeoRepSession() { if (getParameters().getGeoRepSessionId() != null) { return geoRepDao.getById(getParameters().getGeoRepSessionId()); } return null; }

Target:
private GlusterGeoRepSession getGeoRepSession() { return geoRepDao.getById(getParameters().getGeoRepSessionId()); }
Source:
private String getPluginKeyAndResourcePath(HttpServletRequest request) { return StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + request.getServletPath() + "/"); }

Target:
private static String getPluginKeyAndResourcePath(HttpServletRequest request) { return StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + request.getServletPath() + "/"); }
Source:
public Integer findVersionNumber(ArticleIdentity article, int revisionNumber) { String articleKey = article.getIdentifier(); String uuid = findRevisionUuid(articleKey, revisionNumber); if (uuid == null) { throw entityNotFound("Revision doesn't exist: " + article); } RepoCollectionMetadata collectionMetadata; try { collectionMetadata = contentRepoService.getCollection(RepoVersion.create(articleKey, uuid)); } catch(NotFoundException nfe) { throw entityNotFound(nfe.getMessage() + ": " + articleKey); } return collectionMetadata.getVersionNumber().getNumber(); }

Target:
public int findVersionNumber(ArticleIdentity article, int revisionNumber) { String articleKey = article.getIdentifier(); String uuid = findRevisionUuid(articleKey, revisionNumber); if (uuid == null) { throw reportNotFound(article, "article revision UUID"); } try { return contentRepoService.getCollection(RepoVersion.create(articleKey, uuid)).getVersionNumber().getNumber(); } catch(NotFoundException nfe) { throw reportNotFound(article, "collection", nfe); } }
Source:
public ArchiveContentEncodingDetector(String extension) { Assert.isLegal(extension != null && !extension.isEmpty(), "extension can't be empty"); this.extension = extension; }

Target:
public ArchiveContentEncodingDetector(String extension) { Assert.isLegal(extension != null && !extension.isEmpty() && !extension.endsWith("/"), "extension can't be empty or /"); this.extension = extension; }
Source:
protected void addProcesses(IProcess[] processes) { if (processes != null) { for (IProcess processe : processes) { addProcess(processe); fireChanged(); } } }

Target:
protected void addProcesses(IProcess[] processes) { if (processes != null) { for (IProcess process : processes) { addProcess(process); fireChanged(); } } }
Source:
public void reopenAccount(String newPassword) { clearDisableFlagButton.click(); waitForTextToBePresentInElementByElement( statusMessage, "Successfully removed disabled bit for account" ); newPasswordRadio.click(); newPasswordField.sendKeys(newPassword); newPasswordField.submit(); }

Target:
public void reopenAccount(String newPassword) { newPasswordRadio.click(); newPasswordField.sendKeys(newPassword); newPasswordField.submit(); clearDisableFlagButton.click(); PageObjectLogging.log( "reopenAccount", "account reopened", true ); }
Source:
public Pair<Integer, Boolean> getFormDefIdForRecord(SqlStorage<FormDefRecord> formDefRecordStorage, int formRecordId, FormEntryInstanceState instanceState) throws FormEntryActivity.FormQueryException { Boolean isInstanceReadOnly = false; FormRecord formRecord = FormRecord.getFormRecord(formRecordStorage, formRecordId); mFormRecordPath = formRecord.getFilePath(); if (FormRecord.STATUS_COMPLETE.equals(formRecord.getStatus())) { if (!Boolean.parseBoolean(formRecord.getCanEditWhenComplete())) { isInstanceReadOnly = true; } } Vector<FormDefRecord> formDefRecords = FormDefRecord.getFormDefsByJrFormId(formDefRecordStorage, formRecord.getXmlns()); if (formDefRecords.size() == 1) { FormDefRecord formDefRecord = formDefRecords.get(0); instanceState.setFormDefPath(formDefRecord.getFilePath()); return new Pair<>(formDefRecord.getID(), isInstanceReadOnly); } else if (formDefRecords.size() < 1) { throw new FormEntryActivity.FormQueryException("Parent form does not exist"); } else { throw new FormEntryActivity.FormQueryException("More than one possible parent form"); } }

Target:
public Pair<Integer, Boolean> getFormDefIdForRecord(SqlStorage<FormDefRecord> formDefRecordStorage, int formRecordId, FormEntryInstanceState instanceState) throws FormEntryActivity.FormQueryException { Boolean isInstanceReadOnly = false; FormRecord formRecord = FormRecord.getFormRecord(formRecordStorage, formRecordId); mFormRecordPath = formRecord.getFilePath(); if (FormRecord.STATUS_COMPLETE.equals(formRecord.getStatus())) { if (!Boolean.parseBoolean(formRecord.getCanEditWhenComplete())) { isInstanceReadOnly = true; } } Vector<FormDefRecord> formDefRecords = FormDefRecord.getFormDefsByJrFormId(formDefRecordStorage, formRecord.getXmlns()); if (formDefRecords.size() == 1) { FormDefRecord formDefRecord = formDefRecords.get(0); instanceState.setFormDefPath(formDefRecord.getFilePath()); return new Pair<>(formDefRecord.getID(), isInstanceReadOnly); } else if (formDefRecords.size() < 1) { String error = "No XForm definition defined for this form with namespace " + formRecord.getXmlns(); Logger.log(LogTypes.SOFT_ASSERT, error); throw new FormEntryActivity.FormQueryException(error); } else { String error = "More than one XForm definition present for this form with namespace " + formRecord.getXmlns(); Logger.log(LogTypes.SOFT_ASSERT, error); throw new FormEntryActivity.FormQueryException(error); } }
Source:
public void fulfill() { ConfigureMavenRepositoriesWizard mr = openRepositoriesWizard(); for (ToRemoveMavenRepository r : repo.toRemoveRepositories()) { String id = r.ID() + "-" + r.url(); if (r.hasToExists()) { mr.removeRepo(id); } else if (new DefaultTable(new DefaultGroup("Repositories")).containsItem(id)) { mr.removeRepo(id); } } if (repo.toRemoveRepositories().length == 0) mr.removeAllRepos(); closeRepositoriesWizard(); }

Target:
public void fulfill() { ConfigureMavenRepositoriesWizard mr = openRepositoriesWizard(); DefaultTable repoTable = new DefaultTable(new DefaultGroup("Repositories")); for (ToRemoveMavenRepository r : repo.toRemoveRepositories()) { String id = r.ID() + "-" + r.url(); if (r.hasToExists() || repoTable.containsItem(id)) { mr.removeRepo(id); } } if (repo.toRemoveRepositories().length == 0) mr.removeAllRepos(); closeRepositoriesWizard(); }
Source:
public void initialize() throws InternalErrorException { if(perun.isThisPerunReadOnly()) log.debug("Loading authzresolver manager init in readOnly version."); for (Role role: Role.values()) { try { if (0 == jdbc.queryForInt("select count(*) from roles where name=?", role.getRoleName())) { if(perun.isThisPerunReadOnly()) { log.error("One of default role not exists in DB {}.", role); } else { int newId = Utils.getNewId(jdbc, "roles_id_seq"); jdbc.update("insert into roles (id, name) values (?,?)", newId, role.getRoleName()); } } } catch (RuntimeException e) { throw new InternalErrorException(e); } } }

Target:
public void initialize() throws InternalErrorException { if(perun.isPerunReadOnly()) log.debug("Loading authzresolver manager init in readOnly version."); for (Role role: Role.values()) { try { if (0 == jdbc.queryForInt("select count(*) from roles where name=?", role.getRoleName())) { if(perun.isPerunReadOnly()) { throw new InternalErrorException("One of deafult roles not exists in DB - " + role); } else { int newId = Utils.getNewId(jdbc, "roles_id_seq"); jdbc.update("insert into roles (id, name) values (?,?)", newId, role.getRoleName()); } } } catch (RuntimeException e) { throw new InternalErrorException(e); } } }
Source:
public Response glusterServiceStart(Action action) { return doAction(VdcActionType.ManageGlusterService, new GlusterServiceParameters(null, guid, ServiceType.valueOf(action.getGlusterServiceType()), "start"), action); }

Target:
public Response glusterServiceStart(Action action) { String srvcTypeParam = action.getGlusterServiceType(); if(!isValidServiceType(srvcTypeParam)) { return null; } return doAction(VdcActionType.ManageGlusterService, new GlusterServiceParameters(null, guid, ServiceType.valueOf(srvcTypeParam), "start"), action); }
Source:
private void executeBuild(final String type, final String subType) { final String caption = "Build"; workbenchContext_.setBuildInProgress(true); terminalHelper_.warnBusyTerminalBeforeCommand(new Command() { @Override public void execute() { sourceBuildHelper_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { server_.startBuild(type, subType, new SimpleRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean response) { } @Override public void onError(ServerError error) { super.onError(error); workbenchContext_.setBuildInProgress(false); } }); } }, caption); } }, caption, "Terminal jobs will be terminated. Are you sure?"); }

Target:
private void executeBuild(final String type, final String subType) { final String caption = "Build"; terminalHelper_.warnBusyTerminalBeforeCommand(new Command() { @Override public void execute() { workbenchContext_.setBuildInProgress(true); sourceBuildHelper_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { server_.startBuild(type, subType, new SimpleRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean response) { } @Override public void onError(ServerError error) { super.onError(error); workbenchContext_.setBuildInProgress(false); } }); } }, caption); } }, caption, "Terminal jobs will be terminated. Are you sure?"); }
Source:
public BitmapFont generateFont (FreeTypeFontParameter parameter, FreeTypeBitmapFontData data) { generateData(parameter, data); Array<TextureRegion> regions; if (parameter.packer != null) { regions = parameter.packer.getTextureRegions(parameter.minFilter, parameter.magFilter, parameter.genMipMaps); } else { regions = data.regions; } BitmapFont font = new BitmapFont(data, regions, false); font.setOwnsTexture(parameter.packer == null); return font; }

Target:
public BitmapFont generateFont (FreeTypeFontParameter parameter, FreeTypeBitmapFontData data) { generateData(parameter, data); if (data.regions == null && parameter.packer != null) { data.regions = new Array<TextureRegion>(); parameter.packer.updateTextureRegions(data.regions, parameter.minFilter, parameter.magFilter, parameter.genMipMaps, false); } BitmapFont font = new BitmapFont(data, data.regions, false); font.setOwnsTexture(parameter.packer == null); return font; }
Source:
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { if (this.statisticsEnabled) prepares.incrementAndGet(); Object result = invokeNextInterceptorAndVerifyTransaction(ctx, command); if (!ctx.isOriginLocal()) { if (command.isOnePhaseCommit()) { txTable.remoteTransactionCommitted(command.getGlobalTransaction(), false); } else { txTable.remoteTransactionPrepared(command.getGlobalTransaction()); } } return result; }

Target:
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { if (this.statisticsEnabled) prepares.incrementAndGet(); Object result = invokeNextInterceptorAndVerifyTransaction(ctx, command); if (!ctx.isOriginLocal()) { if (command.isOnePhaseCommit()) { txTable.remoteTransactionCommitted(command.getGlobalTransaction(), true); } else { txTable.remoteTransactionPrepared(command.getGlobalTransaction()); } } return result; }
Source:
public ReflServerStateProvider(Logger logger) { Object serverObject = null; MethodHandle isRunning = null; Class<?> nmsClass = ReflUtil.getNMSClass("MinecraftServer"); try { serverObject = nmsClass.getMethod("getServer").invoke(null); isRunning = MethodHandles.lookup().findVirtual(nmsClass, "isRunning", MethodType.methodType(boolean.class)); } catch (Exception e) { logger.severe("Something's gone terribly wrong!"); e.printStackTrace(); logger.severe("Something's gone terribly wrong!"); } nmsServer = serverObject; nmsIsRunning = isRunning; }

Target:
public ReflServerStateProvider(Logger logger) { Object serverObject = null; MethodHandle isRunning = null; Class<?> nmsClass = ReflUtil.getNMSClass("MinecraftServer"); try { serverObject = nmsClass.getMethod("getServer").invoke(null); isRunning = MethodHandles.lookup().findVirtual(nmsClass, "isRunning", MethodType.methodType(boolean.class)); } catch (Exception e) { e.printStackTrace(); } nmsServer = serverObject; nmsIsRunning = isRunning; }
Source:
public boolean equals(Object obj) { if (obj == null || !(obj instanceof FilterPath)) { return false; } FilterPath other = (FilterPath) obj; if (path == null) { return other.path == null; } return path.equals(other.path); }

Target:
public boolean equals(Object obj) { if (obj == null || !(obj instanceof FilterPath)) return false; FilterPath other = (FilterPath) obj; if (path == null) return other.path == null; return path.equals(other.path); }
Source:
protected void initLineModel(KeyValueLineModel keyValueLineModel, String key) { keyValueLineModel.getValue().setIsAvailable(false); keyValueLineModel.getValues().setIsAvailable(false); }

Target:
protected void initLineModel(KeyValueLineModel keyValueLineModel, String key) { }
Source:
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = true; for ( final Object element : list ) { if (element != null && !(element instanceof Boolean)) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not a Boolean")); } else { result &= element != null && element == Boolean.TRUE; } } return FEELFnResult.ofResult( result ); }

Target:
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) { if ( list == null ) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null")); } boolean result = true; boolean containsNull = false; for ( final Object element : list ) { if (element != null && !(element instanceof Boolean)) { return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "an element in the list is not a Boolean")); } else { if (element != null) { result &= (Boolean) element; } else if (!containsNull) { containsNull = true; } } } if (containsNull && result) { return FEELFnResult.ofResult( null ); } else { return FEELFnResult.ofResult( result ); } }
Source:
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String title = request.getParameter("title"); String description = request.getParameter("description"); Part filePart = request.getPart("file[0]"); String fileName = filePart.getSubmittedFileName(); final UserSession session = UserSessionUtil.resumeSession(request); if (session == null) { return; } FileMetadata fileMetadata = SQLSource.interact(new SQLInteractionInterface<FileMetadata>() { @Override public FileMetadata run(Connection connection) throws ServiceException, SQLException { int classId = Integer.parseInt(request.getParameter("class")); return FileMetadata.create(connection, session.getUser(), classId, new Date()); } }); String filePath = FILEPATH_PREFIX + fileMetadata.getCourse() + fileName; saveFile(filePart.getInputStream(), filePath); }

Target:
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String title = request.getParameter("title"); String description = request.getParameter("description"); Part filePart = request.getPart("file[0]"); String fileName = filePart.getSubmittedFileName(); final UserSession session = UserSessionUtil.resumeSession(request); if (session == null) { throw new ServiceException(ServiceStatus.NOT_AUTHENTICATED); } FileMetadata fileMetadata = SQLSource.interact(new SQLInteractionInterface<FileMetadata>() { @Override public FileMetadata run(Connection connection) throws ServiceException, SQLException { int classId = Integer.parseInt(request.getParameter("class")); return FileMetadata.create(connection, session.getUser(), classId, new Date()); } }); String filePath = FILEPATH_PREFIX + fileMetadata.getCourse() + fileName; if (!saveFile(filePart.getInputStream(), filePath, fileName)) { throw new ServiceException(ServiceStatus.SERVER_UPLOAD_ERROR); } }
Source:
public ThrottlingExceptionRoutePolicy(int threshold, long failureWindow, long halfOpenAfter, List<Class<?>> handledExceptions) { this.throttledExceptions = handledExceptions; this.failureWindow = failureWindow; this.halfOpenAfter = halfOpenAfter; this.failureThreshold = threshold; this.keepOpen.set(false); }

Target:
public ThrottlingExceptionRoutePolicy(int threshold, long failureWindow, long halfOpenAfter, List<Class<?>> handledExceptions) { this(threshold, failureWindow, halfOpenAfter, handledExceptions, false); }