auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void validateEmptyBucketToTempQueueMap(String senderId) { GatewaySender sender = getGatewaySender(senderId); int size = 0; Set queues = ((AbstractGatewaySender) sender).getQueues(); for (Object queue : queues) { PartitionedRegion region = (PartitionedRegion) ((ConcurrentParallelGatewaySenderQueue) queue).getRegion(); int buckets = region.getTotalNumberOfBuckets(); for (int bucket = 0; bucket < buckets; bucket++) { BlockingQueue newQueue = ((ConcurrentParallelGatewaySenderQueue) queue).getBucketTmpQueue((int) bucket); if (newQueue != null) { size += newQueue.size(); } } } final int finalSize = size; assertEquals("Expected elements in TempQueueMap: " + 0 + " but actual size: " + finalSize, 0, finalSize); }

Target:
public static void validateEmptyBucketToTempQueueMap(String senderId) { GatewaySender sender = getGatewaySender(senderId); int size = 0; Set<RegionQueue> queues = ((AbstractGatewaySender) sender).getQueues(); for (Object queue : queues) { PartitionedRegion region = (PartitionedRegion) ((ConcurrentParallelGatewaySenderQueue) queue).getRegion(); int buckets = region.getTotalNumberOfBuckets(); for (int bucket = 0; bucket < buckets; bucket++) { BlockingQueue<GatewaySenderEventImpl> newQueue = ((ConcurrentParallelGatewaySenderQueue) queue).getBucketTmpQueue(bucket); if (newQueue != null) { size += newQueue.size(); } } } final int finalSize = size; assertEquals("Expected elements in TempQueueMap: " + 0 + " but actual size: " + finalSize, 0, finalSize); }
Source:
public static void addSerializableSupport(JDefinedClass jclass) { jclass._implements(Serializable.class); try { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); processDefinedClassForSerializableSupport(jclass, dataOutputStream); dataOutputStream.flush(); final MessageDigest digest = MessageDigest.getInstance("SHA"); final byte[] digestBytes = digest.digest(byteArrayOutputStream.toByteArray()); long serialVersionUID = 0L; for (int i = Math.min(digestBytes.length, 8) - 1; i >= 0; i--) { serialVersionUID = serialVersionUID << 8 | (long)(digestBytes[i] & 0xff); } JFieldVar serialUIDField = jclass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, long.class, "serialVersionUID"); serialUIDField.init(JExpr.lit(serialVersionUID)); } catch (IOException exception) { final InternalError internalError = new InternalError(exception.getMessage()); internalError.initCause(exception); throw internalError; } catch (NoSuchAlgorithmException exception) { final RuntimeException securityException = new SecurityException(exception.getMessage()); securityException.initCause(exception); throw securityException; } }

Target:
public static void addSerializableSupport(JDefinedClass jclass) { jclass._implements(Serializable.class); try { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); processDefinedClassForSerializableSupport(jclass, dataOutputStream); dataOutputStream.flush(); final MessageDigest digest = MessageDigest.getInstance("SHA"); final byte[] digestBytes = digest.digest(byteArrayOutputStream.toByteArray()); long serialVersionUID = 0L; for (int i = Math.min(digestBytes.length, 8) - 1; i >= 0; i--) { serialVersionUID = serialVersionUID << 8 | (long)(digestBytes[i] & 0xff); } JFieldVar serialUIDField = jclass.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, long.class, "serialVersionUID"); serialUIDField.init(JExpr.lit(serialVersionUID)); } catch (IOException exception) { throw new GenerationException("IOException while generating serialversionUID field while adding serializable support to class: " + jclass.fullName(), exception); } catch (NoSuchAlgorithmException exception) { throw new GenerationException("SHA algorithm not found when trying to generate serialversionUID field while adding serializable support to class: " + jclass.fullName(), exception); } }
Source:
public RepositoryFile createFile( final Serializable parentFolderId, final RepositoryFile file, final IRepositoryFileData data, final String versionMessage ) { Constructor exceptionConstructor = null; try { exceptionConstructor = UnifiedRepositoryCreateFileException.class.getConstructor( String.class, Throwable.class ); } catch ( NoSuchMethodException e ) { e.printStackTrace(); } return callLogThrow( new Callable<RepositoryFile>() { public RepositoryFile call() throws Exception { return delegatee.createFile( parentFolderId, file, data, versionMessage ); } }, Messages.getInstance().getString( "ExceptionLoggingDecorator.createFile", file.getName() ), exceptionConstructor ); }

Target:
public RepositoryFile createFile( final Serializable parentFolderId, final RepositoryFile file, final IRepositoryFileData data, final String versionMessage ) { Constructor exceptionConstructor = null; try { exceptionConstructor = UnifiedRepositoryCreateFileException.class.getConstructor( String.class, Throwable.class ); } catch ( NoSuchMethodException e ) { logger.error( e ); } return callLogThrow( new Callable<RepositoryFile>() { public RepositoryFile call() throws Exception { return delegatee.createFile( parentFolderId, file, data, versionMessage ); } }, Messages.getInstance().getString( "ExceptionLoggingDecorator.createFile", file.getName() ), exceptionConstructor ); }
Source:
public static OrderLinePriceUpdateRequestBuilder prepare(final org.compiere.model.I_C_OrderLine orderLine) { return builder() .updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true) .updateLineNetAmt(true) .orderLine(InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class)) .resultUOM(ResultUOM.PRICE_UOM_IF_ORDERLINE_IS_NEW); }

Target:
public static OrderLinePriceUpdateRequestBuilder prepare(final org.compiere.model.I_C_OrderLine orderLine) { return builder() .updateLineNetAmt(true) .orderLine(InterfaceWrapperHelper.create(orderLine, I_C_OrderLine.class)) .resultUOM(ResultUOM.PRICE_UOM_IF_ORDERLINE_IS_NEW); }
Source:
public byte getAbsSendTimeExtensionID(){ return extensionID == -1 ? extensionID_for_debugging : extensionID ; }

