auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void subscribe(@Context SseEventSink sink) throws IOException { synchronized (outputLock) { if (sink == null) { throw new IllegalStateException("No client connected."); } } eventSink = sink; if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }

Target:
public void subscribe(@Context SseEventSink sink) throws IOException { if (sink == null) { throw new IllegalStateException("No client connected."); } eventSink = sink; if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }
Source:
public boolean same() { boolean same; final String mine = Manifests.read("Rultor-Revision"); try { final String base; try { base = new JdkRequest( URI.create("<LINK_0>") ) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .body(); } catch (IOException ex) { throw new IllegalStateException(ex); } if (mine.equals(base) || !base.matches("[a-f0-9]+")) { same = true; } else { same = false; Logger.info( Main.class, "#same(): we're in %s while %s is the newest one", mine, base ); } } catch (AssertionError ex) { Logger.warn(Main.class, "#same(): %s", ex); same = true; } return same; }

Target:
public boolean same() { boolean same; final String mine = Manifests.read("Rultor-Revision"); try { final String base; try { base = new JdkRequest("<LINK_0>") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .body(); } catch (IOException ex) { throw new IllegalStateException(ex); } if (mine.equals(base) || !base.matches("[a-f0-9]+")) { same = true; } else { same = false; Logger.info( Main.class, "#same(): we're in %s while %s is the newest one", mine, base ); } } catch (AssertionError ex) { Logger.warn(Main.class, "#same(): %s", ex); same = true; } return same; }
Source:
private String decodeAlarm(String event) { if (event.equals('Z')) { return Position.ALARM_LOW_BATTERY; } else if (event.equals('X')) { return Position.ALARM_GEOFENCE_ENTER; } else if (event.equals('T')) { return Position.ALARM_TAMPERING; } else if (event.equals("H")) { return Position.ALARM_POWER_OFF; } else if (event.equals('X')) { return Position.ALARM_GEOFENCE_ENTER; } else if (event.equals('8')) { return Position.ALARM_SHOCK; } else if (event.equals('7') && event.equals('4')) { return Position.ALARM_GEOFENCE_EXIT; } else if (event.equals('6')) { return Position.ALARM_OVERSPEED; } else if (event.equals('3')) { return Position.ALARM_SOS; } return null; }

Target:
private String decodeAlarm(String event) { switch (event) { case "Z": return Position.ALARM_LOW_BATTERY; case "X": return Position.ALARM_GEOFENCE_ENTER; case "T": return Position.ALARM_TAMPERING; case "H": return Position.ALARM_POWER_OFF; case "8": return Position.ALARM_SHOCK; case "7": case "4": return Position.ALARM_GEOFENCE_EXIT; case "6": return Position.ALARM_OVERSPEED; case "3": return Position.ALARM_SOS; default: return null; } }
Source:
private void validateModel(BpmnModel model) throws Exception { FlowElement flowElement = model.getMainProcess().getFlowElement("Task_17unmd8"); assertNotNull(flowElement); assertTrue(flowElement instanceof Task); checkXml(model); }

Target:
private void validateModel(BpmnModel model) throws Exception { FlowElement flowElement = model.getMainProcess().getFlowElement("Task_17unmd8"); assertThat(flowElement).isNotNull(); assertThat(flowElement instanceof Task).isTrue(); checkXml(model); }
Source:
public void run() { switch (filterManager.getCurrentSynchronizationBehavior()) { case ASK_EACH_TIME: SynchronizerDialog dialog = new SynchronizerDialog(shell, EMFCompareRCPUIMessages .getString("FilterAction.SYNCHRONIZATION_DIALOG_TITLE"), EMFCompareRCPUIMessages.getString("FilterAction.SYNCHRONIZATION_DIALOG_MESSAGE"), EMFCompareRCPUIMessages .getString("FilterAction.SYNCHRONIZATION_DIALOG_TOGGLE_MESSAGE")); dialog.open(); if (dialog.synchronize()) { setSelectedGroupAsDefault(isChecked()); } SynchronizationBehavior synchronizationBehavior = dialog.getSynchronizationBehavior(); filterManager.setCurrentSynchronizationBehavior(synchronizationBehavior); break; case ALWAYS: setSelectedGroupAsDefault(isChecked()); break; case NEVER: break; default: EMFCompareRCPUIPlugin.getDefault().log(IStatus.WARNING, "Unhandle case for syncrhonization filter behavior preference value"); break; } }

Target:
public void run() { MessageDialogWithToggle dialog = new SynchronizerDialog(shell, EMFCompareRCPUIMessages .getString("FilterAction.synchronization.dialog.title"), EMFCompareRCPUIMessages.getString("FilterAction.synchronization.dialog.message"), EMFCompareRCPUIMessages.getString("FilterAction.synchronization.dialog.toggle.message")); dialog.setPrefKey(FiltersPreferencePage.SYNCHRONIZATION_BEHAVIOR); dialog.setPrefStore(new ScopedPreferenceStore(new InstanceScope(), EMFCompareRCPUIPlugin.PLUGIN_ID)); if (dialog.open() == IDialogConstants.YES_ID) { setSelectedGroupAsDefault(isChecked()); } }
Source:
private boolean isChannelPubSub(String channelName) { return channelName != null && (channelName.startsWith(TAP_CHANNEL_PREFIX) || channelName.startsWith(TOPIC_CHANNEL_PREFIX)); }

Target:
private boolean isChannelPubSub(String channelName) { Assert.isTrue(StringUtils.hasText(channelName), "Channel name should not be empty/null."); return (channelName.startsWith(TAP_CHANNEL_PREFIX) || channelName.startsWith(TOPIC_CHANNEL_PREFIX)); }
Source:
public void writeTo(WritableByteChannel channel) throws IOException { if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate((int) sizeInBytes()); writeHeader(); bufferToSend.putShort((short) flags.ordinal()); bufferToSend.putLong(partition); bufferToSend.putInt(ids.size()); for (BlobId id : ids) { ByteBuffer buf = id.toBytes(); bufferToSend.putShort((short)id.sizeInBytes()); bufferToSend.put(buf.array()); } bufferToSend.flip(); } if (bufferToSend.remaining() > 0) { int written = channel.write(bufferToSend); sizeSent += written; } }

