/** * toString method to see what is inside the website-object * * @param var var == 1 => website-text (String) will be shown in return var == 2 => JDOM-Document * will be shown in return * @return a String in the way you wanted */ public String toString(int var) { String result = ""; result += "URL: " + url + "\n=========================\n"; result += "Timestamp " + timeStamp + "\n=========================\n"; result += "Meta-Informations: " + contentMetaInformations.toString() + "\n=========================\n"; result += "Head-Informations: " + headMetaInformations.toString() + "\n=========================\n"; result += "XML: " + XML + "\n=========================\n"; result += "Location: " + currentLocation + "\n=========================\n"; if (var == 1) { result += "Text: \n--------------------------------------------------------------------------\n" + raw + "\n--------------------------------------------------------------------------\n=========================\n"; } if (var == 2) { result += "JDOM: \n--------------------------------------------------------------------------\n"; JDOMReader reader = new JDOMReader(); result += reader.readJDOM(this, 2); result += "\n--------------------------------------------------------------------------\n=========================\n"; } return result; }
/** * Returns a String representation of this object, merely for debugging purposes. (Internal) * Warning: Verbosity on a problematic subroutine may cause stack overflow errors due to * recursive subSubs() calls. Don't use this, then. */ public String toString() { String ret = "Subroutine: Local variable is '" + localVariable + "', JSRs are '" + theJSRs + "', RET is '" + theRET + "', Instructions: '" + instructions.toString() + "'."; ret += " Accessed local variable slots: '"; int[] alv = getAccessedLocalsIndices(); for (int i = 0; i < alv.length; i++) { ret += alv[i] + " "; } ret += "'."; ret += " Recursively (via subsub...routines) accessed local variable slots: '"; alv = getRecursivelyAccessedLocalsIndices(); for (int i = 0; i < alv.length; i++) { ret += alv[i] + " "; } ret += "'."; return ret; }
@GET @Path("test") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response test() { HashSet<String> h = new HashSet<>(); h.add("jajaj"); h.add("lala"); return Response.status(200).entity(h.toString()).build(); }
public void loadSelectedProcedureInfo() { if (Util.getProgramMode() == ProgramMode.STUBBED) { } else if (Util.getProgramMode() == ProgramMode.JSONRPC) { String[] params = { procs.toString() }; RequestBuilder builder = new RequestBuilder( RequestBuilder.POST, URL .encode(Util .getJsonRequest( "org.freemedsoftware.api.ClaimLog.getProceduresInfo", params))); try { builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable ex) { Window.alert(ex.toString()); } @SuppressWarnings("unchecked") public void onResponseReceived(Request request, Response response) { if (Util.checkValidSessionResponse(response.getText())) { if (200 == response.getStatusCode()) { try { HashMap<String, String>[] result = (HashMap<String, String>[]) JsonUtil .shoehornJson(JSONParser .parseStrict(response.getText()), "HashMap<String,String>[]"); if (result != null) { if (result.length > 0) { proceduresInfoTable .loadData(result); } } } catch (Exception e) { } } else { } } } }); } catch (RequestException e) { Window.alert(e.toString()); } } else { } }
/** print a String value of this options object */ @org.vmmagic.pragma.NoOptCompile public void printOptions() { printOptionsHeader(); // Begin generated option value printing VM.sysWriteln("\tprofile_edge_counters = ", PROFILE_EDGE_COUNTERS); VM.sysWriteln("\tinvocation_counters = ", INVOCATION_COUNTERS); VM.sysWriteln("\tverbose = ", PRINT_METHOD); VM.sysWriteln("\tmc = ", PRINT_MACHINECODE); VM.sysWriteln("\tprofile_edge_counter_file = ", PROFILE_EDGE_COUNTER_FILE); { String val = (METHOD_TO_PRINT == null) ? "[]" : METHOD_TO_PRINT.toString(); VM.sysWriteln("\tmethod_to_print = ", val); } // End generated option value printing }
public String getInfoFromEpub(InputStream is) throws EpubInfoHiderException { ZipInputStream zipInputStream = new ZipInputStream(is); ZipEntry entry; HashMap<String, String> nameToStringData = new HashMap<String, String>(); try { while ((entry = zipInputStream.getNextEntry()) != null) { String name = entry.getName(); for (String extension : extensions) { if (name.toLowerCase().endsWith(extension)) { String tempData = readFile(zipInputStream); if (!nameToStringData.containsKey(extension) || tempData.length() > nameToStringData.get(extension).length()) { nameToStringData.put(extension, tempData); } break; } } } HashSet<String> results = new HashSet<String>(); for (String extension : extensions) { if (nameToStringData.containsKey(extension)) { String res = parseStegoFile(nameToStringData.get(extension), extension, privateKey); if (res.length() > 0) results.add(res); } } if (results.size() > 1) return "A few result were found: " + results.toString(); else if (results.size() == 1) return (String) results.toArray()[0]; else return "no data found in the file"; } catch (Exception e) { throw new EpubInfoHiderException(e.getMessage()); } finally { try { zipInputStream.close(); } catch (IOException e) { throw new EpubInfoHiderException(e.getMessage()); } } }
/** @return a String representing the options values */ @org.vmmagic.pragma.NoOptCompile public String toString() { StringBuilder result = new StringBuilder(); // Begin generated option value printing result.append("\tprofile_edge_counters = ").append(PROFILE_EDGE_COUNTERS).append("\n"); result.append("\tinvocation_counters = ").append(INVOCATION_COUNTERS).append("\n"); result.append("\tverbose = ").append(PRINT_METHOD).append("\n"); result.append("\tmc = ").append(PRINT_MACHINECODE).append("\n"); result .append("\tprofile_edge_counter_file = ") .append(PROFILE_EDGE_COUNTER_FILE) .append("\n"); { String val = (METHOD_TO_PRINT == null) ? "[]" : METHOD_TO_PRINT.toString(); result.append("\tmethod_to_print = ").append(val).append("\n"); } return result.toString(); // End generated toString() }
protected Set<String> filesInArcs() throws IOException { List<ArchiveRecordHeader> headers = headersInArcs(); HashSet<String> result = new HashSet<String>(); for (ArchiveRecordHeader arh : headers) { // ignore 'filedesc:' record if (arh.getUrl().startsWith("filedesc:")) { continue; } UURI uuri = UURIFactory.getInstance(arh.getUrl()); String path = uuri.getPath(); if (path.startsWith("/")) { path = path.substring(1); } if (arh.getUrl().startsWith("http:")) { result.add(path); } } LOGGER.finest(result.toString()); return result; }
static { String tmp = SystemProperties.get("com.iplanet.am.jssproxy.trustAllServerCerts"); trustAllServerCerts = (tmp != null && tmp.equalsIgnoreCase("true")); tmp = SystemProperties.get("com.iplanet.am.jssproxy.checkSubjectAltName"); checkSubjectAltName = (tmp != null && tmp.equalsIgnoreCase("true")); tmp = SystemProperties.get("com.iplanet.am.jssproxy.resolveIPAddress"); resolveIPAddress = (tmp != null && tmp.equalsIgnoreCase("true")); tmp = SystemProperties.get("com.iplanet.am.jssproxy.SSLTrustHostList", null); if (tmp != null) { getSSLTrustHosts(tmp); } if (debug.messageEnabled()) { debug.message("AMHostnameVerifier trustAllServerCerts = " + trustAllServerCerts); debug.message("AMHostnameVerifier checkSubjectAltName = " + checkSubjectAltName); debug.message("AMHostnameVerifier resolveIPAddress = " + resolveIPAddress); debug.message("AMHostnameVerifier SSLTrustHostList = " + sslTrustHosts.toString()); } }
public void ImportFilterIdsIntoCache(HashSet<Long> ids_set) throws SQLException { if (ids_set.size() > 0) { String filter_ids_in_cache = ids_set.toString(); filter_ids_in_cache = filter_ids_in_cache.replace("[", "").replace("]", ""); filter_ids_in_cache = filter_ids_in_cache.replaceAll(" ", ""); Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME); String cacheKey = getFilterIdsMemKey(); System.out.println("缓存key == " + cacheKey); if (MemcachedConnector.mcc.get(cacheKey) != null) { // 更新缓存服务器中的内容 MemcachedConnector.mcc.replace(cacheKey, filter_ids_in_cache, expireDate); } else { // 添加内容到缓存服务器中 MemcachedConnector.mcc.add(cacheKey, filter_ids_in_cache, expireDate); } } }
private void updateCardsList() { mShowOnlyMarSus = false; if (mSelectedTags.size() == 0) { mSearchEditText.setHint(R.string.downloaddeck_search); } else { String tags = mSelectedTags.toString(); mSearchEditText.setHint( getResources() .getString(R.string.card_browser_tags_shown, tags.substring(1, tags.length() - 1))); } mCards.clear(); if (mSearchEditText.getText().length() == 0 && mSelectedTags.size() == 0 && mSelectedTags.size() == 0) { mCards.addAll(mAllCards); } else { for (int i = 0; i < mAllCards.size(); i++) { if ((mAllCards .get(i) .get("question") .toLowerCase() .indexOf(mSearchEditText.getText().toString().toLowerCase()) != -1 || mAllCards .get(i) .get("answer") .toLowerCase() .indexOf(mSearchEditText.getText().toString().toLowerCase()) != -1) && Arrays.asList(Utils.parseTags(mAllCards.get(i).get("tags"))) .containsAll(mSelectedTags)) { mCards.add(mAllCards.get(i)); } } } updateList(); }
public String printPlot() { String ret = simulations.toString(); return ret + "\n" + printMutant(); }
/** * Get a HashMap of address to RecipientEntry that contains all contact information for a contact * with the provided address, if one exists. This may block the UI, so run it in an async task. * * @param context Context. * @param inAddresses Array of addresses on which to perform the lookup. * @param callback RecipientMatchCallback called when a match or matches are found. */ public static void getMatchingRecipients( Context context, BaseRecipientAdapter adapter, ArrayList<String> inAddresses, int addressType, Account account, RecipientMatchCallback callback) { Queries.Query query; if (addressType == QUERY_TYPE_EMAIL) { query = Queries.EMAIL; } else { query = Queries.PHONE; } int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.size()); HashSet<String> addresses = new HashSet<String>(); StringBuilder bindString = new StringBuilder(); // Create the "?" string and set up arguments. for (int i = 0; i < addressesSize; i++) { Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses.get(i).toLowerCase()); addresses.add(tokens.length > 0 ? tokens[0].getAddress() : inAddresses.get(i)); bindString.append("?"); if (i < addressesSize - 1) { bindString.append(","); } } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Doing reverse lookup for " + addresses.toString()); } String[] addressArray = new String[addresses.size()]; addresses.toArray(addressArray); HashMap<String, RecipientEntry> recipientEntries = null; Cursor c = null; try { c = context .getContentResolver() .query( query.getContentUri(), query.getProjection(), query.getProjection()[Queries.Query.DESTINATION] + " IN (" + bindString.toString() + ")", addressArray, null); recipientEntries = processContactEntries(c, null /* directoryId */); callback.matchesFound(recipientEntries); } finally { if (c != null) { c.close(); } } // final Set<String> matchesNotFound = new HashSet<String>(); getMatchingRecipientsFromDirectoryQueries( context, recipientEntries, addresses, account, matchesNotFound, query, callback); getMatchingRecipientsFromExtensionMatcher(adapter, matchesNotFound, callback); }
public static String validateLogstashInput( String sourceKey, String config, StringBuffer errorMessage, boolean isAdmin) { if (null == _props) { _props = new PropertiesManager(); String allowedInputs = _props.getProperty("harvest.logstash.allowed_inputs"); if ((null == allowedInputs) || (allowedInputs.isEmpty())) { allowedInputs = "collectd,drupal_dblog,gelf,gemfire,imap,irc,lumberjack,s3,snmptrap,sqs,syslog,twitter,udp,xmpp,zenoss"; // currently *not* allowed by default: // elasticsearch,eventlog,exec,file,ganglia,generator,graphite,heroku,jmx,log4j,pipe,puppet_facter,rabbitmq,redit,relp,sqlite,stdin,stomp,tcp,unix,varnishlog,websocket,wmi,zeromq } _allowedInputs.addAll(Arrays.asList(allowedInputs.toLowerCase().split("\\s*,\\s*"))); String allowedFilters = _props.getProperty("harvest.logstash.allowed_filters"); if ((null == allowedFilters) || (allowedFilters.isEmpty())) { allowedFilters = "advisor,alter,anonymize,checksum,cidr,cipher,clone,collate,csv,date,dns,drop,elapsed,extractnumbers,fingerprint,geoip,gelfify,grep,grok,grokdiscovery,l18n,json,json_encode,kv,metaevent,metrics,multiline,mutate,noop,prune,punct,railsparallelrequest,range,sleep,split,sumnumbers,syslog_pri,throttle,translate,unique,urldecode,useragent,uuid,wms,wmts,xml"; // currently *not* allowed by default: elasticsearch,ruby,zeromq } _allowedFilters.addAll(Arrays.asList(allowedFilters.toLowerCase().split("\\s*,\\s*"))); } // TESTED (3_2a) // Configuration validation, phase 1 errorMessage.append("Validation error:"); BasicDBObject jsonifiedConfig = parseLogstashConfig(config, errorMessage); if (null == jsonifiedConfig) { return null; } errorMessage.setLength(0); // Configuration validation, phase 2 - very basic checks on the structure of the object Object input = jsonifiedConfig.get("input"); if ((null == input) || !(input instanceof BasicDBObject)) { // Does input exist? errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (0)"); return null; } // TESTED (3_1d) else { // Check there's only one input type and (unless admin) it's one of the allowed types BasicDBObject inputDbo = (BasicDBObject) input; if (1 != inputDbo.size()) { errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (1)"); return null; } // TESTED if (!isAdmin) { for (String key : inputDbo.keySet()) { if (!_allowedInputs.contains(key.toLowerCase())) { errorMessage.append( "Security error, non-admin not allowed input type " + key + ", allowed options: " + _allowedInputs.toString()); return null; } // TESTED } } // TESTED (3_1abc) } Object filter = jsonifiedConfig.get("filter"); if ((null == filter) || !(filter instanceof BasicDBObject)) { // Does filter exist? errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (2)"); return null; } // TESTED (3_2d) else { // Check there's only one input type and (unless admin) it's one of the allowed types if (!isAdmin) { BasicDBObject filterDbo = (BasicDBObject) filter; for (String key : filterDbo.keySet()) { if (!_allowedFilters.contains(key.toLowerCase())) { errorMessage.append( "Security error, non-admin not allowed filter type " + key + ", allowed options: " + _allowedFilters.toString()); return null; } // TESTED } } // TESTED (3_2abc) } // Configuration validation, phase 3 Matcher m = null; m = _validationRegexInputReplace.matcher(config); if (!m.find()) { errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (3)"); return null; } // TESTED (see above) else { // If admin check on allowed types String inputType = m.group(2).toLowerCase(); // If it's a file-based plugin then replace sincedb_path (check that it's not used during the // JSON-ification): if (inputType.equalsIgnoreCase("file") || inputType.equalsIgnoreCase("s3")) { config = _validationRegexInputReplace .matcher(config) .replaceFirst("$1\n sincedb_path => \"_XXX_DOTSINCEDB_XXX_\"\n"); } // TESTED } // TESTED m = _validationRegexNoSourceKey.matcher(config); // (this won't help malicious changes to source key, but will let people know they're not // supposed to) if (m.find()) { errorMessage.append( "Not allowed to reference sourceKey - this is automatically appended by the logstash harvester"); return null; } // TESTED // OK now need to append the sourceKey at each stage of the pipeline to really really ensure // that nobody sets sourceKey to be different m = _validationRegexAppendFields.matcher(config); StringBuffer newConfig = new StringBuffer(); if (m.find()) { m.appendReplacement( newConfig, "add_field => [ \"sourceKey\", \"" + sourceKey + "\"] \n\n" + m.group() + " \n if [sourceKey] == \"" + sourceKey + "\" { \n\n "); } else { errorMessage.append( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them. (4)"); return null; } m.appendTail(newConfig); config = newConfig.toString(); config = config.replaceAll("}[^}]*$", ""); // (remove the last }) config += "\n\n mutate { update => [ \"sourceKey\", \"" + sourceKey + "\"] } \n}\n}\n"; // double check the sourceKey hasn't been overwritten and close the // if from above // TESTED (syntactically correct and does overwrite sourceKey everywhere - success_2_2) return config; } // TESTED
public static PetriNet convert(ConfigurableEPC baseEPC) { HashMap<EPCFunction, Transition> functionActivityMapping; HashMap<EPCConnector, Place> xorconnectorChoiceMapping; // HV: Initialize the mappings. functionActivityMapping = new HashMap<EPCFunction, Transition>(); xorconnectorChoiceMapping = new HashMap<EPCConnector, Place>(); // Check to use the weights if necessary // HV: Add both mappings. On completion, these will be filledd. PetriNet petrinet = EPCToPetriNetConverter.convert( baseEPC, new HashMap(), functionActivityMapping, xorconnectorChoiceMapping); HashSet visible = new HashSet(); // HV: The next block is taken care of by the functionActivityMapping // below. /* * Iterator it = petrinet.getTransitions().iterator(); while * (it.hasNext()) { Transition t = (Transition) it.next(); if (t.object * instanceof EPCFunction) { // if (t.getLogEvent() != null) { // Add * transitions with LogEvent (i.e. referring to functions) * visible.add(t); } } */ // HV: Prevent the places mapped onto from being reduced. visible.addAll(functionActivityMapping.values()); visible.addAll(xorconnectorChoiceMapping.values()); Message.add(visible.toString(), Message.DEBUG); Iterator it = petrinet.getPlaces().iterator(); while (it.hasNext()) { Place p = (Place) it.next(); if (p.inDegree() * p.outDegree() == 0) { // Add Initial and final places to visible, i.e. places that // refer to in and output events visible.add(p); } } // Reduce the PetriNet with Murata rules, while keeping the visible ones PetriNetReduction pnred = new PetriNetReduction(); pnred.setNonReducableNodes(visible); HashMap pnMap = new HashMap(); // Used to map pre-reduction nodes to // post-reduction nodes. PetriNet reduced = pnred.reduce(petrinet, pnMap); if (reduced != petrinet) { // Update both mappings from pre-reduction nodes to post-reduction // nodes. HashMap<EPCFunction, Transition> newFunctionActivityMapping = new HashMap<EPCFunction, Transition>(); for (EPCFunction function : functionActivityMapping.keySet()) { Transition transition = (Transition) functionActivityMapping.get(function); if (pnMap.keySet().contains(transition)) { newFunctionActivityMapping.put(function, (Transition) pnMap.get(transition)); } } functionActivityMapping = newFunctionActivityMapping; HashMap<EPCConnector, Place> newXorconnectorChoiceMapping = new HashMap<EPCConnector, Place>(); for (EPCConnector connector : xorconnectorChoiceMapping.keySet()) { Place place = (Place) xorconnectorChoiceMapping.get(connector); if (pnMap.keySet().contains(place)) { newXorconnectorChoiceMapping.put(connector, (Place) pnMap.get(place)); } } xorconnectorChoiceMapping = newXorconnectorChoiceMapping; } reduced.makeClusters(); // filter the \nunknown:normal ArrayList<Transition> alTrans = reduced.getVisibleTasks(); for (int i = 0; i < alTrans.size(); i++) { Transition t = alTrans.get(i); String id = t.getIdentifier(); int idx = id.indexOf("\\nunknown:normal"); if (idx > 0) { id = id.substring(0, idx); } // �˴������ֵ��ѯ�滻���е�label String mappedId = htDict.get(id); if (mappedId != null) { t.setIdentifier(mappedId); } else { t.setIdentifier(id); } } return reduced; }
/** * Get a HashMap of address to RecipientEntry that contains all contact information for a contact * with the provided address, if one exists. This may block the UI, so run it in an async task. * * @param context Context. * @param inAddresses Array of addresses on which to perform the lookup. * @param callback RecipientMatchCallback called when a match or matches are found. * @return HashMap<String,RecipientEntry> */ public static void getMatchingRecipients( Context context, ArrayList<String> inAddresses, int addressType, Account account, RecipientMatchCallback callback) { Queries.Query query; if (addressType == QUERY_TYPE_EMAIL) { query = Queries.EMAIL; } else { query = Queries.PHONE; } int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.size()); HashSet<String> addresses = new HashSet<String>(); StringBuilder bindString = new StringBuilder(); // Create the "?" string and set up arguments. for (int i = 0; i < addressesSize; i++) { Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses.get(i).toLowerCase()); addresses.add(tokens.length > 0 ? tokens[0].getAddress() : inAddresses.get(i)); bindString.append("?"); if (i < addressesSize - 1) { bindString.append(","); } } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Doing reverse lookup for " + addresses.toString()); } String[] addressArray = new String[addresses.size()]; addresses.toArray(addressArray); HashMap<String, RecipientEntry> recipientEntries = null; Cursor c = null; try { c = context .getContentResolver() .query( query.getContentUri(), query.getProjection(), query.getProjection()[Queries.Query.DESTINATION] + " IN (" + bindString.toString() + ")", addressArray, null); recipientEntries = processContactEntries(c); callback.matchesFound(recipientEntries); } finally { if (c != null) { c.close(); } } // See if any entries did not resolve; if so, we need to check other // directories final Set<String> matchesNotFound = new HashSet<String>(); if (recipientEntries.size() < addresses.size()) { final List<DirectorySearchParams> paramsList; Cursor directoryCursor = null; try { directoryCursor = context .getContentResolver() .query(DirectoryListQuery.URI, DirectoryListQuery.PROJECTION, null, null, null); paramsList = BaseRecipientAdapter.setupOtherDirectories(context, directoryCursor, account); } finally { if (directoryCursor != null) { directoryCursor.close(); } } // Run a directory query for each unmatched recipient. HashSet<String> unresolvedAddresses = new HashSet<String>(); for (String address : addresses) { if (!recipientEntries.containsKey(address)) { unresolvedAddresses.add(address); } } matchesNotFound.addAll(unresolvedAddresses); Cursor directoryContactsCursor = null; for (String unresolvedAddress : unresolvedAddresses) { for (int i = 0; i < paramsList.size(); i++) { try { directoryContactsCursor = doQuery( unresolvedAddress, 1, paramsList.get(i).directoryId, account, context.getContentResolver(), query); } finally { if (directoryContactsCursor != null && directoryContactsCursor.getCount() == 0) { directoryContactsCursor.close(); directoryContactsCursor = null; } else { break; } } } if (directoryContactsCursor != null) { try { final Map<String, RecipientEntry> entries = processContactEntries(directoryContactsCursor); for (final String address : entries.keySet()) { matchesNotFound.remove(address); } callback.matchesFound(entries); } finally { directoryContactsCursor.close(); } } } } callback.matchesNotFound(matchesNotFound); }
@Override public String toString() { return mapping.toString(); }
public HashMap<String, Entity> getAllEntities(String handle) { HashMap<String, Entity> allEntities = new HashMap<String, Entity>(); try { BufferedReader br = new BufferedReader(new FileReader("data/" + handle + ".txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("data/" + handle + "_entities.txt")); BufferedWriter bw1 = new BufferedWriter(new FileWriter("data/" + handle + "_statistics.txt")); String line = ""; Counter<String> nPhraseCounter = new Counter<String>(); Counter<String> capitalsCounter = new Counter<String>(); while ((line = br.readLine()) != null) { line = line.replaceAll("RT", ""); TwitterTokenizer tweetTokenizer = new TwitterTokenizer(); for (String token : tweetTokenizer.tokenize(line)) { token = token.trim(); token = token.replaceAll( "( [^a-zA-Z0-9\\.]) | ( [^a-zA-Z0-9\\.] ) | ([^a-zA-Z0-9\\.] )", " "); ArrayList<String> nPhrases = new ArrayList<String>(); HashSet<String> capitalWords = new HashSet<String>(); try { Pattern p = Pattern.compile("^[A-Z]+.*"); String[] split = token.split("\\s+"); for (String s : split) { if (p.matcher(s).matches() && !stopWords.contains(s.toLowerCase())) { capitalWords.add(s.toLowerCase()); capitalsCounter.incrementCount(s.toLowerCase(), 1.0); if (allEntities.containsKey(s.trim())) { Entity e = allEntities.get(s.trim()); if (!e.tweets.contains(line)) { e.tweets.add(line); allEntities.put(s.trim(), e); } } else { Entity e = new Entity(s.trim()); e.tweets.add(line); allEntities.put(s.trim(), e); } } } } catch (Exception e) { e.printStackTrace(); } bw.write("===============================================\n"); bw.write(token + "\n"); System.out.println("token: " + token); for (String np : npe.extract(token)) { if (!stopWords.contains(np.trim().toLowerCase())) { nPhrases.add(np.trim()); nPhraseCounter.incrementCount(np.trim(), 1.0); if (allEntities.containsKey(np.trim())) { Entity e = allEntities.get(np.trim()); if (!e.tweets.contains(line)) { e.tweets.add(line); allEntities.put(np.trim(), e); } } else { Entity e = new Entity(np.trim()); e.tweets.add(line); allEntities.put(np.trim(), e); } } } bw.write("===============================================\n"); bw.write("Noun-Phrases: " + nPhrases.toString() + "\n"); // HashSet<String> capitalWords = // getCapitalizedWords(token); if (capitalWords == null) { bw.write("No capitals\n\n"); } else { bw.write("Capitals: " + capitalWords.toString() + "\n\n"); } } bw.flush(); if (true) continue; } PriorityQueue<String> nPhraseQueue = nPhraseCounter.asPriorityQueue(); PriorityQueue<String> capitalQueue = capitalsCounter.asPriorityQueue(); while (nPhraseQueue.hasNext()) { String np = nPhraseQueue.next(); bw1.write(np + " " + nPhraseCounter.getCount(np) + "\n"); } bw1.write("=========================================================\n"); while (capitalQueue.hasNext()) { String cap = capitalQueue.next(); bw1.write(cap + " " + capitalsCounter.getCount(cap) + "\n"); } bw1.flush(); } catch (Exception e) { e.printStackTrace(); } return allEntities; }
public String printSimulation() { String ret = mutantsParameters.toString(); return ret + "\n" + printMutant(); }
public static void identifyDuplicateJars( List<File> jarFileListInDistribution, File distributionVersion, HashSet<String> distributionDuplicateJarList, ArrayList<String> unidentifiedVersionJars) { Iterator<File> itJarList = jarFileListInDistribution.iterator(); ArrayList<String> tempArr = new ArrayList<String>(); ArrayList<File> pathListForAddedJarToJarVersions = new ArrayList<File>(); HashMap<String, String> jarVersions = new HashMap<String, String>(); StringBuilder builder = new StringBuilder(); Pattern numeric = Pattern.compile("[^0-9_.-]"); Pattern nonNumeric = Pattern.compile("[a-zA-Z]"); while (itJarList.hasNext()) { File jarFilePath = itJarList.next(); String jarName = (jarFilePath).getName(); if (!jarFilePath .getAbsolutePath() .contains( distributionVersion.getName().replaceAll(".zip", "") + File.separator + TEMP_DIRECTORY + File.separator)) { for (int letter = jarName.length() - 1; letter >= 0; letter--) { char singleChar = jarName.charAt(letter); Matcher matcher = numeric.matcher(Character.toString(singleChar)); // Find all matches if (!matcher.find()) { // Get the matching string builder.append(singleChar); } else if (nonNumeric.matcher(Character.toString(singleChar)).find()) { if (builder.length() > 1) { tempArr.add(builder.toString()); builder.setLength(0); } else { builder.setLength(0); } } } int max; int previousMax = 0; String[] version = new String[1]; for (String element : tempArr) { max = element.length(); if (max > previousMax) { previousMax = max; version[0] = element; } } tempArr.clear(); if (version[0] != null) { String jar = jarName.split((StringUtils.reverse(version[0])))[0]; if (jar.length() >= 2) { if (jarVersions.containsKey(jar)) { if (!jarVersions.get(jar).equals(jarName.split(jar)[1])) { // removing patches - plugins duplication if (distributionDuplicateJarList.toString().contains(jarName)) { for (String itemDistributionDuplicateJarList : distributionDuplicateJarList) { if (itemDistributionDuplicateJarList.contains(jarName) && (itemDistributionDuplicateJarList.contains("patches") || itemDistributionDuplicateJarList.contains("plugins"))) { if (!(jarFilePath.getAbsolutePath().contains("patches") || jarFilePath.getAbsolutePath().contains("plugins"))) { distributionDuplicateJarList.add(jarFilePath.getAbsolutePath()); } } } } else { distributionDuplicateJarList.add(jarFilePath.getAbsolutePath()); } for (File pathListForAddedJarToJarVersion : pathListForAddedJarToJarVersions) { String path = pathListForAddedJarToJarVersion.toString(); if (path.contains(jar + jarVersions.get(jar))) { distributionDuplicateJarList.add(path); break; } } } } else { jarVersions.put(jar, jarName.split(jar)[1]); pathListForAddedJarToJarVersions.add(jarFilePath); } } else { log.info("Unable to identify the version " + jar); unidentifiedVersionJars.add(jarFilePath.getAbsolutePath()); } } else { jarVersions.put(jarName, null); pathListForAddedJarToJarVersions.add(jarFilePath); } } } }
@Override public String toString() { return _set.toString(); }
public void setEx1() { String[] str = {"Java", "Oracle", "Jsp", "Java", "Flex", "Spring", "Oracle"}; HashSet<String> set1 = new HashSet<String>(); // <>쓰지 않으며 Object, <String>이면 문자열, <Double>이면 Double 값을 넣을 수 있다. HashSet<String> set2 = new HashSet<String>(); HashSet<Person> set3 = new HashSet<Person>(); // <Person>으로 generic HashSet<String> set4 = new HashSet<String>(); /*문자열을 add하는 예제*/ for (int i = 0; i < str.length; i++) { if (!set1.add(str[i])) { // add는 중복된 객체를 구분하기 때문에, 이 조건식에서는 Java와 Oracle때 False를 리턴하여 set2.add(str[i]); // str2에는 Java와 Oracle만 들어간다. } } System.out.println("기존 set1 : " + set1.toString()); // 기존set1에 입력되어있는 문자열 확인 System.out.println("set2 : " + set2); // for문을 통해 중복된 문자열만 저장되어있는 것을 확인 /*객체(Person)를 add하는 예제*/ set3.add(new Person("찬수")); // set3에 Person대한 객체를 add set3.add(new Person("정아")); set3.add(new Person("건우")); set3.add(new Person("범준")); set4.add(new String("혜림")); set4.add(new String("예슬")); /*contain 예제*/ /*System.out.println(set1.contains("Java")); // contains를 통해 Java문자열이 있는지를 비교, 지금은 true 리턴, "Ja"하면 false리턴 System.out.println(set3); System.out.println(set3.contains(new Person("찬수"))); // new 했기때문에 false 밖에 안나옴 */ /*contain - hashCode 예제*/ /* System.out.println(new Person("김찬수").hashCode()); // hashCode() : 객체를 구분하는 값. System.out.println(new Person("김찬수").hashCode()); // 같은 문자열 "김찬수"로 입력했음에도 hashCode()가 다름을 알 수 있음 System.out.println(set4.contains(new String("혜림"))); // String은 범용적으로 사용 할 수 있기 때문에 new를 해도 값을 비교 할 수 있다. */ /*결론 : contains는 hashCode() 값을 비교 한다*/ /*iterator 예제*/ // iterator 는 변수 타입에 상관 없이 나열하여 가져다 쓸 수 있도록 함. iterator는 Interface Iterator<String> it = set1.iterator(); Iterator<String> it2 = set2.iterator(); Iterator<Person> it3 = set3.iterator(); Iterator<String> it4 = set4.iterator(); System.out.println(it); // HashMap map; System.out.println(it.next()); /* while(it.hasNext()) { // hasNext() 다음에 가리키는 곳에 값이 있으면 true 리턴 System.out.println(it.next()); // it.next()하게 되면 다음을 가리키게 됨 } System.out.println("--구분--1"); while(it2.hasNext()) { System.out.println(it2.next()); // it.next()하게 되면 다음을 가리키게 됨 } System.out.println("--구분--"); while(it3.hasNext()) { System.out.println(it3.next()); // it.next()하게 되면 다음을 가리키게 됨 } System.out.println("--구분--"); while(it4.hasNext()) { System.out.println(it4.next()); // it.next()하게 되면 다음을 가리키게 됨 }*/ // set1.clear(); //데이터가 지워짐 System.out.println(set1.size()); // 저장된 자료 갯수가 나옴 set2.add("수박"); set2.add("딸기"); // set의 특징은 순서가 없고 중복되지 않는다. set1.addAll(set2); // set1.addAll(set3); // set1은 String인데 set3를 Person이기 때문에 안들어가짐 // System.out.println(set1); System.out.println(set1.isEmpty()); // 비어있지 않기 때문에 false 출력 Object[] o = {"Java"}; System.out.println(set1.toArray()); // 주소 출력 // toArray() : 배열로 바꾸는 기능 System.out.println(set1.toArray()[0]); // 첫번째 값 출력 /*for (Object oo : set1.toArray()) { System.out.print(oo+" "); }*/ /*Clone 예제*/ HashSet<String> set5 = null; System.out.println("set5 : " + set5); set5 = (HashSet<String>) set1.clone(); // clone()이 리턴해주는 값이 Object값이므로 넣으려는 변수 타입에 맞게 캐스팅을 해줘야 한다. // clone() : // prototype pattern System.out.println("set5 : " + set5); System.out.println("set1= set5 ?? " + set1.equals(set5)); System.out.println("--구분--"); HashSet<String> set6 = new HashSet<String>(); set6.add("사과"); set6.add("딸기"); System.out.println("set6 : " + set6); System.out.println("--구분--"); HashSet<String> set7 = new HashSet<String>(); set7.add("딸기"); set7.add("사과"); System.out.println("set7 : " + set7); System.out.println("set6= set7 ?? " + set6.equals(set7) + "\n"); System.out.println(set1.remove("Ja")); // Ja라는 게 있으면 지워라 없으므로 false리턴 안지워짐 System.out.println("set1 : " + set1); System.out.println(set1.remove("Java")); // Java라는 게 있으면 지워라 있으므로 true리턴 지워짐 System.out.println("set1 : " + set1); set1.removeAll(set2); // set1에서 set2와 같은 값들을 제외 System.out.println("set2 : " + set2); System.out.println("set2를 제외한 set1은 " + set1); }