Example usage for java.util Hashtable put

List of usage examples for java.util Hashtable put

Introduction

In this page you can find the example usage for java.util Hashtable put.

Prototype

public synchronized V put(K key, V value) 

Source Link

Document

Maps the specified key to the specified value in this hashtable.

Usage

From source file:com.qwazr.server.GenericServer.java

private void startHttpServer(final ServerConfiguration.WebConnector connector,
        final ServletContextBuilder context, final AccessLogger accessLogger)
        throws IOException, ServletException, OperationsException, MBeanException {

    if (context == null || context.getServlets().isEmpty())
        return;/*from   w  w  w.  ja v  a 2  s .c  o m*/

    context.setIdentityManager(getIdentityManager(connector));

    contextAttributes.forEach(context::addServletContextAttribute);

    if (context.getIdentityManager() != null && !StringUtils.isEmpty(connector.authentication)) {
        if (hostnamePrincipalResolver != null)
            HostnameAuthenticationMechanism.register(context, hostnamePrincipalResolver);
        final LoginConfig loginConfig = Servlets.loginConfig(connector.realm);
        for (String authmethod : StringUtils.split(connector.authentication, ','))
            loginConfig.addLastAuthMethod(authmethod);
        context.setLoginConfig(loginConfig);
    }

    final DeploymentManager manager = servletContainer.addDeployment(context);
    manager.deploy();

    LOGGER.info(() -> "Start the connector " + configuration.listenAddress + ":" + connector.port);

    HttpHandler httpHandler = manager.start();
    final LogMetricsHandler logMetricsHandler = new LogMetricsHandler(httpHandler, configuration.listenAddress,
            connector.port, context.jmxName, accessLogger);
    deploymentManagers.add(manager);
    httpHandler = logMetricsHandler;

    final Undertow.Builder servletBuilder = Undertow.builder()
            .addHttpListener(connector.port, configuration.listenAddress)
            .setServerOption(UndertowOptions.NO_REQUEST_TIMEOUT, 10000)
            .setServerOption(UndertowOptions.RECORD_REQUEST_START_TIME, true)
            .setServerOption(UndertowOptions.ENABLE_STATISTICS, true)
            .setServerOption(UndertowOptions.ENABLE_HTTP2, true).setHandler(httpHandler);
    start(servletBuilder.build());

    // Register MBeans
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final Hashtable<String, String> props = new Hashtable<>();
    props.put("type", "connector");
    props.put("name", context.jmxName);
    final ObjectName name = new ObjectName(
            "com.qwazr.server." + serverCounter.incrementAndGet() + "." + context.jmxName, props);
    mbs.registerMBean(logMetricsHandler, name);
    registeredObjectNames.add(name);
    connectorsStatistics.add(logMetricsHandler);
}

From source file:com.softlayer.objectstorage.Client.java

/**
 * Utility for authorizing and adding the auth token to the header
 * //from   w  w  w.  j a v  a 2 s .c  o  m
 * @return Hashtable with auth params set
 * @throws IOException
 */
protected Hashtable<String, String> createAuthParams() throws IOException {
    if (authToken == null)
        this.auth(this.username, this.password);
    Hashtable<String, String> params = new Hashtable<String, String>();
    params.put(Client.X_AUTH_TOKEN, this.authToken);
    return params;
}

From source file:hd.controller.AddImageToProjectServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w w .  j  a  v a  2  s .  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();
                    }
                }
            }
            //Init Jpa
            CategoryJpaController categoryJpa = new CategoryJpaController(emf);
            StyleJpaController styleJpa = new StyleJpaController(emf);
            ProjectJpaController projectJpa = new ProjectJpaController(emf);
            IdeaBookPhotoJpaController photoJpa = new IdeaBookPhotoJpaController(emf);
            // get Object Category by categoryId
            int cateId = Integer.parseInt((String) params.get("ddlCategory"));
            Category cate = categoryJpa.findCategory(cateId);
            // get Object Style by styleId
            int styleId = Integer.parseInt((String) params.get("ddlStyle"));
            Style style = styleJpa.findStyle(styleId);
            // get Object Project by projectId
            int projectId = Integer.parseInt((String) params.get("txtProjectId"));
            Project project = projectJpa.findProject(projectId);
            project.setStatus(Constant.STATUS_WAIT);
            projectJpa.edit(project);
            //Get param
            String title = (String) params.get("title");
            String description = (String) params.get("description");

            String url = "images/" + fileName;
            //Init IdeabookPhoto
            IdeaBookPhoto photo = new IdeaBookPhoto(title, url, description, cate, style, project);
            photoJpa.create(photo);
            url = "ViewMyProjectDetailServlet?txtProjectId=" + projectId;

            //System
            HDSystem system = new HDSystem();
            system.setNotificationProject(request);
            response.sendRedirect(url);
        }
    } catch (Exception e) {
        log("Error at AddImageToProjectServlet: " + e.getMessage());
    } finally {
        out.close();
    }
}

From source file:com.softeffect.primemovers.ui.ClientApplication.java

