auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testPromotionEnvironmentShouldIncludeTargetParameters() throws Exception { String paramName = "param"; InheritanceProjectsPair inheritanceProjectPair = j.createInheritanceProjectDerivedWithBase(); JobPropertyImpl promotion = new JobPropertyImpl(inheritanceProjectPair.getBase()); inheritanceProjectPair.getBase().addProperty(promotion); inheritanceProjectPair.getBase().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); inheritanceProjectPair.getDerived().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); PromotionProcess promo1 = promotion.addProcess("promo1"); promo1.conditions.add(new SelfPromotionCondition(false)); for (ItemListener l : ItemListener.all()) { l.onLoaded(); } String paramValue = "someString"; j.assertBuildStatusSuccess(inheritanceProjectPair.getDerived().scheduleBuild2(0, new Cause.UserCause(), new ParametersAction(new StringParameterValue(paramName, paramValue)))); j.waitUntilNoActivity(); promotion = inheritanceProjectPair.getDerived().getProperty(JobPropertyImpl.class, IMode.INHERIT_FORCED); promo1 = promotion.getItem("promo1"); Promotion pb = promo1.getBuildByNumber(1); assertEquals(paramValue, pb.getEnvironment(TaskListener.NULL).get(paramName, null)); }

Target:
public void testPromotionEnvironmentShouldIncludeTargetParameters() throws Exception { String paramName = "param"; InheritanceProjectsPair inheritanceProjectPair = j.createInheritanceProjectDerivedWithBase(); JobPropertyImpl promotion = new JobPropertyImpl(inheritanceProjectPair.getBase()); inheritanceProjectPair.getBase().addProperty(promotion); inheritanceProjectPair.getBase().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); inheritanceProjectPair.getDerived().addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(paramName, ""))); PromotionProcess promo1 = promotion.addProcess("promo1"); promo1.conditions.add(new SelfPromotionCondition(false)); fireItemListeners(); String paramValue = "someString"; j.assertBuildStatusSuccess(inheritanceProjectPair.getDerived().scheduleBuild2(0, new Cause.UserCause(), new ParametersAction(new StringParameterValue(paramName, paramValue)))); j.waitUntilNoActivity(); promotion = inheritanceProjectPair.getDerived().getProperty(JobPropertyImpl.class, IMode.INHERIT_FORCED); promo1 = promotion.getItem("promo1"); Promotion pb = promo1.getBuildByNumber(1); assertEquals(paramValue, pb.getEnvironment(TaskListener.NULL).get(paramName, null)); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String xAuth = ((HttpServletRequest) request).getHeader("X-Auth-Token"); if (!Strings.isNullOrEmpty(xAuth)) { AuthenticationToken authenticationToken = authenticationTokenRepository.findByToken(xAuth) .orElseThrow(() -> new TokenNotFoundException(xAuth)); if (authenticationToken.isValid()) { User user = authenticationToken.getUser(); SecurityContextHolder.getContext() .setAuthentication(new PreAuthenticatedAuthenticationToken(user, "N/A", user.getAuthorities())); } else { throw new NonceExpiredException("Token expired!"); } } chain.doFilter(request, response); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String xAuth = ((HttpServletRequest) request).getHeader("X-Auth-Token"); if (!Strings.isNullOrEmpty(xAuth)) { AuthenticationToken authenticationToken = extractOptional(authenticationTokenRepository.findByToken(xAuth), response); if (authenticationToken.isValid()) { User user = authenticationToken.getUser(); SecurityContextHolder.getContext() .setAuthentication(new PreAuthenticatedAuthenticationToken(user, "N/A", user.getAuthorities())); } else { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token Expired"); } } chain.doFilter(request, response); }
Source:
private HttpResponse executeRequest(HttpRequestBase request) { try { if (authHeaderValue != null) { request.addHeader("Authorization", authHeaderValue); } logger.info(request.toString()); HttpResponse response = httpClient.execute(request, context); validate(request, response); logger.info(response.getStatusLine().toString()); for(Header h: response.getAllHeaders()){ logger.finer(h.toString()); } return response; } catch (IOException e) { logger.log(Level.SEVERE,"Aborting request",e); request.abort(); throw new ServerException(e); } }

Target:
private HttpResponse executeRequest(HttpRequestBase request) { try { if (authHeaderValue != null) { request.addHeader("Authorization", authHeaderValue); } logger.info(request.toString()); HttpResponse response = httpClient.execute(request, context); validate(request, response); logger.info(response.getStatusLine().toString()); if(logger.isLoggable(Level.FINER)) { for (Header h : response.getAllHeaders()) { logger.finer(h.toString()); } } return response; } catch (IOException e) { logger.log(Level.SEVERE, "Aborting request", e); request.abort(); throw new ServerException(e); } }
Source:
@Override public void onDisplayPreferenceDialog(Preference preference) { final DialogFragment f; if (preference instanceof FontPreference) f = FontPreference.FontPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof ThemePreference) f = ThemePreference.ThemePreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof EditTextPreferenceFix) f = EditTextPreferenceFix.EditTextPreferenceFixFragment.newInstance(preference.getKey()); else if (preference instanceof ClearCertPreference) f = ClearCertPreference.ClearCertPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof RingtonePreferenceFix) { Intent intent = ((RingtonePreferenceFix) preference).makeRingtoneRequestIntent(); startActivityForResult(intent, 0); return; } else { super.onDisplayPreferenceDialog(preference); return; } f.setTargetFragment(this, 0); f.show(getFragmentManager(), FRAGMENT_DIALOG_TAG); }

