Example usage for java.util Map.Entry toString

List of usage examples for java.util Map.Entry toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String obtainOauth2Data(String destinationUrl) throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {/*from   w ww.  jav  a 2 s. c om*/
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - unexpected body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    {
        URI nakedUri;
        try {
            nakedUri = new URI(destinationUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error";
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    String contentType = entity.getContentType().getValue();
                    if (contentType.toLowerCase().contains("xml")) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                        StringBuilder b = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            b.append(line);
                        }
                        String value = b.toString();
                        return value;
                    } else {
                        logger.error("unexpected body");
                        return "Error";
                    }
                } else {
                    logger.error("unexpected missing body");
                    return "Error";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }
}

From source file:org.apache.hadoop.hbase.coprocessor.TestMasterObserver.java

@Test
public void testRegionTransitionOperations() throws Exception {
    MiniHBaseCluster cluster = UTIL.getHBaseCluster();

    HMaster master = cluster.getMaster();
    MasterCoprocessorHost host = master.getMasterCoprocessorHost();
    CPMasterObserver cp = (CPMasterObserver) host.findCoprocessor(CPMasterObserver.class.getName());
    cp.enableBypass(false);//  ww w  . ja va  2 s . com
    cp.resetStates();

    HTable table = UTIL.createTable(TEST_TABLE, TEST_FAMILY);

    try {
        UTIL.createMultiRegions(table, TEST_FAMILY);
        UTIL.waitUntilAllRegionsAssigned(TEST_TABLE);

        NavigableMap<HRegionInfo, ServerName> regions = table.getRegionLocations();
        Map.Entry<HRegionInfo, ServerName> firstGoodPair = null;
        for (Map.Entry<HRegionInfo, ServerName> e : regions.entrySet()) {
            if (e.getValue() != null) {
                firstGoodPair = e;
                break;
            }
        }
        assertNotNull("Found a non-null entry", firstGoodPair);
        LOG.info("Found " + firstGoodPair.toString());
        // Try to force a move
        Collection<ServerName> servers = master.getClusterStatus().getServers();
        String destName = null;
        String serverNameForFirstRegion = firstGoodPair.getValue().toString();
        LOG.info("serverNameForFirstRegion=" + serverNameForFirstRegion);
        boolean found = false;
        // Find server that is NOT carrying the first region
        for (ServerName info : servers) {
            LOG.info("ServerName=" + info);
            if (!serverNameForFirstRegion.equals(info.getServerName())) {
                destName = info.toString();
                found = true;
                break;
            }
        }
        assertTrue("Found server", found);
        LOG.info("Found " + destName);
        master.getMasterRpcServices().moveRegion(null, RequestConverter.buildMoveRegionRequest(
                firstGoodPair.getKey().getEncodedNameAsBytes(), Bytes.toBytes(destName)));
        assertTrue("Coprocessor should have been called on region move", cp.wasMoveCalled());

        // make sure balancer is on
        master.balanceSwitch(true);
        assertTrue("Coprocessor should have been called on balance switch", cp.wasBalanceSwitchCalled());

        // turn balancer off
        master.balanceSwitch(false);

        // wait for assignments to finish, if any
        AssignmentManager mgr = master.getAssignmentManager();
        Collection<RegionState> transRegions = mgr.getRegionStates().getRegionsInTransition().values();
        for (RegionState state : transRegions) {
            mgr.getRegionStates().waitOnRegionToClearRegionsInTransition(state.getRegion());
        }

        // move half the open regions from RS 0 to RS 1
        HRegionServer rs = cluster.getRegionServer(0);
        byte[] destRS = Bytes.toBytes(cluster.getRegionServer(1).getServerName().toString());
        //Make sure no regions are in transition now
        waitForRITtoBeZero(master);
        List<HRegionInfo> openRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
        int moveCnt = openRegions.size() / 2;
        for (int i = 0; i < moveCnt; i++) {
            HRegionInfo info = openRegions.get(i);
            if (!info.isMetaTable()) {
                master.getMasterRpcServices().moveRegion(null, RequestConverter
                        .buildMoveRegionRequest(openRegions.get(i).getEncodedNameAsBytes(), destRS));
            }
        }
        //Make sure no regions are in transition now
        waitForRITtoBeZero(master);
        // now trigger a balance
        master.balanceSwitch(true);
        boolean balanceRun = master.balance();
        assertTrue("Coprocessor should be called on region rebalancing", cp.wasBalanceCalled());
    } finally {
        UTIL.deleteTable(TEST_TABLE);
    }
}

From source file:uk.ac.soton.itinnovation.easyjena.core.impl.JenaOntologyManager.java

