List of usage examples for java.util Hashtable put
public synchronized V put(K key, V value)
From source file:hd.controller.AddImageToIdeaBookServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j ava 2s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { //to do } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException 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("UTF-8")); } else if (!item.isFormField()) { try { long time = System.currentTimeMillis(); String itemName = item.getName(); fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName; File savedFile = new File(RealPath); item.write(savedFile); String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName; // savedFile = new File(localPath); // item.write(savedFile); } catch (Exception e) { e.printStackTrace(); } } } String ideaBookIdTemp = (String) params.get("txtIdeabookId"); int ideaBookId = Integer.parseInt(ideaBookIdTemp); IdeaBookDAO ideabookDao = new IdeaBookDAO(); String tilte = (String) params.get("newGalleryName"); String description = (String) params.get("GalleryDescription"); String url = "images/" + fileName; IdeaBookPhotoDAO photoDAO = new IdeaBookPhotoDAO(); IdeaBookPhoto ideaBookPhoto = photoDAO.insertIdeaBookPhoto(tilte, description, url, ideaBookId); HDSystem system = new HDSystem(); system.setNotificationIdeaBook(request); response.sendRedirect("MyIdeaBookDetailServlet?txtIdeabookId=" + ideaBookId); } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
From source file:gov.pnnl.goss.gridappsd.GridAppsDataSourcesComponentTests.java
@Test /**//from w w w . j av a2 s . co m * Succeeds when the proper number of properties are set on the updated call, and datasourcebuilder.create is called, and the correct registered datasource name is added */ public void registryKeysExistWhen_dataSourcesStarted() { ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class); try { //When datasourceBuilder.create is called add a face datasource object to the datasourceRegistry (similar to what the actual implementation would do) Answer answer = new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); String dsName = args[0].toString(); datasourceRegistry.add(dsName, datasourceObject); return null; } }; Mockito.doAnswer(answer).when(datasourceBuilder).create(argCaptor.capture(), Mockito.any()); } catch (Exception e) { e.printStackTrace(); } Properties datasourceProperties = new Properties(); GridAppsDataSourcesImpl dataSources = new GridAppsDataSourcesImpl(logger, datasourceBuilder, datasourceRegistry, datasourceProperties); Hashtable<String, String> props = new Hashtable<String, String>(); String datasourceName = "pnnl.goss.sql.datasource.gridappsd"; props.put("name", datasourceName); props.put(DataSourceBuilder.DATASOURCE_USER, "gridappsduser"); props.put(DataSourceBuilder.DATASOURCE_PASSWORD, "gridappsdpw"); props.put(DataSourceBuilder.DATASOURCE_URL, "mysql://lalala"); props.put("driver", "com.mysql.jdbc.Driver"); dataSources.updated(props); assertEquals(5, datasourceProperties.size()); dataSources.start(); //verify datasourceBuilder.create(datasourceName, datasourceProperties); try { Mockito.verify(datasourceBuilder).create(argCaptor.capture(), Mockito.any()); assertEquals(datasourceName, argCaptor.getValue()); } catch (ClassNotFoundException e) { e.printStackTrace(); assert (false); } catch (Exception e) { e.printStackTrace(); assert (false); } //verify registeredDatasources.add(datasourceName); List<String> registeredDatasources = dataSources.getRegisteredDatasources(); assertEquals(1, registeredDatasources.size()); // test get data source keys Collection<String> dsKeys = dataSources.getDataSourceKeys(); assertEquals(datasourceName, dsKeys.toArray()[0]); // test get data source by key DataSourcePooledJdbc obj = dataSources.getDataSourceByKey(datasourceName); assertEquals(datasourceObject, obj); // test get connection by key dataSources.getConnectionByKey(datasourceName); try { Mockito.verify(datasourceObject).getConnection(); } catch (SQLException e) { e.printStackTrace(); } //verify datasourceregistry size assertEquals(1, datasourceRegistry.getAvailable().size()); }
From source file:edu.ku.brc.specify.tasks.DataEntryConfigDlg.java
@Override protected void addItem(final JList list, final Vector<TaskConfigItemIFace> itemList) { // Hash all the names so we can figure out which forms are not used Hashtable<String, Object> hash = new Hashtable<String, Object>(); ListModel model = stdPanel.getOrderModel(); for (int i = 0; i < model.getSize(); i++) { DataEntryView dev = (DataEntryView) model.getElementAt(i); hash.put(dev.getView(), dev); }// w w w.j ava 2s . c o m model = miscPanel.getOrderModel(); for (int i = 0; i < model.getSize(); i++) { DataEntryView dev = (DataEntryView) model.getElementAt(i); hash.put(dev.getView(), dev); } // Add only the unused forms (does NOT return internal views). List<String> uniqueList = new Vector<String>(); List<ViewIFace> views = ((SpecifyAppContextMgr) AppContextMgr.getInstance()).getAllViews(); Hashtable<String, ViewIFace> newAvailViews = new Hashtable<String, ViewIFace>(); for (ViewIFace view : views) { //System.out.println("["+view.getName()+"]["+view.getTitle()+"]"); if (hash.get(view.getName()) == null) { DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(view.getClassName()); if (ti != null) { if (!ti.isHidden() && !InteractionsTask.isInteractionTable(ti.getTableId())) { hash.put(view.getName(), view); String title = StringUtils.isNotEmpty(view.getObjTitle()) ? view.getObjTitle() : ti != null ? ti.getTitle() : view.getName(); if (newAvailViews.get(title) != null) { title = view.getName(); } uniqueList.add(title); newAvailViews.put(title, view); } } else { System.err.println("DBTableInfo was null for class[" + view.getClassName() + "]"); } } } if (uniqueList.size() == 0) { JOptionPane.showMessageDialog(this, getResourceString("DET_DEV_NONE_AVAIL"), getResourceString("DET_DEV_NONE_AVAIL_TITLE"), JOptionPane.INFORMATION_MESSAGE); return; } Collections.sort(uniqueList); ToggleButtonChooserDlg<String> dlg = new ToggleButtonChooserDlg<String>((Frame) UIRegistry.getTopWindow(), "DET_AVAIL_VIEWS", uniqueList); dlg.setUseScrollPane(true); UIHelper.centerAndShow(dlg); if (!dlg.isCancelled()) { model = list.getModel(); for (String title : dlg.getSelectedObjects()) { ViewIFace view = newAvailViews.get(title); DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(view.getClassName()); String frmTitle = StringUtils.isNotEmpty(view.getObjTitle()) ? view.getObjTitle() : ti != null ? ti.getTitle() : view.getName(); DataEntryView dev = new DataEntryView(frmTitle, // Title view.getName(), // Name ti != null ? ti.getName() : null, // Icon Name view.getObjTitle(), // ToolTip model.getSize(), // Order true); dev.setTableInfo(ti); ((DefaultListModel) model).addElement(dev); itemList.add(dev); } //pack(); } setHasChanged(true); }
From source file:UndoExample5.java
public void createMenuBar() { // Remove the existing menu items int count = menuBar.getMenuCount(); for (int i = 0; i < count; i++) { menuBar.remove(menuBar.getMenu(0)); }//w w w. ja va 2 s . c o m // Build the new menu. Action[] actions = pane.getActions(); Hashtable actionHash = new Hashtable(); count = actions.length; for (int i = 0; i < count; i++) { actionHash.put(actions[i].getValue(Action.NAME), actions[i]); } // Add the font menu JMenu menu = MenuBuilder.buildMenu("Font", fontSpec, actionHash); if (menu != null) { menuBar.add(menu); } // Add the alignment menu menu = MenuBuilder.buildMenu("Align", alignSpec, actionHash); if (menu != null) { menuBar.add(menu); } }
From source file:com.autentia.tnt.manager.billing.BillManager.java
public List<BillBreakDown> getAllBitacoreBreakDowns(Date start, Date end, Project project) { final List<BillBreakDown> desgloses = new ArrayList<BillBreakDown>(); ActivityDAO activityDAO = ActivityDAO.getDefault(); ActivitySearch actSearch = new ActivitySearch(); actSearch.setBillable(new Boolean(true)); actSearch.setStartStartDate(start);/*w ww . j a v a2s. c om*/ actSearch.setEndStartDate(end); List<Activity> actividadesTotal = new ArrayList<Activity>(); Hashtable user_roles = new Hashtable(); ProjectRoleDAO projectRoleDAO = ProjectRoleDAO.getDefault(); ProjectRoleSearch prjRolSearch = new ProjectRoleSearch(); prjRolSearch.setProject(project); List<ProjectRole> roles = projectRoleDAO.search(prjRolSearch, new SortCriteria("id", false)); for (ProjectRole proyRole : roles) { actSearch.setRole(proyRole); List<Activity> actividades = activityDAO.search(actSearch, new SortCriteria("startDate", false)); actividadesTotal.addAll(actividades); } for (Activity act : actividadesTotal) { String key = act.getRole().getId().toString() + act.getUser().getId().toString(); if (!user_roles.containsKey(key)) { Hashtable value = new Hashtable(); value.put("ROLE", act.getRole()); value.put("USER", act.getUser()); user_roles.put(key, value); } } Enumeration en = user_roles.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); Hashtable pair = (Hashtable) user_roles.get(key); actSearch.setBillable(new Boolean(true)); actSearch.setStartStartDate(start); actSearch.setEndStartDate(end); ProjectRole pR = (ProjectRole) pair.get("ROLE"); User u = (User) pair.get("USER"); actSearch.setRole(pR); actSearch.setUser(u); List<Activity> actividadesUsuarioRol = activityDAO.search(actSearch, new SortCriteria("startDate", false)); BillBreakDown brd = new BillBreakDown(); brd.setConcept("Imputaciones (usuario - rol): " + u.getName() + " - " + pR.getName()); brd.setAmount(pR.getCostPerHour()); IvaApplicator.applyIvaToTaxableObject(start, brd); BigDecimal unitsTotal = new BigDecimal(0); for (Activity act : actividadesUsuarioRol) { BigDecimal unitsActual = new BigDecimal(act.getDuration()); unitsActual = unitsActual.divide(new BigDecimal(60), 2, RoundingMode.HALF_UP); unitsTotal = unitsTotal.add(unitsActual); } brd.setUnits(unitsTotal); brd.setSelected(true); desgloses.add(brd); } ProjectCostDAO prjCostDAO = ProjectCostDAO.getDefault(); ProjectCostSearch prjCostSearch = new ProjectCostSearch(); prjCostSearch.setProject(project); List<ProjectCost> costes = prjCostDAO.search(prjCostSearch, new SortCriteria("id", false)); for (ProjectCost proyCost : costes) { BillBreakDown brd = new BillBreakDown(); brd.setConcept("Coste: " + proyCost.getName()); brd.setUnits(new BigDecimal(1)); brd.setAmount(proyCost.getCost()); IvaApplicator.applyIvaToTaxableObject(start, brd); brd.setSelected(true); desgloses.add(brd); } return desgloses; }
From source file:com.glaf.core.web.springmvc.MxDiskFileManagerJsonController.java
@RequestMapping public void show(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html; charset=UTF-8"); String serviceKey = request.getParameter("serviceKey"); LoginContext loginContext = RequestUtils.getLoginContext(request); // ?? /var/www/upload/ String rootPath = SystemProperties.getAppPath() + "/upload/" + loginContext.getUser().getId() + "/"; // URL?? http://www.yoursite.com/upload/ String rootUrl = request.getContextPath() + "/upload/" + loginContext.getUser().getId() + "/"; if (StringUtils.isNotEmpty(serviceKey)) { rootPath = rootPath + serviceKey + "/"; rootUrl = rootUrl + serviceKey + "/"; }/*w w w. java2 s. c om*/ // ?? String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" }; // ?path??URL String path = request.getParameter("path") != null ? request.getParameter("path") : ""; String currentPath = rootPath + path; String currentUrl = rootUrl + 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) : ""; } // ??name or size or type String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name"; // ??.. if (path.indexOf("..") >= 0) { response.getWriter().write(getError("Access is not allowed.")); return; } // ??/ if (!"".equals(path) && !path.endsWith("/")) { response.getWriter().write(getError("Parameter is not valid.")); return; } // ?? File currentPathFile = new File(currentPath); if (!currentPathFile.isDirectory()) { response.getWriter().write(getError("Directory does not exist.")); return; } // ???? List<Hashtable<String, Object>> fileList = new java.util.ArrayList<Hashtable<String, Object>>(); if (currentPathFile != null && currentPathFile.listFiles() != null) { File[] filelist = currentPathFile.listFiles(); if (filelist != null) { for (int i = 0, len = filelist.length; i < len; i++) { File file = filelist[i]; 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 = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); hash.put("is_dir", false); hash.put("has_file", false); hash.put("filesize", file.length()); hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt)); hash.put("filetype", fileExt); } hash.put("filename", fileName); hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified())); fileList.add(hash); } } } if ("size".equals(order)) { Collections.sort(fileList, new SizeComparator()); } else if ("type".equals(order)) { Collections.sort(fileList, new TypeComparator()); } else { Collections.sort(fileList, new NameComparator()); } JSONObject result = new JSONObject(); result.put("moveup_dir_path", moveupDirPath); result.put("current_dir_path", currentDirPath); result.put("current_url", currentUrl); result.put("total_count", fileList.size()); result.put("file_list", fileList); response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(result.toString()); }
From source file:com.glaf.core.web.springmvc.MxDBFileManagerJsonController.java
@RequestMapping public void show(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html; charset=UTF-8"); LoginContext loginContext = RequestUtils.getLoginContext(request); // ??/* w w w. j a v a 2s. co m*/ String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" }; // ??name or size or type String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "filename"; String businessKey = request.getParameter("businessKey"); String serviceKey = request.getParameter("serviceKey"); BlobItemQuery query = new BlobItemQuery(); query.createBy(loginContext.getActorId()); if (StringUtils.isNotEmpty(businessKey)) { query.businessKey(businessKey); } if (StringUtils.isNotEmpty(serviceKey)) { query.serviceKey(serviceKey); } else { query.serviceKey("IMG_" + loginContext.getActorId()); } if ("size".equals(order)) { query.setSortField("size"); } else if ("type".equals(order)) { query.setSortField("type"); } else { query.setSortField("filename"); } List<DataFile> dataFiles = blobService.getBlobList(query); // ???? List<Hashtable<?, ?>> fileList = new java.util.ArrayList<Hashtable<?, ?>>(); if (dataFiles != null && !dataFiles.isEmpty()) { for (DataFile file : dataFiles) { Hashtable<String, Object> hash = new Hashtable<String, Object>(); String fileName = file.getFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); hash.put("is_dir", false); hash.put("has_file", false); hash.put("filesize", file.getSize()); hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt)); hash.put("filetype", fileExt); hash.put("filename", file.getFileId()); hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.getLastModified())); fileList.add(hash); } } if ("size".equals(order)) { Collections.sort(fileList, new SizeComparator()); } else if ("type".equals(order)) { Collections.sort(fileList, new TypeComparator()); } else { Collections.sort(fileList, new NameComparator()); } JSONObject result = new JSONObject(); result.put("moveup_dir_path", request.getContextPath() + "/rs/blob/file/"); result.put("current_dir_path", request.getContextPath() + "/rs/blob/file/"); result.put("current_url", request.getContextPath() + "/rs/blob/file/"); result.put("total_count", fileList.size()); result.put("file_list", fileList); response.setContentType("application/json; charset=UTF-8"); response.getWriter().write(result.toString()); }
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Asserts a users credentials. Returns an LdapContext if assertion is successful * or an exception for any other reason. * * @param userDn the users DN to assert//from w w w.j av a 2s . c o m * @param password the password to assert * @return the LdapContext upon a successful connection * @throws NamingException when unable to establish a connection * @since 1.4.0 */ public LdapContext createLdapContext(String userDn, String password) throws NamingException { if (StringUtils.isEmpty(userDn) || StringUtils.isEmpty(password)) { throw new NamingException("Username or password cannot be empty or null"); } final Hashtable<String, String> env = new Hashtable<>(); if (StringUtils.isNotBlank(LDAP_SECURITY_AUTH)) { env.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTH); } env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, LDAP_URL); if (IS_LDAP_SSLTLS) { env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory"); } try { return new InitialLdapContext(env, null); } catch (CommunicationException e) { LOGGER.error("Failed to connect to directory server", e); throw (e); } catch (NamingException e) { throw new NamingException("Failed to authenticate user"); } }
From source file:net.sf.ehcache.distribution.JNDIManualRMICacheManagerPeerProvider.java
/** * Register a new peer by looking it up in JNDI and storing * in a local cache the Context./*from w w w . j a v a 2 s. co m*/ * * @param jndiProviderUrl */ private Context registerPeerToContext(String jndiProviderUrl) { String initialContextFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (LOG.isDebugEnabled()) { LOG.debug("registerPeerToContext: " + jndiProviderUrl + " " + extractProviderUrl(jndiProviderUrl) + " with " + initialContextFactory); } Hashtable hashTable = new Hashtable(1); hashTable.put(Context.PROVIDER_URL, extractProviderUrl(jndiProviderUrl)); Context initialContext = null; try { initialContext = new InitialContext(hashTable); registerPeerToContext(jndiProviderUrl, initialContext); } catch (NamingException e) { LOG.warn(jndiProviderUrl + " " + e.getMessage()); registerPeerToContext(jndiProviderUrl, null); } return initialContext; }
From source file:HashTagSegmenter.java
private Hashtable<String, String> getWordListHashTable() throws IOException { Hashtable<String, String> tempWordList = new Hashtable<String, String>(); File file = new File(wordListLocation); BufferedReader br = new BufferedReader(new FileReader(file)); String line;// w ww.ja v a2 s . co m while ((line = br.readLine()) != null) { // process the line. tempWordList.put(line, line); } br.close(); return tempWordList; }