Target:
public byte getAbsSendTimeExtensionID(){ return extensionID; }
Source:
public void put(K key, T obj) throws GoraException { try { if (obj.isDirty()) { Column pkc = kuduMapping.getPrimaryKey().get(0); Upsert upsert = table.newUpsert(); PartialRow row = upsert.getRow(); KuduClientUtils.addObjectRow(row, pkc, key); Schema schema = obj.getSchema(); List<Schema.Field> fields = schema.getFields(); for (Schema.Field field : fields) { Column mappedColumn = kuduMapping.getFields().get(field.name()); Object fieldValue = obj.get(field.pos()); if (mappedColumn != null && fieldValue != null) { Schema fieldSchema = field.schema(); Object serializedObj = serializeFieldValue(fieldSchema, fieldValue); KuduClientUtils.addObjectRow(row, mappedColumn, serializedObj); } else { row.setNull(mappedColumn.getName()); } } session.apply(upsert); } else { LOG.info("Ignored putting object in the store as it is neither " + "new, neither dirty.", new Object[]{obj}); } } catch (Exception e) { throw new GoraException(e); } }

Target:
public void put(K key, T obj) throws GoraException { try { if (obj.isDirty()) { Column pkc = kuduMapping.getPrimaryKey().get(0); Upsert upsert = table.newUpsert(); PartialRow row = upsert.getRow(); KuduClientUtils.addObjectRow(row, pkc, key); Schema schemaObj = obj.getSchema(); List<Schema.Field> fields = schemaObj.getFields(); for (Schema.Field field : fields) { Column mappedColumn = kuduMapping.getFields().get(field.name()); if (mappedColumn != null) { Object fieldValue = obj.get(field.pos()); if (fieldValue != null) { Schema fieldSchema = field.schema(); Object serializedObj = serializeFieldValue(fieldSchema, fieldValue); KuduClientUtils.addObjectRow(row, mappedColumn, serializedObj); } else { row.setNull(mappedColumn.getName()); } } else { throw new GoraException("Unmapped field : " + field.name()); } } session.apply(upsert); } else { LOG.info("Ignored putting object in the store as it is neither " + "new, neither dirty.", new Object[]{obj}); } } catch (Exception e) { throw new GoraException(e); } }
Source:
private static void createClause(Map<String, String> map) { boolean isEnd = true; for (String key : map.keySet()) { if (isEnd) { whereClause += "\"%" + key + "%\""; isEnd = false; } else { whereClause += " OR DeviceName LIKE"; whereClause += "\"%" + key + "%\""; } } }

Target:
private static void createClause(Map<String, String> map) { driverQueryClause = "Win32_PnPSignedDriver WHERE DeviceName LIKE "; boolean isEnd = true; for (String key : map.keySet()) { if (isEnd) { driverQueryClause += "\"%" + key + "%\""; isEnd = false; } else { driverQueryClause += " OR DeviceName LIKE"; driverQueryClause += "\"%" + key + "%\""; } } }
Source:
@Override @Nullable public T read(JsonReader in) throws IOException { JsonElement tree = adapter.read(in); T deserialized = delegate.fromJsonTree(tree); return allRequiredFieldsPresent(deserialized, requiredFields) ? deserialized : null; }

Target:
@Override @Nullable public T read(JsonReader in) throws IOException { T deserialized = delegate.read(in); return allRequiredFieldsPresent(deserialized, requiredFields) ? deserialized : null; }
Source:
public void add(PipelineTimelineEntry pipelineTimelineEntry) { CaseInsensitiveString pipelineName = new CaseInsensitiveString(pipelineTimelineEntry.getPipelineName()); PipelineTimelineEntrySet pipelineTimelineEntrySet = initializePita(pipelineName); pipelineTimelineEntrySet.getNaturalOrderSet().add(pipelineTimelineEntry); pipelineTimelineEntrySet.getScheduledOrderSet().add(pipelineTimelineEntry); pipelineTimelineEntry.setInsertedBefore(naturalOrderAfter(pipelineTimelineEntry)); pipelineTimelineEntry.setInsertedAfter(naturalOrderBefore(pipelineTimelineEntry)); pipelineTimelineEntry.updateNaturalOrder(); pipelineTimelineEntrySet.updateMaximumId(pipelineTimelineEntry.getId()); }

Target:
public void add(PipelineTimelineEntry pipelineTimelineEntry) { CaseInsensitiveString pipelineName = new CaseInsensitiveString(pipelineTimelineEntry.getPipelineName()); PipelineTimelineEntrySet pipelineTimelineEntrySet = initializePipelineEntriesFor(pipelineName); pipelineTimelineEntrySet.getNaturalOrderSet().add(pipelineTimelineEntry); pipelineTimelineEntrySet.getScheduledOrderSet().add(pipelineTimelineEntry); pipelineTimelineEntry.setInsertedBefore(naturalOrderAfter(pipelineTimelineEntry)); pipelineTimelineEntry.setInsertedAfter(naturalOrderBefore(pipelineTimelineEntry)); pipelineTimelineEntry.updateNaturalOrder(); pipelineTimelineEntrySet.updateMaximumId(pipelineTimelineEntry.getId()); }
Source:
public static void testLoadBalancing_slave() throws SQLException { Set<String> connectedHosts = new HashSet<String>(); Set<HostSpec> tryConnectedHosts = new HashSet<HostSpec>(); for (int i = 0; i < 20; ++i) { getConnection(secondary, true, true, fake1, master1, secondary1, secondary2); connectedHosts.add(getRemoteHostSpec()); tryConnectedHosts.addAll(hostStatusMap.keySet()); if (tryConnectedHosts.size() == 4) { break; } } assertEquals("Never connected to all salve hosts", new HashSet<String>(asList(secondaryIP, secondaryIP2)), connectedHosts); assertEquals("Never tried to connect to maste and fake node", 4, tryConnectedHosts.size()); getConnection(preferSecondary, false, true, fake1, master1, secondary1); assertRemote(secondaryIP); connectedHosts.clear(); for (int i = 0; i < 20; ++i) { getConnection(secondary, false, true, fake1, master1, secondary1, secondary2); connectedHosts.add(getRemoteHostSpec()); if (connectedHosts.size() == 2) { break; } } assertEquals("Never connected to all secondary hosts", new HashSet<String>(asList(secondaryIP, secondaryIP2)), connectedHosts); }