Target:
@Override public void onDisplayPreferenceDialog(Preference preference) { final DialogFragment f; if (preference instanceof FontPreference) f = FontPreference.FontPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof ThemePreference) f = ThemePreference.ThemePreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof FilePreference) f = FilePreference.FilePreferenceFragment.newInstance(preference.getKey(), PREF_SSH_KEY.equals(preference.getKey()) ? 1 : 2); else if (preference instanceof EditTextPreferenceFix) f = EditTextPreferenceFix.EditTextPreferenceFixFragment.newInstance(preference.getKey()); else if (preference instanceof ClearCertPreference) f = ClearCertPreference.ClearCertPreferenceFragment.newInstance(preference.getKey()); else if (preference instanceof RingtonePreferenceFix) { Intent intent = ((RingtonePreferenceFix) preference).makeRingtoneRequestIntent(); startActivityForResult(intent, 0); return; } else { super.onDisplayPreferenceDialog(preference); return; } f.setTargetFragment(this, 0); f.show(getFragmentManager(), FRAGMENT_DIALOG_TAG); }
Source:
public void shouldPropagateRuntimeException() throws AuthenticationException { final RuntimeException e = new NullPointerException(); when(underlying.authorize(principal, role)).thenThrow(e); expected.expect(CoreMatchers.sameInstance(e)); cached.authorize(principal, role); }

Target:
public void shouldPropagateRuntimeException() throws AuthenticationException { final RuntimeException e = new NullPointerException(); when(underlying.authorize(principal, role)).thenThrow(e); assertThatNullPointerException() .isThrownBy(() -> cached.authorize(principal, role)) .isSameAs(e); }
Source:
@Override public boolean equalsDeep(SqlNode node, Litmus litmus) { if (node == this) { return true; } if (!(node instanceof SqlCall)) { return litmus.fail("{} != {}", this, node); } SqlCall that = (SqlCall) node; if (!equalDeep(this.getFunctionQuantifier(), that.getFunctionQuantifier(), litmus)) { return litmus.fail("{} != {}", this, node); } if (!this.getOperator().getName().equalsIgnoreCase(that.getOperator().getName())) { return litmus.fail("{} != {}", this, node); } return equalDeep(this.getOperandList(), that.getOperandList(), litmus); }

Target:
@Override public boolean equalsDeep(SqlNode node, Litmus litmus) { if (node == this) { return true; } if (!(node instanceof SqlCall)) { return litmus.fail("{} != {}", this, node); } SqlCall that = (SqlCall) node; if (!this.getOperator().getName().equalsIgnoreCase(that.getOperator().getName())) { return litmus.fail("{} != {}", this, node); } if (!equalDeep(this.getFunctionQuantifier(), that.getFunctionQuantifier(), litmus)) { return litmus.fail("{} != (function quantifier differs)", this, node); } return equalDeep(this.getOperandList(), that.getOperandList(), litmus); }
Source:
public void setUp() throws IOException { validator = new VariantLoaderStepParametersValidator(); final File dir = TestFileUtils.getResource("/parameters-validation/"); final File inputVcf = TestFileUtils.getResource("/parameters-validation/file.vcf.gz"); dir.setReadable(true); dir.setWritable(true); inputVcf.setReadable(true); parameters = new TreeMap<>(); parameters.put(JobParametersNames.DB_NAME, new JobParameter("database")); parameters.put(JobParametersNames.DB_COLLECTIONS_VARIANTS_NAME, new JobParameter("variants")); parameters.put(JobParametersNames.DB_COLLECTIONS_FILES_NAME, new JobParameter("files")); parameters.put(JobParametersNames.INPUT_STUDY_ID, new JobParameter("inputStudyId")); parameters.put(JobParametersNames.INPUT_VCF_ID, new JobParameter("inputVcfId")); parameters.put(JobParametersNames.INPUT_VCF, new JobParameter(inputVcf.getCanonicalPath())); optionalParameters = new TreeMap<>(); optionalParameters.put(JobParametersNames.INPUT_VCF_AGGREGATION, new JobParameter("NONE")); optionalParameters.put(JobParametersNames.CONFIG_CHUNK_SIZE, new JobParameter("100")); }

Target:
public void setUp() throws IOException { validator = new VariantLoaderStepParametersValidator(); requiredParameters = new TreeMap<>(); requiredParameters.put(JobParametersNames.DB_NAME, new JobParameter("database")); requiredParameters.put(JobParametersNames.DB_COLLECTIONS_VARIANTS_NAME, new JobParameter("variants")); requiredParameters.put(JobParametersNames.INPUT_STUDY_ID, new JobParameter("inputStudyId")); requiredParameters.put(JobParametersNames.INPUT_VCF_ID, new JobParameter("inputVcfId")); requiredParameters.put(JobParametersNames.INPUT_VCF_AGGREGATION, new JobParameter("NONE")); requiredParameters.put(JobParametersNames.INPUT_VCF, new JobParameter(temporaryFolderRule.newFile().getCanonicalPath())); optionalParameters = new TreeMap<>(); optionalParameters.put(JobParametersNames.CONFIG_CHUNK_SIZE, new JobParameter("100")); }
Source:
public void if_with_nested_foreach_nested_do_while() { verifyBlockCfg("" + "ifCond(succ = [forCond, END]);" + "if (a) {" + " foreach ( forCond(succ = [innerIfCond, END]) as $key) {" + " innerIfCond(succ = [ifBody, doBody]);" + " if (a) {" + " ifBody( succ = [doBody] );" + " }" + " do {" + " doBody( succ = [doCond] );" + " } while (doCond( succ = [doBody, forCond] ));" + " }" + "}"); }

Target:
public void if_with_nested_foreach_nested_do_while() { verifyBlockCfg("" + "if (ifCond(succ = [forCond, END])) {" + " foreach ( forCond(succ = [innerIfCond, END]) as $foo) {" + " innerIfCond(succ = [ifBody, doBody]);" + " if (a) {" + " ifBody( succ = [doBody] );" + " }" + " do {" + " doBody( succ = [doCond] );" + " } while (doCond( succ = [doBody, forCond] ));" + " }" + "}"); }
Source:
private static RunCondition getIgnoreConditionOnMethod(Description aDescription) { try { ConditionalRun[] annotation = aDescription.getTestClass().getMethod(aDescription.getMethodName()).getAnnotationsByType(ConditionalRun.class); return new IgnoreConditionCreator(aDescription.getTestClass(), annotation).create(); } catch (NoSuchMethodException | SecurityException ex) { throw new RuntimeException(ex); } }

