Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:de.shadowhunt.subversion.internal.ProbeServerOperation.java

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {/*w  ww .j a v  a  2  s  .c o  m*/
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("options");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeEmptyElement("activity-collection-set");
        writer.writeEndElement(); //options
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body: " + e.getMessage(), e);
    }

    final DavTemplateRequest request = new DavTemplateRequest("OPTIONS", repository);
    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:io.hypertrack.sendeta.model.CountryMaster.java

private CountryMaster(Context context) {
    mContext = context;/*from   ww  w  . j a v a2  s.com*/
    Resources res = mContext.getResources();

    // builds country data from json
    InputStream is = res.openRawResource(R.raw.countries);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String jsonString = writer.toString();
    JSONArray json = new JSONArray();
    try {
        json = new JSONArray(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mCountryList = new String[json.length()];
    for (int i = 0; i < json.length(); i++) {
        JSONObject node = json.optJSONObject(i);
        if (node != null) {
            Country country = new Country();
            country.mCountryIso = node.optString("iso");
            country.mDialPrefix = node.optString("tel");
            country.mCountryName = getCountryName(node.optString("iso"));
            country.mImageId = getCountryFlagImageResource(node.optString("iso"));

            mCountries.add(country);
            mCountryList[i] = country.mCountryIso;
        }
    }
}

From source file:com.mobeelizer.java.connection.MobeelizerConnectionServiceImpl.java

private MobeelizerOperationStatus<String> executeAndGetContent(final HttpRequestBase request) {
    HttpClient client = httpClient();/* w ww  . j  a v a  2 s.c o  m*/

    InputStream is = null;
    Reader reader = null;

    if (!delegate.isNetworkAvailable()) {
        return new MobeelizerOperationStatus<String>(MobeelizerOperationErrorImpl.missingConnectionError());
    }

    delegate.setProxyIfNecessary(request);

    MobeelizerOperationError error = null;

    try {
        HttpResponse response = client.execute(request);

        int status = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            return new MobeelizerOperationStatus<String>(MobeelizerOperationErrorImpl.connectionError());
        }
        is = entity.getContent();
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
        String content = writer.toString().trim();

        if (status == HttpStatus.SC_OK) {
            return new MobeelizerOperationStatus<String>(content);
        } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR && content.trim().length() > 0) {
            JSONObject json = new JSONObject(content);
            error = MobeelizerOperationErrorImpl.serverError(json);
        } else {
            error = MobeelizerOperationErrorImpl.connectionError(status);
        }

    } catch (JSONException e) {
        error = MobeelizerOperationErrorImpl.exception(e);
    } catch (IOException e) {
        error = MobeelizerOperationErrorImpl.exception(e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                delegate.logDebug(e.getMessage());
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                delegate.logDebug(e.getMessage());
            }
        }
        client.getConnectionManager().shutdown();
    }
    return new MobeelizerOperationStatus<String>(error);
}