public ClientApplication() {
    clientFacade = new AppClientFacade();

    Hashtable domains = new Hashtable();
    Domain statusDomain = new Domain("STATUS");
    statusDomain.addDomainPair("ACTIVE", "Active");
    statusDomain.addDomainPair("EXPIRED", "Expired");
    domains.put(statusDomain.getDomainId(), statusDomain);

    Properties props = new Properties();

    ClientSettings clientSettings = new ClientSettings(new EnglishOnlyResourceFactory("TZS", props, true),
            domains);//  w w w . ja v a 2  s . c o m

    ClientSettings.BACKGROUND = "background4.jpg";
    ClientSettings.TREE_BACK = "treeback2.jpg";
    ClientSettings.VIEW_BACKGROUND_SEL_COLOR = true;
    ClientSettings.VIEW_MANDATORY_SYMBOL = false;
    ClientSettings.FILTER_PANEL_ON_GRID = true;
    ClientSettings.ASK_BEFORE_CLOSE = true;

    ClientSettings.GRID_PROFILE_MANAGER = new FileGridProfileManager();
    ClientSettings.LOOKUP_FRAME_CONTENT = LookupController.GRID_AND_FILTER_FRAME;
    ClientSettings.MDI_TOOLBAR = new DefaultToolBar();

    LoginDialog d = new LoginDialog(null, false, this, "Authentication", "Login", 'L', "Exit", 'E',
            "Store Account", applicationInfo.getName());

}

From source file:com.softlayer.objectstorage.Client.java

/**
 * convenience method for making an auth call to objectstorage via restlet
 * client/*w w w  .j  a  v a2 s .co m*/
 * 
 * 
 * @param username
 *            username for SL portal user to be used for susequent calls
 * @param password
 *            password for the given user or the api key as a String
 * 
 * @throws IOException
 */
protected void auth(String username, String password) throws IOException {

    Hashtable<String, String> params = new Hashtable<String, String>();
    params.put(USERNAME, username);
    params.put(PASSWORD, password);

    ClientResource client = this.get(params, authurl);

    this.authToken = getCustomHttpHeader(X_AUTH_TOKEN, client);
    this.storageurl = getCustomHttpHeader(X_STORAGE_URL, client);
    this.cdnurl = getCustomHttpHeader(X_CDN_MANAGEMENT_URL, client);

}

From source file:eionet.cr.api.xmlrpc.XmlRpcServices.java

@Override
public Vector getXmlFilesBySchema(String schemaIdentifier) throws CRException {

    if (logger.isInfoEnabled()) {
        logger.info("Entered " + Thread.currentThread().getStackTrace()[1].getMethodName());
    }//from  w  w  w .  j  a v a  2s  .  c  o m

    Vector result = new Vector();
    try {
        if (!StringUtils.isBlank(schemaIdentifier)) {

            SearchDAO searchDao = DAOFactory.get().getDao(SearchDAO.class);
            Map<String, String> criteria = new HashMap<String, String>();
            criteria.put(Predicates.CR_SCHEMA, schemaIdentifier);

            SearchResultDTO<SubjectDTO> searchResult = searchDao.searchByFilters(criteria, false, null, null,
                    null, true);

            int subjectCount = searchResult.getMatchCount();

            logger.debug(getClass().getSimpleName() + ".getXmlFilesBySchema(" + schemaIdentifier + "), "
                    + subjectCount + " subjects found in total");

            List<SubjectDTO> subjects = searchResult.getItems();
            if (subjects != null && !subjects.isEmpty()) {
                for (SubjectDTO subjectDTO : subjects) {

                    String lastModif = subjectDTO.getObjectValue(Predicates.CR_LAST_MODIFIED);
                    Hashtable hashtable = new Hashtable();
                    hashtable.put("uri", subjectDTO.getUri());
                    hashtable.put("lastModified", lastModif == null ? "" : lastModif.trim());
                    result.add(hashtable);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        if (t instanceof CRException) {
            throw (CRException) t;
        } else {
            throw new CRException(t.toString(), t);
        }
    }

    return result;
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {/* w ww.jav  a2  s  .c o  m*/
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

From source file:Controller.ControllerCustomers.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w ww . j a v  a  2s .c om
 * @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);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txtpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = (String) params.get("txtrole");
                    String anh = (String) params.get("txtanh");
                    //Update  product
                    if (fileName.equals("")) {

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh);
                        CustomerDAO.SuaThongTinKhachHang(Cus);
                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role,
                                "upload\\" + fileName);
                        CustomerDAO.SuaThongTinKhachHang(Cus);

                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    System.out.println(e);
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

}

From source file:de.betterform.connector.xmlrpc.XMLRPCURIResolver.java

/**
 * Parses the URI into three elements./*from   w ww . ja  v  a2 s .  c  o m*/
 * The xmlrpc URL, the function and the params
 *
 * @return a Vector
 */
private Vector parseURI(URI uri) {
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    String query = uri.getQuery();

    /* Split the path up into basePath and function */
    int finalSlash = path.lastIndexOf('/');
    String basePath = "";
    if (finalSlash > 0) {
        basePath = path.substring(1, finalSlash);
    }
    String function = path.substring(finalSlash + 1, path.length());

    String rpcURL = "http://" + host + ":" + port + "/" + basePath;

    log.debug("New URL  = " + rpcURL);
    log.debug("Function = " + function);

    Hashtable paramHash = new Hashtable();

    if (query != null) {
        String[] params = query.split("&");

        for (int i = 0; i < params.length; i++) {
            log.debug("params[" + i + "] = " + params[i]);
            String[] keyval = params[i].split("=");
            log.debug("\t" + keyval[0] + " -> " + keyval[1]);
            paramHash.put(keyval[0], keyval[1]);
        }
    }

    Vector ret = new Vector();
    ret.add(rpcURL);
    ret.add(function);
    ret.add(paramHash);
    return ret;
}

From source file:edu.harvard.mcz.imagecapture.encoder.LabelEncoder.java

private BitMatrix getQRCodeMatrix() {
    BitMatrix result = null;//from w  ww  .j  a v  a  2  s  .c om
    QRCodeWriter writer = new QRCodeWriter();
    try {
        String data = label.toJSONString();
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hints = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); // set ErrorCorrectionLevel here
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        result = writer.encode(data, BarcodeFormat.QR_CODE, 200, 200, hints);
    } catch (WriterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}