/**
 * Loads an ontology's imports from a model and initialise the ontology manager for use with this model.
 * This is not supposed to be used externally and thus declared protected.
 *
 * @param m the model to process//from ww w.j av  a  2s. co m
 * @param baseURI the baseURI of this model
 * @param location the loading type for import statements
 * @return the loaded ontology
 *
 * @see JenaOntologyManager.LoadingLocation
 */
protected Model loadOntologyModel(Model m, String baseURI, LoadingLocation location) {

    //sanity check
    LoadingLocation loc = location;
    if (location == null) {
        logger.info("No loading location has been specified. Using all possible locations by default.");
        loc = LoadingLocation.ALL;
    }

    long start = System.currentTimeMillis();

    //this is the starting point for the model to be returned. If imports are loaded, this will be enhanced
    Model loadedModel = m;

    //init semantic factory as a container for prefixes
    semanticFactory.addMappingsFromModel(m);

    //add prefixes from map to jena map (needs to be done to include "standard" prefixes from semantic factory
    m.setNsPrefixes(semanticFactory.getNamespaces());

    //check imports are supposed to be loaded
    if (!loc.equals(LoadingLocation.NONE)) {

        logger.debug("Loading location: {}", loc.toString());

        //collect imports
        Map<String, String> startMap = new HashMap<>();

        //iterate over all imports. key is the short prefix, value is the IRI, then recursively load imports.
        Iterator<Map.Entry<String, String>> it = getImports(m, false).entrySet().iterator();
        while (it.hasNext()) {

            Map.Entry<String, String> s = it.next();
            logger.debug("Next namespace: " + s.toString());

            //prepare variables
            String prefix = s.getKey();
            String iri = s.getValue();

            //collect import in map
            startMap.put(prefix, iri);

            //already add to namespaces map (grab every namespace here we can get for a better factory)
            semanticFactory.addPrefixURIMapping(prefix, iri);

            //skip base ontology and ignore existing mappings
            if (prefix.isEmpty() || importLocationMap.containsKey(iri)
            //TODO: is there a better way to skip ontotext ontologies because of timeout?
                    || ("pext".equals(prefix) && "http://proton.semanticweb.org/protonext#".equals(iri))
                    || ("psys".equals(prefix) && "http://proton.semanticweb.org/protonsys#".equals(iri))) {
                continue;
            }

            //if no mapping exists, use default location setting
            if (!importLocationMap.containsKey(iri)) {

                boolean found = false;

                //the obvious choice: load from web if allowed
                if (loc.getNumVal() % 2 != 0) {
                    logger.debug("Trying to load <{}> from web...", iri);
                    //Check URL exists. This is not a duplicate of the checking method in addImportLocationMapping()
                    //but a complement. This check is for ontologies, for which no mapping has been added.
                    found = urlExists(iri);
                }

                //unless the mapping has been specified prior to this method being called, we have no way of
                //knowing where to load from.
                if (!found) {
                    logger.debug("Import <{}> could not be found", iri);
                }
            }
        }

        //recursively add namespaces, starting with the original ontology's imports
        addImportNamespaces(startMap, loc);

        //create temporary OntModel for access to document manager (needed for loading imports)
        //OWL_MEM_RDFS_INF prevents SPIN rules from running
        OntModel ontModel = JenaUtil.createOntologyModel(OntModelSpec.OWL_MEM, JenaUtil.createDefaultModel());
        OntDocumentManager dm = ontModel.getDocumentManager();

        //write mappings to Jena's document manager
        importLocationMap.entrySet().stream().forEach(mapping -> {
            String newuri = mapping.getKey();
            if (newuri.endsWith("#")) {
                newuri = newuri.substring(0, newuri.length() - 1);
            }
            //if there is no mapping yet, the mapping request will return the uri
            if (dm.doAltURLMapping(newuri).equals(newuri)) {
                dm.addAltEntry(newuri, mapping.getValue().getLocation());
            }
        });

        //list mappings
        Iterator<String> iter = dm.listDocuments();
        if (iter.hasNext()) {
            logger.debug("Listing documents mappings:");
            while (iter.hasNext()) {
                String s = iter.next();
                logger.debug(" - {}", s);
            }
        } else {
            logger.debug("No import documents mapped to disk for this ontology");
        }

        //imports should be sorted now, so model can be put into ontmodel
        ontModel.add(m);

        //actually get triples from imported ontologies
        if (!loc.equals(LoadingLocation.NONE)) {
            long oldSize = ontModel.size();
            ontModel.loadImports();
            logger.debug("Imports loaded, old size: {}, new size: {}", oldSize, ontModel.size());
        }

        //remove unnecessary ontology objects (may have been created by loading imports)
        //--find all ontologies except base ontology (the document loaded)
        List<String> ontologies = new ArrayList<>();
        ExtendedIterator<Ontology> onts = ontModel.listOntologies();
        while (onts.hasNext()) {
            Ontology o = onts.next();
            String testURI = baseURI;
            if (testURI == null && semanticFactory.getBaseURI() != null) {
                testURI = semanticFactory.getBaseURI();
            }
            //list extra ontologies
            if (testURI != null && !testURI.isEmpty()
                    && !o.getURI().equals(testURI.substring(0, testURI.length() - 1))) {
                logger.debug("Ontology found in model: {}", o.getURI());
                ontologies.add(o.getURI());
            }
        }
        //--find all ontology statements
        Set<Statement> ontStatements = new HashSet<>();
        ontModel.listStatements().toList().stream().filter(s -> ontologies.contains(s.getSubject().toString()))
                .forEach(s -> ontStatements.add(s));
        //--remove them
        ontStatements.stream().filter(s -> ontModel.contains(s)).forEach(s -> {
            logger.debug("Removing ontology statement {}", s.toString());
            ontModel.remove(s);
        });
        ontModel.rebind();

        //write contents of ontModel back to "normal" Jena model for return
        loadedModel = JenaUtil.createDefaultModel().add(ontModel);

        //take care of prefixes separately as this doesn't happen automatically
        loadedModel.setNsPrefixes(semanticFactory.getNamespaces());

    } else {
        logger.debug("Not loading any imports");
    }

    long end = System.currentTimeMillis();
    long time = end - start;

    if (baseURI != null) {
        logger.info("Ontology <{}> loaded from {} in {}ms, containing {} triples", baseURI, loc.toString(),
                time, loadedModel.size());
    } else {
        logger.info("Ontology loaded from {} in {}ms, containing {} triples. No default namespace.",
                loc.toString(), time, loadedModel.size());
    }

    return loadedModel;
}

