Example usage for java.io InputStream toString

List of usage examples for java.io InputStream toString

Introduction

In this page you can find the example usage for java.io InputStream toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.ichi2.anki.AnkiDroidProxy.java

public String getDecks() {
    // Log.i(AnkiDroidApp.TAG, "getDecks - user = " + username + ", password = " + password);
    String decksServer = "{}";

    try {/*from   www .ja va2s  .co  m*/
        // FIXME: Client is hardcoded.
        String data = "p=" + URLEncoder.encode(mPassword, "UTF-8") + "&client=ankidroid-0.4&u="
                + URLEncoder.encode(mUsername, "UTF-8") + "&d=None&sources=" + URLEncoder.encode("[]", "UTF-8")
                + "&libanki=0.9.9.8.6&pversion=5";

        // Log.i(AnkiDroidApp.TAG, "Data json = " + data);
        HttpPost httpPost = new HttpPost(SYNC_URL + "getDecks");
        StringEntity entity = new StringEntity(data);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept-Encoding", "identity");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);
        Log.i(AnkiDroidApp.TAG, "Response = " + response.toString());
        HttpEntity entityResponse = response.getEntity();
        Log.i(AnkiDroidApp.TAG, "Entity's response = " + entityResponse.toString());
        InputStream content = entityResponse.getContent();
        Log.i(AnkiDroidApp.TAG, "Content = " + content.toString());
        decksServer = Utils.convertStreamToString(new InflaterInputStream(content));
        Log.i(AnkiDroidApp.TAG, "String content = " + decksServer);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.i(AnkiDroidApp.TAG, "ClientProtocolException = " + e.getMessage());
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
    }

    return decksServer;
}

From source file:com.ichi2.anki.AnkiDroidProxy.java