Target:
private static RunCondition getIgnoreConditionOnMethod(Description aDescription) { try { ConditionalRun[] annotations = aDescription.getTestClass().getMethod(aDescription.getMethodName()).getAnnotationsByType(ConditionalRun.class); return new IgnoreConditionCreator(aDescription.getTestClass(), annotations).create(); } catch (NoSuchMethodException | SecurityException ex) { throw new RuntimeException(ex); } }
Source:
private ArrayList<Map<String, String>> formatDepictions(JsonObject mediaResponse) { try { JsonArray depictionArray = (JsonArray) mediaResponse.get("Depiction"); ArrayList<Map<String, String>> depictedItemList = new ArrayList<>(); try { for (int i = 0; i <depictionArray.size() ; i++) { JsonObject depictedItem = (JsonObject) depictionArray.get(i); Map <String, String> depictedObject = new HashMap<>(); depictedObject.put("label", depictedItem.get("label").toString().substring(3, depictedItem.get("label").toString().length()-3)); depictedObject.put("id", depictedItem.get("id").toString().substring(1, depictedItem.get("id").toString().length() - 1)); depictedItemList.add(depictedObject); } return depictedItemList; } catch (NullPointerException e) { return new ArrayList<>(); } } catch (ClassCastException c) { return new ArrayList<>(); } }

Target:
private ArrayList<Map<String, String>> formatDepictions(JsonObject mediaResponse) { try { JsonArray depictionArray = (JsonArray) mediaResponse.get("Depiction"); ArrayList<Map<String, String>> depictedItemList = new ArrayList<>(); try { for (int i = 0; i <depictionArray.size() ; i++) { JsonObject depictedItem = (JsonObject) depictionArray.get(i); Map <String, String> depictedObject = new HashMap<>(); String label = depictedItem.get("label").toString(); String id = depictedItem.get("id").toString(); String transformedLabel = label.substring(3, label.length()-3); String transformedId = id.substring(1,id.length() - 1); depictedObject.put("label", transformedLabel); depictedObject.put("id", transformedId); depictedItemList.add(depictedObject); } return depictedItemList; } catch (NullPointerException e) { return new ArrayList<>(); } } catch (ClassCastException c) { return new ArrayList<>(); } }
Source:
public void initialize(ScriptContext context) { Object attr = context.getAttribute(OUTPUT_ATTR); if (attr != null) { attribute = String.valueOf(attr); } Object sum = context.getAttribute(OUTPUT_SUM); doSum = Boolean.parseBoolean(String.valueOf(sum)); Object count = context.getAttribute(OUTPUT_COUNT); doCount = Boolean.parseBoolean(String.valueOf(count)); Object average = context.getAttribute(OUTPUT_AVG); doAverage = Boolean.parseBoolean(String.valueOf(average)); Object max = context.getAttribute(OUTPUT_MAX); doMax = Boolean.parseBoolean(String.valueOf(max)); Object min = context.getAttribute(OUTPUT_MIN); doMin = Boolean.parseBoolean(String.valueOf(min)); attributeValues = new LinkedList<Double>(); }

Target:
public void initialize(ScriptContext context) { Object attr = context.getAttribute(OUTPUT_ATTR); if (attr != null) { attribute = String.valueOf(attr); Object sum = context.getAttribute(OUTPUT_SUM); doSum = Boolean.parseBoolean(String.valueOf(sum)); Object count = context.getAttribute(OUTPUT_COUNT); doCount = Boolean.parseBoolean(String.valueOf(count)); Object average = context.getAttribute(OUTPUT_AVG); doAverage = Boolean.parseBoolean(String.valueOf(average)); Object max = context.getAttribute(OUTPUT_MAX); doMax = Boolean.parseBoolean(String.valueOf(max)); Object min = context.getAttribute(OUTPUT_MIN); doMin = Boolean.parseBoolean(String.valueOf(min)); attributeValues = new LinkedList<Double>(); } }
Source:
public Object setCaller(InvocationContext ctx) throws Exception { Subject caller=null; java.security.Principal p = ejbContext.getCallerPrincipal(); if (!startupBean.isInitialized()) { String notInitMessage = "Tried to call REST endpoint but the server has not finished to startup"; log.warn(notInitMessage); Response.ResponseBuilder builder; builder = Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(notInitMessage); return builder.build(); } if (p!=null) { caller = subjectManager.getSubjectByName(p.getName()); } if (caller==null) { throw new IllegalAccessException("No calling principal provided"); } caller = sessionManager.put(caller); AbstractRestBean target = (AbstractRestBean) ctx.getTarget(); target.caller = caller; Object result = ctx.proceed(); if (result instanceof StreamingOutput) { return new SecureStreamingOutput((StreamingOutput) result, caller); } sessionManager.invalidate(caller.getSessionId()); return result; }

Target:
public Object setCaller(InvocationContext ctx) throws Exception { Subject caller=null; java.security.Principal p = ejbContext.getCallerPrincipal(); if (!startupBean.isInitialized()) { String notInitMessage = "Tried to call REST endpoint but the server is not ready - still booting up"; log.debug(notInitMessage); return Response.status(Response.Status.SERVICE_UNAVAILABLE) .header("Retry-After", "30").entity(notInitMessage).build(); } if (p!=null) { caller = subjectManager.getSubjectByName(p.getName()); } if (caller==null) { throw new IllegalAccessException("No calling principal provided"); } caller = sessionManager.put(caller); AbstractRestBean target = (AbstractRestBean) ctx.getTarget(); target.caller = caller; Object result = ctx.proceed(); if (result instanceof StreamingOutput) { return new SecureStreamingOutput((StreamingOutput) result, caller); } sessionManager.invalidate(caller.getSessionId()); return result; }
Source:
public void testTempAuthRequest() throws Exception { Properties overrides = null; test(overrides); overrides = new Properties(); overrides.setProperty(SwiftAuthenticationModule.TEMP_AUTH_HEADER_USER , "X-Auth-User"); overrides.setProperty(SwiftAuthenticationModule.TEMP_AUTH_HEADER_PASS , "X-Auth-Pass"); test(overrides); }

