List of usage examples for java.util Collections enumeration
public static <T> Enumeration<T> enumeration(final Collection<T> c)
From source file:com.linkedin.databus2.relay.GoldenGateEventProducer.java
/** * The method takes the an inputstream as an input and wraps it around with xml tags, * sets the xml encoding and xml version specified in the physical sources config. * @param compositeInputStream The inputstream to be wrapped with the xml tags * @return/*from www .j a va 2 s . c o m*/ */ private InputStream wrapStreamWithXmlTags(InputStream compositeInputStream) { String xmlVersion = _pConfig.getXmlVersion(); String xmlEncoding = _pConfig.getXmlEncoding(); String xmlStart = "<?xml version=\"" + xmlVersion + "\" encoding=\"" + xmlEncoding + "\"?>\n<root>"; String xmlEnd = "</root>"; _log.info("The xml start tag used is:" + xmlStart); List xmlTagsList = Arrays.asList(new InputStream[] { new ByteArrayInputStream(xmlStart.getBytes(Charset.forName(xmlEncoding))), compositeInputStream, new ByteArrayInputStream(xmlEnd.getBytes(Charset.forName(xmlEncoding))), }); Enumeration<InputStream> streams = Collections.enumeration(xmlTagsList); SequenceInputStream seqStream = new SequenceInputStream(streams); return seqStream; }
From source file:com.temenos.interaction.media.hal.TestHALProvider.java
private Metadata createObjectNestedVocabMetadataStub() { EntityMetadata vocs = new EntityMetadata("Children"); Vocabulary vocId = new Vocabulary(); vocId.setTerm(new TermValueType(TermValueType.TEXT)); vocs.setPropertyVocabulary("name", vocId); Vocabulary vocBody = new Vocabulary(); vocBody.setTerm(new TermValueType(TermValueType.INTEGER_NUMBER)); vocs.setPropertyVocabulary("age", vocBody); Vocabulary vocRides = new Vocabulary(); vocRides.setTerm(new TermComplexType(true)); vocs.setPropertyVocabulary("tuitions", vocRides); Vocabulary vocTutionName = new Vocabulary(); vocTutionName.setTerm(new TermValueType(TermValueType.TEXT)); vocs.setPropertyVocabulary("TutionName", vocTutionName, Collections.enumeration(Collections.singletonList("tuitions"))); Vocabulary vocTutionDuration = new Vocabulary(); vocTutionName.setTerm(new TermValueType(TermValueType.TEXT)); vocs.setPropertyVocabulary("Duration", vocTutionDuration, Collections.enumeration(Collections.singletonList("tuitions"))); Vocabulary vocAddress = new Vocabulary(); vocAddress.setTerm(new TermComplexType(true)); vocs.setPropertyVocabulary("address", vocAddress); Vocabulary vocAddressHouseNumber = new Vocabulary(); vocAddressHouseNumber.setTerm(new TermValueType(TermValueType.NUMBER)); vocs.setPropertyVocabulary("houseNumber", vocAddressHouseNumber, Collections.enumeration(Arrays.asList(new String[] { "address" }))); Vocabulary vocAddressRoadName = new Vocabulary(); vocAddressRoadName.setTerm(new TermValueType(TermValueType.NUMBER)); vocs.setPropertyVocabulary("roadName", vocAddressRoadName, Collections.enumeration(Arrays.asList(new String[] { "address" }))); Metadata metadata = new Metadata("Family"); metadata.setEntityMetadata(vocs);//from w w w . ja v a 2 s . c o m return metadata; }
From source file:org.languagetool.rules.de.GermanSpellerRule.java
@Nullable private static MorfologikMultiSpeller getSpeller(Language language, UserConfig userConfig, String languageVariantPlainTextDict) { if (!language.getShortCode().equals(Locale.GERMAN.getLanguage())) { throw new IllegalArgumentException("Language is not a variant of German: " + language); }/*from w ww .j a v a 2s.c om*/ try { String morfoFile = "/de/hunspell/de_" + language.getCountries()[0] + ".dict"; if (JLanguageTool.getDataBroker().resourceExists(morfoFile)) { // spell data will not exist in LibreOffice/OpenOffice context List<String> paths = Arrays.asList("/de/hunspell/spelling.txt"); StringBuilder concatPaths = new StringBuilder(); List<InputStream> streams = new ArrayList<>(); for (String path : paths) { concatPaths.append(path).append(";"); streams.add(JLanguageTool.getDataBroker().getFromResourceDirAsStream(path)); } try (BufferedReader br = new BufferedReader( new InputStreamReader(new SequenceInputStream(Collections.enumeration(streams)), UTF_8))) { BufferedReader variantReader = null; if (languageVariantPlainTextDict != null && !languageVariantPlainTextDict.isEmpty()) { InputStream variantStream = JLanguageTool.getDataBroker() .getFromResourceDirAsStream(languageVariantPlainTextDict); variantReader = new ExpandingReader( new BufferedReader(new InputStreamReader(variantStream, UTF_8))); } return new MorfologikMultiSpeller(morfoFile, new ExpandingReader(br), concatPaths.toString(), variantReader, languageVariantPlainTextDict, userConfig != null ? userConfig.getAcceptedWords() : Collections.emptyList(), MAX_EDIT_DISTANCE); } } else { return null; } } catch (IOException e) { throw new RuntimeException("Could not set up morfologik spell checker", e); } }
From source file:com.twinsoft.convertigo.beans.core.Sequence.java
private void clean() { cleanCopies();/*from w w w .j a va2 s . c o m*/ Enumeration<Long> e = Collections.enumeration(loadedSteps.keySet()); while (e.hasMoreElements()) { Long stepPriority = (Long) e.nextElement(); resetLoadedStepAsyncThreadRunning(stepPriority); } if (vAllSteps != null) { vAllSteps.clear(); vAllSteps = null; } if (childrenSteps != null) { childrenSteps.clear(); childrenSteps = null; } if (executedSteps != null) { executedSteps.clear(); executedSteps = null; } if (workerElementMap != null) { workerElementMap.clear(); workerElementMap = null; } if (loadedProjects != null) { if (Engine.isEngineMode()) { synchronized (loadedProjects) { loadedProjects.clear(); } } } if (xpathApi != null) { xpathApi.release(); xpathApi = null; } stepHttpState = null; }
From source file:de.tor.tribes.ui.views.DSWorkbenchSOSRequestAnalyzer.java
private void findFakes() { Boolean fakesOrAGsFound = false; if (GlobalOptions.getProperties().getBoolean("sos.mark.all.duplicates.as.fake")) { List<Village> sourcesOnce = new ArrayList<>(); List<Village> sourcesMoreThanOnce = new ArrayList<>(); for (ManageableType manTyp : SOSManager.getSingleton().getAllElements()) { SOSRequest pRequest = (SOSRequest) manTyp; for (Village target : pRequest.getTargets()) { TargetInformation targetInfo = pRequest.getTargetInformation(target); for (Village targetSource : targetInfo.getSources()) { if (sourcesOnce.contains(targetSource) && !sourcesMoreThanOnce.contains(targetSource)) { sourcesMoreThanOnce.add(targetSource); } else { sourcesOnce.add(targetSource); }//from w ww. ja va 2 s . c o m } } } for (ManageableType manTyp : SOSManager.getSingleton().getAllElements()) { SOSRequest pRequest = (SOSRequest) manTyp; for (Village target : pRequest.getTargets()) { TargetInformation targetInfo = pRequest.getTargetInformation(target); Enumeration<TimedAttack> attacks = Collections.enumeration(targetInfo.getAttacks()); while (attacks.hasMoreElements()) { TimedAttack att = attacks.nextElement(); //check for snobs long sendTime = att.getlArriveTime() - (long) (DSCalculator.calculateMoveTimeInSeconds(att.getSource(), target, DataHolder.getSingleton().getUnitByPlainName("ram").getSpeed()) * 1000); if (sendTime >= System.currentTimeMillis()) { att.setPossibleSnob(true); att.setPossibleFake(false); fakesOrAGsFound = true; } //check for multiple attacks from same source if (sourcesMoreThanOnce.contains(att.getSource())) { if (!att.isPossibleSnob()) {//ignore snobs att.setPossibleSnob(false); att.setPossibleFake(true); fakesOrAGsFound = true; } } } } } } else { for (ManageableType manTyp : SOSManager.getSingleton().getAllElements()) { SOSRequest pRequest = (SOSRequest) manTyp; for (Village target : pRequest.getTargets()) { TargetInformation targetInfo = pRequest.getTargetInformation(target); //check for multiple attacks from same source to same target for (Village source : targetInfo.getSources()) { if (targetInfo.getAttackCountFromSource(source) > 1) { for (TimedAttack att : targetInfo.getAttacksFromSource(source)) { if (!att.isPossibleFake() && !att.isPossibleSnob()) {//check only once long sendTime = att.getlArriveTime() - (long) (DSCalculator.calculateMoveTimeInSeconds(source, target, DataHolder.getSingleton().getUnitByPlainName("ram").getSpeed()) * 1000); if (sendTime < System.currentTimeMillis()) { att.setPossibleSnob(false); att.setPossibleFake(true); } else { att.setPossibleSnob(true); att.setPossibleFake(false); } fakesOrAGsFound = true; } } } } } } } if (fakesOrAGsFound) { //if we have found something inside the Atts we have to rebuild the Defence requests logger.debug("refreshing deff requests"); for (ManageableType manTyp : SOSManager.getSingleton().getAllElements()) { SOSRequest pRequest = (SOSRequest) manTyp; for (Village target : pRequest.getTargets()) { pRequest.getDefenseInformation(target).updateAttackInfo(); } } } }
From source file:com.twinsoft.convertigo.beans.core.Sequence.java
private void cleanCopies() { Enumeration<String> e; e = Collections.enumeration(childrenSteps.keySet()); while (e.hasMoreElements()) { String timeID = (String) e.nextElement(); cleanCopie(timeID);// w w w .j a v a 2 s . com } //System.out.println("Sequence copies :" + copies.size()); e = Collections.enumeration(copies.keySet()); while (e.hasMoreElements()) { String timeID = (String) e.nextElement(); //System.out.println("Sequence needs to clean copy of "+step.name+" ("+timeID+")"); cleanCopie(timeID); } copies.clear(); }
From source file:net.bull.javamelody.TestMonitoringFilter.java
private void monitoring(Map<HttpParameter, String> parameters, boolean checkResultContent) throws IOException, ServletException { final HttpServletRequest request = createNiceMock(HttpServletRequest.class); expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes(); expect(request.getRequestURL()).andReturn(new StringBuffer("/test/monitoring")).anyTimes(); expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); expect(request.getRemoteAddr()).andReturn("here").anyTimes(); final Random random = new Random(); if (random.nextBoolean()) { expect(request.getHeaders("Accept-Encoding")) .andReturn(Collections.enumeration(Arrays.asList("application/gzip"))).anyTimes(); } else {/*from ww w . j a v a 2 s .c o m*/ expect(request.getHeaders("Accept-Encoding")) .andReturn(Collections.enumeration(Arrays.asList("text/html"))).anyTimes(); } for (final Map.Entry<HttpParameter, String> entry : parameters.entrySet()) { if (HttpParameter.REQUEST == entry.getKey()) { expect(request.getHeader(entry.getKey().getName())).andReturn(entry.getValue()).anyTimes(); } else { expect(entry.getKey().getParameterFrom(request)).andReturn(entry.getValue()).anyTimes(); } } final Range range = Period.JOUR.getRange(); final List<JavaInformations> javaInformationsList = Collections .singletonList(new JavaInformations(null, false)); // getAttribute("range") et getAttribute("javaInformationsList") pour PdfController expect(request.getAttribute("range")).andReturn(range).anyTimes(); expect(request.getAttribute("javaInformationsList")).andReturn(javaInformationsList).anyTimes(); if (parameters.isEmpty() || HttpPart.JNLP.getName().equals(parameters.get(HttpParameter.PART))) { // dans au moins un cas on met un cookie final Cookie[] cookies = { new Cookie("dummy", "dummy"), new Cookie(PERIOD_COOKIE_NAME, Period.SEMAINE.getCode()), }; expect(request.getCookies()).andReturn(cookies).anyTimes(); } final HttpServletResponse response = createNiceMock(HttpServletResponse.class); final ByteArrayOutputStream output = new ByteArrayOutputStream(); expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(output)).anyTimes(); final StringWriter stringWriter = new StringWriter(); expect(response.getWriter()).andReturn(new PrintWriter(stringWriter)).anyTimes(); final FilterChain chain = createNiceMock(FilterChain.class); replay(request); replay(response); replay(chain); monitoringFilter.doFilter(request, response, chain); verify(request); verify(response); verify(chain); if (checkResultContent) { assertTrue("result", output.size() != 0 || stringWriter.getBuffer().length() != 0); } }
From source file:com.twinsoft.convertigo.beans.transactions.HtmlTransaction.java
@Override public String generateWsdlType(Document document) throws Exception { HtmlConnector connector = (HtmlConnector) getParent(); String prefix = getXsdTypePrefix(); // First regenerates wsdltype for default transaction : will contains all types!! if (!isDefault) { HtmlTransaction defaultTransaction = (HtmlTransaction) connector.getDefaultTransaction(); defaultTransaction.generateWsdlType(document); defaultTransaction.hasChanged = true; }/*from www.j ava 2 s .com*/ // Retrieve extraction rules schemas List<HtmlScreenClass> screenClasses = connector.getAllScreenClasses(); Map<String, ScreenClass> ht = new HashMap<String, ScreenClass>(screenClasses.size()); String normalizedScreenClassName; int i; for (ScreenClass screenClass : screenClasses) { normalizedScreenClassName = StringUtils.normalize(screenClass.getName()); ht.put(normalizedScreenClassName, screenClass); } Map<String, String> names = new HashMap<String, String>(); Map<String, String> types = new HashMap<String, String>(); List<String> schemas = new LinkedList<String>(); screenClass = connector.getDefaultScreenClass(); if (screenClass != null) { addExtractionRuleShemas(names, types, schemas, screenClass); } // Retrieve statements schemas for (Statement statement : getStatements()) { addStatementSchemas(schemas, statement); } // Construct transaction schema String transactionName = StringUtils.normalize(prefix + getName(), true) + "Response"; String schema = "<?xml version=\"1.0\" encoding=\"" + getEncodingCharSet() + "\" ?>\n"; schema += "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"; String all, obSchema; all = ""; for (i = 0; i < schemas.size(); i++) { obSchema = schemas.get(i); all += obSchema; } if (isDefault) { String group = ""; String groupName = StringUtils.normalize(connector.getName(), true) + "Types"; group += "<xsd:group name=\"" + groupName + "\">\n"; group += "<xsd:sequence>\n"; group += all; group += "</xsd:sequence>\n"; group += "</xsd:group>\n"; schema += "<xsd:complexType name=\"" + transactionName + "\">\n"; schema += "<xsd:sequence>\n"; schema += "<xsd:element minOccurs=\"0\" maxOccurs=\"1\" name=\"error\" type=\"p_ns:ConvertigoError\"/>\n"; schema += "<xsd:group minOccurs=\"0\" maxOccurs=\"1\" ref=\"p_ns:" + groupName + "\"/>\n"; schema += "</xsd:sequence>\n"; schema += "</xsd:complexType>\n"; schema += group; for (Enumeration<String> e = Collections.enumeration(types.keySet()); e.hasMoreElements();) { String typeSchema = (String) types.get(e.nextElement()); schema += typeSchema; } } else { schema += "<xsd:complexType name=\"" + transactionName + "\">\n"; schema += "<xsd:sequence>\n"; schema += "<xsd:element minOccurs=\"0\" maxOccurs=\"1\" name=\"error\" type=\"p_ns:ConvertigoError\"/>\n"; schema += all; schema += "</xsd:sequence>\n"; schema += "</xsd:complexType>\n"; } schema += "</xsd:schema>\n"; String prettyPrintedText = XMLUtils.prettyPrintDOM(schema); int index = prettyPrintedText.indexOf("<xsd:schema") + "<xsd:schema".length(); index = prettyPrintedText.indexOf('\n', index); prettyPrintedText = prettyPrintedText.substring(index + 1); prettyPrintedText = prettyPrintedText.substring(0, prettyPrintedText.indexOf("</xsd:schema>")); //prettyPrintedText = removeTab(prettyPrintedText); return prettyPrintedText; }
From source file:com.twinsoft.convertigo.eclipse.editors.connector.HtmlConnectorDesignComposite.java
private void parseHttpData(HTTPStatement httpStatement, String line, String method) { line = TextCodec.UTF8inURLDecode(line); //decode url variables StringTokenizer stData = new StringTokenizer(line, "&"); String left, right, name, value, dataName; Object ob, dataValue;//from w w w . j av a 2 s. c o m Map<String, Object> names; boolean bMulti; List<String> v; v = null; names = new HashMap<String, Object>(); while (stData.hasMoreTokens()) { String dataElement = stData.nextToken(); if (dataElement.indexOf('=') != -1) { left = dataElement.substring(0, dataElement.indexOf('=')); right = (dataElement.indexOf('=') < dataElement.length() ? dataElement.substring(dataElement.indexOf('=') + 1) : ""); name = left.trim(); value = right.trim(); if (names.containsKey(name)) { ob = names.get(name); if (ob instanceof String) { v = new ArrayList<String>(); v.add((String) ob); } else if (ob instanceof List) { v = GenericUtils.cast(ob); } if (v != null) { v.add(value); names.put(name, v); } } else { names.put(name, value); } } } for (Enumeration<String> e = Collections.enumeration(names.keySet()); e.hasMoreElements();) { dataName = e.nextElement(); dataValue = names.get(dataName); bMulti = dataValue instanceof List; httpStatement.addData(dataName, dataValue, bMulti, method); } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.SchedulerStateRest.java
@Override @GET//from w ww .j a v a 2 s. co m @GZIP @Path("jobs/{jobid}/log/full") @Produces("application/json") public InputStream jobFullLogs(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @QueryParam("sessionid") String session) throws NotConnectedRestException, UnknownJobRestException, UnknownTaskRestException, PermissionRestException, IOException { if (sessionId == null) { sessionId = session; } try { Scheduler scheduler = checkAccess(sessionId, "jobs/" + jobId + "/log/full"); JobState jobState = scheduler.getJobState(jobId); List<TaskState> tasks = jobState.getTasks(); List<InputStream> streams = new ArrayList<>(tasks.size()); Collections.sort(tasks, TaskState.COMPARE_BY_FINISHED_TIME_ASC); for (TaskState taskState : tasks) { InputStream inputStream = null; try { if (taskState.isPreciousLogs()) { inputStream = retrieveTaskLogsUsingDataspaces(sessionId, jobId, taskState.getId()); } else { String taskLogs = retrieveTaskLogsUsingDatabase(sessionId, jobId, taskState.getName()); if (!taskLogs.isEmpty()) { inputStream = IOUtils.toInputStream(taskLogs); } logger.warn("Retrieving truncated logs for task '" + taskState.getId() + "'"); } } catch (Exception e) { logger.info("Could not retrieve logs for task " + taskState.getId() + " (could be a non finished or killed task)", e); } if (inputStream != null) { streams.add(inputStream); } } if (streams.isEmpty()) { return null; // will produce HTTP 204 code } else { return new SequenceInputStream(Collections.enumeration(streams)); } } catch (PermissionException e) { throw new PermissionRestException(e); } catch (UnknownJobException e) { throw new UnknownJobRestException(e); } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } }