Example usage for java.util Map isEmpty

List of usage examples for java.util Map isEmpty

Introduction

In this page you can find the example usage for java.util Map isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:it.scoppelletti.programmerpower.web.security.CompositeDecisionManagerContributor.java

/**
 * Restituisce la lista dei configurazioni di attributi di controllo che
 * devono essere considerate da un componente di controllo.
 * /*from  ww  w  .  j a  v  a 2s  .c  o  m*/
 * @param  beanName Nome del bean.
 * @param  applCtx  Contesto dell’applicazione.
 * @return          Collezione.
 */
static List<FilterInvocationSecurityMetadataSource> listSecurityMetadataSource(String beanName,
        ApplicationContext applCtx) {
    String targetName;
    FilterInvocationSecurityMetadataSource securityMds;
    List<FilterInvocationSecurityMetadataSource> list;
    Map<String, CompositeDecisionManagerContributor> contributorMap;

    if (Strings.isNullOrEmpty(beanName)) {
        throw new ArgumentNullException("beanName");
    }
    if (applCtx == null) {
        throw new ArgumentNullException("applCtx");
    }

    list = new ArrayList<FilterInvocationSecurityMetadataSource>();

    myLogger.trace("Searching for CompositeDecisionManagerContributor " + "beans with targetName={}.",
            beanName);
    contributorMap = applCtx.getBeansOfType(CompositeDecisionManagerContributor.class, true, true);
    if (contributorMap == null || contributorMap.isEmpty()) {
        myLogger.warn("No CompositeDecisionManagerContributor bean found.");
        return list;
    }

    for (Map.Entry<String, CompositeDecisionManagerContributor> entry : contributorMap.entrySet()) {
        targetName = entry.getValue().getTargetName();
        if (Strings.isNullOrEmpty(targetName)) {
            myLogger.warn("Invalid CompositeDecisionManagerContributor bean.",
                    new PropertyNotSetException(entry.getKey(), "targetName"));
            continue;
        }
        if (!beanName.equals(targetName)) {
            continue;
        }

        myLogger.trace("Found CompositeDecisionManagerContributor bean {}" + "for bean {}.", entry.getKey(),
                beanName);

        securityMds = entry.getValue().getSecurityMetadataSource();
        if (securityMds == null) {
            myLogger.warn("Invalid CompositeDecisionManagerContributor bean.",
                    new PropertyNotSetException(entry.getKey(), "securityMetadataSource"));
            continue;
        }

        list.add(securityMds);
    }
    if (list.isEmpty()) {
        myLogger.warn("SecurityMetadataSource list is empty for bean {}.", beanName);
    }

    return list;
}

From source file:com.cisco.oss.foundation.message.HornetQMessagingFactory.java

/**
 * build once the hornetq service locator.
 * this is where we read the ost port list from configuration
 *///from  w w w  .ja va  2  s.co  m