public void createDeck(String name) {
    Log.i(AnkiDroidApp.TAG, "createDeck");
    // Log.i(AnkiDroidApp.TAG, "user = " + username + ", password = " + password);

    try {/*from w w w  .  j a  v  a 2 s  .  c om*/
        String data = "p=" + URLEncoder.encode(mPassword, "UTF-8") + "&u="
                + URLEncoder.encode(mUsername, "UTF-8") + "&d=None&name=" + URLEncoder.encode(name, "UTF-8");

        // Log.i(AnkiDroidApp.TAG, "Data json = " + data);
        HttpPost httpPost = new HttpPost(SYNC_URL + "createDeck");
        StringEntity entity = new StringEntity(data);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept-Encoding", "identity");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);
        Log.i(AnkiDroidApp.TAG, "Response = " + response.toString());
        HttpEntity entityResponse = response.getEntity();
        Log.i(AnkiDroidApp.TAG, "Entity's response = " + entityResponse.toString());
        InputStream content = entityResponse.getContent();
        Log.i(AnkiDroidApp.TAG, "Content = " + content.toString());
        Log.i(AnkiDroidApp.TAG,
                "String content = " + Utils.convertStreamToString(new InflaterInputStream(content)));

        // Add created deck to the list of decks on server
        mDecks.put(name, new JSONArray("[0,0]"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.i(AnkiDroidApp.TAG, "ClientProtocolException = " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.ichi2.anki.AnkiDroidProxy.java

/**
 * Anki Desktop -> libanki/anki/sync.py, HttpSyncServerProxy - applyPayload
 *
 * @param payload//from w  w  w .  j  ava  2 s  . c  o  m
 */
public JSONObject applyPayload(JSONObject payload) {
    Log.i(AnkiDroidApp.TAG, "applyPayload");
    // Log.i(AnkiDroidApp.TAG, "user = " + username + ", password = " + password + ", payload = " +
    // payload.toString());
    JSONObject payloadReply = new JSONObject();

    try {
        // FIXME: Try to do the connection without encoding the payload in Base 64
        String data = "p=" + URLEncoder.encode(mPassword, "UTF-8") + "&u="
                + URLEncoder.encode(mUsername, "UTF-8") + "&d=" + URLEncoder.encode(mDeckName, "UTF-8")
                + "&payload="
                + URLEncoder.encode(Base64.encodeBytes(Utils.compress(payload.toString().getBytes())), "UTF-8")
                + "&base64=" + URLEncoder.encode("true", "UTF-8");

        // Log.i(AnkiDroidApp.TAG, "Data json = " + data);
        HttpPost httpPost = new HttpPost(SYNC_URL + "applyPayload");
        StringEntity entity = new StringEntity(data);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept-Encoding", "identity");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);
        Log.i(AnkiDroidApp.TAG, "Response = " + response.toString());
        HttpEntity entityResponse = response.getEntity();
        Log.i(AnkiDroidApp.TAG, "Entity's response = " + entityResponse.toString());
        InputStream content = entityResponse.getContent();
        Log.i(AnkiDroidApp.TAG, "Content = " + content.toString());
        String contentString = Utils.convertStreamToString(new InflaterInputStream(content));
        Log.i(AnkiDroidApp.TAG, "Payload response = ");
        payloadReply = new JSONObject(contentString);
        Utils.printJSONObject(payloadReply, false);
        Utils.saveJSONObject(payloadReply);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.i(AnkiDroidApp.TAG, "ClientProtocolException = " + e.getMessage());
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
    }

    return payloadReply;
}

From source file:com.ichi2.anki.AnkiDroidProxy.java

/**
 * Anki Desktop -> libanki/anki/sync.py, HttpSyncServerProxy - summary
 * /*www. j a  v  a2 s  .  com*/
 * @param lastSync
 */
public JSONObject summary(double lastSync) {

    Log.i(AnkiDroidApp.TAG, "Summary Server");

    // Log.i(AnkiDroidApp.TAG, "user = " + username + ", password = " + password + ", lastSync = " + lastSync);
    JSONObject summaryServer = new JSONObject();

    try {
        // FIXME: Try to do the connection without encoding the lastSync in Base 64
        String data = "p=" + URLEncoder.encode(mPassword, "UTF-8") + "&u="
                + URLEncoder.encode(mUsername, "UTF-8") + "&d=" + URLEncoder.encode(mDeckName, "UTF-8")
                + "&lastSync="
                + URLEncoder.encode(
                        Base64.encodeBytes(
                                Utils.compress(String.format(Utils.ENGLISH_LOCALE, "%f", lastSync).getBytes())),
                        "UTF-8")
                + "&base64=" + URLEncoder.encode("true", "UTF-8");

        // Log.i(AnkiDroidApp.TAG, "Data json = " + data);
        HttpPost httpPost = new HttpPost(SYNC_URL + "summary");
        StringEntity entity = new StringEntity(data);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept-Encoding", "identity");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);
        Log.i(AnkiDroidApp.TAG, "Response = " + response.toString());
        HttpEntity entityResponse = response.getEntity();
        Log.i(AnkiDroidApp.TAG, "Entity's response = " + entityResponse.toString());
        InputStream content = entityResponse.getContent();
        Log.i(AnkiDroidApp.TAG, "Content = " + content.toString());
        summaryServer = new JSONObject(Utils.convertStreamToString(new InflaterInputStream(content)));
        Log.i(AnkiDroidApp.TAG, "Summary server = ");
        Utils.printJSONObject(summaryServer);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.i(AnkiDroidApp.TAG, "ClientProtocolException = " + e.getMessage());
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
    }

    return summaryServer;
}

From source file:org.collectionspace.csp.helper.core.ConfigFinder.java

public File resolveEntityAsFile(String publicId, String systemId) throws SAXException, IOException {
    try {/*from  ww  w .j  av a2  s  .com*/
        File out = getDataFromEnvironmentVariableAsFile();
        if (out != null) {
            return out;
        }

        if (ctx != null && "-//CSPACE//ROOT".equals(publicId)) {
            InputStream outStream = getDataFromAttribute();
            if (outStream != null) {
                log.warn(String.format(
                        "Configuration not found as a file but as a string in the environment: %s",
                        outStream.toString()));
                return null;
            }

            out = getDataFromAttributePathAsFile();
            if (out != null) {
                return out;
            }

            out = getDataFromNameAsFile();
            if (out != null) {
                return out;
            }
        }

        // use config from tomcat-main/src/main/resources if this is a test
        // run by mvn
        if ("-//CSPACE//TESTROOT".equals(publicId)) {
            out = getConfigFileViaClassLoader(systemId);
            if (out != null) {
                return out;
            }
        }

        out = getDataFromJBossPathAsFile(systemId);
        if (out != null) {
            return out;
        }

        out = getDataFromClasspathAsFile(systemId); // running tests find the resource/entity here
        if (out != null) {
            return out;
        }

        out = getConfigFileViaClassLoader(systemId);
        if (out != null) {
            return out;
        }

        throw new SAXException("No such file " + systemId);
    } catch (CSPDependencyException e) {
        throw new SAXException("Error parsing", e);
    }
}

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphExecuter.java

public void loadGraph(final InputStream fileStream, final boolean addUI) throws GraphException {

    try {/*from   w  ww. ja  v  a 2 s  .  c o m*/
        if (fileStream == null)
            return;
        final Graph graphFromFile = GPFProcessor.readGraph(new InputStreamReader(fileStream), null);

        setGraph(graphFromFile, addUI);
    } catch (Throwable e) {
        throw new GraphException("Unable to load graph " + fileStream.toString() + '\n' + e.getMessage());
    }
}

From source file:org.nuxeo.theme.themes.ThemeParser.java

private static void registerThemeFromInputStream(final ThemeDescriptor themeDescriptor, final InputStream in,
        boolean preload) throws ThemeIOException, ThemeException {
    String themeName = null;//from  ww w. j av  a  2 s.  com

    final InputSource is = new InputSource(in);
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        dbf.setFeature("http://xml.org/sax/features/validation", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (ParserConfigurationException e) {
        log.debug("Could not set DTD non-validation feature");
    }

    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new ThemeIOException(e);
    }
    Document document;
    try {
        document = db.parse(is);
    } catch (SAXException e) {
        throw new ThemeIOException(e);
    } catch (IOException e) {
        throw new ThemeIOException(e);
    }
    final org.w3c.dom.Element docElem = document.getDocumentElement();
    if (!docElem.getNodeName().equals(DOCROOT_NAME)) {
        throw new ThemeIOException("No <" + DOCROOT_NAME + "> document tag found in " + in.toString()
                + ", ignoring the resource.");
    }

    themeName = docElem.getAttributes().getNamedItem("name").getNodeValue();
    if (!ThemeManager.validateThemeName(themeName)) {
        throw new ThemeIOException(
                "Theme names may only contain alpha-numeric characters, underscores and hyphens: " + themeName);
    }
    themeDescriptor.setName(themeName);

    loadTheme(themeDescriptor, docElem, preload);
}

From source file:com.ichi2.anki.SyncClient.java

public static void fullSyncFromServer(String password, String username, String deckName, String deckPath) {
    // Log.i(AnkiDroidApp.TAG, "password = " + password + ", user = " + username + ", d = " + deckName);

    try {/*from w  ww  .j  a  v a2s .  c o  m*/
        String data = "p=" + URLEncoder.encode(password, "UTF-8") + "&u=" + URLEncoder.encode(username, "UTF-8")
                + "&d=" + URLEncoder.encode(deckName, "UTF-8");

        // Log.i(AnkiDroidApp.TAG, "Data json = " + data);
        HttpPost httpPost = new HttpPost(AnkiDroidProxy.SYNC_URL + "fulldown");
        StringEntity entity = new StringEntity(data);
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);
        Log.i(AnkiDroidApp.TAG, "Response = " + response.toString());
        HttpEntity entityResponse = response.getEntity();
        Log.i(AnkiDroidApp.TAG, "Entity's response = " + entityResponse.toString());
        InputStream content = entityResponse.getContent();
        Log.i(AnkiDroidApp.TAG, "Content = " + content.toString());
        Utils.writeToFile(new InflaterInputStream(content), deckPath);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.i(AnkiDroidApp.TAG, "ClientProtocolException = " + e.getMessage());
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
    }
}

From source file:org.ounl.lifelonglearninghub.learntracker.gis.ou.db.ws.ActivityWSDeleteAsyncTask.java

public int deleteActivities(long lCheckIn, String sUserId) {

    // e.g. query
    // https://lifelong-learning-hub.appspot.com/_ah/api/activityendpoint/v1/activity/checkin/{activity_date_checkin}/user/{user_id}
    // e.g. query
    // https://lifelong-learning-hub.appspot.com/_ah/api/activityendpoint/v1/activity/checkin/867232233232/user/Bernd

    InputStream is = null;
    String url = Session.getSingleInstance().getWSPath() + "/_ah/api/activityendpoint/v1/activity/checkin/"
            + lCheckIn + "/user/" + sUserId;

    try {//from   ww  w.j  a va 2 s.co  m
        Log.d(CLASSNAME, " Querying to backend deleteActivities check in:" + lCheckIn + " user:" + sUserId);
        HttpClient httpclient = new DefaultHttpClient();

        HttpDelete httpdelete = new HttpDelete(url);
        HttpResponse response = httpclient.execute(httpdelete);

        // HttpGet httpget = new HttpGet(url);
        // HttpResponse response = httpclient.execute(httpget);

        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
            return 0;
        }

        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d(CLASSNAME, "deleteActivities returns [" + is.toString() + "]");

    } catch (Exception e) {
        Log.e(CLASSNAME, "Error in http connection " + e.toString());
    }

    // TODO this method should return the numer of items deleted in backend
    // Issue 15
    // https://code.google.com/p/lifelong-learning-hub/issues/detail?id=15

    return 1;
}

From source file:info.rmapproject.api.responsemgr.DiscoResponseManager.java

/**
 * Creates new RMap:DiSCO from valid client-provided RDF.
 *
 * @param discoRdf the disco rdf/*from  ww  w.  ja  v a 2 s.co  m*/
 * @param contentType the content type
 * @return HTTP Response
 * @throws RMapApiException the RMap API exception
 */
public Response createRMapDiSCO(InputStream discoRdf, RDFType contentType) throws RMapApiException {
    boolean reqSuccessful = false;
    Response response = null;
    try {

        log.info("New DiSCO create request initiated (id=" + discoRdf.hashCode() + ")");

        if (discoRdf == null || discoRdf.toString().length() == 0) {
            throw new RMapApiException(ErrorCode.ER_NO_DISCO_RDF_PROVIDED);
        }
        if (contentType == null) {
            throw new RMapApiException(ErrorCode.ER_NO_CONTENT_TYPE_PROVIDED);
        }

        RMapDiSCO rmapDisco = rdfHandler.rdf2RMapDiSCO(discoRdf, contentType, Constants.BASE_URL);
        if (rmapDisco == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_RDF_TO_DISCO_FAILED);
        }

        //Get the current user to associate with the DiSCO creation
        RMapRequestAgent reqAgent = apiUserService.getCurrentRequestAgent();

        RMapEventCreation discoEvent = (RMapEventCreation) rmapService.createDiSCO(rmapDisco, reqAgent);
        if (discoEvent == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_CREATEDISCO_NOT_COMPLETED);
        }

        URI uDiscoURI = rmapDisco.getId().getIri();
        if (uDiscoURI == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_GET_DISCOID_RETURNED_NULL);
        }
        String sDiscoURI = uDiscoURI.toString();
        if (sDiscoURI.length() == 0) {
            throw new RMapApiException(ErrorCode.ER_CORE_DISCOURI_STRING_EMPTY);
        }

        log.info("New DiSCO created (id=" + discoRdf.hashCode() + ") with URI " + sDiscoURI);

        URI uEventURI = discoEvent.getId().getIri();
        if (uEventURI == null) {
            throw new RMapApiException(ErrorCode.ER_CORE_GET_EVENTID_RETURNED_NULL);
        }
        String sEventURI = uEventURI.toString();
        if (sEventURI.length() == 0) {
            throw new RMapApiException(ErrorCode.ER_CORE_EVENTURI_STRING_EMPTY);
        }

        String newEventURL = Utils.makeEventUrl(sEventURI);
        String newDiscoUrl = Utils.makeDiscoUrl(sDiscoURI);

        String linkRel = "<" + newEventURL + ">" + ";rel=\"" + PROV.WASGENERATEDBY + "\"";

        response = Response.status(Response.Status.CREATED).entity(sDiscoURI).location(new URI(newDiscoUrl)) //switch this to location()
                .header("Link", linkRel) //switch this to link()
                .build();

        reqSuccessful = true;
    } catch (RMapApiException ex) {
        throw RMapApiException.wrap(ex);
    } catch (RMapDefectiveArgumentException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_GET_DISCO_BAD_ARGUMENT);
    } catch (RMapException ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_CORE_GENERIC_RMAP_EXCEPTION);
    } catch (Exception ex) {
        throw RMapApiException.wrap(ex, ErrorCode.ER_UNKNOWN_SYSTEM_ERROR);
    } finally {
        if (rmapService != null)
            rmapService.closeConnection();
        if (!reqSuccessful && response != null)
            response.close();
    }
    return response;
}