Example usage for com.fasterxml.jackson.databind ObjectMapper configure

List of usage examples for com.fasterxml.jackson.databind ObjectMapper configure

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper configure.

Prototype

public ObjectMapper configure(JsonGenerator.Feature f, boolean state) 

Source Link

Document

Method for changing state of an on/off JsonGenerator feature for JsonFactory instance this object mapper uses.

Usage

From source file:com.fizzed.stork.test.HelloMain.java

static public void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    HelloOutput output = new HelloOutput();
    output.setConfirm("Hello World!");
    output.setEnvironment(System.getenv());
    output.setSystemProperties(System.getProperties());
    output.setArguments(Arrays.asList(args));

    mapper.writeValue(System.out, output);
}

From source file:org.test.beans.JsonBeanTest.java

public static void main(String[] arg) throws IOException {
    System.out.println("Application Started");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    UserMaster um = mapper.readValue(userMasterJson, UserMaster.class);
    System.out.println(um);/*from   w  ww  .  java 2  s  .co  m*/
    UserTrans ut = mapper.readValue(userTransJson, UserTrans.class);
    System.out.println(ut);
    UserTrans utn = mapper.readValue(userTransJsonMore, UserTrans.class);
    System.out.println(utn);
    System.out.println(mapper.writeValueAsString(ut));

}

From source file:com.amazonaws.services.iot.client.sample.shadowEcho.ShadowEchoSample.java

public static void main(String args[])
        throws IOException, AWSIotException, AWSIotTimeoutException, InterruptedException {
    CommandArguments arguments = CommandArguments.parse(args);
    initClient(arguments);//from  w w w  .j  a v  a  2  s.  co  m

    String thingName = arguments.getNotNull("thingName", SampleUtil.getConfig("thingName"));
    AWSIotDevice device = new AWSIotDevice(thingName);

    awsIotClient.attach(device);
    awsIotClient.connect();

    // Delete existing document if any
    device.delete();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Thing thing = new Thing();

    while (true) {
        long desired = thing.state.desired.counter;
        thing.state.reported.counter = desired;
        thing.state.desired.counter = desired + 1;

        String jsonState = objectMapper.writeValueAsString(thing);

        try {
            // Send updated document to the shadow
            device.update(jsonState);
            System.out.println(System.currentTimeMillis() + ": >>> " + jsonState);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": update failed for " + jsonState);
            continue;
        }

        try {
            // Retrieve updated document from the shadow
            String shadowState = device.get();
            System.out.println(System.currentTimeMillis() + ": <<< " + shadowState);

            thing = objectMapper.readValue(shadowState, Thing.class);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": get failed for " + jsonState);
            continue;
        }

        Thread.sleep(1000);
    }

}

From source file:fr.cvlaminck.merging.samples.contacts.Application.java

public static void main(String[] args) throws IOException {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

    /**//from   w  ww . ja v a2  s .co m
     * The first entry only contains mailing address.
     */
    final Contact entry1 = new Contact("John", "Doe", "777. Rainbow road", "777", "City");
    System.out.println("/*-----------------------------------------*/");
    System.out.println("/*             Entry : John Doe            */");
    System.out.println("/*-----------------------------------------*/");
    objectMapper.writeValue(System.out, entry1);
    System.out.println();
    System.out.println();

    /**
     * The second entry considered as duplicate contains some phone numbers
     * for the contact
     */
    final Contact entry2 = new Contact("John", "Doe", "+33777777777");
    System.out.println("/*-----------------------------------------*/");
    System.out.println("/*           Duplicated : John Doe         */");
    System.out.println("/*-----------------------------------------*/");
    objectMapper.writeValue(System.out, entry2);
    System.out.println();
    System.out.println();

    /**
     * Before doing any merge operation, we need to configure the merging library.
     * To configure the library, you need to instantiate a ValueMergers.
     * The ValuesMergers is a collection ValueMerger. This collection defines which
     * type of field can be merged by the library and which merging strategy can be
     * used for this type of field.
     *
     * For the sample, we uses a PreConfiguredValueMergers that contains all ValueMerger
     * implemented in the core library. There is other implementation of ValueMergers that
     * you can use in your application.
     */
    ValueMergers valueMergers = new DefaultValueMergers(); //TODO
    valueMergers.registerValueMerger(new UseRightIfLeftIsNullObjectValueMerger());
    valueMergers.registerValueMerger(new AddInRightCollectionValueMerger());

    /**
     * Then we instantiate the core element of the library.
     * The ObjectMerger is the object that will allow you to merge your objects.
     */
    ObjectMerger objectMerger = new DefaultObjectMerger(valueMergers);

    /**
     * The last step before merging two objects together is to create an ObjectMergingStrategy.
     * This defines which merging strategy must be used to merge values contained in a field.
     *
     * For this sample, we will use MutableObjectMergingStrategy implementation that allow you to define
     * the strategy at runtime.
     */
    MutableObjectMergingStrategy objectMergingStrategy = new MutableObjectMergingStrategy(Contact.class);
    objectMergingStrategy.setDefaultStrategyForType(Object.class, MergingStrategies.useRightIfLeftIsNull);
    objectMergingStrategy.setDefaultStrategyForType(Collection.class, MergingStrategies.addInRightCollection);

    /**
     * Finally, we merge both objects and take a look at the result.
     */
    final Contact result = objectMerger.merge(entry1, entry2, objectMergingStrategy);

    System.out.println("/*-----------------------------------------*/");
    System.out.println("/*             Merged : John Doe           */");
    System.out.println("/*-----------------------------------------*/");
    objectMapper.writeValue(System.out, result);
}