private static void init() {
    try {

        cleanup();

        //            nettyFactory = HornetQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName())).createSessionFactory();
        Configuration configuration = ConfigurationFactory.getConfiguration();
        Configuration subset = configuration.subset("service.hornetq.connections");

        final Map<String, Map<String, String>> serverConnections = ConfigUtil
                .parseComplexArrayStructure("service.hornetq.connections");
        boolean isVersionPrinted = false;
        if (serverConnections != null && !serverConnections.isEmpty()) {
            if (isActiveActiveMode(subset)) {
                final ArrayList<String> serverConnectionKeys = Lists.newArrayList(serverConnections.keySet());
                Collections.sort(serverConnectionKeys);
                for (String serverConnectionKey : serverConnectionKeys) {
                    String host1Param = "service.hornetq.connections." + serverConnectionKey
                            + ".instance1.host";
                    String port1Param = "service.hornetq.connections." + serverConnectionKey
                            + ".instance1.port";
                    String jmxPort1Param = "service.hornetq.connections." + serverConnectionKey
                            + ".instance1.jmxPort";
                    String host2Param = "service.hornetq.connections." + serverConnectionKey
                            + ".instance2.host";
                    String port2Param = "service.hornetq.connections." + serverConnectionKey
                            + ".instance2.port";
                    String host1 = configuration.getString(host1Param, null);
                    String port1 = configuration.getString(port1Param, null);
                    String host2 = configuration.getString(host2Param, null);
                    String port2 = configuration.getString(port2Param, null);

                    if (StringUtils.isAnyBlank(host1Param, host2Param, port1Param, port2Param)) {
                        throw new IllegalArgumentException(
                                "each HornetQ active active pair must contain all these suffixed {instance1.host, instance1.port, instance2.host, instance2.port} - but some are missing");
                    }

                    if (!isVersionPrinted) {
                        printHQVersion(host1, configuration.getString(jmxPort1Param, "3900"));
                    }
                    transportConfigurationsArray = new TransportConfiguration[2];
                    List<TransportConfiguration> transportConfigurations = new ArrayList<TransportConfiguration>();

                    Map<String, Object> map1 = new HashMap<String, Object>();
                    map1.put("host", host1);
                    map1.put("port", port1);

                    transportConfigurations
                            .add(new TransportConfiguration(NettyConnectorFactory.class.getName(), map1));

                    Map<String, Object> map2 = new HashMap<String, Object>();
                    map2.put("host", host2);
                    map2.put("port", port2);

                    transportConfigurations
                            .add(new TransportConfiguration(NettyConnectorFactory.class.getName(), map2));

                    transportConfigurations.toArray(transportConfigurationsArray);
                    connect();
                }

            } else {

                final ArrayList<String> serverConnectionKeys = Lists.newArrayList(serverConnections.keySet());
                Collections.sort(serverConnectionKeys);

                printHQVersion(serverConnections, serverConnectionKeys);

                transportConfigurationsArray = new TransportConfiguration[serverConnectionKeys.size()];
                List<TransportConfiguration> transportConfigurations = new ArrayList<TransportConfiguration>();

                for (String serverConnectionKey : serverConnectionKeys) {

                    Map<String, String> serverConnection = serverConnections.get(serverConnectionKey);

                    Map<String, Object> map = new HashMap<String, Object>();

                    map.put("host", serverConnection.get("host"));
                    map.put("port", serverConnection.get("port"));

                    transportConfigurations
                            .add(new TransportConfiguration(NettyConnectorFactory.class.getName(), map));

                }

                transportConfigurations.toArray(transportConfigurationsArray);
                connect();
            }

        } else {
            throw new IllegalArgumentException(
                    "'service.hornetq.connections' must contain at least on host/port pair.");
        }

        setupConsumers();

    } catch (Exception e) {
        LOGGER.error("can't create hornetq service locator: {}", e, e);
        throw new QueueException(e);
    }

}

From source file:com.joyent.manta.util.MantaUtils.java

/**
 * Converts a map of string to object values to a pure string map.
 *
 * @param map map to convert/*  w w  w  .  ja v  a  2 s. c o  m*/
 * @return a string map
 */
public static Map<String, String> asStringMap(final Map<String, ?> map) {
    Validate.notNull(map, "Map must not be null");

    if (map.isEmpty()) {
        return Collections.emptyMap();
    }

    final Map<String, String> stringMap = new LinkedHashMap<>(map.size());

    // Silly Java generics won't covert wildcard to simple generic
    @SuppressWarnings("unchecked")
    final Map<String, Object> objectMap = (Map<String, Object>) map;
    final Set<Map.Entry<String, Object>> entrySet = objectMap.entrySet();

    for (Map.Entry<String, Object> next : entrySet) {
        final Object obj = next.getValue();
        final String value;

        if (obj == null || obj instanceof String) {
            value = (String) obj;
        } else if (obj instanceof InetAddress) {
            value = ((InetAddress) obj).getHostAddress();
        } else if (obj instanceof Map) {
            value = csv((Map) obj);
        } else if (obj instanceof Iterable) {
            value = csv((Iterable) obj);
        } else if (obj instanceof CharSequence) {
            value = String.valueOf(obj);
        } else {
            value = obj.toString();
        }

        stringMap.put(next.getKey(), value);
    }

    return Collections.unmodifiableMap(stringMap);
}

From source file:Main.java