Target:
public void testTempAuthRequest() throws Exception { Properties overrides = new Properties(); test(overrides, "X-Storage-User", "X-Storage-Pass"); }
Source:
private List<CassandraPartition> getCassandraPartitions(CassandraTable table, TupleDomain<ColumnHandle> tupleDomain) { if (tupleDomain.isNone()) { return ImmutableList.of(); } List<Set<Object>> partitionKeysList = getPartitionKeysList(table, tupleDomain); Set<List<Object>> filterList = Sets.cartesianProduct(partitionKeysList); if (filterList.isEmpty()) { return cassandraSession.getPartitions(table, ImmutableList.of()); } return ImmutableList.copyOf(cassandraSession.getPartitions(table, partitionKeysList)); }

Target:
private List<CassandraPartition> getCassandraPartitions(CassandraTable table, TupleDomain<ColumnHandle> tupleDomain) { if (tupleDomain.isNone()) { return ImmutableList.of(); } List<Set<Object>> partitionKeysList = getPartitionKeysList(table, tupleDomain); Set<List<Object>> filterList = Sets.cartesianProduct(partitionKeysList); if (filterList.isEmpty()) { return cassandraSession.getPartitions(table, ImmutableList.of()); } return cassandraSession.getPartitions(table, partitionKeysList); }
Source:
private Group(@JsonProperty("id") String id, @JsonProperty("externalId") String externalId, @JsonProperty("meta") Meta meta, @JsonProperty(value = "schemas", required = true) Set<String> schemas, @JsonProperty("displayName") String displayName, @JsonProperty("members") Set<MemberRef> members) { super(id, externalId, meta, schemas); this.displayName = displayName; this.members = (members != null ? members : new HashSet<MemberRef>()); }

Target:
private Group(@JsonProperty("id") String id, @JsonProperty("externalId") String externalId, @JsonProperty("meta") Meta meta, @JsonProperty(value = "schemas", required = true) Set<String> schemas, @JsonProperty("displayName") String displayName, @JsonProperty("members") Set<MemberRef> members) { super(id, externalId, meta, schemas); this.displayName = displayName; this.members = (members != null ? members : Collections.<MemberRef>emptySet()); }
Source:
private NewTableConfiguration setLocalityForNewTable(CommandLine cl, NewTableConfiguration ntc) { HashMap<String,Set<Text>> localityGroupMap = new HashMap<>(); String[] options = cl.getOptionValues(createTableOptLocalityProps.getOpt()); for (String localityInfo : options) { final String parts[] = localityInfo.split("=", 2); if (parts.length < 2) throw new IllegalArgumentException("Missing '=' or there are spaces between entries"); final String groupName = parts[0]; final HashSet<Text> colFams = new HashSet<>(); for (String family : parts[1].split(",")) colFams.add(new Text(family.getBytes(Shell.CHARSET))); localityGroupMap.put(groupName, colFams); } ntc.setLocalityGroups(localityGroupMap); return ntc; }

Target:
private NewTableConfiguration setLocalityForNewTable(CommandLine cl, NewTableConfiguration ntc) { HashMap<String,Set<Text>> localityGroupMap = new HashMap<>(); String[] options = cl.getOptionValues(createTableOptLocalityProps.getOpt()); for (String localityInfo : options) { final String parts[] = localityInfo.split("=", 2); if (parts.length < 2) throw new IllegalArgumentException("Missing '=' or there are spaces between entries"); final String groupName = parts[0]; final HashSet<Text> colFams = new HashSet<>(); for (String family : parts[1].split(",")) colFams.add(new Text(family.getBytes(Shell.CHARSET))); if (localityGroupMap.put(groupName, colFams) != null) throw new IllegalArgumentException("Duplicate locality group name found. Group names must be unique"); } ntc.setLocalityGroups(localityGroupMap); return ntc; }
Source:
public final <R> Observable<R> concatMapEager(Func1<? super T, ? extends Observable<? extends R>> mapper, int capacityHint, int maxConcurrent) { if (capacityHint < 1) { throw new IllegalArgumentException("capacityHint > 0 required but it was " + capacityHint); } return lift(new OperatorEagerConcatMap<T, R>(mapper, capacityHint, maxConcurrent)); }

Target:
public final <R> Observable<R> concatMapEager(Func1<? super T, ? extends Observable<? extends R>> mapper, int capacityHint, int maxConcurrent) { if (capacityHint < 1) { throw new IllegalArgumentException("capacityHint > 0 required but it was " + capacityHint); } if (maxConcurrent < 1) { throw new IllegalArgumentException("maxConcurrent > 0 required but it was " + capacityHint); } return lift(new OperatorEagerConcatMap<T, R>(mapper, capacityHint, maxConcurrent)); }
Source:
public boolean apply(Collection<Command> cmdList) { try { DirCacheEditor ed = contents.editor(); for (Command cmd : cmdList) { apply(ed, cmd); } ed.finish(); return true; } catch (DirCacheNameConflictException e) { String r1 = refName(e.getPath1()); String r2 = refName(e.getPath2()); for (Command c : cmdList) { if (r1.equals(c.getRefName()) || r2.equals(c.getRefName())) { c.setResult(LOCK_FAILURE); break; } } return abort(cmdList); } catch (LockFailureException e) { return abort(cmdList); } }

Target:
public boolean apply(Collection<Command> cmdList) { try { DirCacheEditor ed = contents.editor(); for (Command cmd : cmdList) { apply(ed, cmd); } ed.finish(); return true; } catch (DirCacheNameConflictException e) { String r1 = refName(e.getPath1()); String r2 = refName(e.getPath2()); for (Command cmd : cmdList) { if (r1.equals(cmd.getRefName()) || r2.equals(cmd.getRefName())) { cmd.setResult(LOCK_FAILURE); break; } } return abort(cmdList); } catch (LockFailureException e) { return abort(cmdList); } }
Source:
public IReviewRemoteFactoryProvider getFactoryProvider() { if ((ReviewsConnector) getConnector() != null) { ReviewsClient client = ((ReviewsConnector) getConnector()).getReviewClient(getTaskRepository()); if (client != null) { return (IReviewRemoteFactoryProvider) client.getFactoryProvider(); } } return null; }