From source file:de.dfki.iui.mmds.dialogue.SiamContext.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override// w  ww. j  a  v  a 2s  .c o  m
public void setLocal(String name, Object value) {
    if (value != null && value.toString().equals("[data: null]") && has("stateID")) {
        // value is variable from scxml model
        String stateID = (String) get("stateID");
        value = null;
        if (DialogueComponent.INSTANCE.idToScxmlState.containsKey(stateID)) {
            TransitionTarget tt = DialogueComponent.INSTANCE.idToScxmlState.get(stateID);
            State state = null;
            if (tt instanceof State) {
                state = (State) tt;
            }
            while (value == null && state != null) {
                // search for variable in scxml-model and set variable with
                // default value in context.
                for (Data data : state.getDatamodel().getData()) {
                    if (data instanceof XData && ((XData) data).getId().equals(name)) {
                        value = ((XData) data).getObject();
                        if (name.startsWith("_variable$")) {
                            Object defaultValue = null;
                            String variableName = name.split("\\$")[1];
                            Variable variable = (Variable) value;
                            if (variable.getDefault() != null && !variable.getDefault().isEmpty()) {
                                if (variable.getEmfType() != null
                                        && variable.getEmfType() instanceof EDataType) {
                                    defaultValue = variable.getEmfType().getEPackage().getEFactoryInstance()
                                            .createFromString((EDataType) variable.getEmfType(),
                                                    variable.getDefault());
                                } else if (variable.getType() != null && !variable.getType().isEmpty()) {
                                    try {
                                        defaultValue = siamStateMachine.siamEvaluator.eval(this,
                                                variable.getDefault());
                                    } catch (IllegalArgumentException | SecurityException
                                            | SCXMLExpressionException e) {
                                        final Writer result = new StringWriter();
                                        final PrintWriter printWriter = new PrintWriter(result);
                                        e.printStackTrace(printWriter);
                                        Logger.getLogger(this.getClass()).warn(String.format(
                                                "Cannot create default variable value \"%s\" for variable \"%s\" of type %s!\n%s",
                                                variable.getDefault(), variable.getName(), variable.getType(),
                                                result.toString()));
                                    }
                                    if (defaultValue == null) {
                                        Logger.getLogger(this.getClass()).warn(String.format(
                                                "Cannot create default variable value \"%s\" for variable \"%s\" of type %s!",
                                                variable.getDefault(), variable.getName(), variable.getType()));
                                    }
                                } else {
                                    Logger.getLogger(this.getClass()).warn(String.format(
                                            "Cannot create default value for variable \"%s\". The type %s is not serializable.",
                                            variable.getName(), variable.getEmfType()));
                                }
                            }
                            super.setLocal(variableName, defaultValue);
                        }
                        break;
                    }
                }
                // go up to containing state and search for variable here
                if (state.eContainer() instanceof State) {
                    state = (State) state.eContainer();
                } else {
                    state = null;
                }
            }
        }
    } else {
        // type check. Convert BDataType to DataType or vice versa if
        // necessary.
        Variable variable = (Variable) get("_variable$" + name);

        if (variable != null && value != null) {
            Class variableInstanceClass;
            if (variable.getEmfType() != null) {
                variableInstanceClass = variable.getEmfType().getInstanceClass();
            } else if (variable.getType() != null && !variable.getType().isEmpty()) {
                try {
                    variableInstanceClass = DialogueComponent.INSTANCE.projectContext.getBundleContext()
                            .getBundle().loadClass(variable.getType());
                } catch (ClassNotFoundException e) {
                    throw new IllegalArgumentException(String.format(
                            "Cannot assign value to variable \"%s\" of type %s. Class \'%s\' does not exist",
                            name, variable.getType(), variable.getType()));
                }
            } else
                throw new IllegalArgumentException(
                        String.format("No type defined for variable \"%s\" in scope of state \"%s\".",
                                variable.getName(), get("stateID")));
            if (!(variableInstanceClass.isInstance(value))
                    && !areMatchingClassTypes(variableInstanceClass, value.getClass())) {
                boolean success = false;
                if (value instanceof BDataType) {
                    ParameterizedType type = (ParameterizedType) value.getClass().getGenericSuperclass();
                    if (((Class) type.getActualTypeArguments()[0]).getName()
                            .equals(variableInstanceClass.getName())) {
                        if (!((BDataType) value).isResolved()
                                && ((BDataType) value).getExpression().isEmpty()) {
                            value = "";
                        } else {
                            value = ((BDataType) value).getValue();
                        }
                        success = true;
                    } else if (((Class) type.getActualTypeArguments()[0]).getName()
                            .equals(String.class.getName())) {
                        if (BDataType.class.isAssignableFrom(variableInstanceClass)) {
                            try {
                                value = variableInstanceClass.getMethod("valueOf", String.class).invoke(null,
                                        value.toString());
                                success = true;
                            } catch (IllegalAccessException | IllegalArgumentException
                                    | InvocationTargetException | NoSuchMethodException | SecurityException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                } else if (variableInstanceClass.getSuperclass() == BDataType.class) {
                    BDataType newValue;
                    try {
                        newValue = (BDataType) variableInstanceClass.newInstance();
                        newValue.setValue(value);
                        value = newValue;
                        success = true;
                    } catch (InstantiationException | IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClassCastException e) {
                        success = false;
                    }
                }
                if (!success) {
                    String message = String.format(
                            "Cannot assign value of type %s to variable \"%s\" of type %s: Wrong type.",
                            value.getClass().getName(), name, variableInstanceClass.getName());
                    Logger.getLogger(this.getClass()).error(message);
                    throw new IllegalArgumentException(message);
                }
            }
        }
    }
    super.setLocal(name, value);
}

From source file:org.alfresco.web.scripts.MessagesWebScript.java

/**
 * Generate the message for a given locale.
 * //from  w w w .  j  a va2  s . co  m
 * @param locale    Java locale format
 * 
 * @return messages as JSON string
 * 
 * @throws IOException
 */
@Override
protected String generateMessages(WebScriptRequest req, WebScriptResponse res, String locale)
        throws IOException {
    Writer writer = new StringBuilderWriter(8192);
    writer.write("if (typeof Alfresco == \"undefined\" || !Alfresco) {var Alfresco = {};}\r\n");
    writer.write("Alfresco.messages = Alfresco.messages || {global: null, scope: {}}\r\n");
    writer.write("Alfresco.messages.global = ");
    JSONWriter out = new JSONWriter(writer);
    try {
        out.startObject();
        Map<String, String> messages = I18NUtil.getAllMessages(I18NUtil.parseLocale(locale));
        for (Map.Entry<String, String> entry : messages.entrySet()) {
            out.writeValue(entry.getKey(), entry.getValue());
        }
        out.endObject();
    } catch (IOException jsonErr) {
        throw new WebScriptException("Error building messages response.", jsonErr);
    }
    writer.write(";\r\n//Make global for sandbox mode\r\nwindow.Alfresco=Alfresco;\r\n");

    return writer.toString();
}

From source file:com.agiro.scanner.android.CaptureActivity.java

public void handleDecode(Invoice invoice, Bitmap debugBmp) {
    //    inactivityTimer.onActivity();
    //    playBeepSoundAndVibrate();
    ImageView debugImageView = (ImageView) findViewById(R.id.debug_image_view);
    debugImageView.setImageBitmap(debugBmp);

    Log.v(TAG, "Got invoice " + invoice);
    if (invoice.isComplete()) {
        new Thread(new Runnable() {

            public void run() {
                AppEngineClient aec = new AppEngineClient(CaptureActivity.this, "patrik.akerfeldt@gmail.com");
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("reference", "12345678"));
                try {
                    Writer w = new StringWriter();
                    HttpResponse res = aec.makeRequest("/add", params);
                    Reader reader = new BufferedReader(
                            new InputStreamReader(res.getEntity().getContent(), "UTF-8"));
                    int n;
                    char[] buffer = new char[1024];
                    while ((n = reader.read(buffer)) != -1) {
                        w.write(buffer, 0, n);
                    }/*from  w  ww .  ja v  a2s.c om*/
                    Log.e(TAG, "Got: " + w.toString());
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }

            }
        }).start();
    }

    //TODO: the isValidCC checking should be optional
    //    if (resultMap.containsKey("reference")) {
    //        String str = resultMap.get("reference").toString();
    //        if (StringDecoder.isValidCC(str)) {
    //           new Thread(new Runnable() {
    //            
    //            public void run() {
    //                 AppEngineClient aec = new AppEngineClient(CaptureActivity.this, "patrik.akerfeldt@gmail.com");
    //                 List<NameValuePair> params = new ArrayList<NameValuePair>();
    //                 params.add(new BasicNameValuePair("reference", "12345678"));
    //                 try {
    //                    Writer w = new StringWriter();
    //                  HttpResponse res = aec.makeRequest("/add", params);
    //                  Reader reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent(), "UTF-8"));
    //                  int n;
    //                  char[] buffer = new char[1024];
    //                  while ((n = reader.read(buffer)) != -1) {
    //                  w.write(buffer, 0, n);
    //                  }
    //                  Log.e(TAG, "Got: " + w.toString());
    //               } catch (Exception e) {
    //                  Log.e(TAG, e.getMessage(), e);
    //               }               
    //
    //            }
    //         }).start();
    //          reference = str;
    //        }
    //    }
    //    if (resultMap.containsKey("amount")) {
    //        String str = resultMap.get("amount").toString();
    //        if (StringDecoder.isValidCC(str)) {
    //            str = str.substring(0,str.length()-1);
    //            str = new StringBuffer(str).insert((str.length()-2), ",").toString();
    //            amount = str;
    //        }
    //    }
    //    if (resultMap.containsKey("account")) {
    //        String str = resultMap.get("account").toString();
    //        if (StringDecoder.isValidCC(str)) {
    //          account = str;
    //        }
    //    }
    //    if (resultMap.containsKey("debug")) {
    //        debug = resultMap.get("debug").toString();
    //    }
    populateList(invoice.getReference(), invoice.getCompleteAmount(), invoice.getGiroAccount(),
            "NOT SUPPORTED");
    onContentChanged();
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitTest.java

private static String toString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {/*from   ww  w .  j  av  a2 s .c o m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    }
    return "";
}

From source file:de.shadowhunt.subversion.internal.LockOperation.java

@Override
protected HttpUriRequest createRequest() {
    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("LOCK", uri);
    if (steal) {// ww  w . j  av  a2 s  . c om
        request.addHeader("X-SVN-Options", "lock-steal");
    }

    final Writer body = new StringBuilderWriter();
    try {
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("lockinfo");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("lockscope");
        writer.writeEmptyElement("exclusive");
        writer.writeEndElement(); // lockscope
        writer.writeStartElement("locktype");
        writer.writeEmptyElement("write");
        writer.writeEndElement(); // locktype
        writer.writeEndElement(); //lockinfo
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java

public String convertStreamToString(InputStream is) throws IOException {
    /*// ww w  .ja  v  a2  s. c om
     * To convert the InputStream to String we use the
     * Reader.read(char[] buffer) method. We iterate until the
     * Reader return -1 which means there's no more data to
     * read. We use the StringWriter class to produce the string.
     */
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[HTMLDownloader.large_buffer_size];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"),
                    HTMLDownloader.large_buffer_size);
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:com.ibm.jaggr.core.impl.layer.LayerTest.java

@Test
public void featureSetUpdatingTests() throws Exception {
    replay(mockAggregator, mockRequest, mockResponse, mockDependencies);
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    String configJson = "{paths:{p1:'p1',p2:'p2'}, packages:[{name:'foo', location:'foo'}]}";
    configRef.set(new ConfigImpl(mockAggregator, tmpdir.toURI(), configJson));
    File cacheDir = mockAggregator.getCacheManager().getCacheDir();
    ConcurrentLinkedHashMap<String, CacheEntry> cacheMap = (ConcurrentLinkedHashMap<String, CacheEntry>) ((LayerCacheImpl) mockAggregator
            .getCacheManager().getCache().getLayers()).getLayerBuildMap();
    long totalSize = 0;
    testDepMap.put("p1/a", (String[]) ArrayUtils.add(testDepMap.get("p2/a"), "p1/aliased/d"));
    List<String> layerCacheInfo = new LinkedList<String>();
    configJson = "{paths:{p1:'p1',p2:'p2'}, aliases:[[/\\/aliased\\//, function(s){if (has('foo')) return '/foo/'; else if (has('bar')) return '/bar/'; has('non'); return '/non/'}]]}";
    configRef.set(new ConfigImpl(mockAggregator, tmpdir.toURI(), configJson));

    MockRequestedModuleNames modules = new MockRequestedModuleNames();
    modules.setModules(Arrays.asList(new String[] { "p1/a", "p1/p1" }));
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(IHttpTransport.OPTIMIZATIONLEVEL_REQATTRNAME, IHttpTransport.OptimizationLevel.NONE);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);

    LayerImpl layer = newLayerImpl(modules.toString(), mockAggregator);

    InputStream in = layer.getInputStream(mockRequest, mockResponse);
    Writer writer = new StringWriter();
    CopyUtil.copy(in, writer);/*w  w w .  j av  a  2 s.c  om*/
    String result = writer.toString();
    totalSize += result.length();
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    Map<String, ICacheKeyGenerator> keyGen = layer.getCacheKeyGenerators();
    System.out.println(keyGen.values());
    assertTrue(keyGen.values().toString().contains("js:(has:[conditionFalse, conditionTrue])"));

    requestAttributes.put(IHttpTransport.EXPANDREQUIRELISTS_REQATTRNAME, Boolean.TRUE);
    Features features = new Features();
    features.put("foo", true);
    requestAttributes.put(IHttpTransport.FEATUREMAP_REQATTRNAME, features);

    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    totalSize += result.length();
    keyGen = layer.getCacheKeyGenerators();
    System.out.println(keyGen.values());
    assertEquals("[added, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    assertTrue(keyGen.values().toString().contains("js:(has:[conditionFalse, conditionTrue, foo])"));
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    features.put("foo", false);
    features.put("bar", true);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    totalSize += result.length();
    keyGen = layer.getCacheKeyGenerators();
    System.out.println(keyGen.values());
    assertEquals("[added, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    assertTrue(keyGen.values().toString().contains("js:(has:[bar, conditionFalse, conditionTrue, foo])"));
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    features.put("foo", true);
    features.put("bar", false);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    totalSize += result.length();
    assertTrue(keyGen == layer.getCacheKeyGenerators());
    assertEquals("[added, update_weights_2]", layerCacheInfo.toString());
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    features.put("foo", false);
    features.put("bar", false);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    totalSize += result.length();
    assertEquals("[added, update_keygen, update_key, update_weights_2]", layerCacheInfo.toString());
    keyGen = layer.getCacheKeyGenerators();
    System.out.println(keyGen.values());
    assertTrue(keyGen.values().toString().contains("js:(has:[bar, conditionFalse, conditionTrue, foo, non])"));
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    features.put("foo", true);
    features.put("bar", true);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    totalSize += result.length();
    assertEquals("[added, update_weights_2]", layerCacheInfo.toString());
    assertTrue(keyGen == layer.getCacheKeyGenerators());
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    features.remove("bar");
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    assertEquals("[hit_1]", layerCacheInfo.toString());
    assertTrue(keyGen == layer.getCacheKeyGenerators());
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

}