public static <T> boolean hasCycle(Collection<T> vertices, Function<T, Collection<T>> neighborExtractor) {
    Map<T, Collection<T>> parents = vertices.stream().collect(toMap(identity(), v -> new ArrayList<T>()));
    vertices.forEach(/*from w ww. j  a  v a  2  s .  c  o m*/
            v -> nullSafeCollection(neighborExtractor.apply(v)).forEach(child -> parents.get(child).add(v)));

    Set<T> roots = vertices.stream().filter(v -> parents.get(v).isEmpty()).collect(Collectors.toSet());

    while (!roots.isEmpty()) {
        T root = roots.iterator().next();
        roots.remove(root);
        parents.remove(root);

        nullSafeCollection(neighborExtractor.apply(root)).forEach(child -> {
            parents.get(child).remove(root);
            if (parents.get(child).isEmpty()) {
                roots.add(child);
            }
        });

    }

    return !parents.isEmpty();
}

From source file:org.wrml.runtime.format.application.vnd.wrml.design.schema.SchemaDesignFormatter.java

public static ObjectNode buildSchemaNode(final ObjectMapper objectMapper, final URI schemaUri,
        final SchemaLoader schemaLoader, final Set<URI> addedBaseSchemaUris) {

    final Prototype prototype = schemaLoader.getPrototype(schemaUri);
    if (prototype == null) {
        return null;
    }//from  w ww . j ava 2 s  .c o m

    final ObjectNode schemaNode = objectMapper.createObjectNode();
    schemaNode.put(PropertyName.localName.name(), prototype.getUniqueName().getLocalName());
    schemaNode.put(PropertyName.title.name(), prototype.getTitle());
    schemaNode.put(PropertyName.uri.name(), schemaUri.toString());
    schemaNode.put(PropertyName.version.name(), prototype.getVersion());

    String titleSlotName = prototype.getTitleSlotName();
    if (StringUtils.isNotBlank(titleSlotName)) {
        schemaNode.put(PropertyName.titleSlotName.name(), titleSlotName);
    } else {
        titleSlotName = getTitleSlotName(schemaUri, schemaLoader);
        if (StringUtils.isNotBlank(titleSlotName)) {
            schemaNode.put(PropertyName.titleSlotName.name(), titleSlotName);
        }
    }

    final Set<String> allSlotNames = prototype.getAllSlotNames();
    if (allSlotNames != null && !allSlotNames.isEmpty()) {
        final ArrayNode propertyNamesNode = objectMapper.createArrayNode();

        for (final String slotName : allSlotNames) {
            final ProtoSlot protoSlot = prototype.getProtoSlot(slotName);
            if (protoSlot instanceof LinkProtoSlot) {
                continue;
            }

            if (protoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                propertyNamesNode.add(slotName);
            }
        }
        if (propertyNamesNode.size() > 0) {
            schemaNode.put(PropertyName.propertyNames.name(), propertyNamesNode);
        }
    }

    final Set<String> keySlotNames = prototype.getDeclaredKeySlotNames();
    if (keySlotNames != null && !keySlotNames.isEmpty()) {
        final ArrayNode keyPropertyNamesNode = objectMapper.createArrayNode();

        for (final String keySlotName : keySlotNames) {
            keyPropertyNamesNode.add(keySlotName);
        }

        if (keyPropertyNamesNode.size() > 0) {
            schemaNode.put(PropertyName.keyPropertyNames.name(), keyPropertyNamesNode);
        }
    }

    final Set<String> allKeySlotNames = prototype.getAllKeySlotNames();
    final ArrayNode allKeySlotNamesNode = objectMapper.createArrayNode();
    schemaNode.put(PropertyName.allKeySlotNames.name(), allKeySlotNamesNode);

    for (final String keySlotName : allKeySlotNames) {
        allKeySlotNamesNode.add(keySlotName);
    }

    final Set<String> comparablePropertyNames = prototype.getComparableSlotNames();
    if (comparablePropertyNames != null && !comparablePropertyNames.isEmpty()) {
        final ArrayNode comparablePropertyNamesNode = objectMapper.createArrayNode();

        for (final String comparablePropertyName : comparablePropertyNames) {
            comparablePropertyNamesNode.add(comparablePropertyName);
        }

        if (comparablePropertyNamesNode.size() > 0) {
            schemaNode.put(PropertyName.comparablePropertyNames.name(), comparablePropertyNamesNode);
        }
    }

    final Map<URI, LinkProtoSlot> linkProtoSlots = prototype.getLinkProtoSlots();
    if (linkProtoSlots != null && !linkProtoSlots.isEmpty()) {
        final ArrayNode linkNamesNode = objectMapper.createArrayNode();

        for (final LinkProtoSlot linkProtoSlot : linkProtoSlots.values()) {
            if (linkProtoSlot.getDeclaringSchemaUri().equals(schemaUri)) {
                linkNamesNode.add(linkProtoSlot.getName());
            }
        }

        if (linkNamesNode.size() > 0) {
            schemaNode.put(PropertyName.linkNames.name(), linkNamesNode);
        }
    }

    final Set<URI> declaredBaseSchemaUris = prototype.getDeclaredBaseSchemaUris();
    if (declaredBaseSchemaUris != null && !declaredBaseSchemaUris.isEmpty() && addedBaseSchemaUris != null) {

        final ArrayNode baseSchemasNode = objectMapper.createArrayNode();
        for (final URI baseSchemaUri : declaredBaseSchemaUris) {
            if (!addedBaseSchemaUris.contains(baseSchemaUri)) {
                final ObjectNode baseSchemaNode = buildSchemaNode(objectMapper, baseSchemaUri, schemaLoader,
                        addedBaseSchemaUris);
                baseSchemasNode.add(baseSchemaNode);
                addedBaseSchemaUris.add(baseSchemaUri);
            }
        }

        if (baseSchemasNode.size() > 0) {
            schemaNode.put(PropertyName.baseSchemas.name(), baseSchemasNode);
        }
    }

    return schemaNode;
}