Target:
public static void testLoadBalancing_slave() throws SQLException { Set<String> connectedHosts = new HashSet<String>(); Set<HostSpec> tryConnectedHosts = new HashSet<HostSpec>(); for (int i = 0; i < 20; ++i) { getConnection(secondary, true, true, fake1, master1, secondary1, secondary2); connectedHosts.add(getRemoteHostSpec()); tryConnectedHosts.addAll(hostStatusMap.keySet()); if (tryConnectedHosts.size() == 4) { break; } } assertEquals("Did not connect to all secondary hosts", new HashSet<String>(asList(secondaryIP, secondaryIP2)), connectedHosts); assertEquals("Did not attempt to connect to master and fake node", 4, tryConnectedHosts.size()); getConnection(preferSecondary, false, true, fake1, master1, secondary1); assertRemote(secondaryIP); connectedHosts.clear(); for (int i = 0; i < 20; ++i) { getConnection(secondary, false, true, fake1, master1, secondary1, secondary2); connectedHosts.add(getRemoteHostSpec()); if (connectedHosts.size() == 2) { break; } } assertEquals("Did not connect to all secondary hosts", new HashSet<String>(asList(secondaryIP, secondaryIP2)), connectedHosts); }
Source:
public void close() throws FlinkKafka011Exception { try { final KafkaTransactionState currentTransaction = currentTransaction(); if (currentTransaction != null) { flush(currentTransaction); switch (semantic) { case EXACTLY_ONCE: break; case AT_LEAST_ONCE: case NONE: currentTransaction.producer.close(0, TimeUnit.SECONDS); break; } } super.close(); } catch (Exception e) { asyncException = ExceptionUtils.firstOrSuppressed(e, asyncException); } finally { if (currentTransaction() != null) { IOUtils.closeQuietly(currentTransaction().producer); } pendingTransactions().forEach(transaction -> IOUtils.closeQuietly(transaction.getValue().producer) ); checkErroneous(); } }

Target:
public void close() throws FlinkKafka011Exception { try { final KafkaTransactionState currentTransaction = currentTransaction(); if (currentTransaction != null) { flush(currentTransaction); switch (semantic) { case EXACTLY_ONCE: break; case AT_LEAST_ONCE: case NONE: currentTransaction.producer.flush(); currentTransaction.producer.close(0, TimeUnit.SECONDS); break; } } super.close(); } catch (Exception e) { asyncException = ExceptionUtils.firstOrSuppressed(e, asyncException); } finally { if (currentTransaction() != null) { IOUtils.closeQuietly(currentTransaction().producer); } pendingTransactions().forEach(transaction -> IOUtils.closeQuietly(transaction.getValue().producer) ); checkErroneous(); } }
Source:
public void test_parameters_retention() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V8)); assumeTrue(ClassFileVersion.ofThisVm().isLessThan(ClassFileVersion.JAVA_V9)); Class<?> typeWithParameters = new ByteBuddy() .subclass(Object.class) .defineMethod("foo", void.class, Visibility.PUBLIC) .withParameter(String.class, "bar") .intercept(StubMethod.INSTANCE) .make() .load(null) .getLoaded(); MockCreationSettings<?> settings = settingsFor(typeWithParameters); @SuppressWarnings("unchecked") Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings)); assertThat(proxy.getClass()).isEqualTo(typeWithParameters); assertThat(new TypeDescription.ForLoadedType(typeWithParameters).getDeclaredMethods().filter(named("foo")) .getOnly().getParameters().getOnly().getName()).isEqualTo("bar"); }

Target:
public void test_parameters_retention() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V8)); assumeTrue(ClassFileVersion.ofThisVm().isLessThan(JAVA_V9)); Class<?> typeWithParameters = new ByteBuddy() .subclass(Object.class) .defineMethod("foo", void.class, Visibility.PUBLIC) .withParameter(String.class, "bar") .intercept(StubMethod.INSTANCE) .make() .load(null) .getLoaded(); MockCreationSettings<?> settings = settingsFor(typeWithParameters); @SuppressWarnings("unchecked") Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings)); assertThat(proxy.getClass()).isEqualTo(typeWithParameters); assertThat(new TypeDescription.ForLoadedType(typeWithParameters).getDeclaredMethods().filter(named("foo")) .getOnly().getParameters().getOnly().getName()).isEqualTo("bar"); }
Source:
public static Family getFamilyFor(Class<? extends Component> ...componentTypes){ BitSet bits = new BitSet(); for (Class<? extends Component> componentType : componentTypes) { bits.set(ComponentType.getIndexFor(componentType)); } String hash = bits.toString(); Family family = families.get(hash, null); if(family == null){ family = new Family(bits); families.put(hash, family); } return family; }

Target:
public static Family getFamilyFor(Class<? extends Component> ...componentTypes){ BitSet bits = new BitSet(); int typesLength = componentTypes.length; for(int i = 0; i < typesLength; i++){ bits.set(ComponentType.getIndexFor(componentTypes[i])); } String hash = bits.toString(); Family family = families.get(hash, null); if(family == null){ family = new Family(bits); families.put(hash, family); } return family; }
Source:
public Content setOwners(Collection<Owner> owners) { this.owners.clear(); if (owners != null) { this.owners.addAll(owners); } return this; }

Target:
public Content setOwners(Collection<Owner> owners) { if (this.owners == null) { this.owners = new HashSet<Owner>(); } this.owners.clear(); if (owners != null) { this.owners.addAll(owners); } return this; }
Source:
private void setAudioTrack() { audioTracks = player.getAvailableAudioTracks(); if (audioTracks != null) { String language = "eng"; for (AudioTrack track : audioTracks) { Log.d("MultiAudio activity", "MultiAudio track language is: " + track.getLanguage()); if (TextUtils.equals(track.getLanguage(), language) && !track.equals(currentAudioTrack)) { player.setAudioTrack(track); break; } } } }

Target:
private void setAudioTrack() { if (player == null) { Log.e(TAG, "Player is null"); return; } audioTracks = player.getAvailableAudioTracks(); if (audioTracks != null) { String language = "eng"; for (AudioTrack track : audioTracks) { Log.d(TAG, "MultiAudio track language is: " + track.getLanguage()); if (TextUtils.equals(track.getLanguage(), language) && currentAudioTrack != null && !track.equals(currentAudioTrack)) { player.setAudioTrack(track); break; } } } }
Source:
public void tick(Level level) { super.tick(level); if(this.contains == null && hit == false) { timeEmpty++; if(timeEmpty >= TIME_FLOAT_UPWARDS) { this.hit(); addToLog("[BUBBLE]\t is empty and floating upwards"); } } if(this.contains == null && hit == true) { timeEmpty++; if(timeEmpty >= TIME_KILL) { this.kill(); addToLog("[BUBBLE]\t was empty and popped"); } } if(this.contains != null) { timeContained++; if(timeContained >= this.contains.getCaughtTime()) { this.contains.revive(); this.contains.setLocation(this.location); level.addUnit(this.contains); this.kill(); } } }

