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:info.globalbus.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*from w  w  w. j a va2s  .co m*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test
            // validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:com.wirelessgalicia.logos.vista.web.services.ConsumidorVistaImplService.java

/**
 * Crea el consumidor de pruebas/*from  w  w  w  .  ja v a 2s.com*/
 */
@Override
public ServiceRegistration registrarConsumidorEventos() {
    if (LOGGER.isTraceEnabled())
        LOGGER.trace("registrarConsumidorEventos(" + consumidorEventosVO + ")");
    this.consumidorEventosService = new ConsumidorEventosVistaService(bundleContext, consumidorEventosVO);
    Hashtable<String, Object> props = new Hashtable<String, Object>();
    props.put(WireConstants.WIREADMIN_CONSUMER_FLAVORS, consumidorEventosVO.getSabores());
    props.put(org.osgi.framework.Constants.SERVICE_PID, consumidorEventosVO.getIdServicio());
    props.put(org.osgi.framework.Constants.SERVICE_DESCRIPTION, consumidorEventosVO.getDescServicio());
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Consumidor que se va a registrar:" + consumidorEventosVO + " flavors: "
                + consumidorEventosVO.getSabores());
    ServiceRegistration serviceReg = bundleContext.registerService(Consumer.class.getName(),
            consumidorEventosService, props);
    return serviceReg;
}

From source file:net.identio.server.service.authentication.ldap.LdapConnectionFactory.java

private InitialLdapContext createContext(LdapAuthMethod ldapAuthMethod, String userDn, String password)
        throws NamingException {

    LOG.debug("Begin creation of an LDAP connection to: {}", ldapAuthMethod.getName());

    int currentUrlIndexTs = currentUrlIndex;

    String currentUrl = ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs);

    Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, currentUrl);

    if (currentUrl.startsWith("ldaps://")) {

        // Add a custom SSL Socket factory to validate server CA
        env.put("java.naming.ldap.factory.socket",
                "net.identio.server.service.authentication.ldap.LdapSslSocketFactory");
    }/*from   w  ww .jav a  2s . co  m*/

    if (userDn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, userDn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    InitialLdapContext ctx;

    try {
        ctx = new InitialLdapContext(env, null);
    } catch (CommunicationException e) {

        LOG.error("Error when contacting LDAP server {}", ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs));

        if (ldapAuthMethod.getLdapUrl().size() > 1) {
            int newCurrentUrlIndex = currentUrlIndexTs < ldapAuthMethod.getLdapUrl().size() - 1
                    ? currentUrlIndexTs + 1
                    : 0;

            LOG.error("Switching to LDAP server {}", ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            currentUrlIndex = newCurrentUrlIndex;

            env.put(Context.PROVIDER_URL, ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            ctx = new InitialLdapContext(env, null);
        } else {
            throw e;
        }
    }

    return ctx;
}

From source file:com.wirelessgalicia.logos.vista.web.services.ConsumidorVistaImplService.java

/**
 * Crea el consumidor de pruebas//from   w w w  .j av a2s . co m
 */
@Override
public ServiceRegistration registrarConsumidorResultados() {
    if (LOGGER.isTraceEnabled())
        LOGGER.trace("registrarConsumidorResultados(" + consumidorResultadosVO + ")");
    this.consumidorResultadosService = new ConsumidorResultadosVistaService(bundleContext,
            consumidorResultadosVO);
    Hashtable<String, Object> props = new Hashtable<String, Object>();
    props.put(WireConstants.WIREADMIN_CONSUMER_FLAVORS, consumidorResultadosVO.getSabores());
    props.put(org.osgi.framework.Constants.SERVICE_PID, consumidorResultadosVO.getIdServicio());
    props.put(org.osgi.framework.Constants.SERVICE_DESCRIPTION, consumidorResultadosVO.getDescServicio());
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Consumidor que se va a registrar:" + consumidorResultadosVO + " flavors: "
                + consumidorResultadosVO.getSabores());
    ServiceRegistration serviceReg = bundleContext.registerService(Consumer.class.getName(),
            consumidorResultadosService, props);
    return serviceReg;
}

From source file:com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServletMappingConfigurationConsumer.java

/**
 * Internal helper to update the server registrations. Invoked on all events, will remove all server registrations and register
 * the servlet again based on active configurations.
 *//* w ww. j a v a2 s.com*/