From source file:com.nts.alphamale.handler.DeviceHandler.java

public static DeviceInfo getDeviceInfomation(String serial) {

    DeviceInfo device;/* w ww  . j a v  a2 s.  c om*/
    if (DataQueue.DEVICE_MAP.containsKey(serial)) {
        return DataQueue.DEVICE_MAP.get(serial);
    }
    device = new DeviceInfo(serial);

    Map<String, String> prop = DeviceHandler.getProp(serial);
    if (!prop.isEmpty()) {
        device.setManufacturer(prop.get("ro.product.manufacturer"));
        device.setDeviceModel(prop.get("ro.product.model"));
        device.setBuild(prop.get("ro.build.version.release"));
    }
    Map<String, Object> input = DeviceHandler.getInputManager(serial);
    if (!input.isEmpty()) {
        // f(input.get("velocity")!=null)
        // device.setVelocity(Double.valueOf(input.get("velocity")));
        if (input.get("xScale") != null)
            device.setxScale(Double.valueOf((String) input.get("xScale")));
        if (input.get("yScale") != null)
            device.setyScale(Double.valueOf((String) input.get("yScale")));
        if (input.get("width") != null)
            device.setWidth(Integer.valueOf((String) input.get("width")));
        if (input.get("height") != null)
            device.setHeight(Integer.valueOf((String) input.get("height")));
        if (input.get("pointerVelocityControlParameters") != null) {
            //   device.setVelocityParams((Map<String,Object>)input.get("pointerVelocityControlParameters"));
        }
        if (input.get("tapInterval") != null) {
            //device.setTapInterval((Double)input.get("tapInterval"));
        }
        if (input.get("tapDragInterval") != null) {
            //device.setTapDragInterval((Double)input.get("tapDragInterval"));
        }
        if (input.get("multitouchSettleInterval") != null) {
            //device.setMultitouchSettleInterval((Double)input.get("multitouchSettleInterval"));
        }
        if (input.get("multitouchMinDistance") != null) {
            //device.setMultitouchMinDistance((Double)input.get("multitouchMinDistance"));
        }
        if (input.get("swipeTransitionAngleCosine") != null) {
            //device.setSwipeTransitionAngleCosine((Double)input.get("swipeTransitionAngleCosine"));
        }
        if (input.get("swipeMaxWidthRatio") != null) {
            //device.setSwipeMaxWidthRatio((Double)input.get("swipeMaxWidthRatio"));
        }
        if (input.get("movementSpeedRatio") != null) {
            //device.setMovementSpeedRatio((Double)input.get("movementSpeedRatio"));
        }
        if (input.get("zoomSpeedRatio") != null) {
            //device.setZoomSpeedRatio((Double)input.get("zoomSpeedRatio"));
        }
    }
    return device;
}

