List of usage examples for java.util Hashtable put
public synchronized V put(K key, V value)
From source file:Controller.ControllerProducts.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w.ja va 2 s. c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); System.out.println("path" + fileName); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; System.out.println("Rpath" + RealPath); File savedFile = new File(RealPath); item.write(savedFile); //System.out.println("upload\\"+fileName); //insert Product String code = (String) params.get("txtcode"); String name = (String) params.get("txtname"); String price = (String) params.get("txtprice"); Products sp = new Products(); sp.InsertProduct(code, name, price, "upload\\" + fileName); RequestDispatcher rd = request.getRequestDispatcher("product.jsp"); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } } } //this.processRequest(request, response); }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
@SuppressWarnings("PMD.ReplaceHashtableWithMap") // Map required by bouncycastle X509 implementation private Hashtable<DERObjectIdentifier, String> buildAttributes( DigitalSigningDistinguishedName distinguishedName) { Hashtable<DERObjectIdentifier, String> attributes = new Hashtable<DERObjectIdentifier, String>(); attributes.put(X509Principal.C, StringUtils.defaultString(distinguishedName.getCountryName())); attributes.put(X509Principal.ST, StringUtils.defaultString(distinguishedName.getStateOrProvinceName())); attributes.put(X509Principal.L, StringUtils.defaultString(distinguishedName.getLocalityName())); attributes.put(X509Principal.O, StringUtils.defaultString(distinguishedName.getOrganizationName())); attributes.put(X509Principal.OU, StringUtils.defaultString(distinguishedName.getOrganizationalUnitName())); attributes.put(X509Principal.CN, StringUtils.defaultString(distinguishedName.getCommonName())); attributes.put(X509Principal.EmailAddress, StringUtils.defaultString(distinguishedName.getEmailAddress())); return attributes; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Gets the initial context/*from w ww .j ava 2 s .c o m*/ * * @param providerUrl * @param bindDN * @param bindPassword * @return */ public static LdapContext getInitialContext(String providerUrl, String bindDN, String bindPassword) { List<String> trace = new ArrayList<String>(); LOGGER.debug("providerURL: " + providerUrl); trace.add("Attempting to connect to the LDAP server..."); if (providerUrl != null && providerUrl.startsWith("ldaps:")) { System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE); trace.add("Using ldaps: with keystore at " + PATH_TO_KEY_STORE); File ks = new File(PATH_TO_KEY_STORE); if (!ks.exists()) { trace.add("*** There is no keystore at " + PATH_TO_KEY_STORE); } } if (providerUrl == null) { LOGGER.warn("LDAP provider URL should not be null."); return null; } Hashtable<String, Object> env = new Hashtable<String, Object>(); if (LOGGER.isDebugEnabled()) { env.put("com.sun.jndi.ldape.trace.ber", System.err); } env.put("java.naming.ldap.version", "3"); env.put("com.sun.jndi.ldap.connect.timeout", "10000"); env.put("com.sun.jndi.dns.timeout.initial", "2000"); env.put("com.sun.jndi.dns.timeout.retries", "3"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, providerUrl); if ((bindDN != null) && !bindDN.equals("")) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, bindDN); env.put(Context.SECURITY_CREDENTIALS, bindPassword); LOGGER.debug("bind with bindDN:" + bindDN + " " + "bindPassword=" + bindPassword.replaceAll(".", "*")); trace.add("Preparing to bind to the LDAP server with DN = " + bindDN + " and password '****"); } else { LOGGER.debug("bind anonymous"); trace.add("Preparing to bind anonymously to the LDAP server"); } try { return new InitialLdapContext(env, null); } catch (NamingException e) { for (String msg : trace) { LOGGER.error(msg); } LOGGER.error("Getting the initial ldap context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); try { new InitialDirContext(env); } catch (NamingException e1) { LOGGER.error("Getting the initial dir context failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return null; } }
From source file:edu.csun.ecs.cs.multitouchj.ui.graphic.WindowManagerCalibratorDefault.java
protected void prepareControls() { if (controls.size() == 0) { try {/* w w w . j av a 2 s .co m*/ String[] types = new String[] { URI_IMAGE_WAITING, URI_IMAGE_OK }; for (Position position : Position.values()) { Hashtable<String, TexturedControl> texturedControls = new Hashtable<String, TexturedControl>(); for (String type : types) { TexturedControl control = new TexturedControl(); control.setTexture(getClass().getResource(type)); texturedControls.put(type, control); } controls.put(position, texturedControls); } } catch (Exception exception) { log.error("Failed to load image.", exception); } } }
From source file:homenet.PortXmlrpc.java
@Override public void send(Packet packet) { _sending = true;/* www.j a v a2 s .co m*/ if ((_node == 0) || (_node == packet.getToNode())) { for (PortListener l : _homeNet._portListeners) { l.portSendingStart(_id); } Hashtable<String, String> xmlpacket = new Hashtable<String, String>(); System.out.println(new String(Base64.encodeBase64(packet.getData()))); String packetBase64 = new String(Base64.encodeBase64(packet.getData())); xmlpacket.put("apikey", _client.apikey); xmlpacket.put("timestamp", getDateAsISO8601String(packet.getTimestamp())); xmlpacket.put("packet", packetBase64); //System.out.println("DAte: "+packet.getTimestamp().toString()); Boolean reply = false; try { reply = (Boolean) _client.execute("homenet.packet.submit", xmlpacket); //reply = (String)homeNetXmlrpcClient.execute("HomeNet.ping", "test test3242342"); } catch (Exception e) { //@todo there are probably some specfic exception we need to filter out to kill bad packets System.out.println("XMLRPC Error: " + e); packet.setStatus(STATUS_READY); System.err.println("Possible network error. Will retry in " + retryDelay + " seconds"); Thread timer = new Thread() { public void run() { try { Thread.sleep(retryDelay * 1000); } catch (Exception e) { } _sending = false; } }; timer.start(); for (PortListener l : _homeNet._portListeners) { l.portSendingEnd(_id); } return; } if (reply == true) { System.out.println("Packet Successfuly sent to HomeNet.me"); } else { System.out.println("Fatal Error"); } } else { System.out.println("Packet Skipped"); } // debugPacket(packet); packet.setStatus(STATUS_SENT); _sending = false; for (PortListener l : _homeNet._portListeners) { l.portSendingEnd(_id); } }
From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java
public static Hashtable<String, Object> getHeaderRecordCatchedData(String group, long serverMsgNum, Context context) {//from ww w.j av a 2 s. c om int groupid = getGroupIdFromName(group, context); Hashtable<String, Object> result = null; DBHelper db = new DBHelper(context); SQLiteDatabase dbread = db.getReadableDatabase(); Cursor c = dbread.rawQuery("SELECT _id, server_article_id, catched FROM headers WHERE subscribed_group_id=" + groupid + " AND server_article_number=" + serverMsgNum, null); if (c.getCount() == 1) { c.moveToFirst(); result = new Hashtable<String, Object>(3); result.put("id", c.getInt(0)); result.put("server_article_id", c.getString(1)); if (c.getInt(2) == 1) result.put("catched", true); else result.put("catched", false); } c.close(); dbread.close(); db.close(); return result; }
From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileX.java
@Override protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData) throws IOException { si = super.extendCMSSignature(signedData, si, parameters, originalData); ASN1ObjectIdentifier attributeId = null; ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); switch (getExtendedValidationType()) { case 1:/* w w w. j a va 2 s . com*/ attributeId = PKCSObjectIdentifiers.id_aa_ets_escTimeStamp; toTimestamp.write(si.getSignature()); // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS 6.3.5, // NOTE 2) toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken) .getAttrType().getDEREncoded()); toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken) .getAttrValues().getDEREncoded()); break; case 2: attributeId = PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp; break; default: throw new IllegalStateException( "CAdES-X Profile: Extended validation is set but no valid type (1 or 2)"); } /* Those are common to Type 1 and Type 2 */ toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs) .getAttrType().getDEREncoded()); toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs) .getAttrValues().getDEREncoded()); toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs) .getAttrType().getDEREncoded()); toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs) .getAttrValues().getDEREncoded()); @SuppressWarnings("unchecked") Hashtable<ASN1ObjectIdentifier, Attribute> unsignedAttrHash = si.getUnsignedAttributes().toHashtable(); Attribute extendedTimeStamp = getTimeStampAttribute(attributeId, getSignatureTsa(), digestAlgorithm, toTimestamp.toByteArray()); unsignedAttrHash.put(attributeId, extendedTimeStamp); return SignerInformation.replaceUnsignedAttributes(si, new AttributeTable(unsignedAttrHash)); }
From source file:com.cloudbase.datacommands.CBSearchCondition.java
/** * Creates a new search condition for geographical searches. This looks for documents whose location data * places them near the given location.//from ww w . j ava2 s .com * @param nearLoc The location we are looking for * @param maxDistance The maximum distance in meters from the given location */ public CBSearchCondition(BlackBerryLocation nearLoc, int maxDistance) { Vector points = new Vector(); points.addElement(Double.toString(nearLoc.getQualifiedCoordinates().getLatitude())); points.addElement(Double.toString(nearLoc.getQualifiedCoordinates().getLongitude())); Hashtable searchQuery = new Hashtable(); this.setField("cb_location"); this.setOperator(CBSearchConditionOperator.CBOperatorEqual); searchQuery.put("$near", points); if (maxDistance > 0) searchQuery.put("$maxDistance", Integer.toString(maxDistance)); this.setValue(searchQuery); this.limit = -1; this.setCommandType(CBDataAggregationCommandType.CBDataAggregationMatch); }
From source file:info.magnolia.templating.jsp.AbstractTagTestCase.java
@Before public void setUp() throws Exception { // need to pass a web.xml file to setup servletunit working directory final ClassLoader classLoader = getClass().getClassLoader(); final URL webXmlUrl = classLoader.getResource("WEB-INF/web.xml"); if (webXmlUrl == null) { Assert.fail("Could not find WEB-INF/web.xml"); }/* w w w.java 2 s.c o m*/ final String path = URLDecoder.decode(webXmlUrl.getFile(), "UTF-8"); HttpUnitOptions.setDefaultCharacterSet("utf-8"); System.setProperty("file.encoding", "utf-8"); // check we can write in jasper's scratch directory final File jspScratchDir = new File("target/jsp-test-scratch-dir"); final String jspScratchDirAbs = jspScratchDir.getAbsolutePath(); if (!jspScratchDir.exists()) { Assert.assertTrue("Can't create path " + jspScratchDirAbs + ", aborting test", jspScratchDir.mkdirs()); } final File checkFile = new File(jspScratchDir, "empty"); Assert.assertTrue("Can't write check file: " + checkFile + ", aborting test", checkFile.createNewFile()); Assert.assertTrue("Can't remove check file:" + checkFile + ", aborting test", checkFile.delete()); // start servletRunner final Hashtable<String, String> params = new Hashtable<String, String>(); params.put("javaEncoding", "utf-8"); params.put("development", "true"); params.put("keepgenerated", "false"); params.put("modificationTestInterval", "1000"); params.put("scratchdir", jspScratchDirAbs); params.put("engineOptionsClass", TestServletOptions.class.getName()); runner = new ServletRunner(new File(path), CONTEXT); runner.registerServlet("*.jsp", "org.apache.jasper.servlet.JspServlet", params); // setup context session = MockUtil.createAndSetHierarchyManager("website", StringUtils.join(new String[] { "/foo/bar.@type=mgnl:page", "/foo/bar.title=Bar title", "/foo/bar/0.text=hello root 1", "/foo/bar.mgnl\\:template=testPageTemplate", "/foo/bar/paragraphs.@type=mgnl:area", "/foo/bar/paragraphs/0.@type=mgnl:component", "/foo/bar/paragraphs/0.@uuid=100", "/foo/bar/paragraphs/1.@type=mgnl:component", "/foo/bar/paragraphs/1.@uuid=101", "/foo/bar/paragraphs/1.text=hello 1", "/foo/bar/paragraphs/1.mgnl\\:template=testParagraph1", "/foo/bar/paragraphs/1/image.@type=mgnl:resource", "/foo/bar/paragraphs/1/image.jcr:data=binary:12345", "/foo/bar/paragraphs/1/image.extension=jpg", "/foo/bar/paragraphs/1/image.fileName=file", }, "\n")); aggState = new AggregationState(); // let's make sure we render stuff on an author instance aggState.setPreviewMode(false); final ServerConfiguration serverCfg = new ServerConfiguration(); serverCfg.setAdmin(true); ConfiguredTemplateDefinition testParagraph0 = new ConfiguredTemplateDefinition(); testParagraph0.setName("testParagraph0"); testParagraph0.setTitle("Test Paragraph 0"); ConfiguredTemplateDefinition testParagraph1 = new ConfiguredTemplateDefinition(); testParagraph1.setName("testParagraph1"); testParagraph1.setTitle("Test Paragraph 1"); testParagraph1.setDialog("testDialog"); ConfiguredTemplateDefinition testParagraph2 = new ConfiguredTemplateDefinition(); testParagraph2.setName("testParagraph2"); testParagraph2.setTitle("Test Paragraph 2"); final TemplateDefinitionProvider p0provider = mock(TemplateDefinitionProvider.class); final TemplateDefinitionProvider p1provider = mock(TemplateDefinitionProvider.class); final TemplateDefinitionProvider p2provider = mock(TemplateDefinitionProvider.class); when(p0provider.getTemplateDefinition()).thenReturn(testParagraph0); when(p0provider.getId()).thenReturn(testParagraph0.getName()); when(p1provider.getTemplateDefinition()).thenReturn(testParagraph1); when(p1provider.getId()).thenReturn(testParagraph1.getName()); when(p2provider.getTemplateDefinition()).thenReturn(testParagraph2); when(p2provider.getId()).thenReturn(testParagraph2.getName()); ComponentsTestUtil.setInstance(ServerConfiguration.class, serverCfg); // register some default components used internally ComponentsTestUtil.setImplementation(MessagesManager.class, DefaultMessagesManager.class); ComponentsTestUtil.setImplementation(I18nContentSupport.class, DefaultI18nContentSupport.class); ComponentsTestUtil.setImplementation(I18nAuthoringSupport.class, DefaultI18nAuthoringSupport.class); ComponentsTestUtil.setImplementation(ContextFactory.class, ContextFactory.class); ComponentsTestUtil.setImplementation(TemplateDefinitionAssignment.class, MetaDataBasedTemplateDefinitionAssignment.class); // configure node2bean because its processor is injected into DefaultMessagesManager constructor ComponentsTestUtil.setImplementation(Node2BeanProcessor.class, Node2BeanProcessorImpl.class); ComponentsTestUtil.setImplementation(TypeMapping.class, TypeMappingImpl.class); ComponentsTestUtil.setImplementation(Node2BeanTransformer.class, Node2BeanTransformerImpl.class); MockContext systemContext = new MockContext(); systemContext.addSession("website", session.getJcrSession()); ComponentsTestUtil.setInstance(SystemContext.class, systemContext); aggState.setCurrentContent(session.getContent("/foo/bar/paragraphs/1")); renderingContext = new AggregationStateBasedRenderingContext(aggState, null); final RenderingEngine renderingEngine = mock(RenderingEngine.class); when(renderingEngine.getRenderingContext()).thenReturn(renderingContext); ComponentsTestUtil.setInstance(RenderingEngine.class, renderingEngine); final TemplateDefinitionRegistry tdr = new TemplateDefinitionRegistry(); tdr.register(p0provider); tdr.register(p1provider); tdr.register(p2provider); ComponentsTestUtil.setInstance(TemplateDefinitionRegistry.class, tdr); req = mock(HttpServletRequest.class); req.setAttribute(Sources.REQUEST_LINKS_DRAWN, Boolean.TRUE); res = mock(HttpServletResponse.class); when(res.getWriter()).thenReturn(null); when(res.isCommitted()).thenReturn(true); ctx = mock(WebContext.class); when(ctx.getAggregationState()).thenReturn(aggState); when(ctx.getLocale()).thenReturn(Locale.US); when(ctx.getResponse()).thenReturn(res); when(ctx.getRequest()).thenReturn(req); MgnlUser mockUser = mock(MgnlUser.class); when(mockUser.getLanguage()).thenReturn("en"); when(ctx.getUser()).thenReturn(mockUser); when(ctx.getContextPath()).thenReturn("contextPath"); when(ctx.getHierarchyManager("website")).thenReturn(session); when(ctx.getJCRSession("website")).thenReturn(session.getJcrSession()); setupExpectations(ctx, req); MgnlContext.setInstance(ctx); }
From source file:com.us.servlet.FileManager.java
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws Exception { // /*from w ww . ja v a2s. c om*/ final String fileRoot = AppHelper.KIND_CONFIG.get(FILE_MGR_ROOT).toString(); File root = FileHelper.getFile(AppHelper.APPSET.getFilePath(), fileRoot); PrintWriter out = resp.getWriter(); final String path = req.getParameter("path") != null ? req.getParameter("path") : ""; final String dirType = req.getParameter("dir").toLowerCase();// ??name or size or type String order = req.getParameter("order") != null ? req.getParameter("order").toLowerCase() : "name"; if (!root.exists()) { root.mkdirs(); } String currentUrl = AppHelper.APPSET.getWebPath() + fileRoot + path; String currentDirPath = path; String moveupDirPath = ""; if (!"".equals(path)) { String str = currentDirPath.substring(0, currentDirPath.length() - 1); moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : ""; } String[] imageType = AppHelper.KIND_CONFIG.get(FILE_IMAGE_TYPE).toString().split(","); // ??.. if (path.indexOf("..") >= 0) { out.println(I118Helper.i118Value("${fileMgr.accessFail}", req)); return; } // ??/ if (!"".equals(path) && !path.endsWith("/")) { out.println(I118Helper.i118Value("${fileMgr.badArgs}", req)); return; } File showDir = FileHelper.getFile(root, currentDirPath); if (!showDir.isDirectory()) { out.println(I118Helper.i118Value("${fileMgr.rootNotExist}", req)); return; } List<Hashtable<String, Object>> fileList = new ArrayList<Hashtable<String, Object>>(); final File[] listFiles = showDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (FileHelper.getFile(dir, name).isDirectory()) { return true; } final List<String> fileTypeList = Arrays .<String>asList(AppHelper.KIND_CONFIG.get(dirType).toString().split(",")); return fileTypeList.contains(FilenameUtils.getExtension(name)); } }); if (listFiles != null) { for (File file : listFiles) { Hashtable<String, Object> hash = new Hashtable<String, Object>(); String fileName = file.getName(); if (file.isDirectory()) { hash.put("is_dir", true); hash.put("has_file", (file.listFiles() != null)); hash.put("filesize", 0L); hash.put("is_photo", false); hash.put("filetype", ""); } else if (file.isFile()) { String fileExt = FilenameUtils.getExtension(fileName).toLowerCase(); hash.put("is_dir", false); hash.put("has_file", false); hash.put("filesize", file.length()); hash.put("is_photo", Arrays.<String>asList(imageType).contains(fileExt)); hash.put("filetype", fileExt); } hash.put("filename", fileName); hash.put("datetime", DateUtil.format(file.lastModified(), DateUtil.DATETIME_PATTERN)); fileList.add(hash); } } if ("size".equals(order)) { Collections.sort(fileList, new SizeComparator<Hashtable<String, Object>>()); } else if ("type".equals(order)) { Collections.sort(fileList, new TypeComparator<Hashtable<String, Object>>()); } else { Collections.sort(fileList, new NameComparator<Hashtable<String, Object>>()); } KindFileMgr mgr = new KindFileMgr(); mgr.setMoveup_dir_path(moveupDirPath); mgr.setCurrent_dir_path(currentDirPath); mgr.setCurrent_url(currentUrl); mgr.setTotal_count(fileList.size()); mgr.setFile_list(fileList); resp.setContentType("application/json; charset=UTF-8"); out.println(JSONHelper.obj2Json(mgr)); }