Target:
public void writeTo(WritableByteChannel channel) throws IOException { if (bufferToSend == null) { bufferToSend = ByteBuffer.allocate((int) sizeInBytes()); writeHeader(); bufferToSend.putShort((short) flags.ordinal()); bufferToSend.putLong(partitionId); bufferToSend.putInt(ids.size()); for (BlobId id : ids) { ByteBuffer buf = id.toBytes(); bufferToSend.putShort(id.sizeInBytes()); bufferToSend.put(buf.array()); } bufferToSend.flip(); } if (bufferToSend.remaining() > 0) { int written = channel.write(bufferToSend); sizeSent += written; } }
Source:
private static String toHex(byte[] digest) { return DatatypeConverter.printHexBinary(digest); }

Target:
protected static String toHex(byte[] digest) { char[] result = new char[digest.length * 2]; for (int i = 0; i < digest.length; i++) { toChars(digest[i], result, i * 2); } return new String(result); }
Source:
public String getMimeType() { switch (imageProfileInt) { case GIF_LRG_INT: return "image/gif"; case JPEG_LRG_INT: case JPEG_MED_INT: case JPEG_RES_H_V_INT: case JPEG_SM_INT: case JPEG_TN_INT: return "image/jpeg"; case PNG_LRG_INT: case PNG_TN_INT: return "image/png"; } return "image/unknown"; }

Target:
public String getMimeType() { switch (getFormat()) { case GIF: return "image/gif"; case JPEG: return "image/jpeg"; case PNG: return "image/png"; default: throw new IllegalStateException("Format is missing from switch statement"); } }
Source:
public void processTimer(ComputationContext context, String key, long timestamp) { if (!TIMER_BATCH.equals(key) || batchRecords.isEmpty()) { return; } processBatch(context); context.setTimer(TIMER_BATCH, System.currentTimeMillis() + thresholdMillis); }

Target:
public void processTimer(ComputationContext context, String key, long timestamp) { if (!TIMER_BATCH.equals(key)) { return; } if (! batchRecords.isEmpty()) { processBatch(context); } context.setTimer(TIMER_BATCH, System.currentTimeMillis() + thresholdMillis); }
Source:
public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new CrashReportWriter()); if(BuildConfig.DEBUG) { StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDropBox(); if (Build.VERSION.SDK_INT >= 11) { builder.detectActivityLeaks(); builder.detectLeakedClosableObjects(); } if(Build.VERSION.SDK_INT >= 16) { builder.detectLeakedRegistrationObjects(); } StrictMode.setVmPolicy(builder.build()); } singleton = this; PodDBAdapter.init(this); UpdateManager.init(this); UserPreferences.init(this); PlaybackPreferences.init(this); NetworkUtils.init(this); EventDistributor.getInstance(); Iconify.with(new FontAwesomeModule()); SPAUtil.sendSPAppsQueryFeedsIntent(this); throw new NullPointerException(); }

Target:
public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new CrashReportWriter()); if(BuildConfig.DEBUG) { StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDropBox(); if (Build.VERSION.SDK_INT >= 11) { builder.detectActivityLeaks(); builder.detectLeakedClosableObjects(); } if(Build.VERSION.SDK_INT >= 16) { builder.detectLeakedRegistrationObjects(); } StrictMode.setVmPolicy(builder.build()); } singleton = this; PodDBAdapter.init(this); UpdateManager.init(this); UserPreferences.init(this); PlaybackPreferences.init(this); NetworkUtils.init(this); EventDistributor.getInstance(); Iconify.with(new FontAwesomeModule()); SPAUtil.sendSPAppsQueryFeedsIntent(this); }
Source:
protected void acquire(TransactionLocks locks) throws IOException { setLockMode(lockType); Set<String> hldrs = new HashSet<>(); if (leaseHolder != null && singleFileLock == null) { hldrs.add(leaseHolder); } else if (leaseHolder != null && singleFileLock != null) { Lease lease = acquireLock(lockType, Lease.Finder.ByHolder, leaseHolder, Lease.getHolderId(leaseHolder)); if (lease != null) { singleFileLease = lease; } } if (locks.containsLock(Type.INode)) { BaseINodeLock inodeLock = (BaseINodeLock) locks.getLock(Type.INode); for (INode f : inodeLock.getAllResolvedINodes()) { if ((f instanceof INodeFile) && f.isUnderConstruction()) { hldrs.add(((INodeFile) f).getFileUnderConstructionFeature().getClientName()); } } } List<String> holders = new ArrayList<>(hldrs); Collections.sort(holders); if(holders.isEmpty() && !locks.containsLock(Type.INode)){ Collection<Lease> allLeases = acquireLockList(lockType, Lease.Finder.All); if (leases != null) { leases.addAll(allLeases); } } for (String h : holders) { Lease lease = acquireLock(lockType, Lease.Finder.ByHolder, h, Lease.getHolderId(h)); if (lease != null) { leases.add(lease); } } }

Target:
protected void acquire(TransactionLocks locks) throws IOException { setLockMode(lockType); Set<String> hldrs = new HashSet<>(); if (leaseHolder != null) { hldrs.add(leaseHolder); } if (locks.containsLock(Type.INode)) { BaseINodeLock inodeLock = (BaseINodeLock) locks.getLock(Type.INode); for (INode f : inodeLock.getAllResolvedINodes()) { if ((f instanceof INodeFile) && f.isUnderConstruction()) { hldrs.add(((INodeFile) f).getFileUnderConstructionFeature().getClientName()); } } } List<String> holders = new ArrayList<>(hldrs); Collections.sort(holders); if (holders.isEmpty() && !locks.containsLock(Type.INode)) { Collection<Lease> allLeases = acquireLockList(lockType, Lease.Finder.All); if (leases != null) { leases.addAll(allLeases); } } for (String h : holders) { Lease lease = acquireLock(lockType, Lease.Finder.ByHolder, h, Lease.getHolderId(h)); if (lease != null) { leases.add(lease); } } }
Source:
public void should_replace_classpath_in_arquillian_xml() throws Exception { final String xml = desc.get().exportAsString(); System.out.println(xml); AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }

Target:
public void should_replace_classpath_in_arquillian_xml() throws Exception { final String xml = desc.get().exportAsString(); AssertXPath.assertXPath(xml, "/arquillian/container/@qualifier", VALUE_EL_OVERRIDE); final URL resource = Thread.currentThread().getContextClassLoader().getResource("arquillian_sysprop.xml"); assertXPath(xml, "/arquillian/container/configuration/property", String.format("-Djavax.net.ssl.trustStore=%s", resource.toString())); }
Source:
public void run() { DateTime fiveMinutesAgo = DateTime.now().minusSeconds(DEAD_CONNECTION_INTERVAL_SECONDS); if (lastHeartbeat.isBefore(fiveMinutesAgo) && es.getState() == ReadyState.OPEN) { try { logger.info("Stream stopped receiving heartbeats- reconnecting."); es.close(); start(); } catch (IOException e) { logger.warn("Encountered exception closing stream connection: " + e.getMessage()); } } }