From source file:com.linkedin.helix.tools.ClusterStateVerifier.java

static boolean verifyBestPossAndExtView(HelixDataAccessor accessor,
        Map<String, Map<String, String>> errStates) {
    try {/*w  ww  . j a v a  2s .  c om*/
        Builder keyBuilder = accessor.keyBuilder();
        // read cluster once and do verification
        ClusterDataCache cache = new ClusterDataCache();
        cache.refresh(accessor);

        Map<String, IdealState> idealStates = cache.getIdealStates();
        if (idealStates == null) // || idealStates.isEmpty())
        {
            // ideal state is null because ideal state is dropped
            idealStates = Collections.emptyMap();
        }

        Map<String, ExternalView> extViews = accessor.getChildValuesMap(keyBuilder.externalViews());
        if (extViews == null) // || extViews.isEmpty())
        {
            extViews = Collections.emptyMap();
        }

        // if externalView is not empty and idealState doesn't exist
        //  add empty idealState for the resource
        for (String resource : extViews.keySet()) {
            if (!idealStates.containsKey(resource)) {
                idealStates.put(resource, new IdealState(resource));
            }
        }

        // calculate best possible state
        BestPossibleStateOutput bestPossOutput = ClusterStateVerifier.calcBestPossState(cache);

        // set error states
        if (errStates != null) {
            for (String resourceName : errStates.keySet()) {
                Map<String, String> partErrStates = errStates.get(resourceName);
                for (String partitionName : partErrStates.keySet()) {
                    String instanceName = partErrStates.get(partitionName);
                    Map<String, String> partStateMap = bestPossOutput.getInstanceStateMap(resourceName,
                            new Partition(partitionName));
                    partStateMap.put(instanceName, "ERROR");
                }
            }
        }

        for (String resourceName : idealStates.keySet()) {
            ExternalView extView = extViews.get(resourceName);
            if (extView == null) {
                LOG.info("externalView for " + resourceName + " is not available");
                return false;
            }

            // step 0: remove empty map and DROPPED state from best possible state
            Map<Partition, Map<String, String>> bpStateMap = bestPossOutput.getResourceMap(resourceName);
            Iterator<Entry<Partition, Map<String, String>>> iter = bpStateMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<Partition, Map<String, String>> entry = iter.next();
                Map<String, String> instanceStateMap = entry.getValue();
                if (instanceStateMap.isEmpty()) {
                    iter.remove();
                } else {
                    // remove instances with DROPPED state
                    Iterator<Map.Entry<String, String>> insIter = instanceStateMap.entrySet().iterator();
                    while (insIter.hasNext()) {
                        Map.Entry<String, String> insEntry = insIter.next();
                        String state = insEntry.getValue();
                        if (state.equalsIgnoreCase("DROPPED")) {
                            insIter.remove();
                        }
                    }
                }
            }

            // System.err.println("resource: " + resourceName + ", bpStateMap: " + bpStateMap);

            // step 1: externalView and bestPossibleState has equal size
            int extViewSize = extView.getRecord().getMapFields().size();
            int bestPossStateSize = bestPossOutput.getResourceMap(resourceName).size();
            if (extViewSize != bestPossStateSize) {
                LOG.info("exterView size (" + extViewSize + ") is different from bestPossState size ("
                        + bestPossStateSize + ") for resource: " + resourceName);
                // System.out.println("extView: " + extView.getRecord().getMapFields());
                // System.out.println("bestPossState: " +
                // bestPossOutput.getResourceMap(resourceName));
                return false;
            }

            // step 2: every entry in external view is contained in best possible state
            for (String partition : extView.getRecord().getMapFields().keySet()) {
                Map<String, String> evInstanceStateMap = extView.getRecord().getMapField(partition);
                Map<String, String> bpInstanceStateMap = bestPossOutput.getInstanceStateMap(resourceName,
                        new Partition(partition));

                boolean result = ClusterStateVerifier.<String, String>compareMap(evInstanceStateMap,
                        bpInstanceStateMap);
                if (result == false) {
                    LOG.info("externalView is different from bestPossibleState for partition:" + partition);
                    return false;
                }
            }
        }
        return true;
    } catch (Exception e) {
        LOG.error("exception in verification", e);
        return false;
    }

}

