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.mirth.connect.connectors.jms.JmsClient.java

private ConnectionFactory lookupConnectionFactoryWithJndi() throws Exception {
    String channelId = connector.getChannelId();
    String channelName = connector.getChannel().getName();

    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {// w  w  w.j av  a2  s  .  c o  m
        MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds);
        Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.PROVIDER_URL,
                replacer.replaceValues(connectorProperties.getJndiProviderUrl(), channelId, channelName));
        env.put(Context.INITIAL_CONTEXT_FACTORY, replacer
                .replaceValues(connectorProperties.getJndiInitialContextFactory(), channelId, channelName));
        env.put(Context.SECURITY_PRINCIPAL,
                replacer.replaceValues(connectorProperties.getUsername(), channelId, channelName));
        env.put(Context.SECURITY_CREDENTIALS,
                replacer.replaceValues(connectorProperties.getPassword(), channelId, channelName));

        initialContext = new InitialContext(env);
        String connectionFactoryName = replacer
                .replaceValues(connectorProperties.getJndiConnectionFactoryName(), channelId, channelName);
        return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:hd.controller.AddImageToProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w  w  .j  av  a  2s  .  co  m*/
 *
 * @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);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            String productID = (String) params.get("txtProductId");
            System.out.println(productID);
            String tilte = (String) params.get("newGalleryName");
            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;
            ProductDAO productDao = new ProductDAO();
            ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID);

            response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:com.tremolosecurity.scale.totp.TotpController.java

@PostConstruct
public void init() {
    this.error = null;
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();//w  ww  . j  a v a2 s .c o m

    this.scaleTotpConfig = (ScaleTOTPConfigType) commonConfig.getScaleConfig();

    this.login = request.getRemoteUser();

    UnisonUserData userData;
    try {
        userData = this.scaleSession.loadUserFromUnison(this.login,
                new AttributeData(scaleTotpConfig.getServiceConfiguration().getLookupAttributeName(),
                        scaleTotpConfig.getUiConfig().getDisplayNameAttribute(),
                        scaleTotpConfig.getAttributeName()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    this.user = userData.getUserObj();

    this.displayName = userData.getUserObj().getDisplayName();

    ScaleAttribute scaleAttr = userData.getUserObj().getAttrs().get(scaleTotpConfig.getAttributeName());
    if (scaleAttr == null) {
        if (logger.isDebugEnabled())
            logger.debug("no sattribute");
        this.error = "Token not found";
        return;
    }

    this.encryptedToken = scaleAttr.getValue();

    try {
        byte[] decryptionKeyBytes = Base64.decodeBase64(scaleTotpConfig.getDecryptionKey().getBytes("UTF-8"));
        SecretKey decryptionKey = new SecretKeySpec(decryptionKeyBytes, 0, decryptionKeyBytes.length, "AES");

        Gson gson = new Gson();
        Token token = gson.fromJson(new String(Base64.decodeBase64(this.encryptedToken.getBytes("UTF-8"))),
                Token.class);
        byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());
        IvParameterSpec spec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, decryptionKey, spec);

        String decryptedJSON = new String(
                cipher.doFinal(Base64.decodeBase64(token.getEncryptedRequest().getBytes("UTF-8"))));

        if (logger.isDebugEnabled())
            logger.debug(decryptedJSON);

        TOTPKey totp = gson.fromJson(decryptedJSON, TOTPKey.class);

        this.otpURL = "otpauth://totp/" + totp.getUserName() + "@" + totp.getHost() + "?secret="
                + totp.getSecretKey();

    } catch (Exception e) {
        e.printStackTrace();
        this.error = "Could not decrypt token";
    }

    try {
        int size = 250;
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(this.otpURL, BarcodeFormat.QR_CODE, size, size, hintMap);
        int CrunchifyWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < CrunchifyWidth; i++) {
            for (int j = 0; j < CrunchifyWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageIO.write(image, "png", baos);

        this.encodedQRCode = new String(Base64.encodeBase64(baos.toByteArray()));
    } catch (Exception e) {
        e.printStackTrace();
        this.error = "Could not encode QR Code";
    }

}

From source file:com.xpn.xwiki.util.Util.java

/**
 * Create a Map from a string holding a space separated list of key=value pairs. If keys or values must contain
 * spaces, they can be placed inside quotes, like <code>"this key"="a larger value"</code>. To use a quote as part
 * of a key/value, use <code>%_Q_%</code>.
 * /*from w w  w . j  av  a2s  . c om*/
 * @param mapString The string that must be parsed.
 * @return A Map containing the keys and values. If a key is defined more than once, the last value is used.
 */
public static Hashtable<String, String> keyValueToHashtable(String mapString) throws IOException {
    Hashtable<String, String> result = new Hashtable<String, String>();
    StreamTokenizer st = new StreamTokenizer(new BufferedReader(new StringReader(mapString)));
    st.resetSyntax();
    st.quoteChar('"');
    st.wordChars('a', 'z');
    st.wordChars('A', 'Z');
    st.whitespaceChars(' ', ' ');
    st.whitespaceChars('=', '=');
    while (st.nextToken() != StreamTokenizer.TT_EOF) {
        String key = st.sval;
        st.nextToken();
        String value = (st.sval != null) ? st.sval : "";
        result.put(key, restoreValue(value));
    }
    return result;
}

From source file:gov.pnnl.goss.gridappsd.GridAppsDataSourcesComponentTests.java

@Test
/**//from   w  ww  .  j  ava  2 s  . c o  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 registryUpdatedWhen_dataSourcesStarted() {
    ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);
    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());

}