From source file:com.linecorp.platform.channel.sample.Main.java

public static void main(String[] args) {

    BusinessConnect bc = new BusinessConnect();

    /**//from   ww w .java 2s .  c o  m
     * Prepare the required channel secret and access token
     */
    String channelSecret = System.getenv("CHANNEL_SECRET");
    String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN");
    if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null
            || channelAccessToken.isEmpty()) {
        System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined.");
        return;
    }

    port(Integer.valueOf(System.getenv("PORT")));
    staticFileLocation("/public");

    /**
     * Define the callback url path
     */
    post("/events", (request, response) -> {
        String requestBody = request.body();

        /**
         * Verify whether the channel signature is valid or not
         */
        String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE");
        if (channelSignature == null || channelSignature.isEmpty()) {
            response.status(400);
            return "Please provide valid channel signature and try again.";
        }
        if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) {
            response.status(401);
            return "Invalid channel signature.";
        }

        /**
         * Parse the http request body
         */
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        EventList events;
        try {
            events = objectMapper.readValue(requestBody, EventList.class);
        } catch (IOException e) {
            response.status(400);
            return "Invalid request body.";
        }

        ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken);

        /**
         * Process the incoming messages/operations one by one
         */
        List<String> toUsers;
        for (Event event : events.getResult()) {
            switch (event.getEventType()) {
            case Constants.EventType.MESSAGE:
                toUsers = new ArrayList<>();
                toUsers.add(event.getContent().getFrom());

                // @TODO: We strongly suggest you should modify this to process the incoming message/operation async
                bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient);
                break;
            case Constants.EventType.OPERATION:
                if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) {
                    String newFriend = event.getContent().getParams().get(0);
                    Profile profile = bc.getProfile(newFriend, apiHttpClient);
                    String displayName = profile == null ? "Unknown" : profile.getDisplayName();
                    toUsers = new ArrayList<>();
                    toUsers.add(newFriend);
                    bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient);
                    Connection connection = null;
                    connection = DatabaseUrl.extract().getConnection();
                    toUsers = bc.getFriends(newFriend, connection);
                    if (toUsers.size() > 0) {
                        bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!",
                                apiHttpClient);
                    }
                    bc.addFriend(newFriend, displayName, connection);
                    if (connection != null) {
                        connection.close();
                    }
                }
                break;
            default:
                // Unknown type?
            }
        }
        return "Events received successfully.";
    });

    get("/", (request, response) -> {
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("message", "Hello World!");
        return new ModelAndView(attributes, "index.ftl");
    }, new FreeMarkerEngine());
}