Target:
public IReviewRemoteFactoryProvider getFactoryProvider() { return (IReviewRemoteFactoryProvider) ((ReviewsConnector) getConnector()).getReviewClient(getTaskRepository()) .getFactoryProvider(); }
Source:
public boolean updatePostContentNewEditor(boolean isAutoSave, String title, String content) { if (mPost == null) { return false; } if (!isAutoSave) { } boolean titleChanged = PostUtils.updatePostTitleIfDifferent(mPost, title); boolean contentChanged; if (compareCurrentMediaMarkedUploadingToOriginal(content)) { contentChanged = true; } else if (mEditorFragment instanceof AztecEditorFragment && ((AztecEditorFragment) mEditorFragment).isHistoryEnabled()) { contentChanged = ((AztecEditorFragment) mEditorFragment).hasHistory() || mMediaInsertedOnCreation; mMediaInsertedOnCreation = false; } else { contentChanged = mPost.getContent().compareTo(content) != 0; } if (contentChanged) { mPost.setContent(content); } if (!mPost.isLocalDraft() && (titleChanged || contentChanged)) { mPost.setIsLocallyChanged(true); mPost.setDateLocallyChanged(DateTimeUtils.iso8601FromTimestamp(System.currentTimeMillis() / 1000)); } return titleChanged || contentChanged; }

Target:
public boolean updatePostContentNewEditor(boolean isAutoSave, String title, String content) { if (mPost == null) { return false; } if (!isAutoSave) { } boolean titleChanged = PostUtils.updatePostTitleIfDifferent(mPost, title); boolean contentChanged; if (mMediaInsertedOnCreation) { mMediaInsertedOnCreation = false; contentChanged = true; } else if (compareCurrentMediaMarkedUploadingToOriginal(content)) { contentChanged = true; } else if (mEditorFragment instanceof AztecEditorFragment && ((AztecEditorFragment) mEditorFragment).isHistoryEnabled()) { contentChanged = ((AztecEditorFragment) mEditorFragment).hasHistory(); } else { contentChanged = mPost.getContent().compareTo(content) != 0; } if (contentChanged) { mPost.setContent(content); } if (!mPost.isLocalDraft() && (titleChanged || contentChanged)) { mPost.setIsLocallyChanged(true); mPost.setDateLocallyChanged(DateTimeUtils.iso8601FromTimestamp(System.currentTimeMillis() / 1000)); } return titleChanged || contentChanged; }
Source:
public NodeInfo getNodeInfo() { return this.getProperty(GenericProperties.NODE_INFO); }

Target:
public NodeInfo getNodeInfo() { return null; }
Source:
public void testConnectorAbortsHandshakeOnUnknownPskIdentity() throws Exception { final CountDownLatch latch = new CountDownLatch(1); clientConfig = new DtlsConnectorConfig.Builder(clientEndpoint) .setPskStore(new StaticPskStore("unknownIdentity", CLIENT_IDENTITY_SECRET.getBytes())) .build(); client = new DTLSConnector(clientConfig); client.setErrorHandler(new ErrorHandler() { @Override public void onError(InetSocketAddress peerAddress, AlertLevel level, AlertDescription description) { latch.countDown(); assertThat(level, is(AlertLevel.FATAL)); assertThat(peerAddress, is(serverEndpoint)); } }); client.start(); SimpleMessageCallback callback = new SimpleMessageCallback(); RawData data = RawData.outbound("Hello".getBytes(), serverEndpoint, null, callback, false); client.send(data); assertTrue(latch.await(MAX_TIME_TO_WAIT_SECS, TimeUnit.SECONDS)); assertThat("Error callback missing", callback.getError(MAX_TIME_TO_WAIT_SECS), is(notNullValue())); }

Target:
public void testConnectorAbortsHandshakeOnUnknownPskIdentity() throws Exception { final CountDownLatch latch = new CountDownLatch(1); clientConfig = new DtlsConnectorConfig.Builder() .setAddress(clientEndpoint) .setPskStore(new StaticPskStore("unknownIdentity", CLIENT_IDENTITY_SECRET.getBytes())) .build(); client = new DTLSConnector(clientConfig); client.setErrorHandler(new ErrorHandler() { @Override public void onError(InetSocketAddress peerAddress, AlertLevel level, AlertDescription description) { latch.countDown(); assertThat(level, is(AlertLevel.FATAL)); assertThat(peerAddress, is(serverEndpoint)); } }); client.start(); SimpleMessageCallback callback = new SimpleMessageCallback(); RawData data = RawData.outbound("Hello".getBytes(), serverEndpoint, null, callback, false); client.send(data); assertTrue(latch.await(MAX_TIME_TO_WAIT_SECS, TimeUnit.SECONDS)); assertThat("Error callback missing", callback.getError(TimeUnit.SECONDS.toMillis(MAX_TIME_TO_WAIT_SECS)), is(notNullValue())); }
Source:
public void prepare(Map<String, Object> conf) throws IOException { this.conf = conf; this.rootDir = DaemonConfig.getCgroupRootDir(this.conf); if (this.rootDir == null) { throw new RuntimeException("Check configuration file. The storm.supervisor.cgroup.rootdir is missing."); } File file = new File(DaemonConfig.getCgroupStormHierarchyDir(conf), rootDir); if (!file.exists()) { LOG.error("{} does not exist", file.getPath()); throw new RuntimeException( "Check if cgconfig service starts or /etc/cgconfig.conf is consistent with configuration file."); } this.center = CgroupCenter.getInstance(); if (this.center == null) { throw new RuntimeException("Cgroup error, please check /proc/cgroups"); } this.prepareSubSystem(this.conf); validatedNumaMap = Utils.getNumaMap(conf); workerToNumaId = new ConcurrentHashMap(); validatedNumaMap = new ConcurrentHashMap(); }