private void updateServletRegistrations() {
    for (ServiceRegistration serviceRegistration : serviceRegistrations) {
        if (serviceRegistration != null) {
            serviceRegistration.unregister();
        }
    }
    serviceRegistrations.clear();

    if (bundleContext != null) {
        for (AdaptiveImageServletMappingConfigurationFactory config : configs.values()) {
            final Hashtable<String, Object> properties = new Hashtable<>();
            properties.put("sling.servlet.methods", new String[] { "GET" });
            properties.put("sling.servlet.resourceTypes", config.getResourceTypes());
            properties.put("sling.servlet.selectors", config.getSelectors());
            properties.put("sling.servlet.extensions", config.getExtensions());
            serviceRegistrations.add(bundleContext.registerService(Servlet.class.getName(),
                    new AdaptiveImageServlet(mimeTypeService, assetStore,
                            oldAISDefaultResizeWidth > 0 ? oldAISDefaultResizeWidth
                                    : config.getDefaultResizeWidth()),
                    properties));
        }
    }
}

From source file:com.nineteendrops.tracdrops.client.core.multicall.MulticallImpl.java

private ArrayList makeMulticall(TracProperties tracProperties) {

    ArrayList<CallElement> registeredCallElements = getMulticalls();
    if (registeredCallElements == null || registeredCallElements.size() == 0) {
        //throw new MulticallInvalidStateException(MessageUtils.getMessage("core.multicall.no.callelements"));
        MessageUtils.registerDebugLog(log, "core.multicall.no.callelements");

        return null;
    }/*from ww  w  .  j a  va 2  s. co m*/

    Multicall multicall = (Multicall) getTracInvocationObject(Multicall.class);

    if (log.isDebugEnabled()) {
        log.debug(MessageUtils.getMessage("core.multicall.preparing.multicall"));
        log.debug(MessageUtils.getMessage("symbol.line.separator"));
    }

    Vector tracCalls = new Vector();
    for (CallElement callElement : registeredCallElements) {
        Hashtable callToTrac = new Hashtable();
        callToTrac.put("methodName", callElement.getTracMethodName());
        callToTrac.put("params", callElement.getParameters());
        tracCalls.add(callToTrac);

        if (log.isDebugEnabled()) {

            logCallElement(callElement);
        }
    }

    Vector results = null;
    try {
        results = multicall.internalMulticall(tracCalls);
    } catch (TracException e) {
        // There was an error in the invocation
        if (isFailureInMethodExecution(e, tracProperties)) {
            dumpMulticallStack(registeredCallElements);
            throw new TracMethodExecutionException(
                    MessageUtils.registerErrorLog(log, "core.multicall.failure.method.invocation"), e);
        } else {
            throw e;
        }
    }

    ArrayList resultsFinal = new ArrayList();

    try {
        int resultOrder = 0;
        for (CallElement call : registeredCallElements) {
            ReturnDecoder returnDecoder = (ReturnDecoder) call.getReturnDecoder().newInstance();
            Object resultDecoded = returnDecoder.decode(((Object[]) results.get(resultOrder++))[0],
                    tracProperties, call.getKeptParametersForDecoder());
            resultsFinal.add(resultDecoded);
        }
    } catch (InstantiationException e) {
        throw new DecodingErrorException(MessageUtils.registerErrorLog(log,
                "core.multicall.error.decoding.return.value", e.getMessage()), e);
    } catch (IllegalAccessException e) {
        throw new DecodingErrorException(MessageUtils.registerErrorLog(log,
                "core.multicall.error.decoding.return.value", e.getMessage()), e);
    }

    return resultsFinal;
}

From source file:gda.jython.authenticator.LdapAuthenticator.java

private boolean checkAuthenticatedUsingServer(String ldapURL, String fedId, String password)
        throws NamingException {

    InitialLdapContext ctx = null;
    try {//from w  w w .  j  av  a 2  s. c o  m
        Hashtable<String, String> env = new Hashtable<String, String>();
        String principal = "CN=" + fedId + adminName;
        env.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, ldapURL);
        ctx = new InitialLdapContext(env, null);
        //if no exception then password is OK
        return true;
    } catch (AuthenticationException ae) {
        logger.error("LDAP AuthenticationException: " + StringEscapeUtils.escapeJava(ae.getMessage()));
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return false;
}

From source file:algorithm.F5SteganographyTest.java

