auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Span[] tokenizePos(String d) { List<Span> tokens = new ArrayList<Span>(); BreakIterator bi = BreakIterator.getWordInstance(locale); bi.setText(d); int lastIndex = bi.first(); while (lastIndex != BreakIterator.DONE) { int firstIndex = lastIndex; lastIndex = bi.next(); if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(d.charAt(firstIndex))) { tokens.add(new Span(firstIndex, lastIndex)); } } return tokens.toArray(new Span[tokens.size()]); }

Target:
public Span[] tokenizePos(String d) { List<Span> tokens = new ArrayList<>(); breakIterator.setText(d); int lastIndex = breakIterator.first(); while (lastIndex != BreakIterator.DONE) { int firstIndex = lastIndex; lastIndex = breakIterator.next(); if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(d.charAt(firstIndex))) { tokens.add(new Span(firstIndex, lastIndex)); } } return tokens.toArray(new Span[tokens.size()]); }
Source:
private void printSummary(cucumber.runtime.Runtime runtime) { runtime.getSummaryCounter().printSummary(out); }

Target:
private void printSummary(cucumber.runtime.Runtime runtime) { runtime.printSummary(out); }
Source:
public boolean step() { if (applyModulesThread != null) { if (!applyModulesThread.isAlive()) { if (oldEnvironment != null) { oldEnvironment.close(); } return true; } return false; } else { ModuleManager moduleManager = context.get(ModuleManager.class); List<Name> moduleIds = Lists.newArrayListWithCapacity(gameManifest.getModules().size()); moduleIds.addAll(gameManifest.getModules().stream().map(NameVersion::getName).collect(Collectors.toList())); DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry()); ResolutionResult result = resolver.resolve(moduleIds); if (result.isSuccess()) { oldEnvironment = moduleManager.getEnvironment(); ModuleEnvironment env = moduleManager.loadEnvironment(result.getModules(), true); for (Module moduleInfo : env.getModulesOrderedByDependencies()) { logger.info("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion()); } EnvironmentSwitchHandler environmentSwitchHandler = context.get(EnvironmentSwitchHandler.class); applyModulesThread = new Thread(() -> environmentSwitchHandler.handleSwitchToGameEnvironment(context)); applyModulesThread.start(); return false; } else { logger.warn("Missing at least one required module or dependency: {}", moduleIds); context.get(GameEngine.class).changeState(new StateMainMenu("Missing required module or dependency")); return true; } } }

Target:
public boolean step() { if (applyModulesThread != null) { if (!applyModulesThread.isAlive()) { if (oldEnvironment != null) { oldEnvironment.close(); } return true; } return false; } else { ModuleManager moduleManager = context.get(ModuleManager.class); List<Name> moduleIds = gameManifest.getModules().stream().map(NameVersion::getName) .collect(Collectors.toCollection(ArrayList::new)); DependencyResolver resolver = new DependencyResolver(moduleManager.getRegistry()); ResolutionResult result = resolver.resolve(moduleIds); if (result.isSuccess()) { oldEnvironment = moduleManager.getEnvironment(); ModuleEnvironment env = moduleManager.loadEnvironment(result.getModules(), true); for (Module moduleInfo : env.getModulesOrderedByDependencies()) { logger.info("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion()); } EnvironmentSwitchHandler environmentSwitchHandler = context.get(EnvironmentSwitchHandler.class); applyModulesThread = new Thread(() -> environmentSwitchHandler.handleSwitchToGameEnvironment(context)); applyModulesThread.start(); return false; } else { logger.warn("Missing at least one required module or dependency: {}", moduleIds); context.get(GameEngine.class).changeState(new StateMainMenu("Missing required module or dependency")); return true; } } }
Source:
private void handleSuccessfulRetry(ExecutionCompletedEvent<HermesResponse> event) { HermesMessage message = event.getResult().getHermesMessage(); messageDeliveryListeners.forEach(l -> l.onSuccessfulRetry(event.getResult(), event.getAttemptCount())); }

Target:
private void handleSuccessfulRetry(ExecutionCompletedEvent<HermesResponse> event) { messageDeliveryListeners.forEach(l -> l.onSuccessfulRetry(event.getResult(), event.getAttemptCount())); }
Source:
public void testClosureEntryPoint() throws Exception { Options opts = new Options(new String[] { "foo.js", "--closure_entry_point", "entryPoint", "--externs", "extern1.js", "extern2.js", "-o", "output.d.ts" }); assertThat(opts.arguments).containsExactly("foo.js"); assertThat(opts.entryPoints).containsExactly("entryPoint"); assertThat(opts.externs).containsExactly("extern1.js", "extern2.js").inOrder(); assertThat(opts.output).isEqualTo("output.d.ts"); }

Target:
public void testClosureEntryPoint() throws Exception { Options opts = new Options(new String[] { "foo.js", "--closure_entry_points", "ns.entryPoint1", "ns.entryPoint2", "--externs", "extern1.js", "extern2.js", "-o", "output.d.ts" }); assertThat(opts.arguments).containsExactly("foo.js"); assertThat(opts.entryPoints).containsExactly("ns.entryPoint1", "ns.entryPoint2"); assertThat(opts.externs).containsExactly("extern1.js", "extern2.js").inOrder(); assertThat(opts.output).isEqualTo("output.d.ts"); }
Source:
public static File newFile(final String parentDir, final String... childDirs) { final List<String> dirs = new ArrayList<>(); dirs.add(parentDir); dirs.addAll(List.of(childDirs)); return new File(String.join(File.separator, dirs)); }

Target:
public static File newFile(final String parentDir, final String... childDirs) { return Path.of(parentDir, childDirs).toFile(); }
Source:
public static DeviceManagementService getDeviceManagementService() throws DeviceManagementServiceException { DeviceManagementService deviceManagementService; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext(); context.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); context.setTenantId(MultitenantConstants.SUPER_TENANT_ID); deviceManagementService = (DeviceManagementService) context .getOSGiService(DeviceManagementService.class, null); if (deviceManagementService == null) { String msg = "Device management service not initialized."; log.error(msg); throw new DeviceManagementServiceException(msg); } PrivilegedCarbonContext.endTenantFlow(); return deviceManagementService; }

Target:
public static DeviceManagementService getDeviceManagementService() throws DeviceManagementServiceException { DeviceManagementService deviceManagementService; PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext(); context.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); context.setTenantId(MultitenantConstants.SUPER_TENANT_ID); deviceManagementService = (DeviceManagementService) context .getOSGiService(DeviceManagementService.class, null); if (deviceManagementService == null) { throw new DeviceManagementServiceException("Device management service is not initialized."); } PrivilegedCarbonContext.endTenantFlow(); return deviceManagementService; }
Source:
private ContentEquivalenceUpdater.Builder<Item> ebsItemUpdater(Set<Publisher> acceptablePublishers, Set<? extends EquivalenceScorer<Item>> scorers) { NullScoreAwareAveragingCombiner<Item> combiner = new NullScoreAwareAveragingCombiner<>(); combiner.setIgnoreNullScoringContent(true); return ContentEquivalenceUpdater.<Item> builder() .withGenerators(ImmutableSet.<EquivalenceGenerator<Item>> of( new BroadcastMatchingItemEquivalenceGenerator(scheduleResolver, channelResolver, acceptablePublishers, Duration.standardMinutes(5), Predicates.alwaysTrue()) )) .withExcludedUris(excludedUrisFromProperties()) .withScorers(scorers) .withCombiner(combiner) .withFilter(this.standardFilter()) .withExtractor(PercentThresholdAboveNextBestMatchEquivalenceExtractor.atLeastNTimesGreater(1.5)) .withHandler(new BroadcastingEquivalenceResultHandler<Item>(ImmutableList.of( EpisodeFilteringEquivalenceResultHandler.relaxed( new LookupWritingEquivalenceHandler<Item>(lookupWriter, acceptablePublishers), equivSummaryStore ), new ResultWritingEquivalenceHandler<Item>(equivalenceResultStore()), new EquivalenceSummaryWritingHandler<Item>(equivSummaryStore), MessageQueueingResultHandler.create( equivAssertDestination(), acceptablePublishers, lookupEntryStore ) ))); }

Target:
private ContentEquivalenceUpdater.Builder<Item> ebsItemUpdater( Set<Publisher> acceptablePublishers, Set<? extends EquivalenceScorer<Item>> scorers ) { NullScoreAwareAveragingCombiner<Item> combiner = new NullScoreAwareAveragingCombiner<>(true); return ContentEquivalenceUpdater.<Item> builder() .withGenerators(ImmutableSet.<EquivalenceGenerator<Item>> of( new BroadcastMatchingItemEquivalenceGenerator( scheduleResolver, channelResolver, acceptablePublishers, Duration.standardMinutes(5), Predicates.alwaysTrue()) )) .withExcludedUris(excludedUrisFromProperties()) .withScorers(scorers) .withCombiner(combiner) .withFilter(this.standardFilter()) .withExtractor( PercentThresholdAboveNextBestMatchEquivalenceExtractor .atLeastNTimesGreater(1.5) ) .withHandler(new BroadcastingEquivalenceResultHandler<Item>(ImmutableList.of( EpisodeFilteringEquivalenceResultHandler.relaxed( new LookupWritingEquivalenceHandler<Item>( lookupWriter, acceptablePublishers), equivSummaryStore ), new ResultWritingEquivalenceHandler<Item>(equivalenceResultStore()), new EquivalenceSummaryWritingHandler<Item>(equivSummaryStore), MessageQueueingResultHandler.create( equivAssertDestination(), acceptablePublishers, lookupEntryStore ) ))); }
Source:
public boolean shouldSkipField(FieldAttributes f) { GsonOmitField annotation = f.getAnnotation(GsonOmitField.class); if (annotation != null) return true; String fieldName = f.getName(); Class<?> definedIn = f.getDeclaringClass(); for (Entry<String, Class<?>> include : serializee.getIncludes().entries()) { if (isCompatiblePath(include, definedIn, fieldName)) { return false; } } for (Entry<String, Class<?>> exclude : serializee.getExcludes().entries()) { if (isCompatiblePath(exclude, definedIn, fieldName)) { return true; } } return !serializee.isRecursive() && !shouldSerializeField(new Mirror().on(definedIn).reflect().field(fieldName).getType()); }

Target:
public boolean shouldSkipField(FieldAttributes f) { SkipSerialization annotation = f.getAnnotation(SkipSerialization.class); if (annotation != null) return true; String fieldName = f.getName(); Class<?> definedIn = f.getDeclaringClass(); for (Entry<String, Class<?>> include : serializee.getIncludes().entries()) { if (isCompatiblePath(include, definedIn, fieldName)) { return false; } } for (Entry<String, Class<?>> exclude : serializee.getExcludes().entries()) { if (isCompatiblePath(exclude, definedIn, fieldName)) { return true; } } return !serializee.isRecursive() && !shouldSerializeField(new Mirror().on(definedIn).reflect().field(fieldName).getType()); }
Source:
private List<ReferenceCountingResourceHolder<ByteBuffer>> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured" ); } final List<ReferenceCountingResourceHolder<ByteBuffer>> mergeBufferHolder; if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new InsufficientResourcesException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } }

Target:
private List<ReferenceCountingResourceHolder<ByteBuffer>> getMergeBuffersHolder( int numBuffers, boolean hasTimeout, long timeoutAt ) { try { if (numBuffers > mergeBufferPool.maxSize()) { throw new ResourceLimitExceededException( "Query needs " + numBuffers + " merge buffers, but only " + mergeBufferPool.maxSize() + " merge buffers were configured. " + "Try raising druid.processing.numMergeBuffers." ); } final List<ReferenceCountingResourceHolder<ByteBuffer>> mergeBufferHolder; if (hasTimeout) { final long timeout = timeoutAt - System.currentTimeMillis(); if (timeout <= 0) { throw new TimeoutException(); } if ((mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers, timeout)).isEmpty()) { throw new TimeoutException("Cannot acquire enough merge buffers"); } } else { mergeBufferHolder = mergeBufferPool.takeBatch(numBuffers); } return mergeBufferHolder; } catch (Exception e) { throw new QueryInterruptedException(e); } }
Source:
public void GetSQLWithPreservedColumnOrder() { com.mysema.query.sql.domain.QEmployee emp1 = new com.mysema.query.sql.domain.QEmployee("emp1"); SQLInsertClause insert = new SQLInsertClause(null, SQLTemplates.DEFAULT, emp1); insert.populate(emp1); SQLBindings sql = insert.getSQL().get(0); assertEquals("The order of columns in generated sql should be predictable", "insert into EMPLOYEE (SALARY, SUPERIOR_ID, DATEFIELD, FIRSTNAME, TIMEFIELD, ID, LASTNAME)" + "values (EMPLOYEE.SALARY, EMPLOYEE.SUPERIOR_ID, EMPLOYEE.DATEFIELD, EMPLOYEE.FIRSTNAME, " + "EMPLOYEE.TIMEFIELD, EMPLOYEE.ID, EMPLOYEE.LASTNAME)", sql.getSQL()); }

Target:
public void GetSQLWithPreservedColumnOrder() { QEmployee emp1 = new QEmployee("emp1"); SQLInsertClause insert = new SQLInsertClause(null, SQLTemplates.DEFAULT, emp1); insert.populate(emp1); SQLBindings sql = insert.getSQL().get(0); assertEquals("The order of columns in generated sql should be predictable", "insert into EMPLOYEE (ID, FIRSTNAME, LASTNAME, SALARY, DATEFIELD, TIMEFIELD, SUPERIOR_ID)\n" + "values (EMPLOYEE.ID, EMPLOYEE.FIRSTNAME, EMPLOYEE.LASTNAME, EMPLOYEE.SALARY, EMPLOYEE.DATEFIELD, EMPLOYEE.TIMEFIELD, EMPLOYEE.SUPERIOR_ID)", sql.getSQL()); }
Source:
private static MapBasedEndpointContext setInfo(OSCoreCtx oscoreCtx, EndpointContext endpointContext) { MapBasedEndpointContext newEndpointContext = MapBasedEndpointContext.addEntries( endpointContext, OSCORE, Boolean.TRUE.toString(), OSCORE_SENDER_ID, oscoreCtx.getSenderIdString(), OSCORE_RECIPIENT_ID, oscoreCtx.getRecipientIdString(), OSCORE_CONTEXT_ID, oscoreCtx.getContextIdString(), OSCORE_URI, oscoreCtx.getUri()); return newEndpointContext; }

Target:
private static MapBasedEndpointContext setInfo(OSCoreCtx oscoreCtx, EndpointContext endpointContext) { if (endpointContext == null) { return null; } List<String> attributes = new ArrayList<String>(); add(attributes, OSCORE_SENDER_ID, oscoreCtx.getSenderIdString()); add(attributes, OSCORE_RECIPIENT_ID, oscoreCtx.getRecipientIdString()); add(attributes, OSCORE_CONTEXT_ID, oscoreCtx.getContextIdString()); add(attributes, OSCORE_URI, oscoreCtx.getUri()); MapBasedEndpointContext newEndpointContext = MapBasedEndpointContext.addEntries(endpointContext, attributes.toArray(new String[attributes.size()])); return newEndpointContext; }
Source:
protected int countEvents(Map<Object, LinkedList<ITmfEvent>> tbl) { Iterator<Entry<Object, LinkedList<ITmfEvent>>> iterator = tbl.entrySet().iterator(); int count = 0; while (iterator.hasNext()) { count += iterator.next().getValue().size(); } return count; }

Target:
protected int countEvents(Map<Object, LinkedList<ITmfEvent>> tbl) { int count = 0; for (LinkedList<ITmfEvent> entry : tbl.values()) { count += entry.size(); } return count; }
Source:
public static String formatDateTimeForComments(Date date, double sessionTimeZone) { if (date == null) { return ""; } SimpleDateFormat sdf = null; Calendar c = Calendar.getInstance(SystemParams.TIME_ZONE); c.setTime(date); String sign = sessionTimeZone > 0 ? "+" : "-"; int hours = (int) sessionTimeZone; int minutes = (int) ((sessionTimeZone - Math.floor(sessionTimeZone)) * 60); String offset = Integer.toString(hours); if (minutes != 0) { offset = Integer.toString(hours) + ":" + Integer.toString(minutes); } String timeZone = TimeZone.getTimeZone("GMT" + sign + offset).getID(); if (c.get(Calendar.HOUR_OF_DAY) == 12 && c.get(Calendar.MINUTE) == 0) { sdf = new SimpleDateFormat("EEE, dd MMM yyyy, hh:mm"); sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); return sdf.format(date) + " NOON UTC"; } sdf = new SimpleDateFormat("EEE, dd MMM yyyy, hh:mm a Z"); sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); return sdf.format(date); }

Target:
public static String formatDateTimeForComments(Date date, double sessionTimeZone) { if (date == null) { return ""; } SimpleDateFormat sdf = null; Calendar c = Calendar.getInstance(SystemParams.TIME_ZONE); TimeZone timeZone = getTimeZoneFromDoubleOffset(sessionTimeZone); c.setTimeZone(timeZone); c.setTime(date); String periodIndicator = c.get(Calendar.HOUR_OF_DAY) == 12 && c.get(Calendar.MINUTE) == 0 ? "'NOON'" : "a"; sdf = new SimpleDateFormat("EEE, dd MMM yyyy, hh:mm " + periodIndicator + " 'UTC'Z"); sdf.setTimeZone(timeZone); return sdf.format(date); }
Source:
public void telemetrySentWorks() throws InterruptedException { for(int i = 0; i < 5; i++) { try { cl.loadClass("sun.java.MyNonExistentClass"); } catch (ClassNotFoundException ignored) { } } ExtensionList.lookupSingleton(Telemetry.TelemetryReporter.class).doRun(); do { Thread.sleep(250); } while (received == null); assertEquals(MissingClassTelemetry.class.getName(), received.getString("type")); JSONArray events = received.getJSONObject("payload").getJSONArray("classMissingEvents"); assertEquals(1, events.size()); assertEquals("sun.java.MyNonExistentClass", ((JSONObject) events.get(0)).get("className")); assertEquals(5, Integer.parseInt( (String) ((JSONObject) events.get(0)).get("occurrences"))); }

Target:
public void telemetrySentWorks() throws InterruptedException { Assume.assumeTrue("The telemetry should be enabled", MissingClassTelemetry.enabled()); for(int i = 0; i < 5; i++) { try { cl.loadClass("sun.java.MyNonExistentClass"); } catch (ClassNotFoundException ignored) { } } ExtensionList.lookupSingleton(Telemetry.TelemetryReporter.class).doRun(); do { Thread.sleep(250); } while (received == null); assertEquals(MissingClassTelemetry.class.getName(), received.getString("type")); JSONArray events = received.getJSONObject("payload").getJSONArray("classMissingEvents"); assertEquals(1, events.size()); assertEquals("sun.java.MyNonExistentClass", ((JSONObject) events.get(0)).get("className")); assertEquals(5, Integer.parseInt( (String) ((JSONObject) events.get(0)).get("occurrences"))); }
Source:
protected int doWrite() { WriteData wd = writeQueue.poll(); if(wd != null) { try { return channel.send(wd.getBuffer(), wd.getAddress()); } catch (IOException e) { return 0; } finally { if(wd.getSlf() != null && !wd.getSlf().isDone()) { wd.getSlf().setResult(0L); } } } return 0; }

Target:
protected int doWrite() { WriteData wd = writeQueue.poll(); if(wd != null) { int size = 0; try { size = channel.send(wd.getBuffer(), wd.getAddress()); wd.getSlf().setResult((long)size); return size; } catch (Exception e) { wd.getSlf().setFailure(e); return 0; } } return 0; }
Source:
private static byte getSaltingByte(byte[] value, int offset, int length, int bucketNum) { HashCode digest = MD5.hashBytes(value, offset, length); byte bucketByte = (byte) ((Math.abs(digest.asInt()) % bucketNum) & 0x0f); return bucketByte; }

Target:
public static byte getSaltingByte(byte[] value, int offset, int length, int bucketNum) { int hash = hashCode(value, offset, length); byte bucketByte = (byte) ((Math.abs(hash) % bucketNum)); return bucketByte; }
Source:
public ConfigInfos validateConnectorConfig(String connClassName, Map<String, String> connConfig) throws JsonProcessingException { String url = endpointForResource(String.format("connector-plugins/%s/config/validate", connClassName)); ObjectMapper mapper = new ObjectMapper(); String content; try { content = mapper.writeValueAsString(connConfig); } catch (IOException e) { throw new ConnectException("Could not serialize connector configuration and execute PUT request"); } Response response = requestPut(url, content); if (response.getStatus() < Response.Status.BAD_REQUEST.getStatusCode()) { return mapper.readValue(response.getEntity().toString(), ConfigInfos.class); } throw new ConnectRestException(response.getStatus(), "Could not execute PUT request. Error response: " + responseToString(response)); }

Target:
public ConfigInfos validateConnectorConfig(String connClassName, Map<String, String> connConfig) { String url = endpointForResource(String.format("connector-plugins/%s/config/validate", connClassName)); String response = putConnectorConfig(url, connConfig); ConfigInfos configInfos; try { configInfos = new ObjectMapper().readValue(response, ConfigInfos.class); } catch (IOException e) { throw new ConnectException("Unable deserialize response into a ConfigInfos object"); } return configInfos; }
Source:
private boolean updateVm(VM vm, Version oldClusterVersion) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setClusterLevelChangeFromVersion(oldClusterVersion); VdcReturnValueBase result = runInternalAction( VdcActionType.UpdateVm, updateParams, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { getReturnValue().setFault(result.getFault()); return false; } return true; }

Target:
private boolean updateVm(VM vm, Version oldClusterVersion) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldClusterVersion); VdcReturnValueBase result = runInternalAction( VdcActionType.UpdateVm, updateParams, cloneContextAndDetachFromParent()); if (!result.getSucceeded()) { getReturnValue().setFault(result.getFault()); return false; } return true; }
Source:
private ClientAuth requireClientAuth(SslConfiguration sslConfig) { return sslConfig.enabled() ? ClientAuth.REQUIRE : ClientAuth.NONE; }

Target:
private ClientAuth requireClientAuth(SslConfiguration sslConfig) { return sslConfig.requireClientAuth() ? ClientAuth.REQUIRE : ClientAuth.NONE; }
Source:
public synchronized void syncRoutingTable(final String serverId) { if (!storeIdToEndpointId.containsValue(serverId)) { msgSender.get().sendRoutingTableSyncReplyMsg(serverId); } else { ongoingSyncs.add(serverId); } }

Target:
public void syncRoutingTable(final String serverId) { checkInitialization(); synchronized (this) { if (!storeIdToBlockIds.containsKey(serverId)) { msgSender.get().sendRoutingTableSyncReplyMsg(serverId); } else { ongoingSyncs.add(serverId); } } }
Source:
private int setWifiTethering(final boolean enable) { int rval = TETHER_ERROR_MASTER_ERROR; final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { final WifiManager mgr = getWifiManager(); if (mgr == null) { mLog.e("setWifiTethering: failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { mWifiTetherRequested = enable; return TETHER_ERROR_NO_ERROR; } return TETHER_ERROR_MASTER_ERRROR; } } finally { Binder.restoreCallingIdentity(ident); } return rval; }

Target:
private int setWifiTethering(final boolean enable) { final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { final WifiManager mgr = getWifiManager(); if (mgr == null) { mLog.e("setWifiTethering: failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { mWifiTetherRequested = enable; return TETHER_ERROR_NO_ERROR; } } } finally { Binder.restoreCallingIdentity(ident); } return TETHER_ERROR_MASTER_ERROR; }
Source:
private static String env(ServletContext context) { String systemEnv = System.getenv("VRAPTOR_ENVIRONMENT"); if (systemEnv != null) { return systemEnv; } String systemProperty = System.getProperty(ENVIRONMENT_PROPERTY); if (systemProperty != null) { return systemProperty; } return context.getInitParameter(ENVIRONMENT_PROPERTY); }

Target:
private static String env(ServletContext context) { String systemEnv = System.getenv("VRAPTOR_ENV"); if (systemEnv != null) { return systemEnv; } String systemProperty = System.getProperty(ENVIRONMENT_PROPERTY); if (systemProperty != null) { return systemProperty; } return context.getInitParameter(ENVIRONMENT_PROPERTY); }
Source:
public static void onFailedAdminLogin(HttpSession httpSess, String username, int tenantId, String tenantDomain, String remoteAddress, String reason) throws Exception { if (httpSess != null) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setUsername(username); carbonContext.setTenantId(tenantId); if (tenantDomain == null) { tenantDomain = carbonContext.getTenantDomain(true); } carbonContext.setTenantDomain(tenantDomain); } Date currentTime = Calendar.getInstance().getTime(); SimpleDateFormat date = new SimpleDateFormat("'['yyyy-MM-dd HH:mm:ss,SSSZ']'"); String msg = "Non-Admin user login attempt \'" + username + "[" + tenantId + "]\' at " + date.format(currentTime); if(!CarbonUtils.isRunningOnLocalTransportMode()){ msg += " from IP address " + remoteAddress; } log.warn(msg); audit.warn(msg); if (httpSess != null) { httpSess.invalidate(); } LoginAttempt loginAttempt = new LoginAttempt(username, tenantId, remoteAddress, new Date(), false, reason); LoginStatDatabase.recordLoginAttempt(loginAttempt); }

Target:
public static void onFailedAdminLogin(HttpSession httpSess, String username, int tenantId, String tenantDomain, String remoteAddress, String reason) throws Exception { if (httpSess != null) { PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); carbonContext.setUsername(username); carbonContext.setTenantId(tenantId); if (tenantDomain == null) { tenantDomain = carbonContext.getTenantDomain(true); } carbonContext.setTenantDomain(tenantDomain); } Date currentTime = Calendar.getInstance().getTime(); SimpleDateFormat date = new SimpleDateFormat("'['yyyy-MM-dd HH:mm:ss,SSSZ']'"); String msg = "Login failed. Unauthorized login attempt \'" + username + "[" + tenantId + "]\' at " + date.format(currentTime); if(!CarbonUtils.isRunningOnLocalTransportMode()){ msg += " from IP address " + remoteAddress; } log.warn(msg); audit.warn(msg); if (httpSess != null) { httpSess.invalidate(); } LoginAttempt loginAttempt = new LoginAttempt(username, tenantId, remoteAddress, new Date(), false, reason); LoginStatDatabase.recordLoginAttempt(loginAttempt); }
Source:
public @ResponseBody Promise<CodeSystems> searchByGet(final CodeSystemRestSearch params) { final IEventBus bus = getBus(); return RepositoryRequests.prepareSearch() .all() .buildAsync() .execute(bus) .thenWith(repos -> searchByGet(params, repos, bus)); }

Target:
public Promise<CodeSystems> searchByGet(final CodeSystemRestSearch params) { checkArgument(params.getSearchAfter() == null, "Parameter 'searchAfter' is not supported for code system search."); final IEventBus bus = getBus(); return RepositoryRequests.prepareSearch() .all() .buildAsync() .execute(bus) .thenWith(repos -> searchByGet(params, repos, bus)); }
Source:
public CompletableFuture<Iterator<Result>> apply(Collection<ConditionalMutation> input) { CompletableFuture<Iterator<Result>> cfRes = new CompletableFuture<>(); if (input.size() == 0) { cfRes.complete(Collections.<Result>emptyList().iterator()); return cfRes; } semaphore.acquire(input.size()); Iterator<Result> iter = cw.write(input.iterator()); CompletableFuture.runAsync(() -> { try { Iterator<Result> iterRes = new IterTask(iter, input.size()).call(); cfRes.complete(iterRes); } catch (Exception e) { cfRes.completeExceptionally(e); } }, es); return cfRes; }

Target:
public CompletableFuture<Iterator<Result>> apply(Collection<ConditionalMutation> input) { if (input.size() == 0) { return CompletableFuture.completedFuture(Collections.<Result>emptyList().iterator()); } semaphore.acquire(input.size()); Iterator<Result> iter = cw.write(input.iterator()); return CompletableFuture.supplyAsync(() -> { try { Builder<Result> imlb = ImmutableList.builder(); while (iter.hasNext()) { Result result = iter.next(); imlb.add(result); } return imlb.build().iterator(); } finally { semaphore.release(input.size()); } }, es); }
Source:
private TableSourceTable applyLimit( long limit, FlinkPreparingTableBase relOptTable) { TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class); DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy(); ((SupportsLimitPushDown) newTableSource).applyLimit(limit); FlinkStatistic statistic = relOptTable.getStatistic(); long newRowCount = 0; if (statistic.getRowCount() != null) { newRowCount = Math.min(limit, statistic.getRowCount().longValue()); } else { newRowCount = limit; } TableStats newTableStats = new TableStats(newRowCount); FlinkStatistic newStatistic = FlinkStatistic.builder() .statistic(statistic) .tableStats(newTableStats) .build(); String[] newExtraDigests = new String[0]; if (limit > 0) { String extraDigest = "limit=[" + limit + "]"; newExtraDigests = new String[]{extraDigest}; } return oldTableSourceTable.copy( newTableSource, newStatistic, newExtraDigests ); }

Target:
private TableSourceTable applyLimit( long limit, FlinkPreparingTableBase relOptTable) { TableSourceTable oldTableSourceTable = relOptTable.unwrap(TableSourceTable.class); DynamicTableSource newTableSource = oldTableSourceTable.tableSource().copy(); ((SupportsLimitPushDown) newTableSource).applyLimit(limit); FlinkStatistic statistic = relOptTable.getStatistic(); long newRowCount = 0; if (statistic.getRowCount() != null) { newRowCount = Math.min(limit, statistic.getRowCount().longValue()); } else { newRowCount = limit; } TableStats newTableStats = new TableStats(newRowCount); FlinkStatistic newStatistic = FlinkStatistic.builder() .statistic(statistic) .tableStats(newTableStats) .build(); String[] newExtraDigests = new String[]{"limit=[" + limit + "]"}; return oldTableSourceTable.copy( newTableSource, newStatistic, newExtraDigests ); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.video_selector); mSelectList = (ListView) findViewById(R.id.select_list); final Button playButton = (Button) findViewById(R.id.play_button); mUrlText = (EditText) findViewById(R.id.video_selection_input); mSelectItems = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { setUpInitialItemList(); } else { requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE); } } else { setUpInitialItemList(); } playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent launch = createLaunchIntent( VideoSelector.this, mUrlText.getText().toString()); startActivity(launch); } }); mLoopingCheckbox = findViewById(R.id.looping_checkbox); mLoopingCheckbox.setChecked(false); mTextureViewCheckbox = findViewById(R.id.use_textureview_checkbox); mTextureViewCheckbox.setChecked(false); mAdvertisementCheckBox = findViewById(R.id.media_type_advertisement); mAdvertisementCheckBox.setChecked(false); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyDeath() .build()); setContentView(R.layout.video_selector); mSelectList = (ListView) findViewById(R.id.select_list); final Button playButton = (Button) findViewById(R.id.play_button); mUrlText = (EditText) findViewById(R.id.video_selection_input); mSelectItems = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { setUpInitialItemList(); } else { requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE); } } else { setUpInitialItemList(); } playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent launch = createLaunchIntent( VideoSelector.this, mUrlText.getText().toString()); startActivity(launch); } }); mLoopingCheckbox = findViewById(R.id.looping_checkbox); mLoopingCheckbox.setChecked(false); mTextureViewCheckbox = findViewById(R.id.use_textureview_checkbox); mTextureViewCheckbox.setChecked(false); mAdvertisementCheckBox = findViewById(R.id.media_type_advertisement); mAdvertisementCheckBox.setChecked(false); }
Source:
public List<Device> getDevicesOfUser(String username, String deviceType, boolean requireDeviceInfo) throws DeviceManagementException { if (username != null && deviceType != null) { if (log.isDebugEnabled()) { log.debug("Get '" + deviceType + "' devices of user with username '" + username + "' requiredDeviceInfo: " + requireDeviceInfo); } } else { String msg = "received incomplete data for getDevicesOfUser"; log.error(msg); throw new DeviceManagementException(msg); } List<Device> userDevices; try { DeviceManagementDAOFactory.openConnection(); userDevices = deviceDAO.getDevicesOfUser(username, deviceType, this.getTenantId()); } catch (DeviceManagementDAOException e) { String msg = "Error occurred while retrieving the list of devices that " + "belong to the user '" + username + "'"; log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the data source"; log.error(msg); throw new DeviceManagementException(msg, e); } catch (Exception e) { String msg = "Error occurred"; log.error(msg, e); throw new DeviceManagementException(msg, e); } finally { DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { return this.getAllDeviceInfo(userDevices); } return userDevices; }

Target:
public List<Device> getDevicesOfUser(String username, String deviceType, boolean requireDeviceInfo) throws DeviceManagementException { if (username == null || deviceType == null) { String msg = "Received incomplete data for getDevicesOfUser"; log.error(msg); throw new DeviceManagementException(msg); } if (log.isDebugEnabled()) { log.debug("Get '" + deviceType + "' devices of user with username '" + username + "' requiredDeviceInfo: " + requireDeviceInfo); } List<Device> userDevices; try { DeviceManagementDAOFactory.openConnection(); userDevices = deviceDAO.getDevicesOfUser(username, deviceType, this.getTenantId()); } catch (DeviceManagementDAOException e) { String msg = "Error occurred while retrieving the list of devices that " + "belong to the user '" + username + "'"; log.error(msg, e); throw new DeviceManagementException(msg, e); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the data source"; log.error(msg); throw new DeviceManagementException(msg, e); } catch (Exception e) { String msg = "Error occurred in getDevicesOfUser for '" + username + "'"; log.error(msg, e); throw new DeviceManagementException(msg, e); } finally { DeviceManagementDAOFactory.closeConnection(); } if (requireDeviceInfo) { return this.getAllDeviceInfo(userDevices); } return userDevices; }
Source:
public Transaction getTransactionById(Object id) { return com.arjuna.ats.internal.jta.transaction.jts.TransactionImple.getTransaction((Uid) id); }

Target:
public Transaction getTransactionById(Object id) { return TransactionImple.getTransaction((Uid) id); }
Source:
private int setWifiTethering(final boolean enable) { int rval = TETHER_ERROR_MASTER_ERROR; final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { mWifiTetherRequested = enable; final WifiManager mgr = getWifiManager(); if (mgr == null) { Log.e(TAG, "setWifiTethering: failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { rval = TETHER_ERROR_NO_ERROR; } } } finally { Binder.restoreCallingIdentity(ident); } return rval; }

Target:
private int setWifiTethering(final boolean enable) { int rval = TETHER_ERROR_MASTER_ERROR; final long ident = Binder.clearCallingIdentity(); try { synchronized (mPublicSync) { mWifiTetherRequested = enable; final WifiManager mgr = getWifiManager(); if (mgr == null) { mLog.e(TAG, "setWifiTethering: failed to get WifiManager!"); return TETHER_ERROR_SERVICE_UNAVAIL; } if ((enable && mgr.startSoftAp(null )) || (!enable && mgr.stopSoftAp())) { rval = TETHER_ERROR_NO_ERROR; } } } finally { Binder.restoreCallingIdentity(ident); } return rval; }
Source:
public void stateChanged(final ChangeEvent<ServerDescription> event) { description = event.getNewValue(); for (final ChangeListener<ServerDescription> listener : changeListeners) { listener.stateChanged(event); } }

Target:
public void stateChanged(final ChangeEvent<ServerDescription> event) { description = event.getNewValue(); for (ChangeListener<ServerDescription> listener : changeListeners) { listener.stateChanged(event); } }
Source:
private ResourceModel parseResource(Node item) { Integer id = Integer.valueOf(item.getAttributes().getNamedItem("ID").getTextContent()); String name = null; Operations operations = Operations.NONE; boolean multiple = false; boolean mandatory = false; Type type = Type.STRING; String rangeEnumeration = null; String units = null; String description = null; for (int i = 0; i < item.getChildNodes().getLength(); i++) { Node field = item.getChildNodes().item(i); switch (field.getNodeName()) { case "Name": name = field.getTextContent(); break; case "Operations": String strOp = field.getTextContent(); if (strOp != null && !strOp.isEmpty()) { operations = Operations.valueOf(strOp); } break; case "MultipleInstances": multiple = "Multiple".equals(field.getTextContent()); break; case "Mandatory": mandatory = "Mandatory".equals(field.getTextContent()); break; case "Type": switch (field.getTextContent()) { case "String": type = Type.STRING; break; case "Integer": type = Type.INTEGER; break; case "Float": type = Type.FLOAT; break; case "Boolean": type = Type.BOOLEAN; break; case "Opaque": type = Type.OPAQUE; break; case "Time": type = Type.TIME; break; case "Objlnk": type = Type.OBJECTLINK; break; } break; case "RangeEnumeration": rangeEnumeration = field.getTextContent(); break; case "Units": units = field.getTextContent(); break; case "Description": description = field.getTextContent(); break; } } return new ResourceModel(id, name, operations, multiple, mandatory, type, rangeEnumeration, units, description); }

Target:
private ResourceModel parseResource(Node item) { Integer id = Integer.valueOf(item.getAttributes().getNamedItem("ID").getTextContent()); String name = null; Operations operations = Operations.NONE; boolean multiple = false; boolean mandatory = false; Type type = Type.STRING; String rangeEnumeration = null; String units = null; String description = null; for (int i = 0; i < item.getChildNodes().getLength(); i++) { Node field = item.getChildNodes().item(i); switch (field.getNodeName()) { case "Name": name = field.getTextContent(); break; case "Operations": String strOp = field.getTextContent(); if (strOp != null && !strOp.isEmpty()) { operations = Operations.valueOf(strOp); } break; case "MultipleInstances": multiple = "Multiple".equals(field.getTextContent()); break; case "Mandatory": mandatory = "Mandatory".equals(field.getTextContent()); break; case "Type": switch (field.getTextContent()) { case "String": type = Type.STRING; break; case "Integer": type = Type.INTEGER; break; case "Float": type = Type.FLOAT; break; case "Boolean": type = Type.BOOLEAN; break; case "Opaque": type = Type.OPAQUE; break; case "Time": type = Type.TIME; break; } break; case "RangeEnumeration": rangeEnumeration = field.getTextContent(); break; case "Units": units = field.getTextContent(); break; case "Description": description = field.getTextContent(); break; } } return new ResourceModel(id, name, operations, multiple, mandatory, type, rangeEnumeration, units, description); }
Source:
MessageCreator(String source, List<String> destination, String text) { if (!Utils.allNotNull(source, destination)) { throw new IllegalArgumentException("source, destination and text must not be null"); } if (destination.contains(source)) { throw new IllegalArgumentException("destination cannot include source"); } this.source = source; this.destination = destination; this.text = text; }

Target:
MessageCreator(String source, List<String> destination, String text) { if (!Utils.allNotNull(source, destination)) { throw new IllegalArgumentException("source, destination must not be null"); } if (destination.contains(source)) { throw new IllegalArgumentException("destination cannot include source"); } this.source = source; this.destination = destination; this.text = text; }
Source:
private byte[] ungzip(byte[] body) { ByteArrayInputStream bytein = new ByteArrayInputStream(body); GZIPInputStream gzin = null; try { gzin = new GZIPInputStream(bytein); ByteArrayOutputStream byteout = new ByteArrayOutputStream(); int res = 0; byte buf[] = new byte[1024]; while (res >= 0) { res = gzin.read(buf, 0, buf.length); if (res > 0) { byteout.write(buf, 0, res); } } byte uncompressed[] = byteout.toByteArray(); return uncompressed; } catch (IOException e) { return null; } }

Target:
private byte[] ungzip(byte[] body) { ByteArrayInputStream bytein = new ByteArrayInputStream(body); try (GZIPInputStream gzin = new GZIPInputStream(bytein); ByteArrayOutputStream byteout = new ByteArrayOutputStream()) { int res = 0; byte buf[] = new byte[1024]; while (res >= 0) { res = gzin.read(buf, 0, buf.length); if (res > 0) { byteout.write(buf, 0, res); } } byte uncompressed[] = byteout.toByteArray(); return uncompressed; } catch (IOException e) { } return null; }
Source:
public void testBuildMessageNumberSetsWithOneString() throws ImapAsyncClientException { final String msgSetStr = "1"; final MessageNumberSet messageNumberSet = new MessageNumberSet(1, 1); final MessageNumberSet[] messageNumberSets = MessageNumberSet.buildMessageNumberSets(msgSetStr); Assert.assertNotNull(messageNumberSets, "Result mismatched."); Assert.assertEquals(messageNumberSets.length, 1, "Result mismatched."); Assert.assertTrue(messageNumberSets[0].equals(messageNumberSet), "Result mismatched"); }

Target:
public void testBuildMessageNumberSetsWithOneString() throws ImapAsyncClientException { final MessageNumberSet[] expectedMsgSets = { new MessageNumberSet(1, 1) }; final String msgSetStr = MessageNumberSet.buildString(expectedMsgSets); final MessageNumberSet[] actualMsgSets = MessageNumberSet.buildMessageNumberSets(msgSetStr); Assert.assertNotNull(actualMsgSets, "buildMessageNumberSets() should not return null."); Assert.assertEquals(actualMsgSets.length, 1, "buildMessageNumberSets() size mismatched."); Assert.assertEquals(actualMsgSets[0], expectedMsgSets[0], "buildMessageNumberSets() mismatched."); }
Source:
public static int get(String token) { int type = reservedKeys.get(token, -1); if (type == -1) { return commandSet.get(token, -1); } return type; }

Target:
static int get(String token) { int type = reservedKeys.get(token, -1); if (type == -1) { return commandSet.get(token, -1); } return type; }
Source:
public Object fromBytes(byte[] bytes) { try { final Object object; final MessageType type = MessageType.values()[bytes[0]]; final byte data = Arrays.copyOfRange(bytes, 1, bytes.length); switch (type) { case USER_MESSAGE: object = userMessageSerde.fromBytes(data); break; case WATERMARK: object = watermarkSerde.fromBytes(data); break; case END_OF_STREAM: object = eosSerde.fromBytes(data); break; default: object = null; break; } return object; } catch (Exception e) { return userMessageSerde.fromBytes(bytes); } }

Target:
public Object fromBytes(byte[] bytes) { try { final Object object; final MessageType type = MessageType.values()[bytes[0]]; final byte data = Arrays.copyOfRange(bytes, 1, bytes.length); switch (type) { case USER_MESSAGE: object = userMessageSerde.fromBytes(data); break; case WATERMARK: object = watermarkSerde.fromBytes(data); break; case END_OF_STREAM: object = eosSerde.fromBytes(data); break; default: throw new UnsupportedOperationException(String.format("Message type %s is not supported", type.name())); } return object; } catch (UnsupportedOperationException ue) { throw new SamzaException(ue); } catch (Exception e) { return userMessageSerde.fromBytes(bytes); } }
Source:
public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { return (getFacing() == facing && energyManager.hasCapability(capability)) || super.hasCapability(capability, facing); }

Target:
public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { return (facing == getFacing() && energyManager.hasCapability(capability)) || super.hasCapability(capability, facing); }
Source:
private void sendAvailablePresenceWithClientIdentifier() { String ver = EntityCapsManager.getInstanceFor(connection).getCapsVersion(); CapsExtension caps = new CapsExtension(XMPP_CLIENT_IDENTIFIER, ver, "sha-1"); Presence p = new Presence(Presence.Type.available); p.addExtension(caps); connection.sendPacket(p); }

Target:
private void sendAvailablePresenceWithClientIdentifier() { String version = EntityCapsManager.getInstanceFor(connection).getCapsVersion(); CapsExtension caps = new CapsExtension(XMPP_CLIENT_IDENTIFIER, version, CAPS_HASH_ALGORITHM); Presence presence = new Presence(Presence.Type.available); presence.addExtension(caps); connection.sendPacket(presence); }
Source:
public void setTaskPropertyCommandTest() throws Exception { SetTaskPropertyCommand cmd; int taskId = 1; String userId = "user"; FaultDataImpl faultData = new FaultDataImpl(); faultData.setAccessType(AccessType.Inline); faultData.setContent("skinned shins".getBytes()); faultData.setFaultName("Whoops!"); faultData.setType("skates"); List<I18NText> textList = new ArrayList<I18NText>(); I18NText text = new I18NTextImpl("nl-NL", "Stroopwafel!"); textList.add(text); Object [][] testData = { { FAULT_PROPERTY, faultData }, { OUTPUT_PROPERTY, new Object() }, { PRIORITY_PROPERTY, 23 }, { TASK_NAMES_PROPERTY, textList }, { EXPIRATION_DATE_PROPERTY, new Date() }, { DESCRIPTION_PROPERTY, new ArrayList<I18NText>() }, { SKIPPABLE_PROPERTY, false }, { SUB_TASK_STRATEGY_PROPERTY, SubTasksStrategy.EndParentOnAllSubTasksEnd } }; TaskContext mockContext = mock(TaskContext.class); TaskInstanceService mockTaskService = mock(TaskInstanceService.class); UserGroupCallback mockUserGroupCallback = mock(UserGroupCallback.class); when(mockContext.getTaskInstanceService()).thenReturn(mockTaskService); when(mockContext.getUserGroupCallback()).thenReturn(mockUserGroupCallback); when(mockUserGroupCallback.existsUser(anyString())).thenReturn(false); for( Object data : testData ) { int property = (Integer) data[0]; cmd = new SetTaskPropertyCommand(taskId, userId, property, data[1]); try { cmd.execute(mockContext); } catch (IllegalArgumentException e) { } } }

Target:
public void setTaskPropertyCommandTest() throws Exception { SetTaskPropertyCommand cmd; int taskId = 1; String userId = "user"; FaultDataImpl faultData = new FaultDataImpl(); faultData.setAccessType(AccessType.Inline); faultData.setContent("skinned shins".getBytes()); faultData.setFaultName("Whoops!"); faultData.setType("skates"); List<I18NText> textList = new ArrayList<I18NText>(); I18NText text = new I18NTextImpl("nl-NL", "Stroopwafel!"); textList.add(text); Object [][] testData = { { FAULT_PROPERTY, faultData }, { OUTPUT_PROPERTY, new Object() }, { PRIORITY_PROPERTY, 23 }, { TASK_NAMES_PROPERTY, textList }, { EXPIRATION_DATE_PROPERTY, new Date() }, { DESCRIPTION_PROPERTY, new ArrayList<I18NText>() }, { SKIPPABLE_PROPERTY, false }, { SUB_TASK_STRATEGY_PROPERTY, SubTasksStrategy.EndParentOnAllSubTasksEnd } }; TaskContext mockContext = mock(TaskContext.class); TaskInstanceService mockTaskService = mock(TaskInstanceService.class); UserGroupCallback mockUserGroupCallback = mock(UserGroupCallback.class); when(mockContext.getTaskInstanceService()).thenReturn(mockTaskService); when(mockContext.getUserGroupCallback()).thenReturn(mockUserGroupCallback); when(mockUserGroupCallback.existsUser(anyString())).thenReturn(false); for( Object data : testData ) { int property = (Integer) data[0]; cmd = new SetTaskPropertyCommand(taskId, userId, property, data[1]); try { cmd.execute(mockContext); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("User user was not found in callback ")); } } }