Target:
public void run() { DateTime reconnectThresholdTime = DateTime.now().minusSeconds(DEAD_CONNECTION_INTERVAL_SECONDS); if (lastHeartbeat.isBefore(reconnectThresholdTime) && es.getState() == ReadyState.OPEN) { try { logger.info("Stream stopped receiving heartbeats- reconnecting."); es.close(); } catch (IOException e) { logger.error("Encountered exception closing stream connection: " + e.getMessage()); } finally { if (es.getState() == ReadyState.SHUTDOWN) { start(); } else { logger.error("Expected ES to be in state SHUTDOWN, but it's currently in state " + es.getState().toString()); } } } }
Source:
public static <E> boolean isEqualCollection(final Collection<? extends E> a, final Collection<? extends E> b, final Equator<? super E> equator) { if(a == null && b == null) { return true; } if(a == null || b == null) { return false; } if (equator == null) { throw new NullPointerException("Equator must not be null."); } if(a.size() != b.size()) { return false; } @SuppressWarnings({ "unchecked", "rawtypes" }) final Transformer<E, ?> transformer = new Transformer() { @Override public EquatorWrapper<?> transform(final Object input) { return new EquatorWrapper(equator, input); } }; return isEqualCollection(collect(a, transformer), collect(b, transformer)); }

Target:
public static <E> boolean isEqualCollection(final Collection<? extends E> a, final Collection<? extends E> b, final Equator<? super E> equator) { if (equator == null) { throw new NullPointerException("Equator must not be null."); } @SuppressWarnings({ "unchecked", "rawtypes" }) final Transformer<E, ?> transformer = new Transformer() { @Override public EquatorWrapper<?> transform(final Object input) { return new EquatorWrapper(equator, input); } }; return isEqualCollection(collect(a, transformer), collect(b, transformer)); }
Source:
public LzoProtobufBlockScheme(Class protoClass) { super(protoClass); }

Target:
public LzoProtobufBlockScheme(Class protoClass) { super(protoClass); LOG.warn("LzoProtobufBlockScheme is deprecated, please use LzoProtobufScheme"); }
Source:
public Resource getConfigFile(String profile, String label, String path) { Assert.isTrue( configClientProperties.getName() != null && !configClientProperties.getName().isEmpty(), "Spring application name is undefined."); Assert.isTrue( configClientProperties.getUri().length > 0 && configClientProperties.getUri()[0] != null && !configClientProperties.getUri()[0].isEmpty(), "Config server URI is undefined."); if (profile == null) { profile = configClientProperties.getProfile(); if (profile == null || profile.isEmpty()) { profile = "default"; } } if (label == null) { label = configClientProperties.getLabel(); } String url = configClientProperties.getUri()[0] + "/" + configClientProperties.getName() + "/" + profile + "/" + (label == null ? path + "?useDefaultLabel" : label + "/" + path); ResponseEntity<Resource> forEntity = restTemplate.getForEntity(url, Resource.class); return forEntity.getBody(); }

Target:
public Resource getConfigFile(String profile, String label, String path) { Assert.isTrue( configClientProperties.getName() != null && !configClientProperties.getName().isEmpty(), "Spring application name is undefined."); Assert.notEmpty(configClientProperties.getUri(), "Config server URI is undefined"); Assert.hasText(configClientProperties.getUri()[0], "Config server URI is undefined."); if (profile == null) { profile = configClientProperties.getProfile(); if (profile == null || profile.isEmpty()) { profile = "default"; } } if (label == null) { label = configClientProperties.getLabel(); } String url = configClientProperties.getUri()[0] + "/" + configClientProperties.getName() + "/" + profile + "/" + (label == null ? path + "?useDefaultLabel" : label + "/" + path); ResponseEntity<Resource> forEntity = restTemplate.getForEntity(url, Resource.class); return forEntity.getBody(); }
Source:
public GeocodingProvider(@AppContext Context context, Preferences preferences) { cache = new LruCache<>(40); if(true == preferences.getGeocodeEnabled()) { if ("".equals(preferences.getOpenCageGeocoderApiKey())) { geocoder = new GeocoderGoogle(context); } else { geocoder = new GeocoderOpencage(preferences.getOpenCageGeocoderApiKey()); } } else { geocoder = new GeocoderNone(); } }

Target:
public GeocodingProvider(@AppContext Context context, Preferences preferences) { cache = new LruCache<>(40); if(preferences.getGeocodeEnabled()) { if ("".equals(preferences.getOpenCageGeocoderApiKey())) { geocoder = new GeocoderGoogle(context); } else { geocoder = new GeocoderOpencage(preferences.getOpenCageGeocoderApiKey()); } } else { geocoder = new GeocoderNone(); } }
Source:
public void configure(Map stormConf, JsonNode filterParams) { JsonNode node = filterParams.get("useText"); if (node != null && node.asBoolean()) { useText = true; } node = filterParams.get("keyName"); if (node != null && node.isTextual()) { key_name = node.asText("signature"); } node = filterParams.get("keyNameCopy"); if (node != null && node.isTextual()) { copyKeyName = node.asText("signatureOld"); System.out.println("HERE: signatureOld" + copyKeyName); } }

Target:
public void configure(Map stormConf, JsonNode filterParams) { JsonNode node = filterParams.get("useText"); if (node != null && node.asBoolean()) { useText = true; } node = filterParams.get("keyName"); if (node != null && node.isTextual()) { key_name = node.asText("signature"); } node = filterParams.get("keyNameCopy"); if (node != null && node.isTextual() && StringUtils.isNotBlank(node.asText(""))) { copyKeyName = node.asText("signatureOld"); } }
Source:
private Account configureMockAccount(String username) { final ProfileImage profileImage = mock(ProfileImage.class); when(profileImage.hasImage()).thenReturn(true); when(profileImage.getImageUrlLarge()).thenReturn("<LINK_0>"); final Account account = mock(Account.class); when(account.getUsername()).thenReturn(username); when(account.getProfileImage()).thenReturn(profileImage); return account; }