@Test
public void f5SteganographyAlgorithmTest() {
    try {//from   ww  w . jav  a  2s .co m
        File carrier = TestDataProvider.JPG_FILE;
        File payload = TestDataProvider.TXT_FILE;
        F5Steganography algorithm = new F5Steganography();
        // Test encapsulation:
        List<File> payloadList = new ArrayList<File>();
        payloadList.add(payload);
        File outputFile = algorithm.encapsulate(carrier, payloadList);
        assertNotNull(outputFile);
        // Test restore:
        Hashtable<String, RestoredFile> outputHash = new Hashtable<String, RestoredFile>();
        for (RestoredFile file : algorithm.restore(outputFile)) {
            outputHash.put(file.getName(), file);
        }
        assertEquals(outputHash.size(), 2);
        RestoredFile restoredCarrier = outputHash.get(carrier.getName());
        RestoredFile restoredPayload = outputHash.get(payload.getName());
        assertNotNull(restoredCarrier);
        assertNotNull(restoredPayload);
        // only original payload can be restored, not carrier
        assertEquals(FileUtils.checksumCRC32(payload), FileUtils.checksumCRC32(restoredPayload));
        assertEquals(FileUtils.checksumCRC32(outputFile), FileUtils.checksumCRC32(restoredCarrier));

        // check restoration metadata:
        assertEquals("" + carrier.getAbsolutePath(), restoredCarrier.originalFilePath);
        assertEquals("" + payload.getAbsolutePath(), restoredPayload.originalFilePath);
        assertEquals(algorithm, restoredCarrier.algorithm);
        // This can't be true for steganography algorithms:
        // assertTrue(restoredCarrier.checksumValid);
        assertTrue(restoredPayload.checksumValid);
        assertTrue(restoredCarrier.wasCarrier);
        assertFalse(restoredCarrier.wasPayload);
        assertTrue(restoredPayload.wasPayload);
        assertFalse(restoredPayload.wasCarrier);
        assertTrue(restoredCarrier.relatedFiles.contains(restoredPayload));
        assertFalse(restoredCarrier.relatedFiles.contains(restoredCarrier));
        assertTrue(restoredPayload.relatedFiles.contains(restoredCarrier));
        assertFalse(restoredPayload.relatedFiles.contains(restoredPayload));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.floggy.persistence.fr2422928.FR2422928AbstractVersionTest.java

/**
 * DOCUMENT ME!/*from   w w w. j  av  a 2 s  .  c  o  m*/
*
* @throws Exception DOCUMENT ME!
*/
public void testFreezedClassIteration() throws Exception {
    Hashtable properties = new Hashtable();
    properties.put(MigrationManager.MIGRATE_FROM_PREVIOUS_1_3_0_VERSION, Boolean.TRUE);
    properties.put(MigrationManager.ITERATION_MODE, Boolean.TRUE);

    Enumeration enumeration = MigrationManager.getInstance().start(Freezed.class, properties);

    assertEquals(2, enumeration.getSize());

    if (enumeration.hasMoreElements()) {
        Hashtable data = enumeration.nextElement();
        assertNull(data.get("uuid"));
        assertNull(data.get("deadline"));
        assertNull(data.get("description"));
        assertNull(data.get("nested"));
        assertEquals(0, ((Short) data.get("code")).shortValue());
    }

    if (enumeration.hasMoreElements()) {
        Hashtable data = enumeration.nextElement();
        assertEquals(Freezed.UUID, data.get("uuid"));
        assertEquals(Freezed.DEADLINE, data.get("deadline"));
        assertEquals(Freezed.DESCRIPTION, data.get("description"));

        FieldPersistableInfo freezedInfo = (FieldPersistableInfo) data.get("nested");
        Freezed nested = new Freezed();
        manager.load(nested, freezedInfo.getId());

        assertEquals(Freezed.NESTED, nested);
        assertEquals(Freezed.CODE, ((Short) data.get("code")).shortValue());
    }
}

From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java

/**
 * displayName and mail are returned always, the map allows us to support
 * getting arbitrary properties in the future, hopefully
 *///from  w w w .  ja  va  2  s.c  o m
public Map<String, String> bind(String loginName, String password) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    LdapContext ctx = null;
    if (activeDirectoryDomain != null) { // we are using Active Directory            
        Control[] controls = new Control[] { control };
        ctx = new InitialLdapContext(env, controls);
        logger.debug("Active Directory LDAP context initialized");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        // javax.naming.AuthenticationException
        ctx.reconnect(controls);
        logger.debug("Active Directory LDAP bind successful");
    } else { // standard LDAP            
        env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase);
        env.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialLdapContext(env, null);
        logger.debug("Standard LDAP bind successful");
    }
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(returningAttributes);
    NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc);
    while (results.hasMoreElements()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();
        logger.debug("attributes: " + attrs);
        Map<String, String> map = new HashMap<String, String>(returningAttributes.length);
        for (String key : returningAttributes) {
            Attribute attr = attrs.get(key);
            if (attr != null) {
                map.put(key, (String) attr.get());
            }
        }
        return map; // there should be only one anyway            
    }
    // if we reached here, there was no search result
    throw new Exception("no results returned from ldap");
}