From source file:HelloSmartsheet.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    try {//  w  ww. j  a v a 2  s.co  m

        System.out.println("STARTING HelloSmartsheet...");
        //Create a BufferedReader to read user input.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter Smartsheet API access token:");
        String accessToken = in.readLine();
        System.out.println("Fetching list of your sheets...");
        //Create a connection and fetch the list of sheets
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        //Read the response line by line.
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        //Use Jackson to conver the JSON string to a List of Sheets
        List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() {
        });
        if (sheets.size() == 0) {
            System.out.println("You don't have any sheets.  Goodbye!");
            return;
        }
        System.out.println("Total sheets: " + sheets.size());
        int i = 1;
        for (Sheet sheet : sheets) {
            System.out.println(i++ + ": " + sheet.name);
        }
        System.out.print("Enter the number of the sheet you want to share: ");

        //Prompt the user to provide the sheet number, the email address, and the access level
        Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected.
        Sheet chosenSheet = sheets.get(sheetNumber - 1);

        System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: ");
        String email = in.readLine();

        System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": ");
        String accessLevel = in.readLine();

        //Create a share object
        Share share = new Share();
        share.setEmail(email);
        share.setAccessLevel(accessLevel);

        System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + ".");

        //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's')
        connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId()))
                .openConnection();
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        //Serialize the Share object
        writer.write(mapper.writeValueAsString(share));
        writer.close();

        //Read the response and parse the JSON
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        Result result = mapper.readValue(response.toString(), Result.class);
        System.out.println("Sheet shared successfully, share ID " + result.result.id);
        System.out.println("Press any key to quit.");
        in.read();

    } catch (IOException e) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(((HttpURLConnection) connection).getErrorStream()));
        String line;
        try {
            response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            Result result = mapper.readValue(response.toString(), Result.class);
            System.out.println(result.message);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:org.honeybee.coderally.Modelt.java

public static void main(String[] args) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    InputStream assets = null;//  w  w w  .ja  va  2  s .  c o m
    TrackData data;

    try {
        assets = Tracks.class.getResourceAsStream("/tracks/space/track.json");
        data = mapper.readValue(assets, TrackData.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(assets);
    }
    Schumacher schewy = new Modelt.Schumacher();

    Walker walker = new Walker(data.checkpoints, schewy);
    schewy.buildMap(data.checkpoints);
    walker.showIt();

}

From source file:com.vethrfolnir.TestJsonAfterUnmarshal.java

public static void main(String[] args) throws Exception {
    ArrayList<TestThing> tsts = new ArrayList<>();

    for (int i = 0; i < 21; i++) {

        final int nr = i;
        tsts.add(new TestThing() {
            {//  w  ww.java2s .  c om
                id = 1028 * nr + 256;
                name = "Name-" + nr;
            }
        });
    }

    ObjectMapper mp = new ObjectMapper();
    mp.setVisibilityChecker(mp.getDeserializationConfig().getDefaultVisibilityChecker()
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE));

    mp.configure(SerializationFeature.INDENT_OUTPUT, true);

    ByteArrayOutputStream br = new ByteArrayOutputStream();
    mp.writeValue(System.err, tsts);
    mp.writeValue(br, tsts);

    ByteArrayInputStream in = new ByteArrayInputStream(br.toByteArray());
    tsts = mp.readValue(in, new TypeReference<ArrayList<TestThing>>() {
    });

    System.err.println();
    System.out.println("Got: " + tsts);
}

