Example usage for org.apache.commons.io IOUtils write

List of usage examples for org.apache.commons.io IOUtils write

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils write.

Prototype

public static void write(StringBuffer data, OutputStream output) throws IOException 

Source Link

Document

Writes chars from a StringBuffer to bytes on an OutputStream using the default character encoding of the platform.

Usage

From source file:com.amazonaws.apigatewaydemo.RequestRouter.java

/**
 * The main Lambda function handler. Receives the request as an input stream, parses the json and looks for the
 * "action" property to decide where to route the request. The "body" property of the incoming request is passed
 * to the DemoAction implementation as a request body.
 *
 * @param request  The InputStream for the incoming event. This should contain an "action" and "body" properties. The
 *                 action property should contain the namespaced name of the class that should handle the invocation.
 *                 The class should implement the DemoAction interface. The body property should contain the full
 *                 request body for the action class.
 * @param response An OutputStream where the response returned by the action class is written
 * @param context  The Lambda Context object
 * @throws BadRequestException    This Exception is thrown whenever parameters are missing from the request or the action
 *                                class can't be found
 * @throws InternalErrorException This Exception is thrown when an internal error occurs, for example when the database
 *                                is not accessible
 *///w  ww  .ja v  a2s.com
public static void lambdaHandler(InputStream request, OutputStream response, Context context)
        throws BadRequestException, InternalErrorException {
    LambdaLogger logger = context.getLogger();

    JsonParser parser = new JsonParser();
    JsonObject inputObj;
    try {
        inputObj = parser.parse(IOUtils.toString(request)).getAsJsonObject();
    } catch (IOException e) {
        logger.log("Error while reading request\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (inputObj == null || inputObj.get("action") == null
            || inputObj.get("action").getAsString().trim().equals("")) {
        logger.log("Invald inputObj, could not find action parameter");
        throw new BadRequestException("Could not find action value in request");
    }

    String actionClass = inputObj.get("action").getAsString();
    DemoAction action;

    try {
        action = DemoAction.class.cast(Class.forName(actionClass).newInstance());
    } catch (final InstantiationException e) {
        logger.log("Error while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final IllegalAccessException e) {
        logger.log("Illegal access while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final ClassNotFoundException e) {
        logger.log("Action class could not be found\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (action == null) {
        logger.log("Action class is null");
        throw new BadRequestException("Invalid action class");
    }

    JsonObject body = null;
    if (inputObj.get("body") != null) {
        body = inputObj.get("body").getAsJsonObject();
    }

    String output = action.handle(body, context);

    try {
        IOUtils.write(output, response);
    } catch (final IOException e) {
        logger.log("Error while writing response\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }
}

From source file:com.athena.peacock.common.core.action.ConfigAction.java

@Override
public String perform() {
    Assert.notNull(fileName, "filename cannot be null.");
    Assert.notNull(properties, "properties cannot be null.");

    File file = new File(fileName);

    Assert.isTrue(file.exists(), fileName + " does not exist.");
    Assert.isTrue(file.isFile(), fileName + " is not a file.");

    logger.debug("[{}] file's configuration will be changed.", fileName);

    try {//from w  w  w. j a v a2s. co m
        String fileContents = IOUtils.toString(file.toURI());

        for (Property property : properties) {
            logger.debug("\"${{}}\" will be changed to \"{}\".", property.getKey(),
                    property.getValue().replaceAll("\\\\", ""));
            fileContents = fileContents.replaceAll("\\$\\{" + property.getKey() + "\\}", property.getValue());
        }

        FileOutputStream fos = new FileOutputStream(file);
        IOUtils.write(fileContents, fos);
        IOUtils.closeQuietly(fos);
    } catch (IOException e) {
        logger.error("IOException has occurred.", e);
    }

    return null;
}

From source file:cf.funge.aworldofplants.RequestRouter.java

/**
 * The main Lambda function handler. Receives the request as an input stream, parses the json and looks for the
 * "action" property to decide where to route the request. The "body" property of the incoming request is passed
 * to the Action implementation as a request body.
 *
 * @param request  The InputStream for the incoming event. This should contain an "action" and "body" properties. The
 *                 action property should contain the namespaced name of the class that should handle the invocation.
 *                 The class should implement the Action interface. The body property should contain the full
 *                 request body for the action class.
 * @param response An OutputStream where the response returned by the action class is written
 * @param context  The Lambda Context object
 * @throws BadRequestException    This Exception is thrown whenever parameters are missing from the request or the action
 *                                class can't be found
 * @throws InternalErrorException This Exception is thrown when an internal error occurs, for example when the database
 *                                is not accessible
 *///from  w  w w  .  j ava  2  s. co m
public static void lambdaHandler(InputStream request, OutputStream response, Context context)
        throws BadRequestException, InternalErrorException {
    LambdaLogger logger = context.getLogger();

    JsonParser parser = new JsonParser();
    JsonObject inputObj;
    try {
        inputObj = parser.parse(IOUtils.toString(request)).getAsJsonObject();
    } catch (IOException e) {
        logger.log("Error while reading request\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (inputObj == null || inputObj.get("action") == null
            || inputObj.get("action").getAsString().trim().equals("")) {
        logger.log("Invald inputObj, could not find action parameter");
        throw new BadRequestException("Could not find action value in request");
    }

    String actionClass = inputObj.get("action").getAsString();
    Action action;

    try {
        action = Action.class.cast(Class.forName(actionClass).newInstance());
    } catch (final InstantiationException e) {
        logger.log("Error while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final IllegalAccessException e) {
        logger.log("Illegal access while instantiating action class\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    } catch (final ClassNotFoundException e) {
        logger.log("Action class could not be found\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }

    if (action == null) {
        logger.log("Action class is null");
        throw new BadRequestException("Invalid action class");
    }

    JsonObject body = null;
    if (inputObj.get("body") != null) {
        body = inputObj.get("body").getAsJsonObject();
    }

    String output = action.handle(body, context);

    try {
        IOUtils.write(output, response);
    } catch (final IOException e) {
        logger.log("Error while writing response\n" + e.getMessage());
        throw new InternalErrorException(e.getMessage());
    }
}

From source file:eu.ggnet.dwoss.util.FileJacket.java

/**
 * Creates a File from the FileJacket and stores it.
 * The File name will be FileJacket.head + Filejacket.suffix
 * <p/>/*from  ww  w  .  j  a v a 2 s. co  m*/
 * @param url the location the File is stored to
 * @return the File
 */
public File toFile(String url) {
    File f = new File(url + "/" + this.head + this.suffix);
    try (FileOutputStream os = new FileOutputStream(f)) {
        IOUtils.write(content, os);
    } catch (IOException e) {
        throw new RuntimeException("File Creation Unseccessful", e);
    }
    return f;
}

From source file:com.lin.umws.service.impl.UserServiceImpl.java

public void mtomUpload(byte[] mtomFile) {
    try {/*  w ww  . ja  v  a  2s. c  om*/
        IOUtils.write(mtomFile, System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.tc.config.HaConfigTest.java

private synchronized void writeConfigFile(String fileContents) {
    try {/*from  ww  w  .  ja  v a2s  . c  o m*/
        FileOutputStream out = new FileOutputStream(tcConfig);
        IOUtils.write(fileContents, out);
        out.close();
    } catch (Exception e) {
        throw Assert.failure("Can't create config file", e);
    }
}

From source file:net.javacrumbs.mocksocket.SampleTest.java

@Test
public void testRequest() throws Exception {
    byte[] dataToWrite = new byte[] { 5, 4, 3, 2 };
    expectCall().andReturn(emptyResponse());

    Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
    IOUtils.write(dataToWrite, socket.getOutputStream());
    socket.close();//w  w w  . j a  va2 s  . c o  m
    assertThat(recordedConnections().get(0), data(is(dataToWrite)));
    assertThat(recordedConnections().get(0), address(is("example.org:1234")));
}

From source file:ctrus.pa.bow.DefaultBagOfWords.java

protected void writeToOutput(String doc) throws IOException {
    if (_singleFileOut) {
        IOUtils.write(doc + "=", _out);
        writeTo(_out);/*  w  ww . java  2s .  c o  m*/
    } else {
        // replace special characters in the file name 
        doc = doc.replace('<', '[');
        doc = doc.replace('>', ']');

        _out = new FileOutputStream(new File(_outputDir, doc));
        writeTo(_out);
        _out.close();
        _out = null;
    }
}

From source file:net.orpiske.ssps.common.digest.Sha1Digest.java

public void save(String source) throws IOException {
    String digest;/*from w ww  .  j  a  va 2  s.c o m*/
    FileOutputStream output = null;

    try {
        digest = calculate(source);

        File file = new File(source + "." + HASH_NAME);

        if (file.exists()) {
            if (!file.delete()) {
                throw new IOException("Unable to delete an existent file: " + file.getPath());
            }
        } else {
            if (!file.createNewFile()) {
                throw new IOException("Unable to create a new file: " + file.getPath());
            }
        }

        output = new FileOutputStream(file);
        IOUtils.write(digest, output);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:mitm.common.sms.transport.gnokii.Gnokii.java

/**
 * Sends the message to the number.//from   w  ww .  ja v  a2 s.  co m
 */
public String sendSMS(String phoneNumber, String message) throws GnokiiException {
    List<String> cmd = new LinkedList<String>();

    cmd.add(GNOKII_BIN);
    cmd.add("--sendsms");
    cmd.add(phoneNumber);

    if (maxMessageSize != DEFAULT_MAX_MESSAGE_SIZE) {
        cmd.add("-l");
        cmd.add(Integer.toString(maxMessageSize));
    }

    if (requestForDeliveryReport) {
        cmd.add("-r");
    }

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        byte[] bytes = MiscStringUtils.toAsciiBytes(message);

        IOUtils.write(bytes, process.getOutputStream());

        process.getOutputStream().close();

        String output = IOUtils.toString(process.getInputStream());

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        if (exitValue != 0) {
            throw new GnokiiException("Error sending SMS. Output: " + output);
        }

        return output;
    } catch (IOException e) {
        throw new GnokiiException(e);
    }
}