From source file:info.magnolia.module.templatingcomponents.jspx.AbstractJspTest.java

@Before
public void setUp() throws Exception {
    // this was mainly copied from displaytag's org.displaytag.test.DisplaytagCase

    // 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) {
        fail("Could not find WEB-INF/web.xml");
    }/*w ww .  java 2s .c  om*/
    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()) {
        assertTrue("Can't create path " + jspScratchDirAbs + ", aborting test", jspScratchDir.mkdirs());
    }
    final File checkFile = new File(jspScratchDir, "empty");
    assertTrue("Can't write check file: " + checkFile + ", aborting test", checkFile.createNewFile());
    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
    websiteHM = MockUtil.createHierarchyManager(StringUtils.join(Arrays.asList("/foo/bar@type=mgnl:content",
            "/foo/bar/MetaData@type=mgnl:metadata", "/foo/bar/MetaData/mgnl\\:template=testPageTemplate",
            "/foo/bar/paragraphs@type=mgnl:contentNode", "/foo/bar/paragraphs/0@type=mgnl:contentNode",
            "/foo/bar/paragraphs/0/text=hello 0", "/foo/bar/paragraphs/0/MetaData@type=mgnl:metadata",
            "/foo/bar/paragraphs/0/MetaData/mgnl\\:template=testParagraph0",
            "/foo/bar/paragraphs/1@type=mgnl:contentNode", "/foo/bar/paragraphs/1/text=hello 1",
            "/foo/bar/paragraphs/1/MetaData@type=mgnl:metadata",
            "/foo/bar/paragraphs/1/MetaData/mgnl\\:template=testParagraph1",
            "/foo/bar/paragraphs/2@type=mgnl:contentNode", "/foo/bar/paragraphs/2/text=hello 2",
            "/foo/bar/paragraphs/2/MetaData@type=mgnl:metadata",
            "/foo/bar/paragraphs/2/MetaData/mgnl\\:template=testParagraph2", ""), "\n"));

    final AggregationState aggState = new AggregationState();
    setupAggregationState(aggState);

    // let's make sure we render stuff on an author instance
    aggState.setPreviewMode(false);

    final ServerConfiguration serverCfg = new ServerConfiguration();
    serverCfg.setAdmin(true);
    ComponentsTestUtil.setInstance(ServerConfiguration.class, serverCfg);

    // register some default components used internally
    ComponentsTestUtil.setInstance(MessagesManager.class, new DefaultMessagesManager());
    final DefaultI18nContentSupport i18nContentSupport = new DefaultI18nContentSupport();
    i18nContentSupport.setEnabled(true);
    i18nContentSupport.addLocale(LocaleDefinition.make("fr", "CH", true));
    i18nContentSupport.addLocale(LocaleDefinition.make("de", "CH", true));
    i18nContentSupport.addLocale(LocaleDefinition.make("de", null, true));
    ComponentsTestUtil.setInstance(I18nContentSupport.class, i18nContentSupport);
    final DefaultI18nAuthoringSupport i18nAuthoringSupport = new DefaultI18nAuthoringSupport();
    i18nAuthoringSupport.setEnabled(true);
    // TODO - tests with i18AuthoringSupport disabled/enabled
    ComponentsTestUtil.setInstance(I18nAuthoringSupport.class, i18nAuthoringSupport);

    final Template t1 = new Template();
    t1.setName("testPageTemplate");
    t1.setI18nBasename("info.magnolia.module.templatingcomponents.test_messages");
    final AbstractAuthoringUiComponentTest.TestableTemplateManager tman = new AbstractAuthoringUiComponentTest.TestableTemplateManager();
    tman.register(t1);
    ComponentsTestUtil.setInstance(TemplateManager.class, tman);
    ComponentsTestUtil.setInstance(RenderingEngine.class, new DefaultRenderingEngine());

    req = createMock(HttpServletRequest.class);
    // cheating - this mock request is NOT the same that's used by htmlunit to do the ACTUAL request
    expect(req.getAttribute(Sources.REQUEST_LINKS_DRAWN)).andReturn(Boolean.FALSE).anyTimes();//times(0, 1);
    req.setAttribute(Sources.REQUEST_LINKS_DRAWN, Boolean.TRUE);
    expectLastCall().anyTimes();//times(0, 1);

    ctx = createMock(WebContext.class);
    expect(ctx.getAggregationState()).andReturn(aggState).anyTimes();
    expect(ctx.getLocale()).andReturn(Locale.US).anyTimes();
    expect(ctx.getContextPath()).andReturn("/lol").anyTimes();
    expect(ctx.getServletContext()).andStubReturn(createMock(ServletContext.class));
    expect(ctx.getRequest()).andStubReturn(req);
    MgnlContext.setInstance(ctx);

    setupExpectations(ctx, websiteHM, req);

    replay(ctx, req);
}

