List of usage examples for java.util Collections list
public static <T> ArrayList<T> list(Enumeration<T> e)
From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java
private void doProcessRequest(Shuttle shuttle) throws IOException, ServletException, EngineException { shuttle.statisticsTaskID = context.statistics.start(EngineStatistics.GET_DOCUMENT); try {//from w ww. ja v a 2s.c o m shuttle.sharedScope = context.getSharedScope(); String domain = shuttle.getRequest(QueryPart.host) + shuttle.getRequest(QueryPart.port); Engine.logSiteClipper.trace("(SiteClipperConnector) Prepare the request for the domain " + domain); if (!shouldRewrite(domain)) { Engine.logSiteClipper.info( "(SiteClipperConnector) The domain " + domain + " is not allowed with this connector"); shuttle.response.sendError(HttpServletResponse.SC_FORBIDDEN, "The domain " + domain + " is not allowed with this connector"); return; } String uri = shuttle.getRequest(QueryPart.uri); Engine.logSiteClipper.info("Preparing " + shuttle.request.getMethod() + " " + shuttle.getRequestUrl()); HttpMethod httpMethod = null; XulRecorder xulRecorder = context.getXulRecorder(); if (xulRecorder != null) { httpMethod = shuttle.httpMethod = xulRecorder.getRecord(shuttle.getRequestUrlAndQuery()); } if (httpMethod == null) { try { switch (shuttle.getRequestHttpMethodType()) { case GET: httpMethod = new GetMethod(uri); break; case POST: httpMethod = new PostMethod(uri); ((PostMethod) httpMethod) .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream())); break; case PUT: httpMethod = new PutMethod(uri); ((PutMethod) httpMethod) .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream())); break; case DELETE: httpMethod = new DeleteMethod(uri); break; case HEAD: httpMethod = new HeadMethod(uri); break; case OPTIONS: httpMethod = new OptionsMethod(uri); break; case TRACE: httpMethod = new TraceMethod(uri); break; default: throw new ServletException( "(SiteClipperConnector) unknown http method " + shuttle.request.getMethod()); } httpMethod.setFollowRedirects(false); } catch (Exception e) { throw new ServletException( "(SiteClipperConnector) unexpected exception will building the http method : " + e.getMessage()); } shuttle.httpMethod = httpMethod; SiteClipperScreenClass screenClass = getCurrentScreenClass(); Engine.logSiteClipper.info("Request screen class: " + screenClass.getName()); for (String name : Collections .list(GenericUtils.<Enumeration<String>>cast(shuttle.request.getHeaderNames()))) { if (requestHeadersToIgnore.contains(HeaderName.parse(name))) { Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring request header " + name); } else { String value = shuttle.request.getHeader(name); Engine.logSiteClipper .trace("(SiteClipperConnector) Copying request header " + name + "=" + value); shuttle.setRequestCustomHeader(name, value); } } Engine.logSiteClipper.debug("(SiteClipperConnector) applying request rules for the screenclass " + screenClass.getName()); for (IRequestRule rule : screenClass.getRequestRules()) { if (rule.isEnabled()) { Engine.logSiteClipper .trace("(SiteClipperConnector) applying request rule " + rule.getName()); rule.fireEvents(); boolean done = rule.applyOnRequest(shuttle); Engine.logSiteClipper.debug("(SiteClipperConnector) the request rule " + rule.getName() + " is " + (done ? "well" : "not") + " applied"); } else { Engine.logSiteClipper .trace("(SiteClipperConnector) skip the disabled request rule " + rule.getName()); } } for (Entry<String, String> header : shuttle.requestCustomHeaders.entrySet()) { Engine.logSiteClipper.trace("(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue()); httpMethod.addRequestHeader(header.getKey(), header.getValue()); } String queryString = shuttle.request.getQueryString(); if (queryString != null) { try { // Fake test in order to check query string validity new URI("http://localhost/index?" + queryString, true, httpMethod.getParams().getUriCharset()); } catch (URIException e) { // Bugfix #2103 StringBuffer newQuery = new StringBuffer(); for (String part : RegexpUtils.pattern_and.split(queryString)) { String[] pair = RegexpUtils.pattern_equals.split(part, 2); try { newQuery.append('&') .append(URLEncoder.encode(URLDecoder.decode(pair[0], "UTF-8"), "UTF-8")); if (pair.length > 1) { newQuery.append('=').append( URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")); } } catch (UnsupportedEncodingException ee) { Engine.logSiteClipper .trace("(SiteClipperConnector) failed to encode query part : " + part); } } queryString = newQuery.length() > 0 ? newQuery.substring(1) : newQuery.toString(); Engine.logSiteClipper.trace("(SiteClipperConnector) re-encode query : " + queryString); } } Engine.logSiteClipper.debug("(SiteClipperConnector) Copying the query string : " + queryString); httpMethod.setQueryString(queryString); // if (context.httpState == null) { // Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID); // context.httpState = new HttpState(); // } else { // Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID); // } getHttpState(shuttle); HostConfiguration hostConfiguration = getHostConfiguration(shuttle); HttpMethodParams httpMethodParams = httpMethod.getParams(); httpMethodParams.setBooleanParameter("http.connection.stalecheck", true); httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); Engine.logSiteClipper.info("Requesting " + httpMethod.getName() + " " + hostConfiguration.getHostURL() + httpMethod.getURI().toString()); HttpClient httpClient = context.getHttpClient3(shuttle.getHttpPool()); HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, shuttle.getHttpPool()); httpClient.executeMethod(hostConfiguration, httpMethod, context.httpState); } else { Engine.logSiteClipper.info("Retrieve recorded response from Context"); } int status = httpMethod.getStatusCode(); shuttle.processState = ProcessState.response; Engine.logSiteClipper.info("Request terminated with status " + status); shuttle.response.setStatus(status); if (Engine.isStudioMode() && status == HttpServletResponse.SC_OK && shuttle.getResponseMimeType().startsWith("text/")) { fireDataChanged(new ConnectorEvent(this, shuttle.getResponseAsString())); } SiteClipperScreenClass screenClass = getCurrentScreenClass(); Engine.logSiteClipper.info("Response screen class: " + screenClass.getName()); if (Engine.isStudioMode()) { Engine.theApp.fireObjectDetected(new EngineEvent(screenClass)); } for (Header header : httpMethod.getResponseHeaders()) { String name = header.getName(); if (responseHeadersToIgnore.contains(HeaderName.parse(name))) { Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring response header " + name); } else { String value = header.getValue(); Engine.logSiteClipper .trace("(SiteClipperConnector) Copying response header " + name + "=" + value); shuttle.responseCustomHeaders.put(name, value); } } Engine.logSiteClipper.debug( "(SiteClipperConnector) applying response rules for the screenclass " + screenClass.getName()); for (IResponseRule rule : screenClass.getResponseRules()) { if (rule.isEnabled()) { Engine.logSiteClipper.trace("(SiteClipperConnector) applying response rule " + rule.getName()); rule.fireEvents(); boolean done = rule.applyOnResponse(shuttle); Engine.logSiteClipper.debug("(SiteClipperConnector) the response rule " + rule.getName() + " is " + (done ? "well" : "not") + " applied"); } else { Engine.logSiteClipper .trace("(SiteClipperConnector) skip the disabled response rule " + rule.getName()); } } for (Entry<String, String> header : shuttle.responseCustomHeaders.entrySet()) { Engine.logSiteClipper.trace( "(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue()); shuttle.response.addHeader(header.getKey(), header.getValue()); } if (shuttle.postInstructions != null) { JSONArray instructions = new JSONArray(); for (IClientInstruction instruction : shuttle.postInstructions) { try { instructions.put(instruction.getInstruction()); } catch (JSONException e) { Engine.logSiteClipper.error( "(SiteClipperConnector) Failed to add a post instruction due to a JSONException", e); } } String codeToInject = "<script>C8O_postInstructions = " + instructions.toString() + "</script>\n" + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path) + "/scripts/jquery.min.js\"></script>\n" + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path) + "/scripts/siteclipper.js\"></script>\n"; String content = shuttle.getResponseAsString(); Matcher matcher = HtmlLocation.head_top.matcher(content); String newContent = RegexpUtils.inject(matcher, codeToInject); if (newContent == null) { matcher = HtmlLocation.body_top.matcher(content); newContent = RegexpUtils.inject(matcher, codeToInject); } if (newContent != null) { shuttle.setResponseAsString(newContent); } else { Engine.logSiteClipper.info( "(SiteClipperConnector) Failed to find a head or body tag in the response content"); Engine.logSiteClipper.trace("(SiteClipperConnector) Response content : \"" + content + "\""); } } long nbBytes = 0L; if (shuttle.responseAsString != null && shuttle.responseAsString.hashCode() != shuttle.responseAsStringOriginal.hashCode()) { OutputStream os = shuttle.response.getOutputStream(); switch (shuttle.getResponseContentEncoding()) { case gzip: os = new GZIPOutputStream(os); break; case deflate: os = new DeflaterOutputStream(os, new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true)); break; default: break; } nbBytes = shuttle.responseAsByte.length; IOUtils.write(shuttle.responseAsString, os, shuttle.getResponseCharset()); os.close(); } else { InputStream is = (shuttle.responseAsByte == null) ? httpMethod.getResponseBodyAsStream() : new ByteArrayInputStream(shuttle.responseAsByte); if (is != null) { nbBytes = 0; OutputStream os = shuttle.response.getOutputStream(); int read = is.read(); while (read >= 0) { os.write(read); os.flush(); read = is.read(); nbBytes++; } is.close(); // nbBytes = IOUtils.copyLarge(is, shuttle.response.getOutputStream()); Engine.logSiteClipper .trace("(SiteClipperConnector) Response body copyied (" + nbBytes + " bytes)"); } } shuttle.response.getOutputStream().close(); shuttle.score = getScore(nbBytes); Engine.logSiteClipper .debug("(SiteClipperConnector) Request terminated with a score of " + shuttle.score); } finally { long duration = context.statistics.stop(shuttle.statisticsTaskID); if (context.requestedObject != null) { try { Engine.theApp.billingManager.insertBilling(context, Long.valueOf(duration), Long.valueOf(shuttle.score)); } catch (Exception e) { Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): [" + e.getClass().getName() + "] " + e.getMessage()); } } } }
From source file:net.spfbl.core.Core.java
private static boolean hasInterface(String netInterface) { try {//from ww w .j av a 2s . c o m Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) { if (netInterface.equals(netint.getName())) { return true; } } return false; } catch (SocketException ex) { return false; } }
From source file:in.andres.kandroid.ui.TaskDetailActivity.java
private void showSubtaskDialog(@Nullable final KanboardSubtask subtask) { View dlgView = getLayoutInflater().inflate(R.layout.dialog_new_subtask, null); final EditText editTitle = (EditText) dlgView.findViewById(R.id.subtask_title); editTitle.setText(subtask == null ? "" : subtask.getTitle()); final Spinner userSpinner = (Spinner) dlgView.findViewById(R.id.user_spinner); ArrayList<String> possibleOwners = Collections.list(users.elements()); possibleOwners.add(0, ""); ArrayAdapter<String> adapter = new ArrayAdapter<>(self, android.R.layout.simple_spinner_item, possibleOwners);//from w w w .java 2 s . co m adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); userSpinner.setAdapter(adapter); if (subtask != null) userSpinner.setSelection(possibleOwners.indexOf(users.get(subtask.getUserId()))); AlertDialog.Builder builder = new AlertDialog.Builder(self); builder.setTitle(getString( subtask == null ? R.string.taskview_fab_new_subtask : R.string.taskview_dlg_update_subtask)); builder.setView(dlgView); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Integer userid = null; if (userSpinner.getSelectedItem() != null) { for (Enumeration<Integer> iter = users.keys(); iter.hasMoreElements();) { Integer key = iter.nextElement(); if (users.get(key).contentEquals((String) userSpinner.getSelectedItem())) { userid = key; break; } } } if (!editTitle.getText().toString().equalsIgnoreCase("")) { if (subtask == null) { Log.i(Constants.TAG, "Creating new subtask."); kanboardAPI.createSubtask(task.getId(), editTitle.getText().toString(), userid, null, null, null); } else { Log.i(Constants.TAG, "Updating subtask."); kanboardAPI.updateSubtask(subtask.getId(), subtask.getTaskId(), editTitle.getText().toString(), userid, null, null, null); } dialog.dismiss(); } } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); }
From source file:org.springframework.boot.SpringApplication.java
/** * Convenient alternative to {@link #setDefaultProperties(Map)}. * @param defaultProperties some {@link Properties} *//*from ww w . j a v a 2s . co m*/ public void setDefaultProperties(Properties defaultProperties) { this.defaultProperties = new HashMap<String, Object>(); for (Object key : Collections.list(defaultProperties.propertyNames())) { this.defaultProperties.put((String) key, defaultProperties.get(key)); } }
From source file:org.jasig.portal.layout.dlm.DistributedLayoutManager.java
protected boolean canAddNode(IUserLayoutNodeDescription node, IUserLayoutNodeDescription parent, String nextSiblingId) throws PortalException { // make sure sibling exists and is a child of nodeId if (nextSiblingId != null && !nextSiblingId.equals("")) { IUserLayoutNodeDescription sibling = getNode(nextSiblingId); if (sibling == null) { throw new PortalException("Unable to find a sibling node " + "with id=\"" + nextSiblingId + "\". Occurred " + "in layout for " + owner.getAttribute(IPerson.USERNAME) + "."); }//w w w .j a v a 2 s. co m if (!parent.getId().equals(getParentId(nextSiblingId))) { throw new PortalException("Given sibling (\"" + nextSiblingId + "\") is not a child of a given parentId (\"" + parent.getId() + "\"). Occurred " + "in layout for " + owner.getAttribute(IPerson.USERNAME) + "."); } } if (parent == null || !node.isMoveAllowed()) return false; if (parent instanceof IUserLayoutFolderDescription && !((IUserLayoutFolderDescription) parent).isAddChildAllowed()) return false; if (nextSiblingId == null || nextSiblingId.equals("")) // end of list targeted return true; // so lets see if we can place it at the end of the sibling list and // hop left until we get into the correct position. Enumeration sibIds = getVisibleChildIds(parent.getId()); List sibs = Collections.list(sibIds); if (sibs.size() == 0) // last node in list so should be ok return true; // reverse scan so that as changes are made the order of the, as yet, // unprocessed nodes is not altered. for (int idx = sibs.size() - 1; idx >= 0; idx--) { IUserLayoutNodeDescription prev = getNode((String) sibs.get(idx)); if (!MovementRules.canHopLeft(node, prev)) return false; if (prev.getId().equals(nextSiblingId)) return true; } return false; // oops never found the sib }
From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java
protected boolean canAddNode(IUserLayoutNodeDescription node, IUserLayoutNodeDescription parent, String nextSiblingId) throws PortalException { // make sure sibling exists and is a child of nodeId if (nextSiblingId != null && !nextSiblingId.equals("")) { IUserLayoutNodeDescription sibling = getNode(nextSiblingId); if (sibling == null) { throw new PortalException("Unable to find a sibling node " + "with id=\"" + nextSiblingId + "\". Occurred " + "in layout for " + owner.getAttribute(IPerson.USERNAME) + "."); }//from w w w. jav a 2 s .c o m if (!parent.getId().equals(getParentId(nextSiblingId))) { throw new PortalException("Given sibling (\"" + nextSiblingId + "\") is not a child of a given parentId (\"" + parent.getId() + "\"). Occurred " + "in layout for " + owner.getAttribute(IPerson.USERNAME) + "."); } } // todo if isFragmentOwner should probably verify both node and parent are part of the // same layout fragment as the fragment owner to insure a misbehaving front-end doesn't // do an improper operation. if (parent == null || !(node.isMoveAllowed() || isFragmentOwner)) return false; if (parent instanceof IUserLayoutFolderDescription && !(((IUserLayoutFolderDescription) parent).isAddChildAllowed()) && !isFragmentOwner) return false; if (nextSiblingId == null || nextSiblingId.equals("")) // end of list targeted return true; // so lets see if we can place it at the end of the sibling list and // hop left until we get into the correct position. Enumeration sibIds = getVisibleChildIds(parent.getId()); List sibs = Collections.list(sibIds); if (sibs.size() == 0) // last node in list so should be ok return true; // reverse scan so that as changes are made the order of the, as yet, // unprocessed nodes is not altered. for (int idx = sibs.size() - 1; idx >= 0; idx--) { IUserLayoutNodeDescription prev = getNode((String) sibs.get(idx)); if (!isFragmentOwner && !MovementRules.canHopLeft(node, prev)) return false; if (prev.getId().equals(nextSiblingId)) return true; } return false; // oops never found the sib }
From source file:cn.remex.core.util.StringUtils.java
/** * ???//from ww w. j a v a 2 s . c o m * Copy the given Enumeration into a String array. * The Enumeration must contain String elements only. * @param enumeration the Enumeration to copy * @return the String array (<code>null</code> if the passed-in * Enumeration was <code>null</code>) nullnull */ public static String[] toStringArray(final Enumeration<?> enumeration) { if (enumeration == null) { return null; } List<?> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); }
From source file:org.opencms.workplace.tools.workplace.logging.CmsLog4JAdminDialog.java
/** * Help function to get all loggers from LogManager.<p> * * @return List of Logger//from w ww .j av a 2s .com */ private List<Logger> getLoggers() { // list of all loggers List<Logger> definedLoggers = new ArrayList<Logger>(); // list of all parent loggers List<Logger> packageLoggers = new ArrayList<Logger>(); @SuppressWarnings("unchecked") List<Logger> curentloggerlist = Collections.list(LogManager.getCurrentLoggers()); Iterator<Logger> it_curentlogger = curentloggerlist.iterator(); // get all current loggers while (it_curentlogger.hasNext()) { // get the logger Logger log = it_curentlogger.next(); String logname = log.getName(); String[] prefix = buildsufix(logname); // create all possible package logger from given logger name for (int i = 0; i < prefix.length; i++) { // get the name of the logger without the prefix String temp = log.getName().replace(prefix[i], ""); // if the name has suffix if (temp.length() > 1) { temp = temp.substring(1); } if (temp.lastIndexOf(".") > 1) { // generate new logger with "org.opencms" prefix and the next element // between the points e.g.: "org.opencms.search" Logger temp_logger = Logger.getLogger(prefix[i] + "." + temp.substring(0, temp.indexOf("."))); // activate the heredity so the logger get the appender from parent logger temp_logger.setAdditivity(true); // add the logger to the packageLoggers list if it is not part of it if (!packageLoggers.contains(temp_logger)) { packageLoggers.add(temp_logger); } } } definedLoggers.add(log); } Iterator<Logger> it_logger = packageLoggers.iterator(); // iterate about all packageLoggers while (it_logger.hasNext()) { Logger temp = it_logger.next(); // check if the logger is part of the logger list if (!definedLoggers.contains(temp)) { // add the logger to the logger list definedLoggers.add(temp); } } // sort all loggers by name Collections.sort(definedLoggers, new Comparator<Object>() { public int compare(Logger o1, Logger o2) { return String.CASE_INSENSITIVE_ORDER.compare(o1.getName(), o2.getName()); } public int compare(Object obj, Object obj1) { return compare((Logger) obj, (Logger) obj1); } }); // return all loggers return definedLoggers; }
From source file:org.batoo.common.util.StringUtils.java
/** * Copy the given Enumeration into a String array. The Enumeration must contain String elements only. * /* ww w . j a va2 s. co m*/ * @param enumeration * the Enumeration to copy * @return the String array (<code>null</code> if the passed-in Enumeration was <code>null</code>) */ public static String[] toStringArray(Enumeration<String> enumeration) { if (enumeration == null) { return null; } final List<String> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); }
From source file:org.jasig.portal.layout.dlm.DistributedLayoutManager.java
private boolean canMoveRight(String nodeId, String targetNextSibId) throws PortalException { IUserLayoutNodeDescription node = getNode(nodeId); Enumeration sibIds = getVisibleChildIds(getParentId(nodeId)); List sibs = Collections.list(sibIds); for (int idx = sibs.indexOf(nodeId) + 1; idx > 0 && idx < sibs.size(); idx++) { String nextSibId = (String) sibs.get(idx); IUserLayoutNodeDescription next = getNode(nextSibId); if (nextSibId != null && next.getId().equals(targetNextSibId)) return true; else if (!MovementRules.canHopRight(node, next)) return false; }//w w w .ja va 2 s . co m if (targetNextSibId == null) // made it to end of sib list and return true; // that is the desired location return false; // oops never found the sib. Should never happen. }