Target:
private Account configureMockAccount(String username) { final ProfileImage profileImage = mock(ProfileImage.class); when(profileImage.hasImage()).thenReturn(true); when(profileImage.getImageUrlLarge()).thenReturn("file:/ final Account account = mock(Account.class); when(account.getUsername()).thenReturn(username); when(account.getProfileImage()).thenReturn(profileImage); return account; }
Source:
public void registerPasswordPolicy() { RealmRepresentation realm = testRealm().toRepresentation(); realm.setPasswordPolicy(LengthPasswordPolicyProviderFactory.ID); testRealm().update(realm); try { loginPage.open(); loginPage.clickRegister(); registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "registerPasswordPolicy@email", "registerPasswordPolicy", "pass", "pass"); registerPage.assertCurrent(); assertEquals("Invalid password: minimum length 8.", registerPage.getError()); events.expectRegister("registerPasswordPolicy", "registerPasswordPolicy@email") .removeDetail(Details.USERNAME) .removeDetail(Details.EMAIL) .user((String) null).error("invalid_registration").assertEvent(); registerPage.register("firstName", "lastName", "registerPasswordPolicy@email", "registerPasswordPolicy", "password", "password"); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); String userId = events.expectRegister("registerPasswordPolicy", "registerPasswordPolicy@email").assertEvent().getUserId(); events.expectLogin().user(userId).detail(Details.USERNAME, "registerpasswordpolicy").assertEvent(); } finally { } }

Target:
public void registerPasswordPolicy() { RealmRepresentation realm = testRealm().toRepresentation(); realm.setPasswordPolicy("length"); testRealm().update(realm); try { loginPage.open(); loginPage.clickRegister(); registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "registerPasswordPolicy@email", "registerPasswordPolicy", "pass", "pass"); registerPage.assertCurrent(); assertEquals("Invalid password: minimum length 8.", registerPage.getError()); events.expectRegister("registerPasswordPolicy", "registerPasswordPolicy@email") .removeDetail(Details.USERNAME) .removeDetail(Details.EMAIL) .user((String) null).error("invalid_registration").assertEvent(); registerPage.register("firstName", "lastName", "registerPasswordPolicy@email", "registerPasswordPolicy", "password", "password"); assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); String userId = events.expectRegister("registerPasswordPolicy", "registerPasswordPolicy@email").assertEvent().getUserId(); events.expectLogin().user(userId).detail(Details.USERNAME, "registerpasswordpolicy").assertEvent(); } finally { } }
Source:
private String progress(VoltDBInterface instance) { String p = "complete"; if (!instance.getNodeStartupComplete()) { int[] n = instance.getNodeStartupProgress(); if (n[1] > 0) { if (n[0] < 0) n[0] = 0; if (n[0] > n[1]) n[0] = n[1]; p = String.format("%d/%d (%d%%)", n[0], n[1], (n[0] * 100) / n[1]); } else { p = "pending"; } } return p; }

Target:
private String progress(VoltDBInterface instance) { String p = "complete"; if (!instance.getNodeStartupComplete()) { int[] n = instance.getNodeStartupProgress(); if (n[1] > 0) { if (n[0] < 0) { n[0] = 0; } if (n[0] > n[1]) { n[0] = n[1]; } p = String.format("%d/%d (%d%%)", n[0], n[1], (n[0] * 100) / n[1]); } else { p = "pending"; } } return p; }
Source:
public static PlanToSpecTransformer forMime(ManagementContext mgmt, String mime) { ServiceLoader<PlanToSpecTransformer> loader = ServiceLoader.load(PlanToSpecTransformer.class); for (PlanToSpecTransformer transformer : loader) { transformer.injectManagementContext(mgmt); if (transformer.accepts(mime)) { return transformer; } } return null; }

Target:
public static PlanToSpecTransformer forMime(ManagementContext mgmt, String mime) { Collection<PlanToSpecTransformer> transformers = all(mgmt); for (PlanToSpecTransformer transformer : transformers) { if (transformer.accepts(mime)) { return transformer; } } throw new IllegalStateException("PlanToSpecTransformer for type " + mime + " not found. Registered transformers are: " + transformers); }
Source:
public T call() throws Exception { while (true) { try { return this.callable.call(); } catch (Exception e) { log.warn("Retry failed"); if (this.context.isExceptionRetryable(e)) { log.warn("Retry failed"); this.context.decreaseAttempts(); if (this.context.getNumberOfAttempts() <= 0) { throw e; } this.context.waitOperation(); continue; } else { throw e; } } } }

Target:
public T call() throws Exception { while (true) { try { return this.callable.call(); } catch (Exception e) { log.warn("Retry failed"); if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } if (this.context.isExceptionRetryable(e)) { this.context.decreaseAttempts(); if (this.context.getNumberOfAttempts() <= 0) { throw e; } this.context.waitOperation(); continue; } else { throw e; } } } }
Source:
public Mapping copyForInheritanceTo(SourceMethod method) { Mapping mapping = new Mapping( sourceName, constant, javaExpression, targetName, dateFormat, defaultValue, isIgnored, mirror, sourceAnnotationValue, targetAnnotationValue, selectionParameters, dependsOnAnnotationValue, dependsOn ); if ( sourceReference != null ) { mapping.sourceReference = sourceReference.copyForInheritanceTo( method ); } mapping.targetReference = targetReference; return mapping; }

Target:
public Mapping copyForInheritanceTo(SourceMethod method) { Mapping mapping = new Mapping( sourceName, constant, javaExpression, targetName, defaultValue, isIgnored, mirror, sourceAnnotationValue, targetAnnotationValue, formattingParameters, selectionParameters, dependsOnAnnotationValue, dependsOn ); if ( sourceReference != null ) { mapping.sourceReference = sourceReference.copyForInheritanceTo( method ); } mapping.targetReference = targetReference; return mapping; }
Source:
public int compareTo(final SubscriptionBillingEvent o) { if (!getEffectiveDate().equals(o.getEffectiveDate())) { return getEffectiveDate().compareTo(o.getEffectiveDate()); } else { return getTotalOrdering().compareTo(o.getTotalOrdering()); } }

Target:
public int compareTo(final SubscriptionBillingEvent o) { if (getEffectiveDate().compareTo(o.getEffectiveDate()) != 0) { return getEffectiveDate().compareTo(o.getEffectiveDate()); } else if (getTotalOrdering().compareTo(o.getTotalOrdering()) != 0) { return getTotalOrdering().compareTo(o.getTotalOrdering()); } else { final Date effectiveDate = getPlan().getCatalog().getEffectiveDate(); final Date oEeffectiveDate = o.getPlan().getCatalog().getEffectiveDate(); return effectiveDate.compareTo(oEeffectiveDate); } }
Source:
private Connection getNewConnection(String host, String user, String passwd, String properties) { Connection newConn = null; String dbURL="jdbc:mysql://" + host + "/" + properties; logger.fine("Getting new MySQL Connection " + dbURL + " " + user + "/" + passwd.replaceAll(".", "*")); try { if (!connectionInitialized) { Class.forName("com.mysql.jdbc.Driver").newInstance(); connectionInitialized = true; } newConn = DriverManager.getConnection(dbURL, user, passwd); if (newConn == null) { logger.severe("Unable to obtain a new database connection, check your MySQL configuration settings."); } } catch (Exception e) { logger.severe("Unable to obtain a new database connection, check your MySQL configuration settings. " + e.getMessage()); } return newConn; }