From source file:AdminExample.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account.
    String user1Email = ""; //You need access to these two email account.
    String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. 
    //joe@gmail.com will get email sent to joe+user1@gmail.com 

    try {//from   w  w w  .j  av a2s  .co m
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding user " + user1Email);

        //Add the users:
        User user = new User();
        user.setEmail(user1Email);
        user.setAdmin(false);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser1Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId());

        user = new User();
        user.setEmail(user2Email);
        user.setAdmin(true);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser2Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId());
        System.out.println("Please visit the email inbox for the users " + user1Email + " and  " + user2Email
                + " and confirm membership to the account.");
        System.out.print("Press Enter to continue");
        in.readLine();

        //List all the users of the org
        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() {
        });

        System.out.println("The following are members of your account: ");

        for (User orgUser : users) {
            System.out.println("\t" + orgUser.getEmail());
        }

        //Create a sheet as the admin
        Sheet newSheet = new Sheet();
        newSheet.setName("Admin's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user1
        newSheet = new Sheet();
        newSheet.setName("User 1's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        //Here is where the magic happens - Any action performed in this call will be on behalf of the
        //user provided. Note that this person must be a confirmed member of your org. 
        //Also note that the email address is url-encoded.
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user2
        newSheet = new Sheet();
        newSheet.setName("User 2's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //List all the sheets in the org:
        System.out.println("The following sheets are owned by members of your account: ");
        connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() {
        });

        for (Sheet orgSheet : allSheets) {
            System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner());
        }

        //Now delete user1 and transfer their sheets to user2
        connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "")
                + "?transferTo=" + newUser2Result.getResult().getId()).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("DELETE");
        Result<Object> resultObject = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Object>>() {
                });

        System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred());

    } catch (IOException e) {

        InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:SheetStructure.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here.

    try {//from w  ww  .j ava2 s  .  c  om

        System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale...");
        //First Create a new sheet.
        String sheetName = "Betty's Bake Sale";
        //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON.
        //Their structure directly relates to the JSON that gets passed through the API.
        //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out.
        Sheet newSheet = new Sheet();
        newSheet.setName(sheetName);
        newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null),
                new Column("Baker", "CONTACT_LIST", null, null, null),
                new Column("Price Per Item", "TEXT_NUMBER", null, null, null),
                new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST",
                        null, null, Arrays.asList("Started", "Finished", "Delivered"))));
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Sheet>>() {
                });
        newSheet = newSheetResult.getResult();
        System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId());

        //Now add a column:
        String columnName = "Delivery Date";
        System.out.println("Adding column " + columnName + " to " + sheetName);
        Column newColumn = new Column(columnName, "DATE", 5);

        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newColumn);
        Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });

        System.out.println(
                "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName());

        //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it.
        System.out.println("Fetching " + newSheet.getName() + " sheet columns...");
        connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        List<Column> allColumns = mapper.readValue(connection.getInputStream(),
                new TypeReference<List<Column>>() {
                });
        System.out.println("Fetched.");

        //Now we will be adding rows
        System.out.println("Inserting rows into " + newSheet.getName());
        List<Row> rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"),
                new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"),
                new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-04"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"),
                new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Started"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"),
                new Cell(allColumns.get(1).id, "sandrassmart@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE),
                new Cell(allColumns.get(4).id, "Finished"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"),
                new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"),
                new Cell(allColumns.get(5).id, "2013-09-05"))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"),
                new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"),
                new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created.

        RowWrapper rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move a row to the top.
        System.out.println("Moving row 6 to the top.");
        RowWrapper moveToTop = new RowWrapper();
        moveToTop.setToTop(true);

        connection = (HttpURLConnection) new URL(
                ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection();
        connection.setRequestMethod("PUT");
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), moveToTop);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
        });

        System.out.println("Row 6 moved to top.");

        //Insert empty rows for spacing
        rows = new ArrayList<Row>();
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, ""))));
        rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setToBottom(true);
        rowWrapper.setRows(rows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName());

        //Move Delivered rows to be children of the last spacer row.
        System.out.println("Moving delivered rows to Delivered section...");
        Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(),
                newRowsResult.result.get(4).getId() };
        RowWrapper parentRowLocation = new RowWrapper();
        parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId());

        for (Long deliveredId : deliveredRowIds) {
            System.out.println("Moving " + deliveredId + " to Delivered.");
            connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection();
            connection.setRequestMethod("PUT");
            connection.addRequestProperty("Authorization", "Bearer " + accessToken);
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            mapper.writeValue(connection.getOutputStream(), parentRowLocation);
            mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() {
            });
            System.out.println("Row id " + deliveredId + " moved.");
        }

        System.out.println("Appending additional rows to items in progress...");

        List<Row> siblingRows = new ArrayList<Row>();
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"),
                new Cell(allColumns.get(1).id, "tomlively@example.com"),
                new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE),
                new Cell(allColumns.get(4).id, "Finished"))));
        siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"),
                new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"),
                new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started"))));
        rowWrapper = new RowWrapper();
        rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId());
        rowWrapper.setRows(siblingRows);

        connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), rowWrapper);
        Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<List<Row>>>() {
                });
        System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName());

        System.out.println("Moving Status column to index 1...");
        Column statusColumn = allColumns.get(4);
        Column moveColumn = new Column();
        moveColumn.setIndex(1);
        moveColumn.setTitle(statusColumn.title);
        moveColumn.setSheetId(newSheet.getId());
        moveColumn.setType(statusColumn.getType());
        connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId()))
                .openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        mapper.writeValue(connection.getOutputStream(), moveColumn);
        Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Column>>() {
                });
        System.out.println("Moved column " + movedColumnResult.getResult().getId());
        System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale.");
    } catch (IOException e) {
        InputStream is = ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}