Target:
public void prepare(Map<String, Object> conf) throws IOException { this.conf = conf; this.rootDir = DaemonConfig.getCgroupRootDir(this.conf); if (this.rootDir == null) { throw new RuntimeException("Check configuration file. The storm.supervisor.cgroup.rootdir is missing."); } File file = new File(DaemonConfig.getCgroupStormHierarchyDir(conf), rootDir); if (!file.exists()) { LOG.error("{} does not exist", file.getPath()); throw new RuntimeException( "Check if cgconfig service starts or /etc/cgconfig.conf is consistent with configuration file."); } this.center = CgroupCenter.getInstance(); if (this.center == null) { throw new RuntimeException("Cgroup error, please check /proc/cgroups"); } this.prepareSubSystem(this.conf); workerToNumaId = new ConcurrentHashMap(); }
Source:
public void visitLambda(PyLambdaExpressionTree pyLambdaExpressionTree) { createScope(pyLambdaExpressionTree, currentScope()); enterScope(pyLambdaExpressionTree); createParameters(pyLambdaExpressionTree.parameters()); super.visitLambda(pyLambdaExpressionTree); super.scopeRootTrees.pop(); }

Target:
public void visitLambda(PyLambdaExpressionTree pyLambdaExpressionTree) { createScope(pyLambdaExpressionTree, currentScope()); enterScope(pyLambdaExpressionTree); createParameters(pyLambdaExpressionTree.parameters()); super.visitLambda(pyLambdaExpressionTree); leaveScope(); }
Source:
public static <T> Collection<Collection<T>> batch( Collection<T> collection, int batchSize ) { Collection<Collection<T>> batches = new ArrayList<>(); Collection<T> batch = new ArrayList<>( batchSize ); int count = 0; for ( T t : collection ) { ( (ArrayList<T>) batch ).add( t ); count++; if ( count >= batchSize ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); batch = new ArrayList<>( batchSize ); count = 0; } } if ( batch != null && !batch.isEmpty() ) { ( (ArrayList<Collection<T>>) batches ).add( batch ); } return batches; }

Target:
public static <T> Collection<Collection<T>> batch( Collection<T> collection, int batchSize ) { Collection<Collection<T>> batches = new ArrayList<>(); List<T> batch = new ArrayList<>( batchSize ); int count = 0; for ( T t : collection ) { batch.add( t ); count++; if ( count >= batchSize ) { batches.add( batch ); batch = new ArrayList<>( batchSize ); count = 0; } } if ( !batch.isEmpty() ) { batches.add( batch ); } return batches; }
Source:
public void onDeadEvent(DeadEvent deadEvent) { Object unhandledEvent = deadEvent.getEvent(); log.warning("No event handler registered for event of type " + unhandledEvent.getClass().getSimpleName() + ": " + unhandledEvent); }

Target:
public void onDeadEvent(DeadEvent deadEvent) { Object unhandledEvent = deadEvent.getEvent(); log.warn("No event handler registered for event of type '{}'", unhandledEvent.getClass().getSimpleName()); }
Source:
public boolean canPrincipalConfigure( IAuthorizationPrincipal principal, String portletDefinitionId) throws AuthorizationException { String owner = IPermission.PORTAL_PUBLISH; String ownerSubscribe = IPermission.PORTAL_SUBSCRIBE; String target = IPermission.PORTLET_PREFIX + portletDefinitionId; IPortletDefinition portlet = this.portletDefinitionRegistry.getPortletDefinition(portletDefinitionId); if (portlet == null) { throw new AuthorizationException("Unable to locate portlet " + portletDefinitionId); } final String activity = IPermission.PORTLET_MODE_CONFIG; final String activitySubscribe = IPermission.PORTLET_CONFIGURE_ACTIVITY; boolean byAdmin = doesPrincipalHavePermission(principal, owner, activity, target); boolean byPrincipal = doesPrincipalHavePermission(principal, ownerSubscribe, activitySubscribe, target); log.info("BEACH TEST: Checking portlet configure abilities. ByAdmin?=["+byAdmin+"], ByPrincipal?=["+byPrincipal+"]" ); return byAdmin || byPrincipal; }

Target:
public boolean canPrincipalConfigure( IAuthorizationPrincipal principal, String portletDefinitionId) throws AuthorizationException { String owner = IPermission.PORTAL_PUBLISH; String target = IPermission.PORTLET_PREFIX + portletDefinitionId; IPortletDefinition portlet = this.portletDefinitionRegistry.getPortletDefinition(portletDefinitionId); if (portlet == null) { throw new AuthorizationException("Unable to locate portlet " + portletDefinitionId); } final String activity = IPermission.PORTLET_MODE_CONFIG; boolean isAllowed = doesPrincipalHavePermission(principal, owner, activity, target); if (this.log.isTraceEnabled()) { log.trace( String.format( "In canPrincipalConfigure() - principal.key=[%s], is allowed?=[%s]", principal.getKey(), isAllowed)); } return isAllowed; }
Source:
public CompletableFuture<Object> invokeAsync() { long accessTime = this.accessTime == -1 ? timeService.wallClockTime() : this.accessTime; boolean touched = internalDataContainer.touch(segment, key, accessTime); if (distributionManager != null && topologyId != -1) { LocalizedCacheTopology lct = distributionManager.getCacheTopology(); int currentTopologyId = lct.getTopologyId(); if (currentTopologyId != topologyId) { return CompletableFutures.completedExceptionFuture(OutdatedTopologyException.RETRY_NEXT_TOPOLOGY); } DistributionInfo di = lct.getSegmentDistribution(segment); if (di.isWriteOwner() && !di.isReadOwner()) { return CompletableFuture.completedFuture(Boolean.TRUE); } } return CompletableFuture.completedFuture(touched); }

Target:
public CompletableFuture<Object> invokeAsync() { return invokeAsync(timeService.wallClockTime()); }
Source:
private boolean isAllowedURL(String url) { boolean isAllowed = false; if (url != null) { if (url.contains("?")) { url = url.substring(0, url.indexOf('?')); } if (url.contains("/login/") || url.contains("/registration/") || url.contains("/user/add")) { isAllowed = true; } } return isAllowed; }

