List of usage examples for java.util Hashtable entrySet
Set entrySet
To view the source code for java.util Hashtable entrySet.
Click Source Link
From source file:solidstack.reflect.Dumper.java
public void dumpTo(Object o, DumpWriter out) { try {/*from w w w . j ava2s . c o m*/ if (o == null) { out.append("<null>"); return; } Class<?> cls = o.getClass(); if (cls == String.class) { out.append("\"").append(((String) o).replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r") .replace("\t", "\\t").replace("\"", "\\\"")).append("\""); return; } if (o instanceof CharSequence) { out.append("(").append(o.getClass().getName()).append(")"); dumpTo(o.toString(), out); return; } if (cls == char[].class) { out.append("(char[])"); dumpTo(String.valueOf((char[]) o), out); return; } if (cls == byte[].class) { out.append("byte[").append(Integer.toString(((byte[]) o).length)).append("]"); return; } if (cls == Class.class) { out.append(((Class<?>) o).getCanonicalName()).append(".class"); return; } if (cls == File.class) { out.append("File( \"").append(((File) o).getPath()).append("\" )"); return; } if (cls == AtomicInteger.class) { out.append("AtomicInteger( ").append(Integer.toString(((AtomicInteger) o).get())).append(" )"); return; } if (cls == AtomicLong.class) { out.append("AtomicLong( ").append(Long.toString(((AtomicLong) o).get())).append(" )"); return; } if (o instanceof ClassLoader) { out.append(o.getClass().getCanonicalName()); return; } if (cls == java.lang.Short.class || cls == java.lang.Long.class || cls == java.lang.Integer.class || cls == java.lang.Float.class || cls == java.lang.Byte.class || cls == java.lang.Character.class || cls == java.lang.Double.class || cls == java.lang.Boolean.class || cls == BigInteger.class || cls == BigDecimal.class) { out.append("(").append(cls.getSimpleName()).append(")").append(o.toString()); return; } String className = cls.getCanonicalName(); if (className == null) className = cls.getName(); out.append(className); if (this.skip.contains(className) || o instanceof java.lang.Thread) { out.append(" (skipped)"); return; } Integer id = this.visited.get(o); if (id == null) { id = ++this.id; this.visited.put(o, id); if (!this.hideIds) out.append(" <id=" + id + ">"); } else { out.append(" <refid=" + id + ">"); return; } if (cls.isArray()) { if (Array.getLength(o) == 0) out.append(" []"); else { out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst(); int rowCount = Array.getLength(o); for (int i = 0; i < rowCount; i++) { out.comma(); dumpTo(Array.get(o, i), out); } out.newlineOrSpace().unIndent().append("]"); } } else if (o instanceof Collection && !this.overriddenCollection.contains(className)) { Collection<?> list = (Collection<?>) o; if (list.isEmpty()) out.append(" []"); else { out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst(); for (Object value : list) { out.comma(); dumpTo(value, out); } out.newlineOrSpace().unIndent().append("]"); } } else if (o instanceof Properties && !this.overriddenCollection.contains(className)) // Properties is a Map, so it must come before the Map { Field def = cls.getDeclaredField("defaults"); if (!def.isAccessible()) def.setAccessible(true); Properties defaults = (Properties) def.get(o); Hashtable<?, ?> map = (Hashtable<?, ?>) o; out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst(); for (Map.Entry<?, ?> entry : map.entrySet()) { out.comma(); dumpTo(entry.getKey(), out); out.append(": "); dumpTo(entry.getValue(), out); } if (defaults != null && !defaults.isEmpty()) { out.comma().append("defaults: "); dumpTo(defaults, out); } out.newlineOrSpace().unIndent().append("]"); } else if (o instanceof Map && !this.overriddenCollection.contains(className)) { Map<?, ?> map = (Map<?, ?>) o; if (map.isEmpty()) out.append(" []"); else { out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst(); for (Map.Entry<?, ?> entry : map.entrySet()) { out.comma(); dumpTo(entry.getKey(), out); out.append(": "); dumpTo(entry.getValue(), out); } out.newlineOrSpace().unIndent().append("]"); } } else if (o instanceof Method) { out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst(); Field field = cls.getDeclaredField("clazz"); if (!field.isAccessible()) field.setAccessible(true); out.comma().append("clazz").append(": "); dumpTo(field.get(o), out); field = cls.getDeclaredField("name"); if (!field.isAccessible()) field.setAccessible(true); out.comma().append("name").append(": "); dumpTo(field.get(o), out); field = cls.getDeclaredField("parameterTypes"); if (!field.isAccessible()) field.setAccessible(true); out.comma().append("parameterTypes").append(": "); dumpTo(field.get(o), out); field = cls.getDeclaredField("returnType"); if (!field.isAccessible()) field.setAccessible(true); out.comma().append("returnType").append(": "); dumpTo(field.get(o), out); out.newlineOrSpace().unIndent().append("}"); } else { ArrayList<Field> fields = new ArrayList<Field>(); while (cls != Object.class) { Field[] fs = cls.getDeclaredFields(); for (Field field : fs) fields.add(field); cls = cls.getSuperclass(); } Collections.sort(fields, new Comparator<Field>() { public int compare(Field left, Field right) { return left.getName().compareTo(right.getName()); } }); if (fields.isEmpty()) out.append(" {}"); else { out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst(); for (Field field : fields) if ((field.getModifiers() & Modifier.STATIC) == 0) if (!this.hideTransients || (field.getModifiers() & Modifier.TRANSIENT) == 0) { out.comma().append(field.getName()).append(": "); if (!field.isAccessible()) field.setAccessible(true); if (field.getType().isPrimitive()) if (field.getType() == boolean.class) // TODO More? out.append(field.get(o).toString()); else out.append("(").append(field.getType().getName()).append(")") .append(field.get(o).toString()); else dumpTo(field.get(o), out); } out.newlineOrSpace().unIndent().append("}"); } } } catch (IOException e) { throw new FatalIOException(e); } catch (Exception e) { dumpTo(e.toString(), out); } }
From source file:org.mahasen.MahasenStorage.java
/** * @param resource//from w ww . j a v a2 s . co m * @param mahasenResource * @return * @throws RegistryException */ private Resource addResourceProperties(Resource resource, MahasenResource mahasenResource) throws RegistryException { try { registry = Activator.getRegistryService().getRegistry("admin", "admin"); } catch (Exception e) { e.printStackTrace(); } for (Map.Entry<String, String> entry : mahasenResource.getProperties().entrySet()) { resource.addProperty(entry.getKey(), entry.getValue()); log.info("property " + entry.getKey() + " =" + entry.getValue() + " adding to resource"); log.info(resource.getProperty(entry.getKey()) + "was added to Resource"); } resource.addProperty(MahasenConstants.FILE_SIZE, String.valueOf(mahasenResource.getFileSize())); log.debug("date added to registry resource " + String.valueOf(mahasenResource.getUploadedDate())); resource.addProperty(MahasenConstants.UPLOADED_DATE, String.valueOf(mahasenResource.getUploadedDate())); String partNames = mahasenResource.getPartNames().toString(); if (mahasenResource.getPartNames().size() != 0) { resource.addProperty(MahasenConstants.PART_NAMES, partNames.substring(1, partNames.length() - 1)); } Hashtable<String, Vector<String>> partsIpTable = mahasenResource.getSplittedPartsIpTable(); if (partsIpTable.entrySet() != null) { for (Map.Entry<String, Vector<String>> entry : partsIpTable.entrySet()) { String entryValue = entry.getValue().toString(); resource.addProperty(entry.getKey(), entryValue.substring(1, entryValue.length() - 1)); System.out.println("parts Ip table entry " + entry.getKey() + " = " + entry.getValue().toString()); } } return resource; }
From source file:fi.laverca.util.CommonsHTTPSender.java
/** * Extracts info from message context.//from w w w . j a v a 2 s. c om * * @param method Post method * @param httpClient The client used for posting * @param msgContext the message context * @param tmpURL the url to post to. * * @throws Exception if any error occurred */ private void addContextInfo(final HttpPost method, final HttpClient httpClient, final MessageContext msgContext, final URL tmpURL) throws Exception { HttpParams params = method.getParams(); if (msgContext.getTimeout() != 0) { // optionally set a timeout for response waits HttpConnectionParams.setSoTimeout(params, msgContext.getTimeout()); } // Always set the 30 second timeout on establishing the connection HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); Message msg = msgContext.getRequestMessage(); if (msg != null) { method.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants())); } if (msgContext.useSOAPAction()) { // define SOAPAction header String action = msgContext.getSOAPActionURI(); if (action != null && !"".equals(action)) method.setHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""); } String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd); // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCred); } // add compression headers if needed if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) { method.addHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { method.addHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP); } // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator<?> i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set. //Let's not duplicate them. String headerName = mimeHeader.getName(); if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) { continue; } method.addHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable<?, ?> userHeaderTable = (Hashtable<?, ?>) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (Iterator<?> e = userHeaderTable.entrySet().iterator(); e.hasNext();) { Map.Entry<?, ?> me = (Map.Entry<?, ?>) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) { HttpProtocolParams.setUseExpectContinue(params, true); } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { String val = me.getValue().toString(); if (null != val) { httpChunkStream = JavaUtils.isTrue(val); } } else { method.addHeader(key, value); } } } }
From source file:com.openmeap.http.FileHandlingHttpRequestExecuterImpl.java
@Override public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams) throws HttpRequestException { // test to determine whether this is a file upload or not. Boolean isFileUpload = false; for (Object o : postParams.values()) { if (o instanceof File) { isFileUpload = true;//from w ww .j a v a2 s. c o m break; } } if (isFileUpload) { try { HttpPost httpPost = new HttpPost(createUrl(url, getParams)); httpPost.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Object o : postParams.entrySet()) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o; if (entry.getValue() instanceof File) { // For File parameters File file = (File) entry.getValue(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(file.toURL().toString()); entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type)); } else { // For usual String parameters entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain", Charset.forName(FormConstants.CHAR_ENC_DEFAULT))); } } httpPost.setEntity(entity); return execute(httpPost); } catch (Exception e) { throw new HttpRequestException(e); } } else { return super.postData(url, getParams, postParams); } }
From source file:org.alfresco.test.util.SiteService.java
/** * Add dashlet to site dashboard/* ww w . j av a 2 s . c o m*/ * * @param userName String identifier * @param password * @param siteName * @param dashlet * @param layout * @param column * @param position * @return true if the dashlet is added * @throws Exception if error */ public boolean addDashlet(final String userName, final String password, final String siteName, final SiteDashlet dashlet, final DashletLayout layout, final int column, final int position) throws Exception { if (!exists(siteName, userName, password)) { throw new RuntimeException("Site doesn't exists " + siteName); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String url = client.getAlfrescoUrl() + DashboardCustomization.ADD_DASHLET_URL; org.json.JSONObject body = new org.json.JSONObject(); org.json.JSONArray array = new org.json.JSONArray(); body.put("dashboardPage", "site/" + siteName + "/dashboard"); body.put("templateId", layout.id); Hashtable<String, String> defaultDashlets = new Hashtable<String, String>(); defaultDashlets.put(SiteDashlet.SITE_MEMBERS.id, "component-1-1"); defaultDashlets.put(SiteDashlet.SITE_CONNTENT.id, "component-2-1"); defaultDashlets.put(SiteDashlet.SITE_ACTIVITIES.id, "component-2-2"); Iterator<Map.Entry<String, String>> entries = defaultDashlets.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); org.json.JSONObject jDashlet = new org.json.JSONObject(); jDashlet.put("url", entry.getKey()); jDashlet.put("regionId", entry.getValue()); jDashlet.put("originalRegionId", entry.getValue()); array.put(jDashlet); } org.json.JSONObject newDashlet = new org.json.JSONObject(); newDashlet.put("url", dashlet.id); String region = "component-" + column + "-" + position; newDashlet.put("regionId", region); array.put(newDashlet); body.put("dashlets", array); HttpPost post = new HttpPost(url); StringEntity se = new StringEntity(body.toString(), AlfrescoHttpClient.UTF_8_ENCODING); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON)); post.setEntity(se); HttpClient clientWithAuth = client.getHttpClientWithBasicAuth(userName, password); try { HttpResponse response = clientWithAuth.execute(post); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { if (logger.isTraceEnabled()) { logger.trace("Dashlet " + dashlet.name + " was added to site " + siteName); } return true; } else { logger.error("Unable to add dashlet to site " + siteName); } } finally { post.releaseConnection(); client.close(); } return false; }
From source file:com.epic.framework.implementation.tapjoy.TapjoyURLConnection.java
/** * Performs a network request call using HTTP POST to the specified URL and parameters. * // w w w . j av a 2 s. c o m * @param url The URL to connect to. * @param params POST parameters in key/value format. * @param paramsData Any additional POST parameters in key/value format. * @return Response from the server. */ public String connectToURLwithPOST(String url, Hashtable<String, String> params, Hashtable<String, String> paramsData) { String httpResponse = null; try { String requestURL = url; // Replaces all spaces. requestURL = requestURL.replaceAll(" ", "%20"); TapjoyLog.i(TAPJOY_URL_CONNECTION, "baseURL: " + url); TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL); HttpPost httpPost = new HttpPost(requestURL); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); Set<Entry<String, String>> entries = params.entrySet(); Iterator<Entry<String, String>> iterator = entries.iterator(); while (iterator.hasNext()) { Entry<String, String> item = iterator.next(); pairs.add(new BasicNameValuePair(item.getKey(), item.getValue())); TapjoyLog.i(TAPJOY_URL_CONNECTION, "key: " + item.getKey() + ", value: " + Uri.encode(item.getValue())); } if (paramsData != null && paramsData.size() > 0) { entries = paramsData.entrySet(); iterator = entries.iterator(); while (iterator.hasNext()) { Entry<String, String> item = iterator.next(); pairs.add(new BasicNameValuePair("data[" + item.getKey() + "]", item.getValue())); TapjoyLog.i(TAPJOY_URL_CONNECTION, "key: " + item.getKey() + ", value: " + Uri.encode(item.getValue())); } } httpPost.setEntity(new UrlEncodedFormEntity(pairs)); TapjoyLog.i(TAPJOY_URL_CONNECTION, "HTTP POST: " + httpPost.toString()); // Create a HttpParams object so we can set our timeout times. HttpParams httpParameters = new BasicHttpParams(); // Time to wait to establish initial connection. HttpConnectionParams.setConnectionTimeout(httpParameters, 15000); // Time to wait for incoming data. HttpConnectionParams.setSoTimeout(httpParameters, 30000); // Create a http client with out timeout settings. HttpClient client = new DefaultHttpClient(httpParameters); HttpResponse response = client.execute(httpPost); HttpEntity entity = response.getEntity(); httpResponse = EntityUtils.toString(entity); TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------"); TapjoyLog.i(TAPJOY_URL_CONNECTION, "response status: " + response.getStatusLine().getStatusCode()); TapjoyLog.i(TAPJOY_URL_CONNECTION, "response size: " + httpResponse.length()); TapjoyLog.i(TAPJOY_URL_CONNECTION, "response: "); TapjoyLog.i(TAPJOY_URL_CONNECTION, "" + httpResponse); TapjoyLog.i(TAPJOY_URL_CONNECTION, "--------------------"); } catch (Exception e) { TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString()); } return httpResponse; }
From source file:org.unitime.commons.hibernate.util.DatabaseUpdate.java
public boolean performUpdate(Element updateElement) { int version = Integer.parseInt(updateElement.attributeValue("version")); Session hibSession = new _RootDAO().getSession(); String schema = _RootDAO.getConfiguration().getProperty("default_schema"); Transaction tx = null;//www . jav a 2 s. co m Hashtable variables = new Hashtable(); try { tx = hibSession.beginTransaction(); sLog.info(" Performing " + updateName() + " update to version " + version + " (" + updateElement.attributeValue("comment") + ")"); for (Iterator i = updateElement.elementIterator(); i.hasNext();) { Element queryElement = (Element) i.next(); String type = queryElement.getName(); String query = queryElement.getText().trim().replaceAll("%SCHEMA%", schema); for (Iterator j = variables.entrySet().iterator(); j.hasNext();) { Map.Entry entry = (Map.Entry) j.next(); query = query.replaceAll("%" + entry.getKey() + "%", entry.getValue().toString()); } String condition = queryElement.attributeValue("condition", "none"); String action = queryElement.attributeValue("action", "next"); String value = queryElement.attributeValue("value"); String into = queryElement.attributeValue("into"); if (queryElement.attribute("onFail") != null) { condition = "fail"; action = queryElement.attributeValue("onFail"); } if (queryElement.attribute("onEqual") != null) { condition = "equal"; action = queryElement.attributeValue("onEqual"); } if (queryElement.attribute("onNotEqual") != null) { condition = "notEqual"; action = queryElement.attributeValue("onNotEqual"); } if (query.length() == 0) continue; try { if (type.equals("hql") || type.equals("sql") || type.equals(iDialectSQL)) { sLog.debug(" -- HQL: " + query + " (con:" + condition + ", act:" + action + ", val:" + value + ")"); Query q = null; try { q = (type.equals("hql") ? hibSession.createQuery(query) : hibSession.createSQLQuery(query)); } catch (QueryException e) { // Work-around Hibernate issue HHH-2697 (https://hibernate.onjira.com/browse/HHH-2697) if (!"hql".equals(type)) { final String sql = query; hibSession.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement = connection.createStatement(); int lines = statement.executeUpdate(sql); sLog.debug(" -- " + lines + " lines affected."); statement.close(); } }); } else throw e; } boolean ok = true; if (into != null) { variables.put(into, q.uniqueResult().toString()); } else if ("equal".equals(condition) && value != null) { ok = value.equals(q.uniqueResult().toString()); } else if ("notEqual".equals(condition) && value != null) { ok = !value.equals(q.uniqueResult().toString()); } else if (q != null) { int lines = q.executeUpdate(); sLog.debug(" -- " + lines + " lines affected."); if ("noChange".equals(condition)) ok = (lines == 0); else if ("change".equals(condition)) ok = (lines > 0); } if (ok) { if ("next".equals(action)) continue; if ("done".equals(action)) break; if ("fail".equals(action)) { sLog.error("Update to " + updateName() + " version " + version + " failed (condition not met for query '" + query + "', con:" + condition + ", act:" + action + ", val:" + value + ")."); tx.rollback(); return false; } } } else { sLog.debug(" -- skip: " + query + " (con:" + condition + ", act:" + action + ", val:" + value + ")"); } } catch (Exception e) { sLog.warn("Query '" + query + "' failed, " + e.getMessage(), e); if (e.getCause() != null && e.getCause().getMessage() != null) sLog.warn("Cause: " + e.getCause().getMessage()); if ("fail".equals(condition)) { if ("next".equals(action)) continue; if ("done".equals(action)) break; } sLog.error("Update to version " + version + " failed."); tx.rollback(); return false; } } ApplicationConfig versionCfg = ApplicationConfig.getConfig(versionParameterName()); if (versionCfg == null) { versionCfg = new ApplicationConfig(versionParameterName()); versionCfg.setDescription("Timetabling " + updateName() + " DB version (do not change -- this is used by automatic database update)"); } versionCfg.setValue(String.valueOf(version)); hibSession.saveOrUpdate(versionCfg); sLog.info(" " + updateName() + " Database version increased to: " + version); if (tx != null && tx.isActive()) tx.commit(); HibernateUtil.clearCache(); return true; } catch (Exception e) { if (tx != null && tx.isActive()) tx.rollback(); sLog.error("Update to version " + version + " failed, reason:" + e.getMessage(), e); return false; } }
From source file:edu.umass.cs.msocket.proxy.console.ConsoleModule.java
/** * Find the <code>ConsoleCommand</code> based on the name of the command from * the <code>commandLine</code> in the <code>hashCommands</code>. If more than * one <code>ConsoleCommand</code>'s command name start the same way, return * the <code>ConsoleCommand</code> with the longest one. * /*from w ww.j a va 2s.c o m*/ * @param commandLine the command line to handle * @param hashCommands the list of commands available for this module * @return the <code>ConsoleCommand</code> corresponding to the name of the * command from the <code>commandLine</code> or <code>null</code> if * there is no matching */ public ConsoleCommand findConsoleCommand(String commandLine, Hashtable<String, ConsoleCommand> hashCommands) { ConsoleCommand foundCommand = null; for (Iterator iter = hashCommands.entrySet().iterator(); iter.hasNext();) { Map.Entry commandEntry = (Map.Entry) iter.next(); String commandName = (String) commandEntry.getKey(); if (commandLine.startsWith(commandName)) { ConsoleCommand command = (ConsoleCommand) commandEntry.getValue(); if (foundCommand == null) { foundCommand = command; } if (command.getCommandName().length() > foundCommand.getCommandName().length()) { foundCommand = command; } } } return foundCommand; }
From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java
/** * Extracts info from message context.//w w w . j a v a 2 s. c om * * @param method Post method * @param httpClient The client used for posting * @param msgContext the message context * @param tmpURL the url to post to. * * @throws Exception * @deprecated */ private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL) throws Exception { // optionally set a timeout for the request if (msgContext.getTimeout() != 0) { /* ISSUE: these are not the same, but MessageContext has only one definition of timeout */ // SO_TIMEOUT -- timeout for blocking reads httpClient.setTimeout(msgContext.getTimeout()); // timeout for initial connection httpClient.setConnectionTimeout(msgContext.getTimeout()); } // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$ if (action == null) { action = ""; //$NON-NLS-1$ } Message msg = msgContext.getRequestMessage(); if (msg != null) { method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()))); } method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$ String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (tmpURL.getUserInfo() != null)) { String info = tmpURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else { userID = info; } } if (userID != null) { Credentials cred = new UsernamePasswordCredentials(userID, passwd); httpClient.getState().setCredentials(null, null, cred); // Change #2 // // Comment out the lines below since they force all authentication // to be Basic. This is a problem if the web service you're invoking // is expecting Digest. // The following 3 lines should NOT be required. But Our SimpleAxisServer fails // during all-tests if this is missing. // StringBuffer tmpBuf = new StringBuffer(); // tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd); // method.addRequestHeader(HTTPConstants.HEADER_AUTHORIZATION, "Basic " + Base64.encode(tmpBuf.toString().getBytes())); } // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) { for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) { java.util.Map.Entry me = (java.util.Map.Entry) e.next(); Object keyObj = me.getKey(); if (null == keyObj) { continue; } String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); method.addRequestHeader(key, value); } } }
From source file:org.alfresco.dataprep.SiteService.java
/** * Add dashlet to site dashboard/* w ww . ja va 2 s .c o m*/ * * @param userName String identifier * @param password String password * @param siteName String site name * @param dashlet Site dashlet * @param layout Dashlet layout * @param column int index of columns * @param position int position in column * @return true if the dashlet is added */ @SuppressWarnings("unchecked") public boolean addDashlet(final String userName, final String password, final String siteName, final SiteDashlet dashlet, final DashletLayout layout, final int column, final int position) { if (!exists(siteName, userName, password)) { throw new RuntimeException("Site doesn't exists " + siteName); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String url = client.getShareUrl() + DashboardCustomization.ADD_DASHLET_URL; JSONObject body = new JSONObject(); JSONArray array = new JSONArray(); body.put("dashboardPage", "site/" + siteName + "/dashboard"); body.put("templateId", layout.id); Hashtable<String, String> defaultDashlets = new Hashtable<String, String>(); defaultDashlets.put(SiteDashlet.SITE_MEMBERS.id, "component-1-1"); defaultDashlets.put(SiteDashlet.SITE_CONNTENT.id, "component-2-1"); defaultDashlets.put(SiteDashlet.SITE_ACTIVITIES.id, "component-2-2"); Iterator<Map.Entry<String, String>> entries = defaultDashlets.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); JSONObject jDashlet = new JSONObject(); jDashlet.put("url", entry.getKey()); jDashlet.put("regionId", entry.getValue()); jDashlet.put("originalRegionId", entry.getValue()); array.add(jDashlet); } JSONObject newDashlet = new JSONObject(); newDashlet.put("url", dashlet.id); String region = "component-" + column + "-" + position; newDashlet.put("regionId", region); array.add(newDashlet); body.put("dashlets", array); HttpPost post = new HttpPost(url); HttpResponse response = client.executeRequest(userName, password, body, post); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { logger.trace("Dashlet " + dashlet.name + " was added to site " + siteName); return true; } else { logger.error("Unable to add dashlet to site " + siteName); } return false; }