From source file:org.grails.datastore.mapping.core.DatastoreUtils.java

/**
 * Process all Datastore Sessions that have been registered for deferred close
 * for the given SessionFactory.//from w  w w .  j  av a 2 s .c om
 * @param datastore the Datastore to process deferred close for
 * @see #initDeferredClose
 * @see #releaseSession
 */
public static void processDeferredClose(Datastore datastore) {
    Assert.notNull(datastore, "No Datastore specified");
    Map<Datastore, Set<Session>> holderMap = deferredCloseHolder.get();
    if (holderMap == null || !holderMap.containsKey(datastore)) {
        throw new IllegalStateException("Deferred close not active for Datastore [" + datastore + "]");
    }
    logger.debug("Processing deferred close of Datastore Sessions");
    Set<Session> sessions = holderMap.remove(datastore);
    for (Session session : sessions) {
        closeSession(session);
    }
    if (holderMap.isEmpty()) {
        deferredCloseHolder.set(null);
    }
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * //from  w  ww  . ja v a2  s. co m
 * @param baseURL
 * @param parametersBody
 * @param sessionId
 * @param fileToUpload - The file to upload.
 * @param filename - The name of the file to use during the upload process.
 * @return The response received from the Minus API.
 * @throws MinusException
 */
public static MinusHttpResponse doUpload(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final File fileToUpload, final String filename) throws MinusException {

    DefaultHttpClient client = null;
    HttpPost uploadRequest = null;
    InputStream responseContent = null;

    try {
        String url = baseURL;
        if (parametersBody != null && !parametersBody.isEmpty()) {
            url += CommonUtils.encodeParams(parametersBody);
        }
        uploadRequest = new HttpPost(url);
        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        FileEntity fileEntity = new FileEntity(fileToUpload, "application/octet-stream");
        uploadRequest.setEntity(fileEntity);

        // We add this headers as specified by the Minus.com API during file
        // upload.
        uploadRequest.addHeader("Content-Disposition", "attachment; filename=a.bin");
        uploadRequest.addHeader("Content-Type", "application/octet-stream");

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

        client.setCookieStore(cookieStore);
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpResponse httpResponse = client.execute(uploadRequest);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        StringBuilder result = new StringBuilder();
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity respEntity = httpResponse.getEntity();
            if (respEntity != null) {
                result.append(EntityUtils.toString(respEntity));
                EntityUtils.consume(respEntity);
            }

        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append(" Upload failed => ").append(httpResponse.getStatusLine());
            if (uploadRequest != null) {
                errMsg.append(" : ").append(uploadRequest.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result.toString(), sessionCookie);

    } catch (Exception e) {
        if (uploadRequest != null) {
            uploadRequest.abort();
        }
        String errMsg = "Error while uploading file (" + fileToUpload + ") : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}

From source file:cmd.SMSDcmd.java

/**
 *
 * @param inputHandler/*from  w w  w  .  j  a  v a2  s  . c o m*/
 * @param outputHandler
 * @param argumentHandler
 * @throws IOException
 * @throws CDKException
 * @throws CloneNotSupportedException
 */
public static void runSingleQueryMultipleTarget(InputHandler inputHandler, OutputHandler outputHandler,
        ArgumentHandler argumentHandler) throws IOException, CDKException, CloneNotSupportedException {
    IAtomContainer query = inputHandler.getQuery();
    String name = (String) query.getProperty(CDKConstants.TITLE);
    boolean removeHydrogens = argumentHandler.isApplyHRemoval();

    /*
     * check connectivity
     */
    boolean flag = ConnectivityChecker.isConnected(query);
    if (!flag) {
        System.err.println("WARNING : Skipping file " + inputHandler.getQueryName() + " not connected ");
        return;
    }
    if (removeHydrogens) {
        query = new AtomContainer(AtomContainerManipulator.removeHydrogens(query));
        query.setProperty(CDKConstants.TITLE, name);
        query.setID(name);
    }

    outputHandler.writeQueryMol(query);

    String out = ".out";
    outputHandler.startAppending(out);

    long startTime = System.currentTimeMillis();
    BaseMapping smsd;
    boolean matchBonds = argumentHandler.isMatchBondType();
    boolean matchRings = argumentHandler.isMatchRingType();
    boolean matchAtomTypes = argumentHandler.isMatchAtomType();

    int targetNumber = 0;
    List<IAtomContainer> allTargets = inputHandler.getAllTargets();
    String targetType = argumentHandler.getTargetType();
    if (allTargets == null) {
        throw new IOException("Unknown input type " + targetType);
    }
    for (IAtomContainer target : allTargets) {
        flag = ConnectivityChecker.isConnected(target);
        if (!flag) {
            logger.error("WARNING : Skipping target AtomContainer " + target.getProperty(CDKConstants.TITLE)
                    + " as it is not connected.");
            continue;
        }

        inputHandler.configure(target, targetType);

        if (argumentHandler.isSubstructureMode()) {
            smsd = runSubstructure(query, target, argumentHandler.getChemFilter(), matchBonds, matchRings,
                    matchAtomTypes);
        } else {
            smsd = run(query, target, argumentHandler.getChemFilter(), matchBonds, matchRings, matchAtomTypes);
        }

        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        outputHandler.writeTargetMol(smsd.getTarget());

        String queryPath = argumentHandler.getQueryFilepath();
        String targetPath = argumentHandler.getTargetFilepath();

        IAtomContainer queryLocal = query.getBuilder().newInstance(IAtomContainer.class,
                smsd.getFirstAtomMapping().getQuery());
        IAtomContainer targetLocal = target.getBuilder().newInstance(IAtomContainer.class,
                smsd.getFirstAtomMapping().getTarget());
        Map<IAtom, IAtom> mcs = smsd.getFirstAtomMapping().getMappingsByAtoms();
        int nAtomsMatched = (mcs == null) ? 0 : mcs.size();
        double tanimotoSimilarity = smsd.getTanimotoSimilarity();
        //print out all mappings
        if (mcs != null && !mcs.isEmpty() && argumentHandler.isAllMapping()) {
            outputHandler.printHeader(queryPath, targetPath, nAtomsMatched);
            int counter = 0;
            for (AtomAtomMapping aam : smsd.getAllAtomMapping()) {
                Map<Integer, Integer> mapping = aam.getMappingsByIndex();
                if (argumentHandler.isImage() && !mapping.isEmpty()) {
                    double stereoScore = smsd.getStereoScore(counter);
                    String label = outputHandler.makeLabel(tanimotoSimilarity, stereoScore);
                    outputHandler.addImage(queryLocal, targetLocal, label, mapping);
                }
                outputHandler.printMapping((counter + 1), mapping);
                counter += 1;
            }
        } //print out top one
        else if (mcs != null && !mcs.isEmpty() && !argumentHandler.isAllMapping()) {
            Map<Integer, Integer> mcsNumber = smsd.getFirstAtomMapping().getMappingsByIndex();
            double stereoScore = smsd.getStereoScore(0);
            outputHandler.printHeader(queryPath, targetPath, nAtomsMatched);
            String qrefName = inputHandler.getQRefName();
            String trefName = inputHandler.getTRefName();
            outputHandler.printTopMapping(nAtomsMatched, mcs, mcsNumber, qrefName, trefName);
            if (argumentHandler.isImage() && !mcs.isEmpty()) {
                String label = outputHandler.makeLabel(tanimotoSimilarity, stereoScore);
                outputHandler.makeImage(queryLocal, targetLocal, label, mcsNumber);
            }
        }
        double tanimotoGraph = smsd.getTanimotoSimilarity();
        //            double tanimotoAtom = smsd.getTanimotoAtomSimilarity();
        //            double tanimotoBond = smsd.getTanimotoBondSimilarity();
        double euclidianGraph = smsd.getEuclideanDistance();
        //            outputHandler.writeResults(queryLocal, targetLocal, tanimotoGraph, tanimotoAtom, tanimotoBond, euclidianGraph, nAtomsMatched, executionTime);

        outputHandler.writeResults(queryLocal, targetLocal, tanimotoGraph, euclidianGraph, nAtomsMatched,
                executionTime);
        if (mcs != null && !mcs.isEmpty() && argumentHandler.isImage()) {
            String qName = inputHandler.getQueryName();
            String tName = inputHandler.getTargetName() + "_" + targetNumber;
            outputHandler.writeImage(qName, tName);
        }
        targetNumber++;
    }
    outputHandler.closeFiles();
}