Target:
private boolean isAllowedURL(String url) { boolean isAllowed = false; if (url != null) { if (url.contains("?")) { url = url.substring(0, url.indexOf('?')); } if (url.contains("/login") || url.contains("/registration/") || url.contains("/user/add")) { isAllowed = true; } } return isAllowed; }
Source:
protected void onSave(CommitBuilder commit) throws IOException, ConfigInvalidException { if (commit.getMessage() == null || "".equals(commit.getMessage())) { commit.setMessage("Updated project configuration\n"); } Config rc = readConfig(PROJECT_CONFIG); Project p = project; if (p.getDescription() != null && !p.getDescription().isEmpty()) { rc.setString(PROJECT, null, KEY_DESCRIPTION, p.getDescription()); } else { rc.unset(PROJECT, null, KEY_DESCRIPTION); } set(rc, ACCESS, null, KEY_INHERIT_FROM, p.getParentName()); set(rc, RECEIVE, null, KEY_REQUIRE_CONTRIBUTOR_AGREEMENT, p.getUseContributorAgreements(), Project.InheritableBoolean.INHERIT); set(rc, RECEIVE, null, KEY_REQUIRE_SIGNED_OFF_BY, p.getUseSignedOffBy(), Project.InheritableBoolean.INHERIT); set(rc, RECEIVE, null, KEY_REQUIRE_CHANGE_ID, p.getRequireChangeID(), Project.InheritableBoolean.INHERIT); set(rc, SUBMIT, null, KEY_ACTION, p.getSubmitType(), defaultSubmitAction); set(rc, SUBMIT, null, KEY_MERGE_CONTENT, p.getUseContentMerge(), Project.InheritableBoolean.INHERIT); set(rc, PROJECT, null, KEY_STATE, p.getState(), null); set(rc, DASHBOARD, null, KEY_DEFAULT, p.getDefaultDashboard()); set(rc, DASHBOARD, null, KEY_LOCAL_DEFAULT, p.getLocalDefaultDashboard()); Set<AccountGroup.UUID> keepGroups = new HashSet<AccountGroup.UUID>(); saveAccountsSection(rc, keepGroups); saveContributorAgreements(rc, keepGroups); saveAccessSections(rc, keepGroups); saveNotifySections(rc, keepGroups); groupsByUUID.keySet().retainAll(keepGroups); saveConfig(PROJECT_CONFIG, rc); saveGroupList(); }

Target:
protected void onSave(CommitBuilder commit) throws IOException, ConfigInvalidException { if (commit.getMessage() == null || "".equals(commit.getMessage())) { commit.setMessage("Updated project configuration\n"); } Config rc = readConfig(PROJECT_CONFIG); Project p = project; if (p.getDescription() != null && !p.getDescription().isEmpty()) { rc.setString(PROJECT, null, KEY_DESCRIPTION, p.getDescription()); } else { rc.unset(PROJECT, null, KEY_DESCRIPTION); } rc.setStringList(ACCESS, null, KEY_INHERIT_FROM, p.getParentNames()); set(rc, RECEIVE, null, KEY_REQUIRE_CONTRIBUTOR_AGREEMENT, p.getUseContributorAgreements(), Project.InheritableBoolean.INHERIT); set(rc, RECEIVE, null, KEY_REQUIRE_SIGNED_OFF_BY, p.getUseSignedOffBy(), Project.InheritableBoolean.INHERIT); set(rc, RECEIVE, null, KEY_REQUIRE_CHANGE_ID, p.getRequireChangeID(), Project.InheritableBoolean.INHERIT); set(rc, SUBMIT, null, KEY_ACTION, p.getSubmitType(), defaultSubmitAction); set(rc, SUBMIT, null, KEY_MERGE_CONTENT, p.getUseContentMerge(), Project.InheritableBoolean.INHERIT); set(rc, PROJECT, null, KEY_STATE, p.getState(), null); set(rc, DASHBOARD, null, KEY_DEFAULT, p.getDefaultDashboard()); set(rc, DASHBOARD, null, KEY_LOCAL_DEFAULT, p.getLocalDefaultDashboard()); Set<AccountGroup.UUID> keepGroups = new HashSet<AccountGroup.UUID>(); saveAccountsSection(rc, keepGroups); saveContributorAgreements(rc, keepGroups); saveAccessSections(rc, keepGroups); saveNotifySections(rc, keepGroups); groupsByUUID.keySet().retainAll(keepGroups); saveConfig(PROJECT_CONFIG, rc); saveGroupList(); }
Source:
public boolean hasCapability(Capability<?> capability, EnumFacing facing) { if (super.hasCapability(capability, facing)) { return true; } return MultipartCapabilityHelper.hasCapability(container, capability, facing); }

Target:
public boolean hasCapability(Capability<?> capability, EnumFacing facing) { if (capability == CapabilityMultipartContainer.MULTIPART_CONTAINER_CAPABILITY || capability == CapabilityMicroblockContainerTile.MICROBLOCK_CONTAINER_CAPABILITY || capability == CapabilitySlottedCapProvider.SLOTTED_CAP_PROVIDER_CAPABILITY) { return true; } if (MultipartCapabilityHelper.hasCapability(container, capability, facing)) { return true; } return super.hasCapability(capability, facing); }
Source:
public void testGetObjectDecimal() throws Throwable { assumeCallableStatementsSupported(); try { Statement stmt = con.createStatement(); stmt.execute( "create temp table decimal_tab ( max_val numeric(30,15), min_val numeric(30,15), nul_val numeric(30,15) )"); stmt.execute( "insert into decimal_tab values (999999999999999.000000000000000,0.000000000000001,null)"); boolean ret = stmt.execute("create or replace function " + "decimal_proc( OUT pmax numeric, OUT pmin numeric, OUT nval numeric) as " + "'begin " + "select max_val into pmax from decimal_tab;" + "select min_val into pmin from decimal_tab;" + "select nul_val into nval from decimal_tab;" + " end;' " + "language plpgsql;"); } catch (Exception ex) { fail(ex.getMessage()); throw ex; } try { CallableStatement cstmt = con.prepareCall("{ call decimal_proc(?,?,?) }"); cstmt.registerOutParameter(1, Types.DECIMAL); cstmt.registerOutParameter(2, Types.DECIMAL); cstmt.registerOutParameter(3, Types.DECIMAL); cstmt.executeUpdate(); BigDecimal val = (BigDecimal) cstmt.getObject(1); assertEquals(new BigDecimal("999999999999999.000000000000000"), val); val = (BigDecimal) cstmt.getObject(2); assertEquals(new BigDecimal("0.000000000000001"), val); val = (BigDecimal) cstmt.getObject(3); assertNull(val); } catch (Exception ex) { fail(ex.getMessage()); } finally { try { Statement dstmt = con.createStatement(); dstmt.execute("drop function decimal_proc()"); } catch (Exception ex) { } } }

