List of usage examples for java.util HashSet contains
public boolean contains(Object o)
From source file:com.bw.hawksword.wiktionary.ExtendedWikiHelper.java
/** * Format the given wiki-style text into formatted HTML content. This will * create headers, lists, internal links, and style formatting for any wiki * markup found.// w w w. j a v a 2s . c o m * * @param wikiText The raw text to format, with wiki-markup included. * @return HTML formatted content, ready for display in {@link WebView}. */ public static String formatWikiText(String wikiText) { if (wikiText == null) { return null; } // Insert a fake last section into the document so our section splitter // can correctly catch the last section. wikiText = wikiText.concat(STUB_SECTION); // Read through all sections, keeping only those matching our filter, // and only including the first entry for each title. HashSet<String> foundSections = new HashSet<String>(); StringBuilder builder = new StringBuilder(); Matcher sectionMatcher = sSectionSplit.matcher(wikiText); while (sectionMatcher.find()) { String title = sectionMatcher.group(1); if (!foundSections.contains(title) && sValidSections.matcher(title).matches()) { String sectionContent = sectionMatcher.group(); foundSections.add(title); builder.append(sectionContent); } } // Our new wiki text is the selected sections only wikiText = builder.toString(); // Apply all formatting rules, in order, to the wiki text for (FormatRule rule : sFormatRules) { wikiText = rule.apply(wikiText); } // Return the resulting HTML with style sheet, if we have content left if (!TextUtils.isEmpty(wikiText)) { return STYLE_SHEET + wikiText; } else { return null; } }
From source file:de.dfki.iui.mmds.core.emf.persistence.EmfPersistence.java
private static void collectObjectsWithoutResource(EObject eObject, HashSet<EObject> alreadyVisited, List<EObject> rootList, NonContainmentReferenceHandling refOption) { if (alreadyVisited.contains(eObject)) return;/*from w w w . j a v a2 s . c om*/ alreadyVisited.add(eObject); if ((eObject.eClass().getEPackage() instanceof EcorePackage)) return; if (eObject.eResource() == null) { if (eObject.eContainer() == null) { rootList.add(eObject); } else { collectObjectsWithoutResource(eObject.eContainer(), alreadyVisited, rootList, refOption); } } for (EReference eref : eObject.eClass().getEAllReferences()) { if (eref.isTransient()) { EAnnotation annotation = eref.getEAnnotation("http:///org/eclipse/emf/ecore/util/ExtendedMetaData"); if (annotation == null || !annotation.getDetails().containsKey("group")) { continue; } } final Object value = eObject.eGet(eref); if (value == null) { continue; } if (value instanceof List) { for (Object obj : (List<?>) value) { if (obj == null) { logger.error("There seems to be a unresolved reference. Please check the console output!"); } collectObjectsWithoutResource((EObject) obj, alreadyVisited, rootList, refOption); } } else { collectObjectsWithoutResource((EObject) value, alreadyVisited, rootList, refOption); } } }
From source file:Main.java
/** * Converts a given object to a form encoded map * @param objName Name of the object/*from w ww . jav a2 s . c o m*/ * @param obj The object to convert into a map * @param objectMap The object map to populate * @param processed List of objects hashCodes that are already parsed * @throws InvalidObjectException */ private static void objectToMap(String objName, Object obj, Map<String, Object> objectMap, HashSet<Integer> processed) throws InvalidObjectException { //null values need not to be processed if (obj == null) return; //wrapper types are autoboxed, so reference checking is not needed if (!isWrapperType(obj.getClass())) { //avoid infinite recursion if (processed.contains(obj.hashCode())) return; processed.add(obj.hashCode()); } //process arrays if (obj instanceof Collection<?>) { //process array if ((objName == null) || (objName.isEmpty())) throw new InvalidObjectException("Object name cannot be empty"); Collection<?> array = (Collection<?>) obj; //append all elements in the array into a string int index = 0; for (Object element : array) { //load key value pair String key = String.format("%s[%d]", objName, index++); loadKeyValuePairForEncoding(key, element, objectMap, processed); } } else if (obj instanceof Map) { //process map Map<?, ?> map = (Map<?, ?>) obj; //append all elements in the array into a string for (Map.Entry<?, ?> pair : map.entrySet()) { String attribName = pair.getKey().toString(); String key = attribName; if ((objName != null) && (!objName.isEmpty())) { key = String.format("%s[%s]", objName, attribName); } loadKeyValuePairForEncoding(key, pair.getValue(), objectMap, processed); } } else { //process objects // invoke getter methods Method[] methods = obj.getClass().getMethods(); for (Method method : methods) { //is a getter? if ((method.getParameterTypes().length != 0) || (!method.getName().startsWith("get"))) continue; //get json attribute name Annotation getterAnnotation = method.getAnnotation(JsonGetter.class); if (getterAnnotation == null) continue; //load key name String attribName = ((JsonGetter) getterAnnotation).value(); String key = attribName; if ((objName != null) && (!objName.isEmpty())) { key = String.format("%s[%s]", objName, attribName); } try { //load key value pair Object value = method.invoke(obj); loadKeyValuePairForEncoding(key, value, objectMap, processed); } catch (Exception ex) { } } // load fields Field[] fields = obj.getClass().getFields(); for (Field field : fields) { //load key name String attribName = field.getName(); String key = attribName; if ((objName != null) && (!objName.isEmpty())) { key = String.format("%s[%s]", objName, attribName); } try { //load key value pair Object value = field.get(obj); loadKeyValuePairForEncoding(key, value, objectMap, processed); } catch (Exception ex) { } } } }
From source file:com.microsoft.azure.storage.table.CEKReturn.java
private static boolean isEncrypted(HashSet<String> encryptedPropertyDetailsSet, String key) { // Handle the case where the property is encrypted. return encryptedPropertyDetailsSet != null && encryptedPropertyDetailsSet.contains(key); }
From source file:edu.umd.cs.submitServer.servlets.RunMoss.java
static private void uploadSubmission(PrintWriter writer, SocketClient socketClient, String classAccount, byte[] bytes, boolean baselline, HashSet<String> extensions) { try {/*from ww w. j a v a2 s . c o m*/ HashSet<String> seen = new HashSet<>(); Map<String, List<String>> files = TextUtilities.scanTextFilesInZip(new ByteArrayInputStream(bytes)); for (Map.Entry<String, List<String>> e : files.entrySet()) { String name = e.getKey(); name = name.substring(name.lastIndexOf('/') + 1); int lastDot = name.lastIndexOf('.'); if (lastDot >= 0 && extensions.contains(name.substring(lastDot)) && seen.add(name)) { name = classAccount + "/" + name; writer.println(" Sending " + name); socketClient.uploadFile(name, e.getValue(), false); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.projity.field.Select.java
public static String toConfigurationXMLOptions(LinkedHashMap map, String keyPrefix) { // MapIterator i = map.i(); Iterator i = map.keySet().iterator(); StringBuffer buf = new StringBuffer(); HashSet duplicateSet = new HashSet(); // don't allow duplicate keys while (i.hasNext()) { String key = (String) i.next(); // notion of key and value is switched String value = (String) map.get(key); int dupCount = 2; String newKey = key;/* ww w .ja v a2 s . com*/ while (duplicateSet.contains(newKey)) { newKey = key + "-" + dupCount++; } key = newKey; duplicateSet.add(key); if (key == null || key.length() == 0) continue; if (value == null || value.length() == 0) continue; key = keyPrefix + key; // String key = "<html>" + keyPrefix + ": " + "<b>" + i.getValue() // +"</b></html>"; buf.append(SelectOption.toConfigurationXML(key, value)); } return buf.toString(); }
From source file:com.addthis.hydra.job.spawn.JobAlertUtil.java
/** * Count the total byte sizes of files along a certain path via mesh * @param jobId The job to check/*from w w w . ja v a 2 s .c o m*/ * @param dirPath The path to check within the jobId, e.g. split/{{now-1}}/importantfiles/*.gz * @return A long representing the total size in bytes of files along the specified path */ public static long getTotalBytesFromMesh(MeshyClient meshyClient, String jobId, String dirPath) { String meshLookupString = "/job*/" + jobId + "/*/gold/" + expandDateMacro(dirPath); if (meshyClient != null) { try { Collection<FileReference> fileRefs = meshyClient.listFiles(new String[] { meshLookupString }); HashSet<String> fileRefKeysUsed = new HashSet<>(); long totalBytes = 0; for (FileReference fileRef : fileRefs) { // Use StreamSourceMeshy to generate a canonical path key. In particular, strip off any multi-minion prefixes if appropriate. String meshFileKey = StreamFileUtil.getCanonicalFileReferenceCacheKey(fileRef.name, pathOff, sortToken, pathTokenOffset); if (!fileRefKeysUsed.contains(meshFileKey)) { totalBytes += fileRef.size; fileRefKeysUsed.add(meshFileKey); } } return totalBytes; } catch (IOException e) { log.warn("Job alert mesh look up failed", e); } } else { log.warn( "Received mesh lookup request job={} dirPath={} while meshy client was not instantiated; returning zero", jobId, dirPath); } return 0; }
From source file:com.oneis.javascript.Runtime.java
private static void recursiveSealObjects(ScriptableObject object, ScriptableObject scope, HashSet<Object> seen, boolean sealThisObject) { // Avoid infinite recursion if (seen.contains(object)) { return;/*from ww w. j a v a 2 s.co m*/ } seen.add(object); for (Object propertyName : object.getAllIds()) { // Seal any getter or setters boolean foundGetter = false; if (propertyName instanceof String) // ConsString is checked -- property names are always proper Strings { for (int s = 0; s <= 1; s++) { boolean setter = (s == 0); Object gs = object.getGetterOrSetter((String) propertyName, 0, setter); // ConsString is checked if (gs != null && gs instanceof ScriptableObject) { if (!setter) { foundGetter = true; } recursiveSealObjects((ScriptableObject) gs, scope, seen, true); } } } // If there wasn't a getter, seal the property if (!foundGetter) { Object property = null; if (propertyName instanceof String) // ConsString is checked { property = object.get((String) propertyName, scope); // ConsString is checked } else if (propertyName instanceof Integer) { property = object.get(((Integer) propertyName).intValue(), scope); } if (property != null && property instanceof ScriptableObject) { recursiveSealObjects((ScriptableObject) property, scope, seen, true); } } } // Seal the prototype too? Scriptable prototype = object.getPrototype(); if (prototype != null && prototype instanceof ScriptableObject) { recursiveSealObjects((ScriptableObject) prototype, scope, seen, true); } // Seal the parent scope? Scriptable parentScope = object.getParentScope(); if (parentScope != null && parentScope instanceof ScriptableObject) { recursiveSealObjects((ScriptableObject) parentScope, scope, seen, true); } // Seal this object if (sealThisObject) { object.sealObject(); } }
From source file:org.epics.archiverappliance.utils.ui.GetUrlContent.java
/** * Get the contents of a redirect URL and use as reponse for the provided HttpServletResponse. * If possible, pass in error responses as well. * @param redirectURIStr   //from w ww . j a va2 s .co m * @param resp HttpServletResponse * @throws IOException   */ public static void proxyURL(String redirectURIStr, HttpServletResponse resp) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet getMethod = new HttpGet(redirectURIStr); getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ try (CloseableHttpResponse response = httpclient.execute(getMethod)) { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); HashSet<String> proxiedHeaders = new HashSet<String>(); proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS)); Header[] headers = response.getAllHeaders(); for (Header header : headers) { if (proxiedHeaders.contains(header.getName())) { logger.debug("Adding headerName " + header.getName() + " and value " + header.getValue() + " when proxying request"); resp.addHeader(header.getName(), header.getValue()); } } if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); try (OutputStream os = resp.getOutputStream(); InputStream is = new BufferedInputStream(entity.getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); resp.flushBuffer(); bytesRead = is.read(buf); } } } else { throw new IOException("HTTP response did not have an entity associated with it"); } } else { logger.error("Invalid status code " + response.getStatusLine().getStatusCode() + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across"); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); bytesRead = is.read(buf); } } resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray())); } } } }
From source file:com.termmed.utils.FileHelper.java
/** * Gets the modules.//from w w w . ja v a 2s .c om * * @param tmpFile the tmp file * @return the modules * @throws IOException Signals that an I/O exception has occurred. */ public static HashSet<String> getModules(String tmpFile) throws IOException { BufferedReader br = getReader(tmpFile); br.readLine(); String line; String[] spl; HashSet<String> modules = new HashSet<String>(); while ((line = br.readLine()) != null) { spl = line.split("\t", -1); if (!modules.contains(spl[3])) { modules.add(spl[3]); } } br.close(); return modules; }