Target:
private Connection getNewConnection(String host, String user, String passwd, String properties) { Connection newConn = null; String dbURL="jdbc:mysql://" + host + "/" + properties; String connectionInfo = dbURL + " " + user + "/PASSWORD_FILTERED"; logger.fine("Getting new MySQL Connection: " + connectionInfo); try { if (!connectionInitialized) { Class.forName("com.mysql.jdbc.Driver").newInstance(); connectionInitialized = true; } newConn = DriverManager.getConnection(dbURL, user, passwd); if (newConn == null) { logger.severe("Unable to obtain a new database connection: " + connectionInfo + ", check your MySQL configuration settings."); } } catch (Exception e) { logger.severe("Unable to obtain a new database connection: " + connectionInfo + ", check your MySQL configuration settings. " + e.getMessage()); } return newConn; }
Source:
public void testSQLSelectInsertWithAPI() throws IOException, ClassNotFoundException { LogicalPlan dag = new LogicalPlan(); String schemaIn = "{\"separator\":\",\",\"quoteChar\":\"\\\"\",\"fields\":[" + "{\"name\":\"RowTime\",\"type\":\"Date\",\"constraints\":{\"format\":\"dd/MM/yyyy hh:mm:ss\"}}," + "{\"name\":\"id\",\"type\":\"Integer\"}," + "{\"name\":\"Product\",\"type\":\"String\"}," + "{\"name\":\"units\",\"type\":\"Integer\"}]}"; String schemaOut = "{\"separator\":\",\",\"quoteChar\":\"\\\"\",\"fields\":[" + "{\"name\":\"RowTime\",\"type\":\"Date\",\"constraints\":{\"format\":\"dd/MM/yyyy hh:mm:ss\"}}," + "{\"name\":\"Product\",\"type\":\"String\"}]}"; SQLExecEnvironment.getEnvironment() .registerTable("ORDERS", new FileEndpoint("/tmp/test", new CSVMessageFormat(schemaIn))) .registerTable("SALES", new FileEndpoint("/tmp/output", "out.tmp", new CSVMessageFormat(schemaOut))) .executeSQL(dag, "INSERT INTO SALES SELECT STREAM FLOOR(ROWTIME TO HOUR), SUBSTRING(PRODUCT, 0, 5) " + "FROM ORDERS WHERE id > 3"); dag.validate(); }

Target:
public void testSQLSelectInsertWithAPI() throws IOException, ClassNotFoundException { LogicalPlan dag = new LogicalPlan(); String schemaIn = "{\"separator\":\",\",\"quoteChar\":\"\\\"\",\"fields\":[" + "{\"name\":\"RowTime\",\"type\":\"Date\",\"constraints\":{\"format\":\"dd/MM/yyyy hh:mm:ss\"}}," + "{\"name\":\"id\",\"type\":\"Integer\"}," + "{\"name\":\"Product\",\"type\":\"String\"}," + "{\"name\":\"units\",\"type\":\"Integer\"}]}"; String schemaOut = "{\"separator\":\",\",\"quoteChar\":\"\\\"\",\"fields\":[" + "{\"name\":\"RowTime\",\"type\":\"Date\",\"constraints\":{\"format\":\"dd/MM/yyyy hh:mm:ss\"}}," + "{\"name\":\"Product\",\"type\":\"String\"}]}"; SQLExecEnvironment.getEnvironment() .registerTable("ORDERS", new FileEndpoint("dummyFilePathInput", new CSVMessageFormat(schemaIn))) .registerTable("SALES", new FileEndpoint("dummyFilePathOutput", "out.tmp", new CSVMessageFormat(schemaOut))) .executeSQL(dag, "INSERT INTO SALES SELECT STREAM FLOOR(ROWTIME TO HOUR), SUBSTRING(PRODUCT, 0, 5) " + "FROM ORDERS WHERE id > 3"); dag.validate(); }
Source:
private void createViewerPage() { Display display= getSite().getShell().getDisplay(); fViewerPage = new Composite(fPagebook, SWT.NULL); fViewerPage.setLayoutData(new GridData(GridData.FILL_BOTH)); fViewerPage.setSize(100, 100); fViewerPage.setLayout(new FillLayout()); fProviders = getContentProviders(); fLabelProviders = getLabelProviders(); fContentProvider= new CHContentProvider(this, display); fLabelProvider = new CHLabelProvider(this, display, fContentProvider); fTreeViewer= new ExtendedTreeViewer(fViewerPage); fTreeViewer.setContentProvider(fContentProvider); fTreeViewer.setLabelProvider(new DecoratingCLabelProvider(fLabelProvider)); fTreeViewer.setAutoExpandLevel(2); fTreeViewer.addOpenListener(new IOpenListener() { @Override public void open(OpenEvent event) { onShowSelectedReference(event.getSelection()); } }); if (fProviders !=null) { for (ICHEContentProvider provider : fProviders) { fTreeViewer.addOpenListener(provider.getCCallHierarchyOpenListener()); } } }