Target:
public void tick(Level level) { super.tick(level); if(this.contains == null) { timeEmpty++; if(!hit) { floatUpwards(); } else { killBubble(); } } else { timeContained++; if(timeContained >= this.contains.getCaughtTime()) { this.contains.revive(); this.contains.setLocation(this.location); level.addUnit(this.contains); this.kill(); } } }
Source:
public boolean hasNext() { if (!hasNext.isPresent()) { try { jobClient.getJobExecutionResult(Thread.currentThread().getContextClassLoader()).get(); } catch (Exception e) { throw new TableException("Failed to wait job finish", e); } hasNext = Optional.of(true); } return hasNext.get(); }

Target:
public boolean hasNext() { if (hasNext == null) { try { jobClient.getJobExecutionResult(classLoader).get(); } catch (Exception e) { throw new TableException("Failed to wait job finish", e); } hasNext = true; } return hasNext; }
Source:
public boolean promptPassword(String msg) { CredentialItem.Password p = new CredentialItem.Password(); if (provider.get(uri, p)) { password = new String(p.getValue()); return true; } else { CredentialItem.StringType v = newPrompt(msg); if (provider.get(uri, v)) { password = v.getValue(); return true; } else { password = null; return false; } } }

Target:
public boolean promptPassword(String msg) { CredentialItem.Password p = new CredentialItem.Password(msg); if (provider.get(uri, p)) { password = new String(p.getValue()); return true; } else { CredentialItem.StringType v = newPrompt(msg); if (provider.get(uri, v)) { password = v.getValue(); return true; } else { password = null; return false; } } }
Source:
public static Method fromString(String string) { Method method = null; switch (string) { case "GET": method = GET; break; case "POST": method = POST; break; case "PUT": method = PUT; break; case "DELETE": method = DELETE; break; default: break; } return method; }

Target:
public static Method fromString(String string) { Method method; switch (string) { case "GET": method = GET; break; case "POST": method = POST; break; case "PUT": method = PUT; break; case "DELETE": method = DELETE; break; default: throw new IllegalArgumentException("Invalid http method: <" + string + ">"); } return method; }
Source:
public void testLockingInterruptiblyCanBeInterrupted() throws Exception { Lock lock = new ReentrantLock(); Exchanger<Thread> testBackgroundThreadExchanger = new Exchanger<>(); Future<Object> future = executor.submit(() -> { testBackgroundThreadExchanger.exchange(Thread.currentThread()); lockingInterruptibly(lock, () -> { throw new AssertionError("test background thread got the lock"); }); throw new AssertionError("lockingInterruptibly returned, InterruptedException was expected"); }); locking(lock, () -> { Thread testBackgroundThread = testBackgroundThreadExchanger.exchange(null, 5, SECONDS); Thread.sleep(40); testBackgroundThread.interrupt(); }); try { future.get(5, SECONDS); fail("ExecutionException was expected"); } catch (ExecutionException expected) { assertTrue(expected.getCause() instanceof InterruptedException); } }

Target:
public void testLockingInterruptiblyCanBeInterrupted() throws Exception { Lock lock = new ReentrantLock(); Exchanger<Thread> exchanger = new Exchanger<>(); Future<Object> future = executor.submit(() -> { exchanger.exchange(Thread.currentThread()); lockingInterruptibly(lock, () -> { throw new AssertionError("test background thread got the lock"); }); throw new AssertionError("lockingInterruptibly returned, InterruptedException was expected"); }); locking(lock, () -> { Thread testBackgroundThread = exchanger.exchange(null, 5, SECONDS); Thread.sleep(40); testBackgroundThread.interrupt(); }); try { future.get(5, SECONDS); fail("ExecutionException was expected"); } catch (ExecutionException expected) { if (!(expected.getCause() instanceof InterruptedException)) { fail("Expected failure caused by interruption", expected); } } }
Source:
private void setBuildsAndWorkspacesDir() { String newBuildsDir = SystemProperties.getString(BUILDS_DIR_PROP); if (newBuildsDir != null && !buildsDir.equals(newBuildsDir)) { LOGGER.log(Level.WARNING, "Changing builds directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{buildsDir, newBuildsDir}); buildsDir = newBuildsDir; } String newWorkspacesDir = SystemProperties.getString(WORKSPACES_DIR_PROP); if (newWorkspacesDir != null && !workspaceDir.equals(newBuildsDir)) { LOGGER.log(Level.WARNING, "Changing workspaces directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{workspaceDir, newWorkspacesDir}); workspaceDir = newWorkspacesDir; } }