From source file:uk.ac.soton.itinnovation.easyjena.core.impl.JenaOntologyManager.java

/**
 * Recursively searches all the prefixes and adds them to the internal map, using the mappings
 * to files on disk if they exist.//from   ww w  . j  a  va  2  s  . c o  m
 *
 * @param uriMap the NSPrefixMap of the current ontology
 */
private void addImportNamespaces(Map<String, String> uriMap, LoadingLocation location) {

    try {
        Iterator<Map.Entry<String, String>> it = uriMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> e = it.next();
            //it.remove();
            //skip unloadable prefixes (timeout)
            //TODO: better solution for breaking off at an invalid XML document?
            if ("xsd".equals(e.getKey()) || "fn".equals(e.getKey()) || "xml".equals(e.getKey())) {
                continue;
            }
            logger.debug("Add namespaces from import {}", e.toString());
            String path;
            //is there a mapping for this import?
            if (importLocationMap.containsKey(e.getValue())) {
                //local location
                path = importLocationMap.get(e.getValue()).getLocation();
                //logger.debug("Key {} contained, location {}", e.getKey(), location);
            } else {
                //web address
                path = e.getValue();
                //logger.debug("Key {} not contained, location {}", e.getKey(), location);
            }

            //add to semantic factory if the file can be loaded locally or from URL (considering location!)
            if ((new File(path)).exists() || (location.getNumVal() % 2 != 0 && urlExists(path))) {

                //actually load the import to look at its defined prefixes and imports
                Model m = FileManager.get().loadModel(path);

                //skip prefixes already processed in an earlier import
                for (Map.Entry<String, String> e2 : m.getNsPrefixMap().entrySet()) {
                    if (!semanticFactory.containsPrefix(e2.getKey()) && !e2.getKey().isEmpty()) {
                        //add this import's prefixes to the collection
                        //note that one URI can have multiple prefixes but not the other way round.
                        logger.debug("Adding new prefix {}", e2);
                        semanticFactory.addPrefixURIMapping(e2.getKey(), e2.getValue());
                    }
                }

                //recurse to retrieve the full tree of namespaces
                //only recurse into true imports here, not defined prefixes
                Map<String, String> importMap = getImports(m, true);
                if (!importMap.isEmpty()) {
                    addImportNamespaces(importMap, location);
                }

            } else {
                logger.debug("Skipping {}: {} can not be opened", e.getKey(), path);
                //only add this prefix and ignore its imports
                semanticFactory.addPrefixURIMapping(e.getKey(), e.getValue());
            }
        }
    } catch (Exception e) {
        logger.error("Error adding import namespaces", e);
    }
}