Target:
private void createViewerPage() { Display display= getSite().getShell().getDisplay(); fViewerPage = new Composite(fPagebook, SWT.NULL); fViewerPage.setLayoutData(new GridData(GridData.FILL_BOTH)); fViewerPage.setSize(100, 100); fViewerPage.setLayout(new FillLayout()); fProviders = CHEProviderSettings.getCCallHierarchyContentProviders(); fLabelProviders = CHEProviderSettings.getCCallHierarchyLabelProviders(); fContentProvider= new CHContentProvider(this, display); fLabelProvider = new CHLabelProvider(this, display, fContentProvider); fTreeViewer= new ExtendedTreeViewer(fViewerPage); fTreeViewer.setContentProvider(fContentProvider); fTreeViewer.setLabelProvider(new DecoratingCLabelProvider(fLabelProvider)); fTreeViewer.setAutoExpandLevel(2); fTreeViewer.addOpenListener(new IOpenListener() { @Override public void open(OpenEvent event) { onShowSelectedReference(event.getSelection()); } }); if (fProviders !=null) { for (ICHEContentProvider provider : fProviders) { fTreeViewer.addOpenListener(provider.getCCallHierarchyOpenListener()); } } }
Source:
private String getPersistentStorageName(String prefix, AzureCredentialView acv, String region, String resourceGroup) { String subscriptionIdPart = encodeString(acv.getSubscriptionId().replaceAll("-", "").toLowerCase()); String regionInitials = WordUtils.initials(Region.findByLabelOrName(region).label(), ' ').toLowerCase(); String resourceGroupPart = encodeString(resourceGroup); String result = String.format("%s%s%s%s", prefix, regionInitials, subscriptionIdPart, resourceGroupPart); if (result.length() > MAX_LENGTH_OF_RESOURCE_NAME) { result = result.substring(0, MAX_LENGTH_OF_RESOURCE_NAME); } LOGGER.debug("Storage account name: {}", result); String message = "Welcome to Tutorialspoint.com"; encodeString(message); return result; }

Target:
private String getPersistentStorageName(String prefix, AzureCredentialView acv, String region, String resourceGroup) { String subscriptionIdPart = encodeString(acv.getSubscriptionId().replaceAll("-", "").toLowerCase()); String regionInitials = WordUtils.initials(Region.findByLabelOrName(region).label(), ' ').toLowerCase(); String resourceGroupPart = encodeString(resourceGroup); String result = String.format("%s%s%s%s", prefix, regionInitials, subscriptionIdPart, resourceGroupPart); if (result.length() > MAX_LENGTH_OF_RESOURCE_NAME) { result = result.substring(0, MAX_LENGTH_OF_RESOURCE_NAME); } LOGGER.debug("Storage account name: {}", result); return result; }
Source:
static String prepareDataSourceInfo( String dataSourceInfo ) { StringBuilder sb = new StringBuilder(); Map<String, String> parameters = DataSourceInfoUtil.parseDataSourceInfo( dataSourceInfo ); parameters.forEach( ( key, value ) -> { String unescapedValue = StringEscapeUtils.unescapeXml( value ); String valueWithEscapedQuotes = DataSourceInfoUtil.escapeQuotes( unescapedValue ); sb.append( key ); sb.append( "=\"" ); sb.append( valueWithEscapedQuotes ); sb.append( "\"" ); sb.append( ";" ); } ); return sb.toString(); }

Target:
static String prepareDataSourceInfo( String dataSourceInfo ) { StringBuilder sb = new StringBuilder(); Map<String, String> parameters = DataSourceInfoUtil.parseDataSourceInfo( dataSourceInfo ); for ( Map.Entry<String, String> entry : parameters.entrySet() ) { String unescapedValue = StringEscapeUtils.unescapeXml( entry.getValue() ); String valueWithEscapedQuotes = DataSourceInfoUtil.escapeQuotes( unescapedValue ); sb.append( entry.getKey() ); sb.append( "=\"" ); sb.append( valueWithEscapedQuotes ); sb.append( "\"" ); sb.append( ";" ); } return sb.toString(); }
Source:
public void addTask(String workflowName, String jobName, TaskConfig taskConfig, long timeoutMs) throws Exception { if (timeoutMs < DEFAULT_SLEEP) { throw new IllegalArgumentException( String.format("Timeout is less than the minimum acceptable timeout value which is %s ms", DEFAULT_SLEEP)); } long endTime = System.currentTimeMillis() + timeoutMs; validateAddTaskConfigs(workflowName, jobName, taskConfig); String nameSpaceJobName = TaskUtil.getNamespacedJobName(workflowName, jobName); WorkflowContext workflowContext = getWorkflowContext(workflowName); JobContext jobContext = getJobContext(nameSpaceJobName); if (workflowContext == null || jobContext == null) { addTaskToJobConfig(workflowName, jobName, taskConfig, endTime); return; } TaskState jobState = workflowContext.getJobState(nameSpaceJobName); if (jobState == null) { addTaskToJobConfig(workflowName, jobName, taskConfig, endTime); return; } if (ILLEGAL_JOB_STATES_FOR_TASK_MODIFICATION.contains(jobState)) { throw new HelixException( String.format("Job %s is in illegal state to accept new task. Job State is %s", nameSpaceJobName, jobState)); } addTaskToJobConfig(workflowName, jobName, taskConfig, endTime); }

Target:
public void addTask(String workflowName, String jobName, TaskConfig taskConfig, long timeoutMs) throws TimeoutException, InterruptedException { if (timeoutMs < DEFAULT_SLEEP) { throw new IllegalArgumentException( String.format("Timeout is less than the minimum acceptable timeout value which is %s ms", DEFAULT_SLEEP)); } long endTime = System.currentTimeMillis() + timeoutMs; validateAddTaskConfigs(workflowName, jobName, taskConfig); String nameSpaceJobName = TaskUtil.getNamespacedJobName(workflowName, jobName); WorkflowContext workflowContext = getWorkflowContext(workflowName); JobContext jobContext = getJobContext(nameSpaceJobName); if (workflowContext == null || jobContext == null) { addTaskToJobConfig(workflowName, jobName, taskConfig, endTime); return; } TaskState jobState = workflowContext.getJobState(nameSpaceJobName); if (ILLEGAL_JOB_STATES_FOR_TASK_MODIFICATION.contains(jobState)) { throw new HelixException( String.format("Job %s is in illegal state to accept new task. Job State is %s", nameSpaceJobName, jobState)); } addTaskToJobConfig(workflowName, jobName, taskConfig, endTime); }
Source:
public Builder() { this(15 * 60 * 1000L, 524288000L, 100, 5, 15, 10, 1, false, null, 0.001F); }

Target:
public Builder() { this(15 * 60 * 1000L, 524288000L, 100, 5, 15, 10, 1, false, null, BalancerStrategy.DEFAULT_BALANCER_SLOPE); }
Source:
public void testTelemetryDisabledByDefault() throws Exception { TestUtils.assertMemoryLeak(() -> { try (CairoEngine engine = new CairoEngine(configuration, null)) { try (Path path = new Path()) { Assert.assertEquals(TableUtils.TABLE_DOES_NOT_EXIST, TableUtils.exists(FF, path, root, "telemetry")); Assert.assertEquals(TableUtils.TABLE_DOES_NOT_EXIST, TableUtils.exists(FF, path, root, "telemetry_config")); } } }); }