Target:
public void testGetObjectDecimal() throws Throwable { assumeCallableStatementsSupported(); try { Statement stmt = con.createStatement(); stmt.execute( "create temp table decimal_tab ( max_val numeric(30,15), min_val numeric(30,15), nul_val numeric(30,15) )"); stmt.execute( "insert into decimal_tab values (999999999999999.000000000000000,0.000000000000001,null)"); boolean ret = stmt.execute("create or replace function " + "decimal_proc( OUT pmax numeric, OUT pmin numeric, OUT nval numeric) as " + "'begin " + "select max_val into pmax from decimal_tab;" + "select min_val into pmin from decimal_tab;" + "select nul_val into nval from decimal_tab;" + " end;' " + "language plpgsql;"); } catch (Exception ex) { fail(ex.getMessage()); throw ex; } try { CallableStatement cstmt = con.prepareCall("{ call decimal_proc(?,?,?) }"); cstmt.registerOutParameter(1, Types.DECIMAL); cstmt.registerOutParameter(2, Types.DECIMAL); cstmt.registerOutParameter(3, Types.DECIMAL); cstmt.executeUpdate(); BigDecimal val = (BigDecimal) cstmt.getObject(1); assertEquals(0, val.compareTo(new BigDecimal("999999999999999.000000000000000"))); val = (BigDecimal) cstmt.getObject(2); assertEquals(0, val.compareTo(new BigDecimal("0.000000000000001"))); val = (BigDecimal) cstmt.getObject(3); assertNull(val); } catch (Exception ex) { fail(ex.getMessage()); } finally { try { Statement dstmt = con.createStatement(); dstmt.execute("drop function decimal_proc()"); } catch (Exception ex) { } } }
Source:
public void receive(Message message) { org.jgroups.Address src = message.src(); short flags = message.getFlags(); byte[] buffer = message.rawBuffer(); int offset = message.offset(); int length = message.length(); RequestCorrelator.Header header = message.getHeader(HEADER_ID); byte type; long requestId; if (header != null) { type = header.type; requestId = header.requestId(); } else { type = SINGLE_MESSAGE; requestId = Request.NO_REQUEST_ID; } Address sender = fromJGroupsAddress(src); if (address == null) { if (trace) log.tracef("Ignoring message received before initial view"); if (type == REQUEST) { sendResponse(fromJGroupsAddress(message.src()), CacheNotFoundResponse.INSTANCE, requestId, null); } return; } switch (type) { case SINGLE_MESSAGE: processSingleMessage(src, flags, buffer, offset, length, requestId, sender); break; case REQUEST: processRequest(src, flags, buffer, offset, length, requestId, sender); break; case RESPONSE: processResponse(src, buffer, offset, length, requestId, sender); break; default: log.error("Invalid message type: " + type + " from " + src); } }

Target:
public void receive(Message message) { processMessage(message); }
Source:
@Test public void byteAdapter() throws Exception { Moshi moshi = new Moshi.Builder().build(); JsonAdapter<Byte> adapter = moshi.adapter(byte.class).lenient(); assertThat(adapter.fromJson("1")).isEqualTo((byte) 1); assertThat(adapter.toJson((byte) 2)).isEqualTo("2"); try { adapter.fromJson("200"); fail(); } catch (NumberFormatException expected) { assertThat(expected.getMessage()).isEqualTo("Expected a byte but was 200 at path $"); } try { adapter.fromJson("null"); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage()).isEqualTo("Expected an int but was NULL at path $"); } try { moshi.adapter(int.class).toJson(null); fail(); } catch (NullPointerException expected) { } }

Target:
@Test public void byteAdapter() throws Exception { Moshi moshi = new Moshi.Builder().build(); JsonAdapter<Byte> adapter = moshi.adapter(byte.class).lenient(); assertThat(adapter.fromJson("1")).isEqualTo((byte) 1); assertThat(adapter.toJson((byte) -2)).isEqualTo("254"); assertThat(adapter.fromJson("-128")).isEqualTo((byte) -128); assertThat(adapter.fromJson("128")).isEqualTo((byte) -128); assertThat(adapter.toJson((byte) -128)).isEqualTo("128"); assertThat(adapter.fromJson("255")).isEqualTo((byte) -1); assertThat(adapter.toJson((byte) -1)).isEqualTo("255"); assertThat(adapter.fromJson("127")).isEqualTo((byte) 127); assertThat(adapter.toJson((byte) 127)).isEqualTo("127"); try { adapter.fromJson("256"); fail(); } catch (NumberFormatException expected) { assertThat(expected.getMessage()).isEqualTo("Expected a byte but was 256 at path $"); } try { adapter.fromJson("-129"); fail(); } catch (NumberFormatException expected) { assertThat(expected.getMessage()).isEqualTo("Expected a byte but was -129 at path $"); } try { adapter.fromJson("null"); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage()).isEqualTo("Expected an int but was NULL at path $"); } try { adapter.toJson(null); fail(); } catch (NullPointerException expected) { } }
Source:
static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } }

Target:
static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); }
Source:
private void setValues( Object... values ) { removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, "composite", encoding, values[i] ); document.add( reusableField ); } }

Target:
private void setValues( Object... values ) { removeAllValueFields(); for ( int i = 0; i < values.length; i++ ) { ValueEncoding encoding = ValueEncoding.forValue( values[i] ); Field reusableField = getFieldWithValue( i, encoding, values[i] ); document.add( reusableField ); } }