_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q169600
StringUtils.getWords
validation
public static List<String> getWords(String text) { List<String> output = new ArrayList<>(); if (isNullOrEmptyTrimmed(text)) { return output; } Pattern p = Pattern.compile("\\b\\p{L}+\\b"); Matcher m = p.matcher(text); while (m.find()) { output.add(m.group()); } return output; }
java
{ "resource": "" }
q169601
StringUtils.trimTextDown
validation
public static String trimTextDown(String text, int size) { if (text == null || text.length() <= size) { return text; } int pos = text.lastIndexOf(" ", size); if (pos < 0) { return text.substring(0, size); } return text.substring(0, pos); }
java
{ "resource": "" }
q169602
StringUtils.trimTextDown
validation
public static String trimTextDown(String text, int sizeMinusAppend, String append) { Assert.notNull(append, "Missing append!"); if (text == null || text.length() <= sizeMinusAppend) { return text; } sizeMinusAppend = sizeMinusAppend - append.length(); int pos = text.lastIndexOf(" ", sizeMinusAppend); if (pos < 0) { return text.substring(0, sizeMinusAppend) + append; } return text.substring(0, pos) + append; }
java
{ "resource": "" }
q169603
StringUtils.asListOfChars
validation
public static List<String> asListOfChars(String text) { List<String> list = new ArrayList<>(); if (StringUtils.isNullOrEmptyTrimmed(text)) { return list; } for (int i = 0; i < text.length(); i++) { list.add(Character.toString(text.charAt(i))); } return list; }
java
{ "resource": "" }
q169604
StringUtils.relevance
validation
public static int relevance(String value, String search) { if (StringUtils.isNullOrEmptyTrimmed(value) || StringUtils.isNullOrEmptyTrimmed(search)) { return -1; } if (search.length() > value.length()) { return -1; } int relevance = -1; // start at -1 ... so -1 is returned for no result int delta = 1; // first delta at 1 ... producing a sum of 0 when first letter is found int len = value.length(); int searchLen = search.length(); int letterIndex = 0; for (int searchIndex = 0; searchIndex < searchLen; searchIndex++) { char match = search.charAt(searchIndex); while (letterIndex < len) { char letter = value.charAt(letterIndex); letterIndex++; if (match == letter) { relevance = relevance + delta; // reverse to get higher value for better match delta = 0; break; } else { delta++; } } // we matched all characters ... and found the last one ... if (delta == 0 && searchIndex == searchLen - 1) { return relevance; } if (letterIndex == len) { break; } } return -1; }
java
{ "resource": "" }
q169605
StringUtils.unQuote
validation
public static String unQuote(String text) { if (isNullOrEmptyTrimmed(text)) { return text; } if ((text.startsWith("\"") && text.endsWith("\"")) || (text.startsWith("'") && text.endsWith("'"))) { return text.substring(1, text.length() - 1); } return text; }
java
{ "resource": "" }
q169606
DateTimeUtils.getTimezoneTime
validation
public static long getTimezoneTime(long time, int timezone) { Calendar calendar = getCalendar(time); int hour = calendar.get(Calendar.HOUR_OF_DAY); hour = (hour + timezone) % 24; if (hour < 0) { hour = 24 + hour; calendar.add(Calendar.DAY_OF_MONTH, -1); } calendar.set(Calendar.HOUR_OF_DAY, hour); return calendar.getTimeInMillis(); }
java
{ "resource": "" }
q169607
Filter.hasTag
validation
public List<Integer> hasTag(final Integer tagID) { final List<Integer> retValue = new ArrayList<Integer>(); for (final FilterTag tag : getFilterTags()) { if (tag.getTag().getTagId().equals(tagID)) retValue.add(tag.getTagState()); } return retValue; }
java
{ "resource": "" }
q169608
CheckstyleViolationCheckMojo.isViolation
validation
private boolean isViolation(String severity) { if ("error".equals(severity)) { return "error".equals(violationSeverity) || "warning".equals(violationSeverity) || "info".equals(violationSeverity); } else if ("warning".equals(severity)) { return "warning".equals(violationSeverity) || "info".equals(violationSeverity); } else if ("info".equals(severity)) { return "info".equals(violationSeverity); } else { return false; } }
java
{ "resource": "" }
q169609
IconTool.iconSeverity
validation
public void iconSeverity(String level) { sink.figure(); sink.figureGraphics("images/icon_" + level + "_sml.gif"); sink.figure_(); }
java
{ "resource": "" }
q169610
IconTool.iconSeverity
validation
public void iconSeverity(String level, int textType) { sink.figure(); sink.figureGraphics("images/icon_" + level + "_sml.gif"); sink.figure_(); if (textType > 0) { sink.nonBreakingSpace(); sink.text(bundle.getString("report.checkstyle." + level + suffix(textType))); } }
java
{ "resource": "" }
q169611
Project.getTagsList
validation
@Transient public String getTagsList(final boolean brLineBreak) { // define the line breaks for html and for tooltips final String lineBreak = brLineBreak ? "<br/>" : "\n"; final String boldStart = brLineBreak ? "<b>" : ""; final String boldEnd = brLineBreak ? "</b>" : ""; final TreeMap<NameIDSortMap, ArrayList<String>> tags = new TreeMap<NameIDSortMap, ArrayList<String>>(); for (final TagToProject tagToProject : tagToProjects) { final Tag tag = tagToProject.getTag(); final Set<TagToCategory> tagToCategories = tag.getTagToCategories(); if (tagToCategories.size() == 0) { NameIDSortMap categoryDetails = new NameIDSortMap("Uncategorised", -1, 0); if (!tags.containsKey(categoryDetails)) tags.put(categoryDetails, new ArrayList<String>()); tags.get(categoryDetails).add(tag.getTagName()); } else { for (final TagToCategory category : tagToCategories) { NameIDSortMap categoryDetails = new NameIDSortMap(category.getCategory().getCategoryName(), category.getCategory().getCategoryId(), category.getCategory().getCategorySort() == null ? 0 : category.getCategory().getCategorySort()); if (!tags.containsKey(categoryDetails)) tags.put(categoryDetails, new ArrayList<String>()); tags.get(categoryDetails).add(tag.getTagName()); } } } String tagsList = ""; for (final NameIDSortMap key : tags.keySet()) { // sort alphabetically Collections.sort(tags.get(key)); if (tagsList.length() != 0) tagsList += lineBreak; tagsList += boldStart + key.getName() + boldEnd + ": "; String thisTagList = ""; for (final String tag : tags.get(key)) { if (thisTagList.length() != 0) thisTagList += ", "; thisTagList += tag; } tagsList += thisTagList + " "; } return tagsList; }
java
{ "resource": "" }
q169612
CSNode.setNextAndClean
validation
@Transient public void setNextAndClean(CSNode next) { setNextInternal(next); if (next != null) { next.setPreviousInternal(this); } }
java
{ "resource": "" }
q169613
CSNode.setPreviousAndClean
validation
@Transient public void setPreviousAndClean(CSNode previous) { setPreviousInternal(previous); if (previous != null) { previous.setNextInternal(this); } }
java
{ "resource": "" }
q169614
NodesContainer.find
validation
public Node find(String host, int port) { return socketToNodeMap.get(Utils.toKey(host, port)); }
java
{ "resource": "" }
q169615
NodesContainer.find
validation
public Set<Node> find(String host) { Set<Node> resultSet = new HashSet<Node>(); if (host != null) { for (Node node : socketToNodeMap.values()) { if (host.equals(node.getHost())) { resultSet.add(node); } } } return resultSet; }
java
{ "resource": "" }
q169616
NodesContainer.getAllNotDead
validation
public Set<Node> getAllNotDead() { Set<Node> allNotDeadNodesSet = new HashSet<Node>(); for (Node node : socketToNodeMap.values()) { if (!NodeStatus.DEAD.equals(node.getStatus())) { allNotDeadNodesSet.add(node); } } return allNotDeadNodesSet; }
java
{ "resource": "" }
q169617
NodesContainer.add
validation
public void add(Node node) { socketToNodeMap.put(Utils.toKey(node), node); sendEvent(node, NodeEventType.ADDED); }
java
{ "resource": "" }
q169618
NodesContainer.remove
validation
public void remove(Node node) { socketToNodeMap.remove(Utils.toKey(node)); sendEvent(node, NodeEventType.REMOVED); }
java
{ "resource": "" }
q169619
NodesContainer.markAsAlive
validation
public void markAsAlive(Node node) { if (!NodeStatus.ALIVE.equals(node.getStatus())) { socketToNodeMap.get(Utils.toKey(node)).markAsAlive(); sendEvent(node, NodeEventType.MARKED_AS_ALIVE); } }
java
{ "resource": "" }
q169620
NodesContainer.markAsDead
validation
public void markAsDead(Node node) { if (!NodeStatus.DEAD.equals(node.getStatus())) { socketToNodeMap.get(Utils.toKey(node)).markAsDead(); sendEvent(node, NodeEventType.MARKED_AS_DEAD); } }
java
{ "resource": "" }
q169621
NodesContainer.sendEvent
validation
private void sendEvent(Node node, NodeEventType type) { NodeEvent event = new NodeEvent(node, type); for (NodeEventHandler handler : handlers) { handler.handle(event); } }
java
{ "resource": "" }
q169622
DefaultCheckstyleExecutor.getCheckstyleVersion
validation
private String getCheckstyleVersion() { Package checkstyleApiPackage = Configuration.class.getPackage(); return (checkstyleApiPackage == null) ? null : checkstyleApiPackage.getImplementationVersion(); }
java
{ "resource": "" }
q169623
DefaultCheckstyleExecutor.configureResourceLocator
validation
private void configureResourceLocator(final ResourceManager resourceManager, final CheckstyleExecutorRequest request, final List<Artifact> additionalArtifacts) { final MavenProject project = request.getProject(); resourceManager.setOutputDirectory(new File(project.getBuild().getDirectory())); // Recurse up the parent hierarchy and add project directories to the search roots MavenProject parent = project; while (parent != null && parent.getFile() != null) { // MCHECKSTYLE-131 ( olamy ) I don't like this hack. // (dkulp) Me either. It really pollutes the location stuff // by allowing searches of stuff outside the current module. File dir = parent.getFile().getParentFile(); resourceManager.addSearchPath(FileResourceLoader.ID, dir.getAbsolutePath()); parent = parent.getParent(); } resourceManager.addSearchPath("url", ""); // MCHECKSTYLE-225: load licenses from additional artifacts, not from classpath if (additionalArtifacts != null) { for (Artifact licenseArtifact : additionalArtifacts) { try { // MCHECKSTYLE-287, MCHECKSTYLE-294: Ignore null licenseArtifacts ... if (licenseArtifact != null) { if (getLogger().isDebugEnabled()) { getLogger().debug("Adding licenceArtifact [" + licenseArtifact.getGroupId() + ":" + licenseArtifact.getArtifactId() + ":" + licenseArtifact.getVersion() + "] to resourceManager."); } resourceManager.addSearchPath("jar", "jar:" + licenseArtifact.getFile().toURI().toURL()); } } catch (MalformedURLException e) { // noop } } } }
java
{ "resource": "" }
q169624
ObjectFactory.build
validation
public T build(Object... attributes) { List<Object> attributeList = new ArrayList<Object>(Arrays.asList(attributes)); //kinda wacky but Arrays.asList returns a unmodifiable list String[] traitNames = getTraitNames(attributeList); applyTraits(traitNames); T object = ReflectionUtils.createObject(factoryClass, constructorArgs); // merge default properties with supplied attributes Map<String, Object> propertyValues = createObjectPropertyValues(this.propertyValues, attributeList); // now set properties and fields to the created object setProperties(object, propertyValues); setFields(object, fieldValues); executeCallbacks(AfterFactoryBuild.class, object); return object; }
java
{ "resource": "" }
q169625
ObjectFactory.createObjectPropertyValues
validation
private Map<String, Object> createObjectPropertyValues(Map<String, Object> defaultPropertyValues, List<Object> attributes) { Map<String, Object> propertyValues = new HashMap<String, Object>(defaultPropertyValues); if(attributes != null) { Iterator<Object> iterator = attributes.iterator(); Map<String, Object> propertyOverrideMap = new HashMap<String, Object>(); while(iterator.hasNext()) { String name = (String)iterator.next(); // we can only create a map entry if we have both a key and value, so make sure there's a value left if(iterator.hasNext()) { Object object = iterator.next(); propertyOverrideMap.put(name, object); } } propertyValues.putAll(propertyOverrideMap); } return propertyValues; }
java
{ "resource": "" }
q169626
ObjectFactory.currentSequence
validation
private int currentSequence(String name) { Map<String, Integer> sequencesForClass = sequences.get(getClass()); if(sequencesForClass == null) { sequencesForClass = new HashMap<String, Integer>(); sequences.put(getClass(), sequencesForClass); } Integer seq = sequencesForClass.get(name); seq = seq == null ? 1 : seq + 1; sequencesForClass.put(name, seq); return seq; }
java
{ "resource": "" }
q169627
NodeID.compareTo
validation
@Override public int compareTo(final NodeID that) { // Fail fast if (that == this) { return 0; } else if (null == that) { return -1; } // Delegate to internal state return this.getId().compareTo(that.getId()); }
java
{ "resource": "" }
q169628
BufferedNodeEventHandler.getAndClearEventslist
validation
public List<NodeEvent> getAndClearEventslist() { ArrayList<NodeEvent> result = new ArrayList<NodeEvent>(eventslist); eventslist.clear(); return result; }
java
{ "resource": "" }
q169629
VisualizationWrappedRootDoc.findPackagesFromClassesInJavaDocRun
validation
public SortedSet<PackageDoc> findPackagesFromClassesInJavaDocRun() { final SortedSet<PackageDoc> toReturn = new TreeSet<>(Comparators.PACKAGE_NAME_COMPARATOR); final ClassDoc[] currentExecutionClasses = classes(); if (currentExecutionClasses != null) { Arrays.stream(currentExecutionClasses) .map(ProgramElementDoc::containingPackage) .forEach(toReturn::add); } // All Done. return toReturn; }
java
{ "resource": "" }
q169630
ReflectionUtils.setProperty
validation
public static boolean setProperty(Object target, String name, Object value) { try { for (PropertyDescriptor pd : Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors()) { if (pd.getWriteMethod() != null && pd.getName().equals(name)) { pd.getWriteMethod().invoke(target, value); return true; } } } catch (Exception e) { throw new RuntimeException(e); } return false; }
java
{ "resource": "" }
q169631
ReflectionUtils.setField
validation
public static boolean setField(Object target, String name, Object value) { try { Field field = target.getClass().getDeclaredField(name); field.setAccessible(true); field.set(target, value); return true; } catch (NoSuchFieldException e) { return false; } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q169632
ReflectionUtils.getAnnotatedMethods
validation
public static List<Method> getAnnotatedMethods(Class targetClass, Class<? extends Annotation> annotationType) { List<Method> annotatedMethods = new ArrayList<Method>(); for(Method method : targetClass.getDeclaredMethods()) { if(method.isAnnotationPresent(annotationType)) { annotatedMethods.add(method); } } return annotatedMethods; }
java
{ "resource": "" }
q169633
ReflectionUtils.invokeMethod
validation
public static void invokeMethod(Object target, Method method, Object... arguments) { method.setAccessible(true); // so we can call private and protected methods too try { method.invoke(target, arguments); } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q169634
ServerTemplate.main
validation
public static void main(String[] args) throws Exception { if (args.length > 0) { loadClasses(args[0]); } startCacheServer(); ConsoleUtils .waitForEnter(JavaProcessLauncher.PROCESS_STARTUP_COMPLETED); stopCacheServer(); }
java
{ "resource": "" }
q169635
CheckstyleReportGenerator.getConfigAttribute
validation
private String getConfigAttribute(Configuration config, ChainedItem<Configuration> parentConfiguration, String attributeName, String defaultValue) { String ret; try { ret = config.getAttribute(attributeName); } catch (CheckstyleException e) { // Try to find the attribute in a parent, if there are any if (parentConfiguration != null) { ret = getConfigAttribute(parentConfiguration.value, parentConfiguration.parent, attributeName, defaultValue); } else { ret = defaultValue; } } return ret; }
java
{ "resource": "" }
q169636
CheckstyleReportGenerator.doRulesSummary
validation
private void doRulesSummary(CheckstyleResults results) { if (checkstyleConfig == null) { return; } sink.section1(); sink.sectionTitle1(); sink.text(bundle.getString("report.checkstyle.rules")); sink.sectionTitle1_(); sink.table(); sink.tableRow(); sink.tableHeaderCell(); sink.text(bundle.getString("report.checkstyle.rule.category")); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text(bundle.getString("report.checkstyle.rule")); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text(bundle.getString("report.checkstyle.violations")); sink.tableHeaderCell_(); sink.tableHeaderCell(); sink.text(bundle.getString("report.checkstyle.column.severity")); sink.tableHeaderCell_(); sink.tableRow_(); // Top level should be the checker. if ("checker".equalsIgnoreCase(checkstyleConfig.getName())) { String category = null; for (ConfReference ref : sortConfiguration(results)) { doRuleRow(ref, results, category); category = ref.category; } } else { sink.tableRow(); sink.tableCell(); sink.text(bundle.getString("report.checkstyle.norule")); sink.tableCell_(); sink.tableRow_(); } sink.table_(); sink.section1_(); }
java
{ "resource": "" }
q169637
CheckstyleReportGenerator.matchRule
validation
public boolean matchRule(AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity) { if (!ruleName.equals(RuleUtil.getName(event))) { return false; } // check message too, for those that have a specific one. // like GenericIllegalRegexp and Regexp if (expectedMessage != null) { // event.getMessage() uses java.text.MessageFormat in its implementation. // Read MessageFormat Javadoc about single quote: // http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html String msgWithoutSingleQuote = StringUtils.replace(expectedMessage, "'", ""); return expectedMessage.equals(event.getMessage()) || msgWithoutSingleQuote.equals(event.getMessage()); } // Check the severity. This helps to distinguish between // different configurations for the same rule, where each // configuration has a different severity, like JavadocMetod. // See also http://jira.codehaus.org/browse/MCHECKSTYLE-41 if (expectedSeverity != null) { return expectedSeverity.equals(event.getSeverityLevel().getName()); } return true; }
java
{ "resource": "" }
q169638
GuestNode.createReceivedAtKey
validation
private String createReceivedAtKey(String fromClusterName, String toClusterName) { return KEY_PREFIX + fromClusterName + "-" + toClusterName + KEY_POSTFIX_DURATION; }
java
{ "resource": "" }
q169639
GuestNode.init
validation
private void init() { try { debug("GuestNode#init(): Creating Cache"); ClientCacheFactory clientCacheFactory = new ClientCacheFactory(); Properties gemfireProperties = PropertiesHelper.filterProperties( System.getProperties(), GEMFIRE_PREFIX); for (Object keyObject : gemfireProperties.keySet()) { String key = (String) keyObject; String value = gemfireProperties.getProperty(key); String name = key.substring(GEMFIRE_PREFIX.length()); debug("GuestNode#init(): Configuring ClientCacheFactory with key = " + name + ", value = " + value); clientCacheFactory.set(name, value); } clientCacheFactory.setPoolSubscriptionEnabled(true); String locators = clustersProperties.getProperty(localClusterName); String[] locatorsArray = locators.split(","); for (String locator : locatorsArray) { String locatorHost = locator.substring(0, locator.indexOf("[")); String locatorPortString = locator.substring( locator.indexOf("[") + 1, locator.indexOf("]")); int locatorPort = Integer.parseInt(locatorPortString); debug("GuestNode#init(): Adding locator to pool: locatorHost = " + locatorHost + ", locatorPort = " + locatorPort); clientCacheFactory.addPoolLocator(locatorHost, locatorPort); } clientCache = clientCacheFactory.create(); ClientRegionFactory<String, Long> clientRegionFactory = clientCache .createClientRegionFactory(ClientRegionShortcut.PROXY); region = clientCache.getRegion(regionName); debug("GuestNode#init(): Get region with name = " + regionName + ": region = " + region); if (region == null) { region = clientRegionFactory.create(regionName); } debug("GuestNode#init(): Create region with name = " + regionName + ": region = " + region); } catch (Throwable t) { debug( "GuestNode#init(): Throwable caught with message = " + t.getMessage(), t); } }
java
{ "resource": "" }
q169640
GuestNode.waitForStarted
validation
private void waitForStarted() { debug("GuestNode#waitForStarted(): Waiting for other clusters started"); while (true) { boolean othersStarted = true; for (Object key : clustersProperties.keySet()) { String clusterName = (String) key; Long startedAt = region.get(createStartedAtKey(clusterName)); debug("GuestNode#waitForStarted(): Checking startedAt: startedAt = " + startedAt + ", processingStartedAt = " + processingStartedAt); if ((startedAt == null) || (startedAt.longValue() < processingStartedAt)) { othersStarted = false; break; } } if (othersStarted) { break; } try { TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD); } catch (InterruptedException e) { } } debug("GuestNode#waitForStarted(): Other clusters started"); }
java
{ "resource": "" }
q169641
GuestNode.waitForSent
validation
private void waitForSent() { debug("GuestNode#waitForSent(): Waiting for other clusters sent"); while (true) { boolean othersSent = true; Map<String, Long> clusterNameToReceivedAtMap = new HashMap<String, Long>(); for (Object key : clustersProperties.keySet()) { String clusterName = (String) key; if (localClusterName.equals(clusterName)) { continue; } Long sentAt = region.get(createSentAtKey(clusterName)); long receivedAt = System.currentTimeMillis(); if ((sentAt != null) && (sentAt.longValue() > processingStartedAt)) { clusterNameToReceivedAtMap.put(clusterName, receivedAt); } } for (Object key : clustersProperties.keySet()) { String clusterName = (String) key; if (localClusterName.equals(clusterName)) { continue; } Long receivedAt = clusterNameToReceivedAtMap.get(clusterName); if (receivedAt == null) { if (othersSent) { othersSent = false; } } else { region.put( createReceivedAtKey(clusterName, localClusterName), receivedAt); } } if (othersSent) { break; } try { TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD); } catch (InterruptedException e) { } } debug("GuestNode#waitForSent(): Other clusters sent"); }
java
{ "resource": "" }
q169642
GuestNode.waitForConnected
validation
private void waitForConnected() { debug("GuestNode#waitForConnected(): Waiting for all the clusters connected"); while (true) { boolean connected = true; for (Object fromKey : clustersProperties.keySet()) { String fromClusterName = (String) fromKey; for (Object toKey : clustersProperties.keySet()) { String toClusterName = (String) toKey; if (fromClusterName.equals(toClusterName)) { continue; } Long receivedAt = region.get(createReceivedAtKey( fromClusterName, toClusterName)); if (receivedAt == null) { connected = false; break; } } } if (connected) { break; } try { TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD); } catch (InterruptedException e) { } } debug("GuestNode#waitForConnected(): All the clusters connected"); }
java
{ "resource": "" }
q169643
GuestNode.waitFor
validation
public boolean waitFor(long timeout) { debug("GuestNode#waitFor(long): Waiting for task finish with timeout = " + timeout); ProcessingTask connectionCheckTask = new ProcessingTask(); Utils.execute(connectionCheckTask, timeout); boolean connected = connectionCheckTask.isConnected(); debug("GuestNode#waitFor(long): Task finished connected = " + connected); return connected; }
java
{ "resource": "" }
q169644
GuestNode.close
validation
public void close() { try { debug("GuestNode#close(): Closing the cache"); clientCache.close(); debug("GuestNode#close(): Cache closed = " + clientCache.isClosed()); } catch (Throwable t) { debug( "GuestNode#close(): Throwable caught with message = " + t.getMessage(), t); } }
java
{ "resource": "" }
q169645
GuestNode.printState
validation
public void printState(boolean connected) { if (!quiet) { StringBuilder sb = new StringBuilder(); if (connected) { sb.append(localClusterName).append(" <= "); Iterator<Object> it = clustersProperties.keySet().iterator(); while (it.hasNext()) { String clusterName = (String) it.next(); if (localClusterName.equals(clusterName)) { continue; } Long sentAt = region.get(createSentAtKey(clusterName)); Long receivedAt = region.get(createReceivedAtKey( clusterName, localClusterName)); long duration = receivedAt - sentAt; sb.append("[").append(clusterName).append(", ") .append(duration).append("ms]"); } } else { sb.append("Connection process is not finished for ").append( localClusterName); } System.out.println(sb.toString()); } }
java
{ "resource": "" }
q169646
GuestNode.main
validation
public static void main(String[] args) { try { if (args.length != 7) { Utils.exitWithFailure(); } String cluster = args[0]; Properties clustersProperties = PropertiesHelper .stringToProperties(args[1]); long timeout = Long.parseLong(args[2]); String regionName = args[3]; boolean debugEnabled = ("true".equals(args[4]) ? true : false); boolean quiet = ("true".equals(args[5]) ? true : false); long processingStartedAt = Long.parseLong(args[6]); GuestNode guestNode = new GuestNode(cluster, clustersProperties, regionName, debugEnabled, quiet, processingStartedAt); boolean connected = guestNode.waitFor(timeout); guestNode.printState(connected); guestNode.close(); if (connected) { Utils.exitWithSuccess(); } Utils.exitWithFailure(); } catch (Throwable t) { Utils.exitWithFailure(); } }
java
{ "resource": "" }
q169647
XClass.getOrderedProperties
validation
public List<XProperty> getOrderedProperties() { final List<XProperty> result = Introspector.getProperties(clazz); Collections.sort(result, new XProperty.NaturalOrder()); return result; }
java
{ "resource": "" }
q169648
XClass.getVersionModelHashCode
validation
public short getVersionModelHashCode(int version) { List<XProperty> classFields = getOrderedProperties(); StringBuilder builder = new StringBuilder(); for (XProperty field : classFields) { if (version == -1 || version >= field.getPropertyVersion()) { builder.append(field.getType()).append(field.getName()); } } int hashCode = builder.toString().hashCode(); return (short) ((hashCode & 0xFFFF ) ^ ((hashCode & 0xFFFF0000) >> 16)) ; }
java
{ "resource": "" }
q169649
PaginatedQuery.getTotalNumberOfPages
validation
public int getTotalNumberOfPages() throws QueryException { prepareResultData(false); if (isEmpty()) { return 1; } int total = totalNumberOfEntries / this.pageSize; if (totalNumberOfEntries % this.pageSize > 0) { total += 1; } return total; }
java
{ "resource": "" }
q169650
PaginatedQuery.getValues
validation
@SuppressWarnings("unchecked") private List<V> getValues(List<Object> entriesKeysForPage) { if (entriesKeysForPage.isEmpty()) { return Collections.emptyList(); } Map<Object, V> entriesMap = queryRegion.getAll(entriesKeysForPage); List<V> entries = new ArrayList<V>(entriesKeysForPage.size()); for (Object key : entriesKeysForPage) { entries.add(entriesMap.get(key)); } return entries; }
java
{ "resource": "" }
q169651
PaginatedQuery.prepareResultData
validation
@SuppressWarnings({ "unchecked" }) private void prepareResultData(boolean force) throws QueryException { if (this.infoLoaded && !force) { return; } PageKey pageKey = newKey(PAGE_NUMBER_FOR_GENERAL_INFO); List<Object> queryInfo = null; if (!force) { queryInfo = paginatedQueryInfoRegion.get(pageKey); } if (queryInfo == null) { Query query = queryService.newQuery(this.queryString); SelectResults<Object> results = null; try { results = (SelectResults<Object>) query.execute(pageKey .getQueryParameters()); } catch (FunctionDomainException e) { handleException(e); } catch (TypeMismatchException e) { handleException(e); } catch (NameResolutionException e) { handleException(e); } catch (QueryInvocationTargetException e) { handleException(e); } if (results.size() > queryLimit) { this.limitExceeded = true; this.totalNumberOfEntries = queryLimit; String msg = "Size of query results has exceeded limit (" + queryLimit + "). Truncated."; logger.warn(msg); } else { limitExceeded = false; this.totalNumberOfEntries = results.size(); } queryInfo = Arrays.asList(new Object[] { results.size(), limitExceeded }); storePage(PAGE_NUMBER_FOR_GENERAL_INFO, queryInfo); List<Object> keys = extractKeys(results); storeResults(keys); } else { this.totalNumberOfEntries = (Integer) queryInfo.get(0); this.limitExceeded = (Boolean) queryInfo.get(1); } this.infoLoaded = true; }
java
{ "resource": "" }
q169652
PaginatedQuery.storeResults
validation
private void storeResults(List<Object> resultKeys) { if (resultKeys.size() > queryLimit) { resultKeys = resultKeys.subList(0, queryLimit); } int keyNumber = 0; int pageNumber = 0; List<Object> page = new ArrayList<Object>(); for (Object key : resultKeys) { if (keyNumber % getPageSize() == 0 && keyNumber != 0) { storePage(++pageNumber, page); page.clear(); } page.add(key); keyNumber++; } if (page.size() > 0 || pageNumber == 0) { storePage(++pageNumber, page); } }
java
{ "resource": "" }
q169653
PersistableObjectFactory.create
validation
public T create(Object... attributes) { // build T object = build(attributes); // excute beforeCreate callback executeCallbacks(BeforeFactoryCreate.class, object); // persist persist(object); // execute after create callback executeCallbacks(AfterFactoryCreate.class, object); // return return object; }
java
{ "resource": "" }
q169654
TagToCategorySortingComparator.compare
validation
@Override public int compare(final TagToCategory o1, final TagToCategory o2) { if (o1 == null && o2 == null) return 0; if (o1 == null) return lessThan; if (o2 == null) return greaterThan; if (o1.getSorting() == null && o2.getSorting() == null) return compareSecondLevel(o1, o2); if (o1.getSorting() == null) return greaterThan; if (o2.getSorting() == null) return lessThan; if (o1.getSorting().equals(o2.getSorting())) return compareSecondLevel(o1, o2); return o1.getSorting().compareTo(o2.getSorting()) * greaterThan; }
java
{ "resource": "" }
q169655
AbstractMigrateLocales.migrateBrokenLocales
validation
private void migrateBrokenLocales(final PreparedStatement preparedStmt, final Map<String, Integer> localeMap) throws SQLException { final Integer enUSLocaleID = localeMap.get("en-US"); if (enUSLocaleID != null && enUSLocaleID > 0) { migrateBrokenLocale(preparedStmt, localeMap, "es_US", enUSLocaleID); migrateBrokenLocale(preparedStmt, localeMap, "en_AU", enUSLocaleID); migrateBrokenLocale(preparedStmt, localeMap, "ar", enUSLocaleID); migrateBrokenLocale(preparedStmt, localeMap, "as", enUSLocaleID); } }
java
{ "resource": "" }
q169656
TopicUtilities.recalculateMinHash
validation
public static boolean recalculateMinHash(final Topic topic, final List<MinHashXOR> minHashXORs) { boolean retValue = false; final Set<MinHash> existingMinHashes = topic.getMinHashes(); final Map<Integer, Integer> minHashes = getMinHashes(topic.getTopicXML(), minHashXORs); for (final Integer funcId : minHashes.keySet()) { boolean found = false; for (final MinHash minHash : existingMinHashes) { if (minHash.getMinHashFuncID().equals(funcId)) { if (!minHash.getMinHash().equals(minHashes.get(funcId))) { minHash.setMinHash(minHashes.get(funcId)); retValue = true; } found = true; break; } } if (!found) { retValue = true; final MinHash minHash = new MinHash(); minHash.setMinHashFuncID(funcId); minHash.setMinHash(minHashes.get(funcId)); topic.addMinHash(minHash); } } return retValue; }
java
{ "resource": "" }
q169657
TopicUtilities.getMinHashes
validation
public static Map<Integer, Integer> getMinHashes(final String xml, final List<MinHashXOR> minHashXORs) { final Map<Integer, Integer> retValue = new HashMap<Integer, Integer>(); // Clean the XML to remove element names and other useless data final String cleanedXML = cleanXMLForMinHash(xml); // the first minhash uses the builtin hashcode only final Integer baseMinHash = getMinHashInternal(cleanedXML, null); if (baseMinHash != null) { retValue.put(0, baseMinHash); } for (int funcId = 1; funcId < org.jboss.pressgang.ccms.model.constants.Constants.NUM_MIN_HASHES; ++funcId) { boolean foundMinHash = false; for (final MinHashXOR minHashXOR : minHashXORs) { if (minHashXOR.getMinHashXORFuncId() == funcId) { final Integer minHash = getMinHashInternal(cleanedXML, minHashXOR.getMinHashXOR()); if (minHash != null) { retValue.put(funcId, minHash); } foundMinHash = true; break; } } if (!foundMinHash) { throw new IllegalStateException("Did not find a minhash xor int for function " + funcId); } } return retValue; }
java
{ "resource": "" }
q169658
TopicUtilities.cleanXMLForMinHash
validation
protected static String cleanXMLForMinHash(final String xml) { // Treat null and empty strings the same final String fixedXML = xml == null ? "" : xml; String text = null; try { final Document doc = XMLUtilities.convertStringToDocument(fixedXML); if (doc != null) { text = doc.getDocumentElement().getTextContent(); } } catch (final Exception ex) { // Do nothing } // the xml was invalid, so just strip out xml elements manually if (text == null) { text = fixedXML.replaceAll("</?.*?/?>", " "); } return text; }
java
{ "resource": "" }
q169659
TopicUtilities.validateAndFixRelationships
validation
public static void validateAndFixRelationships(final Topic topic) { /* remove relationships to this topic in the parent collection */ final ArrayList<TopicToTopic> removeList = new ArrayList<TopicToTopic>(); for (final TopicToTopic topicToTopic : topic.getParentTopicToTopics()) if (topicToTopic.getRelatedTopic().getTopicId().equals(topic.getTopicId())) removeList.add(topicToTopic); for (final TopicToTopic topicToTopic : removeList) topic.getParentTopicToTopics().remove(topicToTopic); /* remove relationships to this topic in the child collection */ final ArrayList<TopicToTopic> removeChildList = new ArrayList<TopicToTopic>(); for (final TopicToTopic topicToTopic : topic.getChildTopicToTopics()) if (topicToTopic.getMainTopic().getTopicId().equals(topic.getTopicId())) removeChildList.add(topicToTopic); for (final TopicToTopic topicToTopic : removeChildList) topic.getChildTopicToTopics().remove(topicToTopic); }
java
{ "resource": "" }
q169660
TopicUtilities.updateContentHash
validation
public static void updateContentHash(final Topic topic) { if (topic.getTopicXML() != null) { topic.setTopicContentHash(HashUtilities.generateSHA256(topic.getTopicXML()).toCharArray()); } }
java
{ "resource": "" }
q169661
TopicUtilities.validateAndFixTags
validation
public static void validateAndFixTags(final Topic topic) { /* * validate the tags that are applied to this topic. generally the gui should enforce these rules, with the exception of * the bulk tag apply function */ // Create a collection of Categories mapped to TagToCategories, sorted by the Category sorting order final TreeMap<Category, ArrayList<TagToCategory>> tagDB = new TreeMap<Category, ArrayList<TagToCategory>>( Collections.reverseOrder()); for (final TopicToTag topicToTag : topic.getTopicToTags()) { final Tag tag = topicToTag.getTag(); for (final TagToCategory tagToCategory : tag.getTagToCategories()) { final Category category = tagToCategory.getCategory(); if (!tagDB.containsKey(category)) tagDB.put(category, new ArrayList<TagToCategory>()); tagDB.get(category).add(tagToCategory); } } // now remove conflicting tags for (final Category category : tagDB.keySet()) { /* sort by the tags position in the category */ Collections.sort(tagDB.get(category), new TagToCategorySortingComparator(false)); /* * because of the way we have ordered the tagDB collections, and the ArrayLists it contains, this process will * remove those tags that belong to lower priority categories, and lower priority tags in those categories */ final ArrayList<TagToCategory> tagToCategories = tagDB.get(category); // remove tags in the same mutually exclusive categories if (category.isMutuallyExclusive() && tagToCategories.size() > 1) { while (tagToCategories.size() > 1) { final TagToCategory tagToCategory = tagToCategories.get(1); /* get the lower priority tag */ final Tag removeTag = tagToCategory.getTag(); /* remove it from the tagDB collection */ tagToCategories.remove(tagToCategory); /* and remove it from the tag collection */ final ArrayList<TopicToTag> removeTopicToTagList = new ArrayList<TopicToTag>(); for (final TopicToTag topicToTag : topic.getTopicToTags()) { if (topicToTag.getTag().equals(removeTag)) removeTopicToTagList.add(topicToTag); } for (final TopicToTag removeTopicToTag : removeTopicToTagList) { topic.getTopicToTags().remove(removeTopicToTag); } } } /* remove tags that are explicitly defined as mutually exclusive */ for (final TagToCategory tagToCategory : tagToCategories) { final Tag tag = tagToCategory.getTag(); for (final Tag exclusionTag : tag.getExcludedTags()) { if (filter(having(on(TopicToTag.class).getTag(), equalTo(tagToCategory.getTag())), topic.getTopicToTags()).size() != 0 && // make /* * sure that we have not removed this tag already */ filter(having(on(TopicToTag.class).getTag(), equalTo(exclusionTag)), topic.getTopicToTags()).size() != 0 && // make /* * sure the exclusion tag exists */ !exclusionTag.equals(tagToCategory.getTag())) // make /* * sure we are not trying to remove ourselves */ { with(topic.getTopicToTags()).remove(having(on(TopicToTag.class).getTag(), equalTo(exclusionTag))); } } } } }
java
{ "resource": "" }
q169662
Comparators.sortClassesPerPackage
validation
public static SortedMap<PackageDoc, SortedSet<ClassDoc>> sortClassesPerPackage(final ClassDoc... classDocs) { final SortedMap<PackageDoc, SortedSet<ClassDoc>> toReturn = new TreeMap<>(Comparators.PACKAGE_NAME_COMPARATOR); if (classDocs != null) { Arrays.stream(classDocs).forEach(current -> { // Retrieve (or create) the SortedSet of ClassDocs for the current PackageDocs. final SortedSet<ClassDoc> classDocsForCurrentPackage = toReturn.computeIfAbsent( current.containingPackage(), k -> new TreeSet<>(Comparators.CLASS_NAME_COMPARATOR)); // Add the current ClassDoc to the SortedSet. classDocsForCurrentPackage.add(current); }); } // All Done. return toReturn; }
java
{ "resource": "" }
q169663
AbstractEnforcerRule.execute
validation
@Override @SuppressWarnings("PMD.PreserveStackTrace") public final void execute(final EnforcerRuleHelper helper) throws EnforcerRuleException { final MavenProject project; try { project = (MavenProject) helper.evaluate("${project}"); } catch (final ExpressionEvaluationException e) { // Whoops. final String msg = "Could not acquire MavenProject. (Expression lookup failure for: " + e.getLocalizedMessage() + ")"; throw new EnforcerRuleException(msg, e); } // Delegate. try { performValidation(project, helper); } catch (RuleFailureException e) { // Create a somewhat verbose failure message. String message = "\n" + "\n#" + "\n# Structure rule failure:" + "\n# " + getShortRuleDescription() + "\n# " + "\n# Message: " + e.getLocalizedMessage() + "\n# " + "\n# Offending project [" + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion() + "]" + "\n#"; final Artifact art = e.getOffendingArtifact(); if (art != null) { message += "\n# Offending artifact [" + art.getGroupId() + ":" + art.getArtifactId() + ":" + art.getVersion() + "]" + "\n#"; } message += "\n"; // Re-throw for pretty print throw new EnforcerRuleException(message); } }
java
{ "resource": "" }
q169664
AbstractEnforcerRule.splice
validation
protected static List<String> splice(final String toSplice) { final List<String> toReturn = new ArrayList<String>(); final StringTokenizer tok = new StringTokenizer(toSplice, ",", false); while (tok.hasMoreTokens()) { toReturn.add(tok.nextToken()); } return toReturn; }
java
{ "resource": "" }
q169665
AbstractEnforcerRule.splice2Pattern
validation
protected static List<Pattern> splice2Pattern(final String toSplice) throws PatternSyntaxException { final List<Pattern> toReturn = new ArrayList<Pattern>(); for (final String current : splice(toSplice)) { toReturn.add(Pattern.compile(current)); } return toReturn; }
java
{ "resource": "" }
q169666
AbstractEnforcerRule.containsPrefix
validation
protected static boolean containsPrefix(final List<String> source, final String toCheck) { if (source != null) { for (final String current : source) { if (toCheck.startsWith(current)) { return true; } } } // The prefix was not found within the provided string toCheck. return false; }
java
{ "resource": "" }
q169667
Factory.getFactoryClass
validation
private static Class<?extends ObjectFactory> getFactoryClass(Class<?> factoryClass) { if(factoryPackages.size() == 0) throw new IllegalArgumentException("No package provide to look for factories."); if(factoryClasses == null) { factoryClasses = new HashMap<Class<?>, Class<? extends ObjectFactory>>(); Set<Class<?extends ObjectFactory>> classes = ReflectionUtils.getSubclassesOf(ObjectFactory.class, factoryPackages); for(Class<?extends ObjectFactory> clazz : classes) { if(! Modifier.isAbstract(clazz.getModifiers())) { try { Constructor constructor = clazz.getConstructor(); ObjectFactory factory = (ObjectFactory)constructor.newInstance(); factoryClasses.put(factory.getFactoryClass(), factory.getClass()); } catch (Exception e) { throw new RuntimeException(e); //should not happen, compiler forces factory classes to implement correct constructor. } } } } return factoryClasses.get(factoryClass); }
java
{ "resource": "" }
q169668
EmailService.send
validation
public void send(String subject, String content) throws MessagingException { MimeMessage message = compose(subject, content, propertiesHelper.getStringProperty("mail.to")); transport(message); }
java
{ "resource": "" }
q169669
EmailService.send
validation
public void send(String subject, String content, String to) throws MessagingException { MimeMessage message = compose(subject, content, to); transport(message); }
java
{ "resource": "" }
q169670
FunctionExecutionThread.executeZeroFunction
validation
private int executeZeroFunction(Pool pool) throws FunctionException, InterruptedException { int result = -1; ResultCollector<?, ?> collector = FunctionService.onServer(pool) .execute(new ZeroFunction()); List<?> functionResult = (List<?>) collector.getResult(); if ((functionResult != null) && (functionResult.size() == 1) && (functionResult.get(0) instanceof Integer)) { result = (Integer) functionResult.get(0); } return result; }
java
{ "resource": "" }
q169671
BucketOrientedQueryFunction.execute
validation
@Override @SuppressWarnings({ "ThrowableInstanceNeverThrown", "unchecked" }) public void execute(FunctionContext functionContext) { ResultSender<Serializable> resultSender = functionContext.getResultSender(); RegionFunctionContext regionFunctionContext = (RegionFunctionContext) functionContext; if (functionContext.getArguments() == null) { handleException(new FunctionException("You must specify function argument for query execution."), resultSender, null); return; } if (!(functionContext.getArguments() instanceof BucketOrientedQueryFunctionArgument)) { handleException(new FunctionException("Function arguments must be of type " + BucketOrientedQueryFunctionArgument.class.getName() + "."), resultSender, null); return; } BucketOrientedQueryFunctionArgument argument = (BucketOrientedQueryFunctionArgument) functionContext .getArguments(); LocalDataSet localData = (LocalDataSet) PartitionRegionHelper.getLocalDataForContext(regionFunctionContext); QueryService queryService = localData.getCache().getQueryService(); String queryStr = argument.getQueryString(); try { Query query = queryService.newQuery(queryStr); SelectResults<?> result = (SelectResults<?>) localData.executeQuery((DefaultQuery) query, argument.getQueryParameters(), localData.getBucketSet()); resultSender.lastResult((Serializable) formatResults(result)); } catch (Exception e) { handleException(e, resultSender, queryStr); } }
java
{ "resource": "" }
q169672
BucketOrientedQueryFunction.handleException
validation
@SuppressWarnings({ "ThrowableInstanceNeverThrown" }) private void handleException(Throwable e, ResultSender<Serializable> resultSender, String queryString) { logger.error("Failed to execute bucket oriented query" + (queryString != null ? ": " + queryString : "."), e); resultSender.sendException(new FunctionException(e.getMessage())); }
java
{ "resource": "" }
q169673
BucketOrientedQueryFunction.formatResults
validation
private List<Object> formatResults(SelectResults<?> selectResults) { List<Object> results = new ArrayList<Object>(selectResults.size() + 1); results.addAll(selectResults.asList()); results.add(selectResults.getCollectionType().getElementType()); return results; }
java
{ "resource": "" }
q169674
AbstractErrorMessageContainer.addErrorMessage
validation
@Override public final void addErrorMessage(final String message) { if (message == null || "".equals(message)) { return; } // All done. errorMessages.add(message); }
java
{ "resource": "" }
q169675
AbstractErrorMessageContainer.getMessage
validation
@Override public String getMessage() { final StringBuilder builder = new StringBuilder(); for (final String current : errorMessages) { builder.append(current).append("\n"); } // All done. return builder.toString(); }
java
{ "resource": "" }
q169676
Utils.isSocketAlive
validation
public static boolean isSocketAlive(String host, int port) { boolean socketAlive = false; Socket socket = null; try { socket = new Socket(host, port); socketAlive = socket.isConnected(); } catch (Throwable t) { // do nothing } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // do nothing } } } return socketAlive; }
java
{ "resource": "" }
q169677
Utils.execute
validation
public static void execute(Thread thread, long timeout) { thread.start(); try { thread.join(timeout); } catch (InterruptedException e) { // Should not be interrupted normally. } if (thread.isAlive()) { thread.interrupt(); } }
java
{ "resource": "" }
q169678
CheckstyleReport.hasResources
validation
private boolean hasResources(List<Resource> resources) { for (Resource resource : resources) { if (new File(resource.getDirectory()).exists()) { return true; } } return false; }
java
{ "resource": "" }
q169679
CheckstyleReport.mergeDeprecatedInfo
validation
private void mergeDeprecatedInfo() throws MavenReportException { if ("sun_checks.xml".equals(configLocation) && !"sun".equals(format)) { configLocation = FORMAT_TO_CONFIG_LOCATION.get(format); throw new MavenReportException("'format' parameter is deprecated: please replace with <configLocation>" + configLocation + "</configLocation>."); } if (StringUtils.isEmpty(propertiesLocation)) { if (propertiesFile != null) { propertiesLocation = propertiesFile.getPath(); throw new MavenReportException("'propertiesFile' parameter is deprecated: please replace with " + "<propertiesLocation>" + propertiesLocation + "</propertiesLocation>."); } else if (propertiesURL != null) { propertiesLocation = propertiesURL.toExternalForm(); throw new MavenReportException("'propertiesURL' parameter is deprecated: please replace with " + "<propertiesLocation>" + propertiesLocation + "</propertiesLocation>."); } } if ("LICENSE.txt".equals(headerLocation)) { File defaultHeaderFile = new File(project.getBasedir(), "LICENSE.txt"); if (!defaultHeaderFile.equals(headerFile)) { headerLocation = headerFile.getPath(); } } if (StringUtils.isEmpty(suppressionsLocation)) { suppressionsLocation = suppressionsFile; if (StringUtils.isNotEmpty(suppressionsFile)) { throw new MavenReportException("'suppressionsFile' parameter is deprecated: please replace with " + "<suppressionsLocation>" + suppressionsLocation + "</suppressionsLocation>."); } } if (StringUtils.isEmpty(packageNamesLocation)) { packageNamesLocation = packageNamesFile; if (StringUtils.isNotEmpty(packageNamesFile)) { throw new MavenReportException("'packageNamesFile' parameter is deprecated: please replace with " + "<packageNamesFile>" + suppressionsLocation + "</packageNamesFile>."); } } }
java
{ "resource": "" }
q169680
CacheUtils.addQueryLimit
validation
public static String addQueryLimit(String queryString, int queryLimit) { int limitIndex = queryString.lastIndexOf("limit"); if (limitIndex == -1) { limitIndex = queryString.lastIndexOf("LIMIT"); } if (limitIndex == -1) { return queryString + " LIMIT " + (queryLimit + 1); } int limitNumber = Integer.parseInt(queryString .substring(limitIndex + 5).trim()); return (limitNumber > queryLimit) ? queryString .substring(0, limitIndex) + " LIMIT " + (queryLimit + 1) : queryString; }
java
{ "resource": "" }
q169681
CacheUtils.getFirstLocatorFromLocatorsString
validation
public static String[] getFirstLocatorFromLocatorsString( String locatorsString) { if (locatorsString == null || locatorsString.length() == 0) { return new String[2]; } String[] firstLocator = new String[2]; firstLocator[0] = locatorsString.substring(0, locatorsString.indexOf('[')).trim(); locatorsString = locatorsString .substring(locatorsString.indexOf('[') + 1); firstLocator[1] = locatorsString.substring(0, locatorsString.indexOf(']')); return firstLocator; }
java
{ "resource": "" }
q169682
CacheUtils.getRegionSize
validation
public static int getRegionSize(Region<?, ?> region) { Function function = new RegionSizeFunction(); FunctionService.registerFunction(function); ResultCollector<?, ?> rc = FunctionService.onRegion(region) .withCollector(new RegionSizeResultCollector()) .execute(function); return (Integer) rc.getResult(); }
java
{ "resource": "" }
q169683
CacheUtils.isGemFireClient
validation
public static boolean isGemFireClient() { GemFireCacheImpl impl = (GemFireCacheImpl) CacheFactory .getAnyInstance(); return impl != null && impl.isClient(); }
java
{ "resource": "" }
q169684
CacheUtils.removeAll
validation
public static <K> void removeAll(Region<K, ?> region, Set<K> keys) { if (keys == null) { throw new NullPointerException(); } if (keys.isEmpty()) { // Nothing to do return; } Function function = new RemoveAllFunction(); FunctionService.registerFunction(function); ResultCollector<?, ?> rc = FunctionService.onRegion(region) .withFilter(keys).withArgs(region.getName()).execute(function); // Obtain result from the collector to return // only after everything is done. rc.getResult(); }
java
{ "resource": "" }
q169685
CacheUtils.retryWithExponentialBackoff
validation
public static <T> T retryWithExponentialBackoff(Retryable<T> runnable, int maxRetries) throws InterruptedException, OperationRetryFailedException { int retry = 0; while (retry < maxRetries) { retry++; try { return runnable.execute(); } catch (OperationRequireRetryException e) { // No-op. } catch (InterruptedException e) { throw e; } if (retry > 1) { long delay = (long) ((BACKOFF_BASE << retry) * Math.random()); log.debug("Operation requested retry. Sleep for {} millis", delay); Thread.sleep(delay); } } throw new OperationRetryFailedException( "Maximum number of operation retries reached"); }
java
{ "resource": "" }
q169686
SVGIcon.generateBufferedImage
validation
protected void generateBufferedImage(TranscoderInput in, int w, int h) throws TranscoderException { BufferedImageTranscoder t = new BufferedImageTranscoder(); if (w != 0 && h != 0) { t.setDimensions(w, h); } t.transcode(in, null); bufferedImage = t.getBufferedImage(); width = bufferedImage.getWidth(); height = bufferedImage.getHeight(); }
java
{ "resource": "" }
q169687
SVGIcon.paintIcon
validation
@Override public void paintIcon(Component c, Graphics g, int x, int y) { if (backgroundColour == null) g.drawImage(bufferedImage, x, y, null); else g.drawImage(bufferedImage, x, y, backgroundColour, null); }
java
{ "resource": "" }
q169688
ConsoleUtils.getReader
validation
private static BufferedReader getReader() { if (bufferedReader == null) { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } return bufferedReader; }
java
{ "resource": "" }
q169689
ConsoleUtils.waitForEnter
validation
public static void waitForEnter(String message) { System.out.println(message); try { getReader().readLine(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
java
{ "resource": "" }
q169690
CheckReplicationTool.execute
validation
public void execute(String[] args, boolean debugEnabled, boolean quiet) { try { this.debugEnabled = debugEnabled; debug("CheckReplicationTool#execute(String[]): args = " + Arrays.asList(args)); parseCommandLineArguments(args); System.out.println("Connecting..."); debug("CheckReplicationTool#execute(String[]): Creating CheckReplicationTool.ProcessorTask with parameters: clustersProperties = " + clustersProperties + ", timeout = " + timeout + ", regionName = " + regionName); ProcessorTask task = new ProcessorTask(clustersProperties, timeout, regionName, debugEnabled, quiet); debug("CheckReplicationTool#execute(String[]): Starting CheckReplicationTool.ProcessorTask"); Utils.execute(task, timeout + DELTA_TIMEOUT); int exitCode = task.getExitCode(); debug("CheckReplicationTool#execute(String[]): CheckReplicationTool.ProcessorTask finished with exitCode = " + exitCode); if (exitCode == 0) { Utils.exitWithSuccess(); } Utils.exitWithFailure(); } catch (Throwable t) { debug( "CheckReplicationTool#execute(String[]): Throwable caught with message = " + t.getMessage(), t); Utils.exitWithFailure("Unexpected throwable", t); } }
java
{ "resource": "" }
q169691
CheckReplicationTool.parseCommandLineArguments
validation
protected void parseCommandLineArguments(String[] commandLineArguments) { Options options = constructGnuOptions(); if (commandLineArguments.length < 1) { printHelp(options); } CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, commandLineArguments); if (line.hasOption(HELP_OPTION)) { printHelp(options); } if (line.hasOption(REGION_OPTION)) { regionName = line.getOptionValue(REGION_OPTION); } if (line.hasOption(TIMEOUT_OPTION)) { String timeoutString = line.getOptionValue(TIMEOUT_OPTION); timeout = Long.parseLong(timeoutString); } if (line.hasOption(CLUSTER_OPTION)) { clustersProperties = line.getOptionProperties(CLUSTER_OPTION); if (clustersProperties.keySet().size() < 2) { Utils .exitWithFailure("At least two clusters should be defined"); } } else { Utils.exitWithFailure("No clusters defined"); } } catch (Throwable t) { Utils .exitWithFailure( "Throwable caught during the command-line arguments parsing", t); } }
java
{ "resource": "" }
q169692
CheckReplicationTool.printHelp
validation
protected void printHelp(final Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("check-replication [options]", options); Utils.exitWithFailure(); }
java
{ "resource": "" }
q169693
CheckReplicationTool.constructGnuOptions
validation
protected Options constructGnuOptions() { final Options gnuOptions = new Options(); gnuOptions .addOption("t", TIMEOUT_OPTION, true, "Timeout, ms. Default timeout is " + DEFAULT_TIMEOUT) .addOption( "r", REGION_OPTION, true, "The name of region for this test. Default name is \"" + DEFAULT_REGION_NAME + "\"") .addOption("h", HELP_OPTION, false, "Print usage information"); @SuppressWarnings("static-access") Option locatorsOption = OptionBuilder .hasArgs() .withDescription( "Cluster name and list of its locators. " + "There should be at least two clusters. " + "Example: -c cluster1=host1[port1],host2[port2] -c cluster2=host3[port3]") .withValueSeparator().withArgName("cluster=locators") .withLongOpt(CLUSTER_OPTION).create("c"); gnuOptions.addOption(locatorsOption); return gnuOptions; }
java
{ "resource": "" }
q169694
HashCodeCollector.aggregateSingleClusterMemberData
validation
private static void aggregateSingleClusterMemberData(List<ResultCollector> taskResults) { for (ResultCollector singleCluster : taskResults) { List membersResult = (List) singleCluster.getResult(); for (Object resultFromNode : membersResult) { System.out.print(((HashMap) resultFromNode).get("ds") + ":"); } System.out.println(); } }
java
{ "resource": "" }
q169695
ExpressionBuilder.notNull
validation
public ExpressionBuilder notNull(final Object property, final String name) { if (property == null) { messageContainer.addErrorMessage("Property '" + name + "' cannot be null"); } return this; }
java
{ "resource": "" }
q169696
Launcher.parseCommandLineArguments
validation
private static void parseCommandLineArguments(String[] commandLineArguments) { Options options = constructGnuOptions(); CommandLineParser parser = new GnuParser(); try { CommandLine line = parser.parse(options, commandLineArguments); if (line.hasOption(HELP_OPTION)) { printHelp(options); } if (line.hasOption(DEBUG_OPTION)) { debugEnabled = true; } if (!debugEnabled && line.hasOption(QUIET_OPTION)) { quiet = true; } } catch (Throwable t) { printHelp(options); } }
java
{ "resource": "" }
q169697
Launcher.printHelp
validation
private static void printHelp(final Options options) { StringBuilder sb = new StringBuilder(); sb.append("java -jar icegem-cache-utils-<version>.jar [options] <"); Command[] commands = Command.values(); for (int i = 0; i < commands.length; i++) { sb.append(commands[i].getName()); if (i < (commands.length - 1)) { sb.append(" | "); } } sb.append("> [command_specific_options]"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(sb.toString(), options); Utils.exitWithFailure(); }
java
{ "resource": "" }
q169698
Launcher.constructGnuOptions
validation
private static Options constructGnuOptions() { final Options gnuOptions = new Options(); gnuOptions.addOption("d", DEBUG_OPTION, false, "Print debug information") .addOption("q", QUIET_OPTION, false, "Quiet output. Doesn't work if --" + DEBUG_OPTION + " specified.") .addOption("h", HELP_OPTION, false, "Print usage information"); return gnuOptions; }
java
{ "resource": "" }
q169699
Launcher.findCommandIndex
validation
private static int findCommandIndex(String[] args) { int commandIndex = -1; for (int i = 0; i < args.length; i++) { for (Command command : Command.values()) { if (command.getName().equals(args[i].trim())) { commandIndex = i; break; } } } return commandIndex; }
java
{ "resource": "" }