From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

private DirContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());

    try {//from  w  w w.  ja  va2s . c o  m
        return contextFactory.createContext(env);
    } catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials(e);
        } else {
            throw LdapUtils.convertLdapException(e);
        }
    }
}

From source file:gov.pnnl.goss.gridappsd.GridAppsDataSourcesComponentTests.java

@Test
/**// w w w. j  a  va 2  s . com
 *    Succeeds when the registry is empty after the service has been stopped
 */
public void registryClearedWhen_dataSourcesStopped() {
    ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);
    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());

    dataSources.stop();

    assertEquals(0, dataSources.getRegisteredDatasources().size());

}

From source file:com.bitcup.configurator.FileConfigProperties.java

private Hashtable<String, String> getHashTable() {
    Hashtable<String, String> ht = new Hashtable<String, String>();
    Iterator<String> keysIterator = getKeysIterator();
    for (; keysIterator.hasNext();) {
        String key = keysIterator.next();
        ht.put(key, this.fileConfig.getString(key));
    }//w ww. j  av a  2 s. co m
    return ht;
}

From source file:org.geowebcache.service.wms.WMSTileFuserTest.java

private WMSLayer createWMSLayer() {
    String[] urls = { "http://localhost:38080/wms" };
    List<String> formatList = new LinkedList<String>();
    formatList.add("image/png");

    Hashtable<String, GridSubset> grids = new Hashtable<String, GridSubset>();

    GridSubset grid = GridSubsetFactory.createGridSubSet(gridSetBroker.WORLD_EPSG4326,
            new BoundingBox(-30.0, 15.0, 45.0, 30), 0, 10);

    grids.put(grid.getName(), grid);
    int[] metaWidthHeight = { 3, 3 };

    WMSLayer layer = new WMSLayer("test:layer", urls, "aStyle", "test:layer", formatList, grids, null,
            metaWidthHeight, "vendorparam=true", false, null);

    layer.initialize(gridSetBroker);/* w ww.j a v  a  2s . c o  m*/

    return layer;
}