Target:
public void testTelemetryDisabledByDefault() throws Exception { TestUtils.assertMemoryLeak(() -> { try (Path path = new Path()) { Assert.assertEquals(TableUtils.TABLE_DOES_NOT_EXIST, TableUtils.exists(FF, path, root, "telemetry")); Assert.assertEquals(TableUtils.TABLE_DOES_NOT_EXIST, TableUtils.exists(FF, path, root, "telemetry_config")); } }); }
Source:
public String toString() { return createQuery(queryMixin.getMetadata().getWhere()).toString(); }

Target:
public String toString() { return asDBObject().toString(); }
Source:
public void VEGalleryTests_001_AddGallery() { int numOfMedias = 9; int numOfGalleries = 1; articleName = PageContent.ARTICLE_NAME_PREFIX + article.getTimeStamp(); VisualEditorPageObject ve = article.openVEOnArticle(wikiURL, articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve.typeTextArea(PageContent.ARTICLE_TEXT); VisualEditorInsertGalleryDialog galleryDialog = ve.clickGalleryButton(); galleryDialog = galleryDialog.searchMedia("he"); ve = galleryDialog.addExistingMedia(numOfMedias); ve.verifyGalleries(numOfGalleries); ve.verifyMediasInGallery(numOfMedias); VisualEditorSaveChangesDialog saveChangesDialog = ve.clickPublishButton(); article = saveChangesDialog.savePage(); article.verifyVEPublishComplete(); article.logOut(wikiURL); }

Target:
public void VEGalleryTests_001_AddGallery() { int numOfMedias = 9; int numOfGalleries = 1; articleName = PageContent.ARTICLE_NAME_PREFIX + article.getTimeStamp(); VisualEditorPageObject ve = article.openVEOnArticle(wikiURL, articleName); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve.typeTextArea(PageContent.ARTICLE_TEXT); VisualEditorInsertGalleryDialog galleryDialog = ve.clickGalleryButton(); galleryDialog = galleryDialog.searchMedia("he"); ve = galleryDialog.addExistingMedia(numOfMedias); ve.verifyGalleries(numOfGalleries); ve.verifyMediasInGallery(numOfMedias); ve.publish(); article.logOut(wikiURL); }
Source:
public void writeObject(ObjectOutput output, CacheContainerAdmin.AdminFlag flag) throws IOException { output.writeUTF(flag.name()); }

Target:
public void writeObject(ObjectOutput output, CacheContainerAdmin.AdminFlag flag) throws IOException { MarshallUtil.marshallEnum(flag, output); }
Source:
public static AllTypes copyOrUpdate(Realm realm, AllTypes object, boolean update, Map<RealmObject,RealmObjectProxy> cache) { if (((RealmObject) object).realm != null && ((RealmObject) object).realm.threadId != realm.threadId) { throw new IllegalArgumentException( "Objects belonging to Realm instances in other threads cannot be copied into this Realm instance."); } if (((RealmObject) object).realm != null && ((RealmObject) object).realm.getPath().equals(realm.getPath())) { return object; } AllTypes realmObject = null; boolean canUpdate = update; if (canUpdate) { Table table = realm.getTable(AllTypes.class); long pkColumnIndex = table.getPrimaryKey(); if (((AllTypesRealmProxyInterface) object).realmGet$columnString() == null) { throw new IllegalArgumentException("Primary key value must not be null."); } long rowIndex = table.findFirstString(pkColumnIndex, ((AllTypesRealmProxyInterface) object).realmGet$columnString()); if (rowIndex != TableOrView.NO_MATCH) { realmObject = new AllTypesRealmProxy(realm.schema.getColumnInfo(AllTypes.class)); ((RealmObject) realmObject).realm = realm; ((RealmObject) realmObject).row = table.getUncheckedRow(rowIndex); cache.put(object, (RealmObjectProxy) realmObject); } else { canUpdate = false; } } if (canUpdate) { return update(realm, realmObject, object, cache); } else { return copy(realm, object, update, cache); } }

Target:
public static AllTypes copyOrUpdate(Realm realm, AllTypes object, boolean update, Map<RealmObject,RealmObjectProxy> cache) { if (((RealmObject) object).realm != null && ((RealmObject) object).realm.threadId != realm.threadId) { throw new IllegalArgumentException( "Objects which belong to Realm instances in other threads cannot be copied into this Realm instance."); } if (((RealmObject) object).realm != null && ((RealmObject) object).realm.getPath().equals(realm.getPath())) { return object; } AllTypes realmObject = null; boolean canUpdate = update; if (canUpdate) { Table table = realm.getTable(AllTypes.class); long pkColumnIndex = table.getPrimaryKey(); if (((AllTypesRealmProxyInterface) object).realmGet$columnString() == null) { throw new IllegalArgumentException("Primary key value must not be null."); } long rowIndex = table.findFirstString(pkColumnIndex, ((AllTypesRealmProxyInterface) object).realmGet$columnString()); if (rowIndex != TableOrView.NO_MATCH) { realmObject = new AllTypesRealmProxy(realm.schema.getColumnInfo(AllTypes.class)); ((RealmObject) realmObject).realm = realm; ((RealmObject) realmObject).row = table.getUncheckedRow(rowIndex); cache.put(object, (RealmObjectProxy) realmObject); } else { canUpdate = false; } } if (canUpdate) { return update(realm, realmObject, object, cache); } else { return copy(realm, object, update, cache); } }
Source:
List<DiscoveryNode> resolve() { if (serviceName != null && !serviceName.isEmpty()) { return getSimpleDiscoveryNodes(client.endpointsByName(serviceName)); } else if (serviceLabel != null && !serviceLabel.isEmpty()) { return getSimpleDiscoveryNodes(client.endpointsByLabel(serviceLabel, serviceLabelValue)); } else if (podLabel != null && !podLabel.isEmpty()) { logger.warning("Using Pod label to discover nodes..."); return getSimpleDiscoveryNodes(client.endpointsByPodLabel(podLabel, podLabelValue)); } return getSimpleDiscoveryNodes(client.endpoints()); }

Target:
List<DiscoveryNode> resolve() { if (serviceName != null && !serviceName.isEmpty()) { logger.fine("Using service name to discover nodes."); return getSimpleDiscoveryNodes(client.endpointsByName(serviceName)); } else if (serviceLabel != null && !serviceLabel.isEmpty()) { logger.fine("Using service label to discover nodes."); return getSimpleDiscoveryNodes(client.endpointsByServiceLabel(serviceLabel, serviceLabelValue)); } else if (podLabel != null && !podLabel.isEmpty()) { logger.fine("Using pod label to discover nodes."); return getSimpleDiscoveryNodes(client.endpointsByPodLabel(podLabel, podLabelValue)); } return getSimpleDiscoveryNodes(client.endpoints()); }
Source:
public void testDeserialize() throws StripeException { LegalEntity le = APIResource.GSON.fromJson(legalEntityHash, LegalEntity.class); assertEquals("sole_prop", le.getType()); assertEquals("business name", le.getBusinessName()); assertEquals("12 Grove Street", le.getAddress().getLine1()); assertEquals(null, le.getAddress().getLine2()); assertEquals("New York", le.getAddress().getCity()); assertEquals("NY", le.getAddress().getState()); assertEquals("10014", le.getAddress().getPostalCode()); assertEquals("US", le.getAddress().getCountry()); assertEquals("Monica", le.getFirstName()); assertEquals("Geller", le.getLastName()); assertEquals(new Integer(4), le.getDob().getDay()); assertEquals(new Integer(4), le.getDob().getMonth()); assertEquals(new Integer(1969), le.getDob().getYear()); assertEquals(new LinkedList<Object>(), le.getAdditionalOwners()); assertEquals("verified", le.getVerification().getStatus()); assertEquals(null, le.getVerification().getDocument()); assertEquals(null, le.getVerification().getDetails()); }

Target:
public void testDeserialize() throws StripeException, IOException { String json = resource("legal_entity.json"); LegalEntity le = APIResource.GSON.fromJson(json, LegalEntity.class); assertEquals("sole_prop", le.getType()); assertEquals("business name", le.getBusinessName()); assertEquals("12 Grove Street", le.getAddress().getLine1()); assertEquals(null, le.getAddress().getLine2()); assertEquals("New York", le.getAddress().getCity()); assertEquals("NY", le.getAddress().getState()); assertEquals("10014", le.getAddress().getPostalCode()); assertEquals("US", le.getAddress().getCountry()); assertEquals("Monica", le.getFirstName()); assertEquals("Geller", le.getLastName()); assertEquals(new Integer(4), le.getDob().getDay()); assertEquals(new Integer(4), le.getDob().getMonth()); assertEquals(new Integer(1969), le.getDob().getYear()); assertEquals(new LinkedList<Object>(), le.getAdditionalOwners()); assertEquals("verified", le.getVerification().getStatus()); assertEquals(null, le.getVerification().getDocument()); assertEquals(null, le.getVerification().getDetails()); }
Source:
public static EObject getExpectedSide(Match match, DifferenceSource source, boolean mergeRightToLeft) { if (match != null) { final Comparison comparison = match.getComparison(); if (comparison.isThreeWay() && mergeRightToLeft == (source == DifferenceSource.LEFT)) { EObject origin = match.getOrigin(); if (origin != null) { return origin; } } if (mergeRightToLeft) { return match.getRight(); } else { return match.getLeft(); } } return null; }

Target:
public static EObject getExpectedSide(Match match, DifferenceSource source, boolean mergeRightToLeft) { EObject result = null; if (match != null) { final Comparison comparison = match.getComparison(); if (comparison.isThreeWay() && mergeRightToLeft == (source == DifferenceSource.LEFT) && match.getOrigin() != null) { result = match.getOrigin(); } else if (mergeRightToLeft) { result = match.getRight(); } else { result = match.getLeft(); } } return result; }
Source:
public void duplicateAttachmentTest(){ BasicDocumentRevision doc1Rev1 = datastore.createDocument(bodyOne); BasicDocumentRevision doc2Rev1 = datastore.createDocument(bodyTwo); File attachmentFile = new File("fixture","attachment_1.txt"); Attachment att1 = new UnsavedFileAttachment(attachmentFile,"text/plain"); Attachment att2 = new UnsavedFileAttachment(attachmentFile,"text/plain"); List<Attachment> doc1Atts = new ArrayList<Attachment>(); List<Attachment>doc2Atts = new ArrayList<Attachment>(); doc1Atts.add(att1); doc2Atts.add(att2); DocumentRevision newRevisionDoc1,newRevisionDoc2 = null; try{ newRevisionDoc1 = datastore.updateAttachments(doc1Rev1, doc1Atts); Assert.assertNotNull("Doc1 revision is null",newRevisionDoc1); List<? extends Attachment> attsForRev = datastore.attachmentsForRevision(newRevisionDoc1); Assert.assertEquals("Didn't get expected number of attachments", doc1Atts.size(), attsForRev.size()); newRevisionDoc2 = datastore.updateAttachments(doc2Rev1,doc2Atts); Assert.assertNotNull("Doc2 revision is null",newRevisionDoc2); attsForRev = datastore.attachmentsForRevision(newRevisionDoc2); Assert.assertEquals("Didn't get expected number of attachments", doc2Atts.size(), attsForRev.size()); } catch (ConflictException conflictException){ Assert.fail("Conflict Exception thrown "+conflictException); } }

Target:
public void duplicateAttachmentTest() { BasicDocumentRevision doc1Rev1 = datastore.createDocument(bodyOne); BasicDocumentRevision doc2Rev1 = datastore.createDocument(bodyTwo); File attachmentFile = new File("fixture", "attachment_1.txt"); Attachment att1 = new UnsavedFileAttachment(attachmentFile, "text/plain"); Attachment att2 = new UnsavedFileAttachment(attachmentFile, "text/plain"); List<Attachment> doc1Atts = new ArrayList<Attachment>(); List<Attachment> doc2Atts = new ArrayList<Attachment>(); doc1Atts.add(att1); doc2Atts.add(att2); DocumentRevision newRevisionDoc1 = null; DocumentRevision newRevisionDoc2 = null; try { newRevisionDoc1 = datastore.updateAttachments(doc1Rev1, doc1Atts); Assert.assertNotNull("Doc1 revision is null", newRevisionDoc1); List<? extends Attachment> attsForRev = datastore .attachmentsForRevision(newRevisionDoc1); Assert.assertEquals("Didn't get expected number of attachments", doc1Atts.size(), attsForRev.size()); newRevisionDoc2 = datastore.updateAttachments(doc2Rev1, doc2Atts); Assert.assertNotNull("Doc2 revision is null", newRevisionDoc2); attsForRev = datastore.attachmentsForRevision(newRevisionDoc2); Assert.assertEquals("Didn't get expected number of attachments", doc2Atts.size(), attsForRev.size()); } catch (ConflictException conflictException) { Assert.fail("Conflict Exception thrown "+conflictException); } }