auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String getPropertyType(String className, String propertyName, XWikiContext context) throws Exception { PropertyClass pc = null; try { pc = (PropertyClass) context.getWiki().getDocument(className, context).getXClass().get(propertyName); } catch (XWikiException e) { LOGGER.error("Failed to get property for document [{}]", propertyName, className, e); } return pc.newProperty().getClass().getName(); }

Target:
private String getPropertyType(String className, String propertyName, XWikiContext context) throws Exception { PropertyClass pc = null; try { pc = (PropertyClass) context.getWiki().getDocument(className, context).getXClass().get(propertyName); } catch (XWikiException e) { LOGGER.error("Failed to get property for document [{}]", propertyName, className, e); } return pc == null ? null : pc.newProperty().getClass().getName(); }
Source:
public void maxSimultaneousCompilations() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.maximumSimultaneousCompilations",4)).thenReturn(4); int i = mocker.getComponentUnderTest().getMaximumSimultaneousCompilations(); assertTrue(i == 4); }

Target:
public void maxSimultaneousCompilations() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.maximumSimultaneousCompilations",4)).thenReturn(4); int i = mocker.getComponentUnderTest().getMaximumSimultaneousCompilations(); assertEquals(4,i); }
Source:
public String getHint() { return getBasePropertyClass().getTranslatedHint(context); }