Target:
private void setBuildsAndWorkspacesDir() throws IOException, InvalidBuildsDir { boolean mustSave = false; String newBuildsDir = SystemProperties.getString(BUILDS_DIR_PROP); if (newBuildsDir != null && !buildsDir.equals(newBuildsDir)) { checkRawBuildsDir(newBuildsDir); LOGGER.log(Level.WARNING, "Changing builds directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{buildsDir, newBuildsDir}); buildsDir = newBuildsDir; mustSave = true; } else if (!isDefaultBuildDir()) { LOGGER.log(Level.INFO, "Using non default builds directories: {0}.", buildsDir); } String newWorkspacesDir = SystemProperties.getString(WORKSPACES_DIR_PROP); if (newWorkspacesDir != null && !workspaceDir.equals(newWorkspacesDir)) { LOGGER.log(Level.WARNING, "Changing workspaces directories from {0} to {1}. Beware that no automated data migration will occur.", new String[]{workspaceDir, newWorkspacesDir}); workspaceDir = newWorkspacesDir; mustSave = true; } else if (!isDefaultWorkspaceDir()) { LOGGER.log(Level.INFO, "Using non default workspaces directories: {0}.", workspaceDir); } if (mustSave) { save(); } }
Source:
private String createLiveInstanceWithUniqueName() { String hostname = "coordinator" + randomGenerator.nextInt(10000); try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { LOG.error(uhe.getMessage()); } long timestamp = System.currentTimeMillis(); String instanceName = String.format("%s-%d", hostname, timestamp); String znodePath = KeyBuilder.liveInstance(_cluster, instanceName); if (_zkclient.exists(znodePath)) { try { int randomInt = randomGenerator.nextInt(10); Thread.sleep(_instanceNameRetryWaitMs + randomInt); } catch (InterruptedException e) { e.printStackTrace(); } _instanceNameRetryWaitMs *= 2; LOG.info("Detected instance name conflicts."); return createLiveInstanceWithUniqueName(); } _zkclient.ensurePath(KeyBuilder.liveInstances(_cluster)); try{ _zkclient.create(KeyBuilder.liveInstance(_cluster, instanceName), "", CreateMode.EPHEMERAL); } catch (ZkNodeExistsException nee) { return createLiveInstanceWithUniqueName(); } _zkclient.ensurePath(KeyBuilder.instance(_cluster, instanceName)); return instanceName; }

Target:
private String createLiveInstanceWithUniqueName() { _zkclient.ensurePath(KeyBuilder.liveInstances(_cluster)); String hostname = "coordinator" + randomGenerator.nextInt(10000); try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { LOG.error(uhe.getMessage()); } String instanceName; while(true) { long timestamp = System.currentTimeMillis(); instanceName = String.format("%s-%d", hostname, timestamp); String znodePath = KeyBuilder.liveInstance(_cluster, instanceName); if (_zkclient.exists(znodePath)) { int sleepDuration = _instanceNameRetryWaitMs + randomGenerator.nextInt(10); try { Thread.sleep(sleepDuration); } catch (InterruptedException e) { LOG.warn("Failed to sleep " + sleepDuration + "for retrying unique instance name " + e.getMessage()); } _instanceNameRetryWaitMs *= 2; LOG.info("Detected instance name conflict, retry again after " + _instanceNameRetryWaitMs + " milliseconds"); continue; } try{ _zkclient.create(KeyBuilder.liveInstance(_cluster, instanceName), "", CreateMode.EPHEMERAL); } catch (ZkNodeExistsException nee) { _instanceNameRetryWaitMs *= 2; LOG.info("Detected instance name conflict, retry again after " + _instanceNameRetryWaitMs + " milliseconds"); continue; } _zkclient.ensurePath(KeyBuilder.instance(_cluster, instanceName)); break; } return instanceName; }
Source:
private String problemsForSubmittingChanges(List<ChangeData> changes, IdentifiedUser identifiedUser) { for (ChangeData c : changes) { try { ChangeControl changeControl = c.changeControl().forUser( identifiedUser); if (!changeControl.isVisible(dbProvider.get())) { return DEFAULT_BLOCKED_HIDDEN_TOPIC_TOOLTIP; } if (!changeControl.canSubmit()) { return DEFAULT_BLOCKED_TOPIC_TOOLTIP; } checkSubmitRule(c, c.currentPatchSet(), false); } catch (OrmException e) { log.error(String.valueOf(e)); throw new OrmRuntimeException(e); } catch (ResourceConflictException e) { return DEFAULT_BLOCKED_TOPIC_TOOLTIP; } } return null; }

Target:
private String problemsForSubmittingChanges(List<ChangeData> changes, IdentifiedUser identifiedUser) { for (ChangeData c : changes) { try { ChangeControl changeControl = c.changeControl().forUser( identifiedUser); if (!changeControl.isVisible(dbProvider.get())) { return BLOCKED_HIDDEN_TOPIC_TOOLTIP; } if (!changeControl.canSubmit()) { return BLOCKED_TOPIC_TOOLTIP; } checkSubmitRule(c, c.currentPatchSet(), false); } catch (OrmException e) { log.error("Error checking if change is submittable", e); throw new OrmRuntimeException(e); } catch (ResourceConflictException e) { return BLOCKED_TOPIC_TOOLTIP; } } return null; }
Source:
public IdentityHashMap<TableScanNode, Void> visitPlan(PlanNode node, Void context) { IdentityHashMap<TableScanNode, Void> ret = new IdentityHashMap<>(); node.getSources().forEach(source -> ret.putAll(source.accept(this, context))); return ret; }

Target:
public Map<TableScanNode, Void> visitPlan(PlanNode node, Void context) { Map<TableScanNode, Void> ret = new IdentityHashMap<>(); node.getSources().forEach(source -> ret.putAll(source.accept(this, context))); return ret; }
Source:
private long calculateSleep(long notifyCount, long numWorkers) { long sleep = notifyCount / numWorkers / 100; if (sleep < MIN_SLEEP_SEC) { return MIN_SLEEP_SEC; } return sleep; }

Target:
private long calculateSleep(long notifyCount, long numWorkers) { long sleep = notifyCount / numWorkers / 100; if (sleep < MIN_SLEEP_SEC) { return MIN_SLEEP_SEC; } else if (sleep > MAX_SLEEP_SEC) { return MAX_SLEEP_SEC; } return sleep; }
Source:
private String escapeKey(String key) { String toBeEscaped = SPACE.matcher(key).replaceAll("\\\\ "); toBeEscaped = COMMA.matcher(toBeEscaped).replaceAll("\\\\,"); return EQUAL.matcher(toBeEscaped).replaceAll("\\="); }

Target:
private String escapeKey(String key) { String toBeEscaped = SPACE.matcher(key).replaceAll("\\\\ "); return COMMA.matcher(toBeEscaped).replaceAll("\\\\,"); }
Source:
public Response send(final Request req, final String home, final String method, final Collection<Map.Entry<String, String>> headers, final InputStream content, final int connect, final int read, final SSLContext context) throws IOException { final SSLContext resolvedContext; if (context == null) { resolvedContext = context(); } else { resolvedContext = context; } return this.origin.send( req, home, method, headers, content, connect, read, resolvedContext ); }

Target:
public Response send(final Request req, final String home, final String method, final Collection<Map.Entry<String, String>> headers, final InputStream content, final int connect, final int read, final SSLContext context) throws IOException { return this.origin.send( req, home, method, headers, content, connect, read, context() ); }
Source:
private JSONObject triggerClauseToJson(TriggerClause clause) throws JSONException { JSONObject ret = new JSONObject(); if (clause instanceof EqualsClauseInTrigger) { EqualsClauseInTrigger eq = (EqualsClauseInTrigger)clause; ret.put("type", "eq"); ret.put("alias", eq.getAlias()); ret.put("field", eq.getField()); ret.put("value", eq.getValue()); }else if (clause instanceof RangeClauseInTrigger) { RangeClauseInTrigger range = (RangeClauseInTrigger)clause; ret.put("type", "range"); ret.put("alias", range.getAlias()); ret.put("field", range.getField()); ret.putOpt("lowerLimit", range.getLowerLimit()); ret.putOpt("upperLimit", range.getUpperLimit()); ret.putOpt("lowerIncluded", range.getLowerIncluded()); ret.putOpt("upperIncluded", range.getUpperIncluded()); } else if(clause instanceof NotEqualsClauseInTrigger) { NotEqualsClauseInTrigger neq = (NotEqualsClauseInTrigger)clause; ret.put("type", "not").put("clause", triggerClauseToJson(neq.getEquals())); } else if (clause instanceof AndClauseInTrigger) { JSONArray clauses = new JSONArray(); for (TriggerClause subClause : ((AndClauseInTrigger)clause).getClauses()) { clauses.put(triggerClauseToJson(subClause)); } ret.put("type", "and").put("clauses", clauses); } else if (clause instanceof OrClauseInTrigger) { JSONArray clauses = new JSONArray(); for (TriggerClause subClause : ((OrClauseInTrigger) clause).getClauses()) { clauses.put(triggerClauseToJson(subClause)); } ret.put("type", "or").put("clauses", clauses); }else{ throw new RuntimeException("not support trigger clause"); } return ret; }

Target:
private JsonObject triggerClauseToJson(TriggerClause clause) { String type; JsonObject ret; if (clause instanceof EqualsClauseInTrigger || clause instanceof RangeClauseInTrigger) { ret = new Gson().toJsonTree(clause).getAsJsonObject(); if (clause instanceof EqualsClauseInTrigger) { type = "eq"; }else { type = "range"; } } else { ret = new JsonObject(); if (clause instanceof NotEqualsClauseInTrigger) { NotEqualsClauseInTrigger neq = (NotEqualsClauseInTrigger) clause; ret.add("clause", triggerClauseToJson(neq.getEquals())); type = "not"; } else if (clause instanceof AndClauseInTrigger) { JsonArray clauses = new JsonArray(); for (TriggerClause subClause : ((AndClauseInTrigger) clause).getClauses()) { clauses.add(triggerClauseToJson(subClause)); } ret.add("clauses", clauses); type = "and"; } else if (clause instanceof OrClauseInTrigger) { JsonArray clauses = new JsonArray(); for (TriggerClause subClause : ((OrClauseInTrigger) clause).getClauses()) { clauses.add(triggerClauseToJson(subClause)); } ret.add("clauses", clauses); type = "or"; } else { throw new RuntimeException("not support trigger clause"); } } ret.addProperty("type", type); return ret; }
Source:
public ViewPage clickApplication(String applicationName) { getDriver().findElementWithoutWaiting(By.xpath( " return new ViewPage(); }

Target:
public ViewPage clickApplication(String applicationName) { getDriver().findElementWithoutWaiting(applicationElement(applicationName)).click(); return new ViewPage(); }
Source:
public static Optional<Long> savedAccountQuestion(final Question question, final ImmutableList<AccountQuestionResponses> todayQuestionResponseList) { for (AccountQuestionResponses accountQuestionResponses : todayQuestionResponseList) { if (accountQuestionResponses.questionId.equals(question.id)) { final Long accountQuestionId = accountQuestionResponses.id; return Optional.of(accountQuestionId); } } return Optional.absent(); }

Target:
public static Optional<Long> savedAccountQuestion(final Question question, final ImmutableList<AccountQuestionResponses> todayQuestionResponseList) { for (AccountQuestionResponses accountQuestionResponses : todayQuestionResponseList) { if (accountQuestionResponses.questionId.equals(question.id)) { final Long accountQuestionId = accountQuestionResponses.id; return Optional.of(accountQuestionResponses.id); } } return Optional.absent(); }
Source:
private void setFixedLengthStreamingMode(HttpURLConnection connection, long length) { try { HttpURLConnection.class.getMethod("setFixedLengthStreamingMode", long.class).invoke(connection, length); } catch (Exception e) { throw new IllegalArgumentException("Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations." + " Use chunked encoding or multi-part upload, if possible, or use a different http driver." + " For more information: <LINK_0>"); } }

Target:
private static void setFixedLengthStreamingMode(HttpURLConnection connection, long length) { try { HttpURLConnection.class.getMethod("setFixedLengthStreamingMode", long.class).invoke(connection, length); } catch (Exception e) { throw new IllegalArgumentException("Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations." + " Use chunked encoding or multi-part upload, if possible, or use a different http driver." + " For more information: <LINK_0>"); } }
Source:
public CompositeCommand combine(CompositeCommand cc) { cc.commands.forEach(commands::add); return this; }

Target:
public CompositeCommand combine(CompositeCommand cc) { commands.addAll(cc.commands); return this; }
Source:
public Kiji retain() { Preconditions.checkState(mRetainCount.incrementAndGet() >= 0, "Cannot retain a closed Kiji."); return this; }

Target:
public Kiji retain() { Preconditions.checkState(mRetainCount.getAndIncrement() >= 0, String.format( "Cannot retain a closed resource: retain counter is %s.", mRetainCount.get())); return this; }
Source:
public void registerHandler(ITraceEventHandler handler) { int pos = Collections.binarySearch(fHandlers, handler, HANDLER_COMPARATOR); if (pos < 0) { fHandlers.add(-pos - 1, handler); } else { fHandlers.add(handler); } }

Target:
public void registerHandler(ITraceEventHandler handler) { int pos = Collections.binarySearch(fHandlers, handler, HANDLER_COMPARATOR); if (pos < 0) { fHandlers.add(-pos - 1, handler); } }
Source:
public void deleteAll() { dataService.findAll(GroupMetadata.GROUP, Group.class).forEach(this::delete); }

Target:
public void deleteAll() { forEachBatched(entities -> delete(entities.stream()), 1000); }
Source:
private long now() { final int mspersec = 1000; final long sinceepoch = new Date().getTime(); final long milliseconds = sinceepoch % mspersec; return sinceepoch - milliseconds; }

Target:
private static long now() { final long sinceepoch = new Date().getTime(); return sinceepoch - (sinceepoch % Tv.THOUSAND); }
Source:
public void updateLastDownload(String taxonomy, Long lastDownload){ SharedPreferences mSettings = OFFApplication.getInstance().getSharedPreferences("prefs", 0); mSettings.edit().putLong("lastDownload" + taxonomy, lastDownload).apply(); Log.i("INFO_URL", "End of import for : " + taxonomy); }

Target:
public void updateLastDownload(String taxonomy, Long lastDownload){ SharedPreferences mSettings = OFFApplication.getInstance().getSharedPreferences("prefs", 0); mSettings.edit().putLong("lastDownload" + taxonomy, lastDownload).apply(); Log.i("INFO_URL", "Set lastDownload of " + taxonomy + " to " + lastDownload); }
Source:
public Response callback() { return Response.serverError().build(); }

Target:
public Response callback() { LOGGER.error( new RuntimeException(), "This endpoint is to be handled by the pac4j filter to redirect users, request should never reach here." ); return Response.serverError().build(); }
Source:
protected void buildVmGraphicsDevices() { boolean graphicsOverriden = vm.isRunOnce() && vm.getGraphicsInfos() != null && !vm.getGraphicsInfos().isEmpty(); Map<GraphicsType, GraphicsInfo> infos = vm.getGraphicsInfos(); Map<String, Object> specParamsFromVm = null; if (infos != null) { specParamsFromVm = new HashMap(); addVmGraphicsOptions(infos, specParamsFromVm, false); } if (graphicsOverriden) { buildVmGraphicsDevicesOverriden(infos, specParamsFromVm); } else { buildVmGraphicsDevicesFromDb(specParamsFromVm); } }

Target:
protected void buildVmGraphicsDevices() { boolean graphicsOverriden = vm.isRunOnce() && vm.getGraphicsInfos() != null && !vm.getGraphicsInfos().isEmpty(); Map<GraphicsType, GraphicsInfo> infos = vm.getGraphicsInfos(); Map<String, Object> specParamsFromVm = null; if (infos != null) { specParamsFromVm = new HashMap(); addVmGraphicsOptions(infos, specParamsFromVm); } if (graphicsOverriden) { buildVmGraphicsDevicesOverriden(infos, specParamsFromVm); } else { buildVmGraphicsDevicesFromDb(specParamsFromVm); } }
Source:
public void onEventMainThread(ReportBackListTask task) { if(task.position == position) { totalPages = task.totalPages; currentPage = task.page; List<ReportBack> reportBacks = task.reportBacks; if(reportBacks != null) { adapter.addAll(reportBacks); } else { Toast.makeText(getActivity(), "report back data failed", Toast.LENGTH_SHORT).show(); } } }

Target:
public void onEventMainThread(ReportBackListTask task) { if(task.position == position) { totalPages = task.totalPages; currentPage = task.page; List<ReportBack> reportBacks = task.reportBacks; adapter.addAll(reportBacks); } }
Source:
public List<String> build() { ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); Preconditions.checkArgument(!inputs.isEmpty(), "At least one input must be specified"); Preconditions.checkArgument(!outputs.isEmpty(), "At least one output must be specified"); args.add(override ? "-y" : "-n"); args.add("-v", this.verbosity.toString()); if (user_agent != null) { args.add("-user-agent", user_agent); } if (startOffset != null) { args.add("-ss", FFmpegUtils.millisecondsToString(startOffset)); } if (format != null) { args.add("-f", format); } if (read_at_native_frame_rate) { args.add("-re"); } if (progress != null) { args.add("-progress", progress.toString()); } args.addAll(extra_args); for (String input : inputs) { args.add("-i", input); } if (pass > 0) { args.add("-pass", Integer.toString(pass)); if (pass_prefix != null) { args.add("-passlogfile").add(pass_directory + pass_prefix); } } for (FFmpegOutputBuilder output : this.outputs) { args.addAll(output.build(pass)); } return args.build(); }

Target:
public List<String> build() { ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); Preconditions.checkArgument(!inputs.isEmpty(), "At least one input must be specified"); Preconditions.checkArgument(!outputs.isEmpty(), "At least one output must be specified"); args.add(override ? "-y" : "-n"); args.add("-v", this.verbosity.toString()); if (user_agent != null) { args.add("-user-agent", user_agent); } if (startOffset != null) { args.add("-ss", FFmpegUtils.millisecondsToString(startOffset)); } if (format != null) { args.add("-f", format); } if (read_at_native_frame_rate) { args.add("-re"); } if (progress != null) { args.add("-progress", progress.toString()); } args.addAll(extra_args); for (String input : inputs) { args.add("-i", input); } if (pass > 0) { args.add("-pass", Integer.toString(pass)); if (pass_prefix != null) { args.add("-passlogfile", pass_directory + pass_prefix); } } for (FFmpegOutputBuilder output : this.outputs) { args.addAll(output.build(pass)); } return args.build(); }
Source:
public MaterialValueManager.Value getMaterialValues() { return ((GlowServer) Bukkit.getServer()).getMaterialValueManager().getValue(getType()); }

Target:
public MaterialValueManager.ValueCollection getMaterialValues() { return ((GlowServer) Bukkit.getServer()).getMaterialValueManager().getValues(getType()); }
Source:
public void start() { keyspace = config.getCacheKeyspace(); maxResultSetSize = config.getNfcMaxResultSetSize(); session = cassandraClient.getSession(); session.execute( getSchemaCreateKeyspace( keyspace ) ); session.execute( getSchemaCreateTable( keyspace ) ); preparedExistQuery = session.prepare( "SELECT count(*) FROM " + keyspace + ".nfc WHERE storekey=? and path=?;" ); preparedCountByStore = session.prepare( "SELECT count(*) FROM " + keyspace + ".nfc WHERE storekey=?;" ); preparedQueryByStore = session.prepare( "SELECT * FROM " + keyspace + ".nfc WHERE storekey=?;" ); preparedDeleteByStore = session.prepare( "DELETE FROM " + keyspace + ".nfc WHERE storekey=?;" ); preparedDelete = session.prepare( "DELETE FROM " + keyspace + ".nfc WHERE storekey=? AND path=?;" ); preparedInsert = session.prepare( "INSERT INTO " + keyspace + ".nfc (storekey,path,creation,expiration) VALUES (?,?,?,?) USING TTL ?;" ); }

Target:
public void start() { inMemoryCache = cacheProducer.getCache( "nfc-in-memory-cache" ); keyspace = config.getCacheKeyspace(); maxResultSetSize = config.getNfcMaxResultSetSize(); session = cassandraClient.getSession(); session.execute( getSchemaCreateKeyspace( keyspace ) ); session.execute( getSchemaCreateTable( keyspace ) ); preparedExistQuery = session.prepare( "SELECT expiration FROM " + keyspace + ".nfc WHERE storekey=? and path=?;" ); preparedCountByStore = session.prepare( "SELECT count(*) FROM " + keyspace + ".nfc WHERE storekey=?;" ); preparedQueryByStore = session.prepare( "SELECT * FROM " + keyspace + ".nfc WHERE storekey=?;" ); preparedDeleteByStore = session.prepare( "DELETE FROM " + keyspace + ".nfc WHERE storekey=?;" ); preparedDelete = session.prepare( "DELETE FROM " + keyspace + ".nfc WHERE storekey=? AND path=?;" ); preparedInsert = session.prepare( "INSERT INTO " + keyspace + ".nfc (storekey,path,creation,expiration) VALUES (?,?,?,?) USING TTL ?;" ); }
Source:
public void run() { startTime = System.currentTimeMillis(); try { TajoConf conf = tajoClient.getConf(); if (conf.getBoolVar(TajoConf.ConfVars.TAJO_MASTER_HA_ENABLE)) { if (!HAServiceUtil.isMasterAlive(conf.get(TajoConf.ConfVars.TAJO_MASTER_CLIENT_RPC_ADDRESS .varname), conf)) { tajoClient.close(); tajoClient = new TajoClient(new TajoConf()); } } response = tajoClient.executeQuery(query); if (response == null) { LOG.error("Internal Error: SubmissionResponse is NULL"); error = new Exception("Internal Error: SubmissionResponse is NULL"); } else if (response.getResultCode() == ClientProtos.ResultCode.OK) { if (response.getIsForwarded()) { queryId = new QueryId(response.getQueryId()); getQueryResult(queryId); } else { if (!response.hasTableDesc() && !response.hasResultSet()) { } else { getSimpleQueryResult(response); } progress.set(100); } } } catch (Exception e) { LOG.error(e.getMessage(), e); error = e; } finally { running.set(false); finishTime = System.currentTimeMillis(); if (queryId != null) { tajoClient.closeQuery(queryId); } } }

Target:
public void run() { startTime = System.currentTimeMillis(); try { TajoConf conf = tajoClient.getConf(); tajoClient = TajoHAClientUtil.getTajoClient(conf, tajoClient); response = tajoClient.executeQuery(query); if (response == null) { LOG.error("Internal Error: SubmissionResponse is NULL"); error = new Exception("Internal Error: SubmissionResponse is NULL"); } else if (response.getResultCode() == ClientProtos.ResultCode.OK) { if (response.getIsForwarded()) { queryId = new QueryId(response.getQueryId()); getQueryResult(queryId); } else { if (!response.hasTableDesc() && !response.hasResultSet()) { } else { getSimpleQueryResult(response); } progress.set(100); } } } catch (Exception e) { LOG.error(e.getMessage(), e); error = e; } finally { running.set(false); finishTime = System.currentTimeMillis(); if (queryId != null) { tajoClient.closeQuery(queryId); } } }
Source:
public void handleNetworkException(VDSNetworkException ex) { boolean saveToDb = true; if(isInServerRebootTimeout()) { return; } if (cachedVds.getStatus() != VDSStatus.Down) { if (isHostInGracePeriod(false)) { if (cachedVds.getStatus() != VDSStatus.Connecting && cachedVds.getStatus() != VDSStatus.PreparingForMaintenance && cachedVds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, cachedVds); logChangeStatusToConnecting(); } else { saveToDb = false; } unrespondedAttempts.incrementAndGet(); } else { if (cachedVds.getStatus() == VDSStatus.Maintenance) { saveToDb = false; } else { List<VmDynamic> vmsRunningOnVds = vmDynamicDao.getAllRunningForVds(getVdsId()); if (cachedVds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.NonResponsive, cachedVds); moveVmsToUnknown(vmsRunningOnVds); int skippedIterationsBeforeFirstTry = Config.<Integer>getValue(ConfigValues.NumberVdsRefreshesBeforeTryToStartUnknownVms); autoRestartUnknownVmsIteration = 0 - skippedIterationsBeforeFirstTry; logHostFailToRespond(ex); resourceManager.getEventListener().vdsNotResponding(cachedVds); } else { saveToDb = false; } restartVmsWithLeaseIfNeeded(vmsRunningOnVds); } } } if (saveToDb) { updateDynamicData(cachedVds.getDynamicData()); updateStatisticsData(cachedVds.getStatisticsData()); } }

Target:
public void handleNetworkException(VDSNetworkException ex) { boolean saveToDb = true; if (isInServerRebootTimeout()) { log.warn("Ignoring communication error for host '{}', because reboot timeout hasn't passed: {}", cachedVds.getHostName(), ex.getMessage()); log.debug("Exception", ex); return; } if (cachedVds.getStatus() != VDSStatus.Down) { if (isHostInGracePeriod(false)) { if (cachedVds.getStatus() != VDSStatus.Connecting && cachedVds.getStatus() != VDSStatus.PreparingForMaintenance && cachedVds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, cachedVds); logChangeStatusToConnecting(); } else { saveToDb = false; } unrespondedAttempts.incrementAndGet(); } else { if (cachedVds.getStatus() == VDSStatus.Maintenance) { saveToDb = false; } else { List<VmDynamic> vmsRunningOnVds = vmDynamicDao.getAllRunningForVds(getVdsId()); if (cachedVds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.NonResponsive, cachedVds); moveVmsToUnknown(vmsRunningOnVds); int skippedIterationsBeforeFirstTry = Config.<Integer>getValue(ConfigValues.NumberVdsRefreshesBeforeTryToStartUnknownVms); autoRestartUnknownVmsIteration = 0 - skippedIterationsBeforeFirstTry; logHostFailToRespond(ex); resourceManager.getEventListener().vdsNotResponding(cachedVds); } else { saveToDb = false; } restartVmsWithLeaseIfNeeded(vmsRunningOnVds); } } } if (saveToDb) { updateDynamicData(cachedVds.getDynamicData()); updateStatisticsData(cachedVds.getStatisticsData()); } }