Target:
public String getHint() { return getBasePropertyClass().getHint(); }
Source:
public Expression lookup(final String pattern) { if (expressionMap.containsKey(pattern)) { return expressionMap.get(pattern); } for (String key : expressionMap.keySet()) { if (key != null && pattern.matches(key)) { Expression expression = expressionMap.get(key); expressionMap.put(pattern, expression); // memoize return expression; } } return null; }

Target:
public Expression lookup(final String pattern) { if (expressionMap.containsKey(pattern)) { return expressionMap.get(pattern); } for (final String key : expressionMap.keySet()) { if (key != null && pattern.matches(key)) { final Expression expression = expressionMap.get(key); expressionMap.put(pattern, expression); // memoize return expression; } } return null; }
Source:
private List<String> buildCommand(String nodeExecutable, List<String> nodeJsArgs, @Nullable String scriptFilename, List<String> args) { List<String> result = new ArrayList<>(); result.add(nodeExecutable); result.addAll(nodeJsArgs); if (scriptFilename != null) { result.add(scriptFilename); } result.addAll(args); return Collections.unmodifiableList(result); }

Target:
private static List<String> buildCommand(String nodeExecutable, List<String> nodeJsArgs, @Nullable String scriptFilename, List<String> args) { List<String> result = new ArrayList<>(); result.add(nodeExecutable); result.addAll(nodeJsArgs); if (scriptFilename != null) { result.add(scriptFilename); } result.addAll(args); return Collections.unmodifiableList(result); }
Source:
public boolean isExcluded(InputFile file) { boolean isMinified = new MinificationAssessor().isMinified(file); if (isMinified) { LOG.debug("File [" + file.toString() + "] looks like a minified file and will not be analyzed"); } return isMinified; }

Target:
public boolean isExcluded(InputFile file) { boolean isMinified = new MinificationAssessor().isMinified(file); if (isMinified) { LOG.debug("File [" + file.uri() + "] looks like a minified file and will not be analyzed"); } return isMinified; }
Source:
private void initializeBaseDirectory(PropertyUtil propertyUtil) throws IOException { String baseDirectoryPath = propertyUtil.extractString(KEY_DATABASE_PATH, DEFAULT_BASE_DIRECTORY); BASE_DIRECTORY = Paths.get(baseDirectoryPath); LOGGER.info("Using \"{}\" as base directory for results database", baseDirectoryPath); if (!Files.isDirectory(BASE_DIRECTORY)) { Files.createDirectories(BASE_DIRECTORY); } }

Target:
private void initializeBaseDirectory(PropertyUtil propertyUtil) throws IOException { String baseDirectoryPath = propertyUtil.extractString(KEY_DATABASE_PATH, DEFAULT_BASE_DIRECTORY); BASE_DIRECTORY = Paths.get(baseDirectoryPath); LOGGER.info("Using \"{}\" as base directory for results database", baseDirectoryPath); Files.createDirectories(BASE_DIRECTORY); }
Source:
public boolean offer(Message msg) { if (capacity == 0) { try { // for synchronous queue, this will block until the sink takes the message from the queue queue.put(msg); } catch (InterruptedException e) { return false; } return true; } return queue.offer(msg); }

Target:
public boolean offer(Message msg) { if (capacity == 0) { try { // for synchronous queue, this will block until the sink takes the message from the queue queue.put(msg); } catch (InterruptedException e) { return false; } return true; } else { return queue.offer(msg); } }
Source:
public void displayHelpWidget() { //display helpWidget //will be implemented at a later stage Window.alert( "Coming soon!" ); }

Target:
public void displayHelpWidget() { //display helpWidget //will be implemented at a later stage }
Source:
private TimedRenderer getCurrentFrame() { // In case the current frame is null, just return an empty timed // renderer as a frame if (frames.get(currentFrame) != null) return frames.get(currentFrame); else { return new TimedRenderer() { @Override public void draw(Batch batch) { } @Override public float getHeight() { return 0; } @Override public float getWidth() { return 0; } @Override public void initialize(Object schemaObject) { } public float surplusTime() { return 0; } }; } }

Target:
private TimedRenderer getCurrentFrame() { return frames.get(currentFrame); }
Source:
private String emailMask(String email){ String[] frag = email.split("@"); //Split id and domain int sid = frag[0].length() / 3 + 1; //Define the id view int sdomain = frag[1].length() / 3 + 1; //Define the domain view String id = frag[0].substring(0, sid) + "*****"; //Build the id String domain = "***" + frag[1].substring(sdomain); //Build the domain return id + "@" + domain; }

Target:
private String emailMask(String email){ String[] frag = email.split("@"); //Split id and domain int sid = frag[0].length() / 3 + 1; //Define the id view (required length >= 1) int sdomain = frag[1].length() / 3; //Define the domain view (required length >= 0) String id = frag[0].substring(0, sid) + "***"; //Build the id String domain = "***" + frag[1].substring(sdomain); //Build the domain return id + "@" + domain; }
Source:
public void getFileName_ReturnsFileNameForSVG() { // given Embedding embedding = new Embedding("image/svg+xml", "some data", null); // when String fileName = embedding.getFileName(); // then assertThat(fileName).isEqualTo("embedding_-642587818.svg"); }

Target:
public void getFileName_ReturnsFileNameForSVG() { // given Embedding embedding = new Embedding("image/svg+xml", "some data"); // when String fileName = embedding.getFileName(); // then assertThat(fileName).isEqualTo("embedding_-642587818.svg"); }
Source:
public void generateReport_OnInvalidPath_ThrowsException() { setUpWithJson(SAMPLE_JSON); // given page = new FeaturesOverviewPage(reportResult, configuration) { @Override public String getWebPage() { // invalid file path return StringUtils.EMPTY; } }; // when thrown.expect(ValidationException.class); Deencapsulation.invoke(page, "generatePage"); }

Target:
public void generateReport_OnInvalidPath_ThrowsException() { // given page = new FeaturesOverviewPage(reportResult, configuration) { @Override public String getWebPage() { // invalid file path return StringUtils.EMPTY; } }; // when thrown.expect(ValidationException.class); Deencapsulation.invoke(page, "generatePage"); }
Source:
public boolean isSleepingConsumer(){ if(System.currentTimeMillis() < this.consumerSleepEndTime){ return true; } return false; }

Target:
public boolean isSleepingConsumer(){ return System.currentTimeMillis() < this.consumerSleepEndTime; }
Source:
private long getMemoryMb(String key) { long memoryMb = 0L; if (key.equals(Constants.MAP_MEMORY_MB_CONF_KEY)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_MAP_MEMORY_MB); }else if (key.equals(Constants.REDUCE_MEMORY_MB_CONF_KEY)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_REDUCE_MEMORY_MB); } if (memoryMb == 0L) { throw new ProcessingException( "While correcting slot millis, " + key + " was found to be 0 "); } return memoryMb; }

Target:
private long getMemoryMb(String key) { long memoryMb = 0L; if (Constants.MAP_MEMORY_MB_CONF_KEY.equals(key)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_MAP_MEMORY_MB); }else if (Constants.REDUCE_MEMORY_MB_CONF_KEY.equals(key)){ memoryMb = this.jobConf.getLong(key, Constants.DEFAULT_REDUCE_MEMORY_MB); } if (memoryMb == 0L) { throw new ProcessingException( "While correcting slot millis, " + key + " was found to be 0 "); } return memoryMb; }
Source:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization String cluster = Cluster.getIdentifier(jobtracker); return cluster != null ? cluster: null; }

Target:
public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } String cluster = null; if (jobtracker != null) { // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization cluster = Cluster.getIdentifier(jobtracker); } return cluster; }
Source:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file ", ioe); throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey + " error: " + ioe.getMessage()); } }

Target:
public void parse(InputStream historyFile, JobKey jobKey) throws ProcessingException { try { jobHistoryListener = new JobHistoryListener(jobKey); JobHistoryCopy.parseHistoryFromIS(historyFile, jobHistoryListener); } catch (IOException ioe) { LOG.error(" Exception during parsing hadoop 1.0 file ", ioe); throw new ProcessingException( " Unable to parse history file in function parse, " + "cannot process this record!" + jobKey + " error: " , ioe); } }
Source:
public void testNonBlockingAcquireBuffer() { SslBufferPool pool = new ThreadLocalSslBufferPool(1, true, true, 1); ByteBuffer buf1 = pool.acquireBuffer(); Assert.assertEquals(pool.getUnacquiredPoolSize(), 0); // Try to acquire buffer. Unlike SslBufferPool, this should not block and will return another buffer. ByteBuffer buf2 = pool.acquireBuffer(); pool.releaseBuffer(buf1); pool.releaseBuffer(buf2); }

Target:
public void testNonBlockingAcquireBuffer() { SslBufferPool pool = new ThreadLocalSslBufferPool(1, true, true, 1); ByteBuffer buf1 = null; ByteBuffer buf2 = null; try { buf1 = pool.acquireBuffer(); Assert.assertEquals(pool.getUnacquiredPoolSize(), 0); // Try to acquire buffer. Unlike SslBufferPool, this should not block and will return another buffer. buf2 = pool.acquireBuffer(); } finally { pool.releaseBuffer(buf1); pool.releaseBuffer(buf2); } }
Source:
public void dosCborObject() throws Throwable { if(true)throw new RuntimeException(); // make a header for a byte[] that is 2^50 long byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); Assert.fail("Should have failed!"); } catch (RuntimeException e) }

Target:
public void dosCborObject() throws Throwable { // make a header for a byte[] that is 2^50 long byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); Assert.fail("Should have failed!"); } catch (RuntimeException e) }
Source:
public int getQueuePositionForSong(long id) { return mTimeline.getPositionForSong(id); }

Target:
public int getQueuePositionForSong(long id) { return mTimeline.getQueuePositionForSong(id); }
Source:
public KijiCell<T> next() { KeyValue kv = mKVs.next(); mNumVersions += 1; try { return new KijiCell<T>(mFamily, mQualifier, kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } catch (IOException ex) { throw new KijiIOException(ex.getMessage()); } }

Target:
public KijiCell<T> next() { KeyValue kv = mKVs.next(); mNumVersions += 1; try { return new KijiCell<T>(mFamily, mQualifier, kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } catch (IOException ex) { throw new KijiIOException(ex); } }
Source:
protected Statement withInterruptIsolation(final Statement statement) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { Thread.interrupted(); // clearing thread interrupted status for isolation } } }; }

Target:
protected final Statement withInterruptIsolation(final Statement statement) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { Thread.interrupted(); // clearing thread interrupted status for isolation } } }; }
Source:
public void testAssumptionFailure(Failure failure) { ignoreCount.getAndIncrement(); }

Target:
public void testAssumptionFailure(Failure failure) { // do nothing: same as passing (for 4.5; may change in 4.6) }
Source:
public void testRemoveElement() { fullList.remove(2); assertFalse(fullList.contains(3)); }

Target:
public void testRemoveElement() { fullList.remove(Integer.valueOf(3)); assertFalse(fullList.contains(3)); }
Source:
protected void after() throws Exception { // do nothing }

Target:
protected void after() throws Throwable { // do nothing }
Source:
public void assumeNotNullSingleNullThrowsException() { try { assumeNotNull(null); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } }

Target:
public void assumeNotNullSingleNullThrowsException() { try { assumeNotNull((Object[]) null); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } }
Source:
public void assumeNotNullThrowsException() { try { Object[] objects = {1, 2, null}; assumeNotNull(objects); fail("should throw AssumptionViolatedException"); } catch (AssumptionViolatedException e) { // expected } }

Target:
public void assumeNotNullThrowsException() { Object[] objects = {1, 2, null}; assumeNotNull(objects); }
Source:
protected void after() throws Throwable { // do nothing }

Target:
protected void after() { // do nothing }
Source:
public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { // don't catch ThreadDeath by accident throw e; } catch (Throwable t) { addError(test, t); } }

Target:
public void runProtected(final Test test, Protectable p) { try { p.protect(); } catch (AssertionFailedError e) { addFailure(test, e); } catch (ThreadDeath e) { // don't catch ThreadDeath by accident throw e; } catch (Throwable e) { addError(test, e); } }
Source:
public static Filter createFilterFromFilterSpec(Description description, String filterSpec) throws FilterFactory.FilterNotCreatedException { if (filterSpec.contains("=")) { String[] tuple = filterSpec.split("=", 2); return createFilter(tuple[0], new FilterFactoryParams(tuple[1])); } else { return createFilter(filterSpec, new FilterFactoryParams()); } }

Target:
public static Filter createFilterFromFilterSpec(Description description, String filterSpec) throws FilterFactory.FilterNotCreatedException { String[] tuple; if (filterSpec.contains("=")) { tuple = filterSpec.split("=", 2); } else { tuple = new String[]{ filterSpec, "" }; } return createFilter(tuple[0], new FilterFactoryParams(tuple[1])); }
Source:
public boolean flush () { boolean success = false; // FIXME: how to hoist the success or failure of write to return it? ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (!nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); } } }); success = true; // FIXME: should reflect the success of NSDictionary write. return success; }

Target:
public boolean flush () { final boolean[] success = {false}; ObjCRuntime.autoreleasepool(new Runnable() { @Override public void run() { if (nsDictionary.writeToFileAtomically(file.getAbsolutePath(), false)) { success[0] = true; } else { Gdx.app.debug("IOSPreferences", "Failed to write NSDictionary to file " + file); } } }); return success[0]; }
Source:
public static boolean isObject(String typeDescriptor) { if (typeDescriptor.length() == 0) return false; char first = typeDescriptor.charAt(0); return first == 'L' || first == '['; }

Target:
public static boolean isObject(String typeDescriptor) { if (typeDescriptor.isEmpty()) return false; char first = typeDescriptor.charAt(0); return first == 'L' || first == '['; }
Source:
public String configList(File workingDirectory, List<String> extraArgs) throws IOException, InterruptedException { // We're adding the -s option to the command, to make sure the command output can be parsed properly. List<String> args = new ArrayList<>(extraArgs); // We will temporarily remove this argument because we do want to get json output for the config list cmd // The required value will be restore later while writing the npmrc file. args.remove("--json=false"); args.add("-s"); return runCommand(workingDirectory, new String[]{"c", "ls", "--json"}, args); }

Target:
public String configList(File workingDirectory, List<String> extraArgs) throws IOException, InterruptedException { // We're adding the -s and --json options to the command, to make sure the command output can be parsed properly. List<String> args = new ArrayList<>(extraArgs); args.add("-s"); args.add("--json"); return runCommand(workingDirectory, new String[]{"c", "ls"}, args); }
Source:
public List<RichFacility> getRichFacilities(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.authorizedInternal(sess, "getRichFacilities_policy")) { throw new PrivilegeException(sess, "getRichFacilities"); } List<Facility> facilities = getFacilitiesManagerBl().getFacilities(sess); facilities.removeIf(facility -> AuthzResolver.authorizedInternal(sess, "filter-getRichFacilities_policy", Collections.singletonList(facility))); return getFacilitiesManagerBl().getRichFacilities(sess, facilities); }

Target:
public List<RichFacility> getRichFacilities(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.authorizedInternal(sess, "getRichFacilities_policy")) { throw new PrivilegeException(sess, "getRichFacilities"); } List<Facility> facilities = getFacilitiesManagerBl().getFacilities(sess); facilities.removeIf(facility -> !AuthzResolver.authorizedInternal(sess, "filter-getRichFacilities_policy", Collections.singletonList(facility))); return getFacilitiesManagerBl().getRichFacilities(sess, facilities); }
Source:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.valueAsString() == null) throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "Value can't be null"); }

Target:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "Value can't be null"); }
Source:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if(attribute.valueAsInteger() == null) { throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "account expiration time shouldn't be null"); } }

Target:
public void checkAttributeSemantics(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws WrongReferenceAttributeValueException { if(attribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, null, facility, null, "account expiration time shouldn't be null"); } }
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongReferenceAttributeValueException { // null attribute if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be null."); if (attribute.valueAsString().isEmpty()) { throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be empty."); } }

Target:
public void checkAttributeSemantics(PerunSessionImpl sess, Group group, Attribute attribute) throws WrongReferenceAttributeValueException { // null attribute if (attribute.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, "Attribute collectionID cannot be null."); }
Source:
public void checkAttributeSemantics(PerunSessionImpl sess, Member member, Attribute attribute) throws InternalErrorException, WrongReferenceAttributeValueException { Attribute currentAttribute = getAttributeValue(sess, member, attribute); if(!attribute.equals(currentAttribute)) throw new WrongReferenceAttributeValueException(attribute, currentAttribute, member, null, "Attribute value is not the highest value from member's UserExtSources Loas."); }

Target:
public void checkAttributeSemantics(PerunSessionImpl sess, Member member, Attribute attribute) throws InternalErrorException, WrongReferenceAttributeValueException { Attribute currentAttribute = getAttributeValue(sess, member, attribute); if(!attribute.equals(currentAttribute)) throw new WrongReferenceAttributeValueException(attribute, currentAttribute, member, null, member, null, "Attribute value is not the highest value from member's UserExtSources Loas."); }
Source:
public String getCurrentDatabaseVersion(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.isAuthorized(sess, Role.SELF) && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) throw new PrivilegeException(sess, "getCurrentDatabaseVersion"); return getDatabaseManagerBl().getCurrentDatabaseVersion(); }

Target:
public String getCurrentDatabaseVersion(PerunSession sess) throws InternalErrorException, PrivilegeException { Utils.checkPerunSession(sess); // Authorization if (!AuthzResolver.isAuthorized(sess, Role.SELF)) throw new PrivilegeException(sess, "getCurrentDatabaseVersion"); return getDatabaseManagerBl().getCurrentDatabaseVersion(); }
Source:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<>(); dependencies.add(A_G_unixGID_namespace + ":*"); dependencies.add(A_R_unixGID_namespace + ":*"); return dependencies; }

Target:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<>(); //Disallowed because of crosschecks between modules and performance reason //dependencies.add(A_G_unixGID_namespace + ":*"); //dependencies.add(A_R_unixGID_namespace + ":*"); //Disallowed because it does not affect value of dependent attribute //dependencies.add(A_R_unixGroupName_namespace + ":*"); return dependencies; }
Source:
public void forceGroupSynchronization(PerunSession sess, Group group) throws GroupSynchronizationAlreadyRunningException, InternalErrorException { Utils.notNull(group, "group"); //Check if the group is not currently in synchronization process if(poolOfGroupsToBeSynchronized.putJobIfAbsent(group, true)) { log.info("Scheduling synchronization for the group by force!", group); } else { throw new GroupSynchronizationAlreadyRunningException(group); } }

Target:
public void forceGroupSynchronization(PerunSession sess, Group group) throws GroupSynchronizationAlreadyRunningException, InternalErrorException { //Check if the group is not currently in synchronization process if(poolOfGroupsToBeSynchronized.putJobIfAbsent(group, true)) { log.info("Scheduling synchronization for the group by force!", group); } else { throw new GroupSynchronizationAlreadyRunningException(group); } }
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { //Null is ok, it means use default permissions in script (probably 0700) if(attribute.getValue() == null) return; String attrValue = (String) attribute.getValue(); Pattern pattern = Pattern.compile("^[01234567]?[01234567]{3}$"); Matcher match = pattern.matcher(attrValue); if(!match.matches()) throw new WrongAttributeValueException(attribute, facility, "Bad format of attribute, (expected something like '750' or '0700')."); }

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { //Null is ok, it means use default permissions in script (probably 0700) if(attribute.getValue() == null) return; String attrValue = (String) attribute.getValue(); Matcher match = pattern.matcher(attrValue); if(!match.matches()) throw new WrongAttributeValueException(attribute, facility, "Bad format of attribute, (expected something like '750' or '0700')."); }
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException { //Null means the same like 0 (not enabled) if(attribute.getValue() == null) return; Integer quotaEnabled = (Integer) attribute.getValue(); if(quotaEnabled > 1 || quotaEnabled < 0) throw new WrongAttributeValueException(attribute, "Attribute has only two possible options for quota: 0 - means not enabled, 1 - means enabled."); }

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException { //Null means the same like 0 (not enabled) if(attribute.getValue() == null) return; Integer quotaEnabled = (Integer) attribute.getValue(); if(quotaEnabled > 1 || quotaEnabled < 0) throw new WrongAttributeValueException(attribute, facility, null, "Attribute has only two possible options for quota: 0 - means not enabled, 1 - means enabled."); }
Source:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { //previous regex ^/[-a-zA-Z0-9_/]*$" Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } if(!shell.startsWith("/")) { throw new WrongAttributeValueException(attribute, "Shell " + shell + " doesnt start with /"); } }

Target:
public void checkFormatOfShell(String shell, Attribute attribute) throws WrongAttributeValueException { //previous regex ^/[-a-zA-Z0-9_/]*$" Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9]+)+$"); Matcher match = pattern.matcher(shell); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad shell attribute format " + shell); } }
Source:
public CRC32CDigestManager(long ledgerId, boolean useV2Protocol, ByteBufAllocator allocator) { super(ledgerId, useV2Protocol, allocator); if (!Sse42Crc32C.isSupported() && !nonSupportedMessagePrinted) { log.error("Sse42Crc32C is not supported, will use a slower CRC32C implementation."); nonSupportedMessagePrinted = true; } }

Target:
public CRC32CDigestManager(long ledgerId, boolean useV2Protocol, ByteBufAllocator allocator) { super(ledgerId, useV2Protocol, allocator); if (!Sse42Crc32C.isSupported() && !nonSupportedMessagePrinted) { log.warn("Sse42Crc32C is not supported, will use a slower CRC32C implementation."); nonSupportedMessagePrinted = true; } }
Source:
public void safeRun() { boolean force = forceGarbageCollection.get(); boolean suspendMajor = suspendMajorCompaction.get(); boolean suspendMinor = suspendMinorCompaction.get(); try { runWithFlags(force, suspendMajor, suspendMinor); } catch (Exception e) { LOG.warn("Failed to complete gc {}", e.getMessage(), e); } if (force) { // only set force to false if it had been true when the garbage // collection cycle started forceGarbageCollection.set(false); } }

Target:
public void safeRun() { boolean force = forceGarbageCollection.get(); boolean suspendMajor = suspendMajorCompaction.get(); boolean suspendMinor = suspendMinorCompaction.get(); runWithFlags(force, suspendMajor, suspendMinor); if (force) { // only set force to false if it had been true when the garbage // collection cycle started forceGarbageCollection.set(false); } }
Source:
public SettableFuture<Boolean> fenceLedger(long ledgerId, byte[] masterKey) throws IOException, BookieException, InterruptedException { LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey); return handle.fenceAndLogInJournal(getJournal(ledgerId)); }

Target:
public SettableFuture<Boolean> fenceLedger(long ledgerId, byte[] masterKey) throws IOException, BookieException { LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey); return handle.fenceAndLogInJournal(getJournal(ledgerId)); }
Source:
void maybeHandleDelayedWriteBookieFailure() { synchronized (metadataLock) { if (delayedWriteFailedBookies.isEmpty()) { return; } Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(); toReplace.putAll(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); // Original intent of this change is to do a best-effort ensemble change. // But this is not possible until the local metadata is completely immutable. // Until the feature "Make LedgerMetadata Immutable #610" Is complete we will use // handleBookieFailure() to handle delayed writes as regular bookie failures. handleBookieFailure(toReplace); } }

Target:
void maybeHandleDelayedWriteBookieFailure() { synchronized (metadataLock) { if (delayedWriteFailedBookies.isEmpty()) { return; } Map<Integer, BookieSocketAddress> toReplace = new HashMap<>(delayedWriteFailedBookies); delayedWriteFailedBookies.clear(); // Original intent of this change is to do a best-effort ensemble change. // But this is not possible until the local metadata is completely immutable. // Until the feature "Make LedgerMetadata Immutable #610" Is complete we will use // handleBookieFailure() to handle delayed writes as regular bookie failures. handleBookieFailure(toReplace); } }
Source:
ConcurrentHashMap<Long, LedgerData> getBookieData(BookieSocketAddress addr) { return data.computeIfAbsent(addr, (key) -> new ConcurrentHashMap<>()); }

Target:
private ConcurrentHashMap<Long, LedgerData> getBookieData(BookieSocketAddress addr) { return data.computeIfAbsent(addr, (key) -> new ConcurrentHashMap<>()); }
Source:
public static ByteBuf generatePacket(long ledgerId, long entryId, long lastAddConfirmed, long length, byte[] data, int offset, int len) { DigestManager dm = null; try { // CRC32 need not password, and is support definitely currently. dm = DigestManager.instantiate(ledgerId, new byte[2], CRC32); } catch (GeneralSecurityException gse) { } return dm.computeDigestAndPackageForSending(entryId, lastAddConfirmed, length, Unpooled.wrappedBuffer(data, offset, len)); }

Target:
public static ByteBuf generatePacket(long ledgerId, long entryId, long lastAddConfirmed, long length, byte[] data, int offset, int len) throws GeneralSecurityException { DigestManager dm = DigestManager.instantiate(ledgerId, new byte[2], CRC32); return dm.computeDigestAndPackageForSending(entryId, lastAddConfirmed, length, Unpooled.wrappedBuffer(data, offset, len)); }
Source:
BookieStateManager(ServerConfiguration conf, RegistrationManager registrationManager) throws IOException { this.conf = conf; this.registrationManager = registrationManager; this.statsLogger = null; this.ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()), NullStatsLogger.INSTANCE); // ZK ephemeral node for this Bookie. this.bookieId = getMyId(); }

Target:
BookieStateManager(ServerConfiguration conf, RegistrationManager registrationManager) throws IOException { this(conf, NullStatsLogger.INSTANCE, registrationManager, new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()), NullStatsLogger.INSTANCE)); }
Source:
public void keySmallerThanTotalSize() { try { new ArrayGroupSort(3, 2); fail("should have failed"); } catch (IllegalArgumentException e) { // ok } }

Target:
public void keySmallerThanTotalSize() { new ArrayGroupSort(3, 2); }
Source:
public void onRotateEntryLog() { // for interleaved ledger storage, we request a checkpoint when rotating a entry log file. // the checkpoint represent the point that all the entries added before this point are already // in ledger storage and ready to be synced to disk. // TODO: we could consider remove checkpointSource and checkpointSouce#newCheckpoint // later if we provide kind of LSN (Log/Journal Squeuence Number) // mechanism when adding entry. {@link https://github.com/apache/bookkeeper/issues/279} if (null != checkpointer) { Checkpoint checkpoint = checkpointSource.newCheckpoint(); checkpointer.startCheckpoint(checkpoint); } }

Target:
public void onRotateEntryLog() { // for interleaved ledger storage, we request a checkpoint when rotating a entry log file. // the checkpoint represent the point that all the entries added before this point are already // in ledger storage and ready to be synced to disk. // TODO: we could consider remove checkpointSource and checkpointSouce#newCheckpoint // later if we provide kind of LSN (Log/Journal Squeuence Number) // mechanism when adding entry. {@link https://github.com/apache/bookkeeper/issues/279} Checkpoint checkpoint = checkpointSource.newCheckpoint(); checkpointer.startCheckpoint(checkpoint); }
Source:
public void start() throws IOException, UnavailableException, InterruptedException, KeeperException, BKException { this.bookie.start(); // fail fast, when bookie startup is not successful if (!this.bookie.isRunning()) { exitCode = bookie.getExitCode(); return; } this.nettyServer.start(); running = true; deathWatcher = new DeathWatcher(conf); deathWatcher.start(); }

Target:
public void start() throws IOException, UnavailableException, InterruptedException, BKException { this.bookie.start(); // fail fast, when bookie startup is not successful if (!this.bookie.isRunning()) { exitCode = bookie.getExitCode(); return; } this.nettyServer.start(); running = true; deathWatcher = new DeathWatcher(conf); deathWatcher.start(); }
Source:
private String requestToString(Object request) { if (request instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.BKPacketHeader header = ((BookkeeperProtocol.Request)request).getHeader(); return String.format("Req(txnId=%d,op=%s,version=%s)", header.getTxnId(), header.getOperation(), header.getVersion()); } else { return request.toString(); } }

Target:
private static String requestToString(Object request) { if (request instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.BKPacketHeader header = ((BookkeeperProtocol.Request)request).getHeader(); return String.format("Req(txnId=%d,op=%s,version=%s)", header.getTxnId(), header.getOperation(), header.getVersion()); } else { return request.toString(); } }
Source:
public BookieNode selectFromNetworkLocation( String networkLoc, Set<Node> excludeBookies, Predicate<BookieNode> predicate, Ensemble<BookieNode> ensemble) throws BKNotEnoughBookiesException { // select one from local rack try { return selectRandomFromRack(networkLoc, excludeBookies, predicate, ensemble); } catch (BKNotEnoughBookiesException e) { LOG.warn("Failed to choose a bookie from : " + "excluded {}, fallback to choose bookie randomly from the cluster.", networkLoc, excludeBookies); LOG.warn("Predicate Ensemble {}", predicate, ensemble); // randomly choose one from whole cluster, ignore the provided predicate. return selectRandom(1, excludeBookies, predicate, ensemble).get(0); } }

Target:
public BookieNode selectFromNetworkLocation( String networkLoc, Set<Node> excludeBookies, Predicate<BookieNode> predicate, Ensemble<BookieNode> ensemble) throws BKNotEnoughBookiesException { // select one from local rack try { return selectRandomFromRack(networkLoc, excludeBookies, predicate, ensemble); } catch (BKNotEnoughBookiesException e) { LOG.warn("Failed to choose a bookie from : " + "excluded {}, fallback to choose bookie randomly from the cluster.", networkLoc, excludeBookies); // randomly choose one from whole cluster, ignore the provided predicate. return selectRandom(1, excludeBookies, predicate, ensemble).get(0); } }
Source:
public ArrayList<BookieSocketAddress> newEnsemble(int ensembleSize, int writeQuorumSize) throws BKNotEnoughBookiesException { try { // we try to only get from the healthy bookies first return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, quarantinedBookies.asMap().keySet()); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, EMPTY_SET); } }

Target:
public ArrayList<BookieSocketAddress> newEnsemble(int ensembleSize, int writeQuorumSize) throws BKNotEnoughBookiesException { try { // we try to only get from the healthy bookies first return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, new HashSet<BookieSocketAddress>( quarantinedBookies.asMap().keySet())); } catch (BKNotEnoughBookiesException e) { if (logger.isDebugEnabled()) { logger.debug("Not enough healthy bookies available, using quarantined bookies"); } return placementPolicy.newEnsemble(ensembleSize, writeQuorumSize, EMPTY_SET); } }
Source:
private void attachedFile() throws ApiError { this.deliveriesBackend.attach(delivery, fileName, in); assertEquals(1, delivery.getAttachments().size()); // Because a simple get did not return the correct deliveryAttachment, we had to do it the fancy way. assertEquals(1, delivery.getAttachments().stream() .map((attachment) -> attachment.getFileName().equals(fileName) ).count()); }

Target:
private void attachedFile() throws ApiError { this.deliveriesBackend.attach(delivery, fileName, in); assertEquals(1, delivery.getAttachments().size()); assertEquals(fileName, delivery.getAttachments().iterator().next().getFileName()); }
Source:
public SpecialPathInfo getSpecialPathInfo( Transfer transfer, String pkgType ) { if ( transfer != null ) { return getSpecialPathInfo( transfer.getLocation(), transfer.getStoragePath(), pkgType ); } // TODO: Return SpecialPathConstants.DEFAULT_FILE or SpecialPathConstants.DEFAULT_DIR or something non-null? return null; }

Target:
public SpecialPathInfo getSpecialPathInfo( Transfer transfer, String pkgType ) { if ( transfer != null ) { return getSpecialPathInfo( transfer.getLocation(), transfer.getPath(), pkgType ); } // TODO: Return SpecialPathConstants.DEFAULT_FILE or SpecialPathConstants.DEFAULT_DIR or something non-null? return null; }
Source:
private String getDescription(long masterKeyId) { CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(masterKeyId); String description = ""; long authSubKeyId = Constants.key.none; try { authSubKeyId = cachedPublicKeyRing.getSecretAuthenticationId(); description += cachedPublicKeyRing.getPrimaryUserId(); } catch (PgpKeyNotFoundException e) { // should never happen, since this is always called after existence of the subkey is assured e.printStackTrace(); } description += " ("+ Long.toHexString(authSubKeyId) +")"; return description; }

Target:
private String getDescription(long masterKeyId) throws PgpKeyNotFoundException { CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(masterKeyId); String description = ""; long authSubKeyId = cachedPublicKeyRing.getSecretAuthenticationId(); description += cachedPublicKeyRing.getPrimaryUserId(); description += " (" + Long.toHexString(authSubKeyId) + ")"; return description; }
Source:
public static void enableKeyserverSync(Context context) {] Account account = KeychainApplication.createAccountIfNecessary(context); if (account == null) { // account failed to be created for some reason, nothing we can do here return; } ContentResolver.setIsSyncable(account, Constants.PROVIDER_AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, Constants.PROVIDER_AUTHORITY, true); ContentResolver.addPeriodicSync( account, Constants.PROVIDER_AUTHORITY, new Bundle(), SYNC_INTERVAL ); }

Target:
public static void enableKeyserverSync(Context context) { Account account = KeychainApplication.createAccountIfNecessary(context); if (account == null) { // account failed to be created for some reason, nothing we can do here return; } ContentResolver.setIsSyncable(account, Constants.PROVIDER_AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, Constants.PROVIDER_AUTHORITY, true); ContentResolver.addPeriodicSync( account, Constants.PROVIDER_AUTHORITY, new Bundle(), SYNC_INTERVAL ); }
Source:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); Long _id = System.currentTimeMillis(); return PendingIntent.getBroadcast(context, _id.intValue(), intent, PendingIntent.FLAG_CANCEL_CURRENT); }

Target:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); //request code should be unique for each call for pending intent so we have taken requestcode //as keyId which is unique for each call as keyId is unique for each passphrase return PendingIntent.getBroadcast(context, (int)keyId, intent, PendingIntent.FLAG_CANCEL_CURRENT); }
Source:
public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; this.configs = other.getConfigs().isEmpty() ? new EnumMap<Capability, ContainerConfig>(Capability.class) : new EnumMap<>(other.getConfigs()); }

Target:
public ContainerSpec(ContainerSpec other) { super(other.getId(), other.getContainerName(), other.getServerTemplateKey()); this.releasedId = other.releasedId; this.status = other.status; this.configs = other.getConfigs().isEmpty() ? new EnumMap<>(Capability.class) : new EnumMap<>(other.getConfigs()); }
Source:
public int acceptsAssignedUser() { if (User.PLANNING_USER.getEntityId().equals(getUser().getEntityId())) { //planning user belongs to all the groups by definition. return 0; } //the user is a potential owner. return TaskHelper.isPotentialOwner(this, getUser()) ? 0 : -1; }

Target:
public boolean acceptsAssignedUser() { if (User.PLANNING_USER.getEntityId().equals(getUser().getEntityId())) { //planning user belongs to all the groups by definition. return true; } return TaskHelper.isPotentialOwner(this, getUser()); }
Source:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { final String key = pwdKeyAliasProperty + "-" + pwdKeyPasswordProperty; if (invocationCache.contains(key)) { return false; } invocationCache.add(key); return true; }

Target:
private static boolean hasNotBeenInvoked(String pwdKeyAliasProperty, String pwdKeyPasswordProperty, String passwordKey) { if (invocationCache.contains(pwdKeyAliasProperty)) { return false; } invocationCache.add(pwdKeyAliasProperty); return true; }
Source:
private boolean initFields() { sessionManager = WebRtcSessionManager.getInstance(this); dbManager = QbUsersDbManager.getInstance(getApplicationContext()); currentSession = sessionManager.getCurrentSession(); if (currentSession == null) { return false; } opponentsIdsList = currentSession.getOpponents(); return true; }

Target:
private void initFields() { dbManager = QbUsersDbManager.getInstance(getApplicationContext()); opponentsIdsList = currentSession.getOpponents(); }
Source:
public void enableDynamicToggle(boolean plugged) { headsetPlugged = plugged; if (isStarted) { if (plugged) { audioSwitchToggleButton.setEnabled(false); audioSwitchToggleButton.setChecked(true); } else { audioSwitchToggleButton.setEnabled(true); audioSwitchToggleButton.setChecked(audioSwitchToggleButton.isChecked()); } } }

Target:
public void enableDynamicToggle(boolean plugged) { headsetPlugged = plugged; if (isStarted) { audioSwitchToggleButton.setEnabled(!plugged); if (plugged) { audioSwitchToggleButton.setChecked(true); } else { audioSwitchToggleButton.setChecked(audioSwitchToggleButton.isChecked()); } } }
Source:
private boolean isEnteredRoomNameValid() { return ValidationUtils.isRoomNameValid(this, chatRoomNameEditText, String.valueOf(chatRoomNameEditText.getText())); }

Target:
private boolean isEnteredRoomNameValid() { return ValidationUtils.isRoomNameValid(this, chatRoomNameEditText, chatRoomNameEditText.getText().toString()); }
Source:
protected void proceedToTheNextActivity() { if (sharedPrefsHelper.hasQbUser()) { OpponentsActivity.start(this, false); } else { LoginActivity.start(this); } finish(); }

Target:
protected void proceedToTheNextActivity() { LoginActivity.start(this); finish(); }
Source:
public void onCallStarted() { mainHandler.post(new Runnable() { @Override public void run() { hideOutgoingScreen(); startTimer(); actionButtonsEnabled(true); } }); }

Target:
public void onCallStarted() { hideOutgoingScreen(); startTimer(); actionButtonsEnabled(true); }
Source:
public void startTimer() { if (!isStarted) { timerChronometer.setVisibility(View.VISIBLE); timerChronometer.setBase(SystemClock.elapsedRealtime()); timerChronometer.start(); isStarted = true; } }

Target:
private void startTimer() { if (!isStarted) { timerChronometer.setVisibility(View.VISIBLE); timerChronometer.setBase(SystemClock.elapsedRealtime()); timerChronometer.start(); isStarted = true; } }
Source:
private void startTimer() { if (!isStarted) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { timerABWithTimer.setVisibility(View.VISIBLE); timerABWithTimer.setBase(SystemClock.elapsedRealtime()); timerABWithTimer.start(); isStarted = true; } }); } }

Target:
private void startTimer() { if (!isStarted) { timerABWithTimer.setVisibility(View.VISIBLE); timerABWithTimer.setBase(SystemClock.elapsedRealtime()); timerABWithTimer.start(); isStarted = true; } }
Source:
public void initCurrentSession(QBRTCSession session) { if (session != null) { Log.d(TAG, "Init new QBRTCSession"); this.currentSession = session; this.currentSession.addSessionCallbacksListener(CallActivity.this); this.currentSession.addSignalingCallback(CallActivity.this); } else { OpponentsActivity.start(this); finish(); } }

Target:
public void initCurrentSession(QBRTCSession session) { if (session != null) { Log.d(TAG, "Init new QBRTCSession"); this.currentSession = session; this.currentSession.addSessionCallbacksListener(CallActivity.this); this.currentSession.addSignalingCallback(CallActivity.this); } }
Source:
public void onBackPressed() { Fragment fragment = getFragmentManager().findFragmentByTag(CONVERSATION_CALL_FRAGMENT); if (fragment == null) { super.onBackPressed(); // logoutSession(); } }

Target:
public void onBackPressed() { }