Example usage for com.fasterxml.jackson.core.type TypeReference TypeReference

List of usage examples for com.fasterxml.jackson.core.type TypeReference TypeReference

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core.type TypeReference TypeReference.

Prototype

protected TypeReference() 

Source Link

Usage

From source file:gis.proj.drivers.SnyderTest.java

public static void main(String... args) {
    SnyderTest sfTest = new SnyderTest();
    JCommander jc = new JCommander(sfTest);

    try {/*from   w w  w. j  ava2s  .  c  o m*/
        jc.parse(args);
    } catch (Exception e) {
        jc.usage();
        System.exit(-10);
    }

    Snyder.printLicenseInformation("SnyderTest");

    double[][] fVal = null; // forward values
    double[][] iVal = null; // inverse values

    Ellipsoid ellip;
    Datum datum;
    Projection proj;

    ArrayList<Fiducial> testData = null;

    try {
        testData = Snyder.fromJSON(new TypeReference<ArrayList<Fiducial>>() {
        }, sfTest.ifName);
    } catch (Exception e) {
    }

    if (testData != null) {
        for (Fiducial sf : testData) {
            ellip = null;
            datum = null;
            proj = null;

            ellip = EllipsoidFactory.getInstance().getEllipsoid(sf.getEllipsoid());

            datum = new Datum();

            for (Entry<String, String> entry : sf.getDatum().entrySet()) {
                datum.setUserOverrideProperty(entry.getKey(),
                        Snyder.parseDatumVal(entry.getValue().toLowerCase()));
            }

            try {
                Class<?> cls = Class.forName(sf.getProjection());
                proj = (Projection) cls.newInstance();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            fVal = proj.forward(new double[] { sf.getLon() * SnyderMath.DEG_TO_RAD },
                    new double[] { sf.getLat() * SnyderMath.DEG_TO_RAD }, ellip, datum);

            iVal = proj.inverse(new double[] { fVal[0][0] }, new double[] { fVal[1][0] }, ellip, datum);

            iVal[0][0] *= SnyderMath.RAD_TO_DEG;
            iVal[1][0] *= SnyderMath.RAD_TO_DEG;

            sf.setPassed(fVal[0][0], fVal[1][0], iVal[0][0], iVal[1][0]);
        }

        try {

            if (sfTest.ofName != null)
                sfTest.om.writeValue(new File(sfTest.ofName), testData);

        } catch (Exception e) {
            System.out.println("Couldn't write the fiducial data results, of=" + sfTest.ofName);
            System.exit(-1);
        }

        System.out.print("\n**********************************************************************\n");
        System.out.print("SNYDER TEST SUMMARY");
        System.out.print("\n**********************************************************************\n");
        System.out.println("\n\t  Total test cases : " + testData.size());
    } else {
        System.out.println("Couldn't load the fiducial data, if=" + sfTest.ifName);
        System.exit(-1);
    }
}

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  w w . ja v  a  2 s .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:net.e2.bw.idreg.db2ldif.Db2Ldif.java

/**
 * Main method//from   w  w w .  j  a  v  a 2  s.  c  o  m
 * @param args runtime arguments
 */
public static void main(String[] args) throws Exception {
    Db2Ldif db2ldif = new Db2Ldif();

    // Preload company data from json file
    ObjectMapper mapper = new ObjectMapper();
    List<Company> companies = mapper.readValue(Db2Ldif.class.getResource("/companies.json"),
            new TypeReference<List<Company>>() {
            });
    companies.forEach(c -> db2ldif.companyData.put(c.uid, c));

    new JCommander(db2ldif, args);
    db2ldif.execute();
}

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 {/*from  w w w .jav  a  2s .com*/

        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: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  a  v a 2 s  .com*/
        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:edu.usu.sdl.wso2client.SampleWSRegistryClient.java

public static void main(String[] args) throws Exception {
    Registry registry = initialize();
    try {//from  w w  w .ja  v a  2s  . co m
        //load component

        List<ComponentAll> components;
        try (InputStream in = new FileInputStream("C:\\temp\\components.json")) {
            components = StringProcessor.defaultObjectMapper().readValue(in,
                    new TypeReference<List<ComponentAll>>() {
                    });
        } catch (IOException ex) {
            throw ex;
        }

        ComponentAll componentAll = components.get(0);

        Resource resource = registry.newResource();
        resource.setContent(componentAll.getComponent().getDescription());

        resource.setDescription("Storefront Component");
        resource.setMediaType("application/openstorefront");
        resource.setUUID(componentAll.getComponent().getComponentId());

        try {
            Map fieldMap = BeanUtils.describe(componentAll.getComponent());
            fieldMap.keySet().stream().forEach((key) -> {
                if ("description".equals(key) == false) {
                    resource.setProperty(Component.class.getSimpleName() + "_" + key, "" + fieldMap.get(key));
                    //System.out.println("key  = " + Component.class.getSimpleName() + "_" + key);
                    //System.out.println("Value  = " + fieldMap.get(key));
                }
            });
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            Logger.getLogger(StringProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }

        String resourcePath = "/storefront/components/" + componentAll.getComponent().getComponentId();
        registry.put(resourcePath, resource);

        //
        System.out.println("A resource added to: " + resourcePath);
        //         registry.rateResource(resourcePath, 4);
        //
        //         System.out.println("Resource rated with 4 stars!");
        //         Comment comment = new Comment();
        //         comment.setText("Testing Connection");
        //         registry.addComment(resourcePath, comment);
        //         System.out.println("Comment added to resource");
        //
        //         Resource getResource = registry.get("/abc2");
        //         System.out.println("Resource retrived");
        //         System.out.println("Printing retrieved resource content: "
        //               + new String((byte[]) getResource.getContent()));

        //         Resource resource = registry.newResource();
        //         resource.setContent("Hello Out there!");
        //
        //         String resourcePath = "/abc3";
        //         registry.put(resourcePath, resource);
        //
        //         System.out.println("A resource added to: " + resourcePath);
        //
        //         registry.rateResource(resourcePath, 4);
        //
        //         System.out.println("Resource rated with 4 stars!");
        //         Comment comment = new Comment();
        //         comment.setText("Testing Connection");
        //         registry.addComment(resourcePath, comment);
        //         System.out.println("Comment added to resource");
        //
        //         Resource getResource = registry.get("/abc3");
        //         System.out.println("Resource retrived");
        //         System.out.println("Printing retrieved resource content: "
        //               + new String((byte[]) getResource.getContent()));
    } finally {
        //Close the session
        ((WSRegistryServiceClient) registry).logut();
    }
    System.exit(0);
}

From source file:com.twitter.ambrose.model.DAGNode.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
    String sourceFile = "pig/src/main/resources/web/data/large-dag.json";
    String json = JSONUtil.readFile(sourceFile);
    List<DAGNode> nodes = JSONUtil.toObject(json, new TypeReference<List<DAGNode>>() {
    });/*from w ww .  j  a va 2s.  c  om*/
    JSONUtil.writeJson(sourceFile + "2", nodes);
}

From source file:org.mitre.mpf.rest.client.Main.java

public static void main(String[] args) throws RestClientException, IOException, InterruptedException {
    System.out.println("Starting rest-client!");

    //not necessary for localhost, but left if a proxy configuration is needed
    //System.setProperty("http.proxyHost","");
    //System.setProperty("http.proxyPort","");  

    String currentDirectory;/*from w w w  .  j av a  2s  . c  o m*/
    currentDirectory = System.getProperty("user.dir");
    System.out.println("Current working directory : " + currentDirectory);

    String username = "mpf";
    String password = "mpf123";
    byte[] encodedBytes = Base64.encodeBase64((username + ":" + password).getBytes());
    String base64 = new String(encodedBytes);
    System.out.println("encodedBytes " + base64);
    final String mpfAuth = "Basic " + base64;

    RequestInterceptor authorize = new RequestInterceptor() {
        @Override
        public void intercept(HttpRequestBase request) {
            request.addHeader("Authorization", mpfAuth /*credentials*/);
        }
    };

    //RestClient client = RestClient.builder().requestInterceptor(authorize).build();
    CustomRestClient client = (CustomRestClient) CustomRestClient.builder()
            .restClientClass(CustomRestClient.class).requestInterceptor(authorize).build();

    //getAvailableWorkPipelineNames
    String url = "http://localhost:8080/workflow-manager/rest/pipelines";
    Map<String, String> params = new HashMap<String, String>();
    List<String> availableWorkPipelines = client.get(url, params, new TypeReference<List<String>>() {
    });
    System.out.println("availableWorkPipelines size: " + availableWorkPipelines.size());
    System.out.println(Arrays.toString(availableWorkPipelines.toArray()));

    //processMedia        
    JobCreationRequest jobCreationRequest = new JobCreationRequest();
    URI uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S001-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S008-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    jobCreationRequest.setExternalId("external id");

    //get first DLIB pipeline
    String firstDlibPipeline = availableWorkPipelines.stream()
            //.peek(pipepline -> System.out.println("will filter - " + pipepline))
            .filter(pipepline -> pipepline.startsWith("DLIB")).findFirst().get();

    System.out.println("found firstDlibPipeline: " + firstDlibPipeline);

    jobCreationRequest.setPipelineName(firstDlibPipeline); //grabbed from 'rest/pipelines' - see #1
    //two optional params
    jobCreationRequest.setBuildOutput(true);
    //jobCreationRequest.setPriority(priority); //will be set to 4 (default) if not set
    JobCreationResponse jobCreationResponse = client.customPostObject(
            "http://localhost:8080/workflow-manager/rest/jobs", jobCreationRequest, JobCreationResponse.class);
    System.out.println("jobCreationResponse job id: " + jobCreationResponse.getJobId());

    System.out.println("\n---Sleeping for 10 seconds to let the job process---\n");
    Thread.sleep(10000);

    //getJobStatus
    url = "http://localhost:8080/workflow-manager/rest/jobs"; // /status";
    params = new HashMap<String, String>();
    //OPTIONAL
    //params.put("v", "") - no versioning currently implemented         
    //id is now a path var - if not set, all job info will returned
    url = url + "/" + Long.toString(jobCreationResponse.getJobId());
    SingleJobInfo jobInfo = client.get(url, params, SingleJobInfo.class);
    System.out.println("jobInfo id: " + jobInfo.getJobId());

    //getSerializedOutput
    String jobIdToGetOutputStr = Long.toString(jobCreationResponse.getJobId());
    url = "http://localhost:8080/workflow-manager/rest/jobs/" + jobIdToGetOutputStr + "/output/detection";
    params = new HashMap<String, String>();
    //REQUIRED  - job id is now a path var and required for this endpoint
    String serializedOutput = client.getAsString(url, params);
    System.out.println("serializedOutput: " + serializedOutput);
}

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 {/*www  . jav a2  s .c  o  m*/

        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();
    }

}

From source file:io.druid.server.sql.SQLRunner.java

public static void main(String[] args) throws Exception {

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SQLRunner", options);
        System.exit(2);/*  w  w w .j a  v  a  2  s  .  c om*/
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
        DruidSQLParser.QueryContext queryContext = parser.query();
        if (parser.getNumberOfSyntaxErrors() > 0)
            throw new IllegalStateException();
        //      parser.setBuildParseTree(true);
        //      System.err.println(q.toStringTree(parser));
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg != null)
            System.err.println(e);
        System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if (parser.groupByDimensions.isEmpty()) {
        query = Druids.newTimeseriesQueryBuilder().dataSource(parser.getDataSource())
                .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .postAggregators(parser.postAggregators).intervals(parser.intervals)
                .granularity(parser.granularity).filters(parser.filter).build();

        typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>() {
        };
    } else {
        query = GroupByQuery.builder().setDataSource(parser.getDataSource())
                .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .setPostAggregatorSpecs(parser.postAggregators).setInterval(parser.intervals)
                .setGranularity(parser.granularity).setDimFilter(parser.filter)
                .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values())).build();

        typeRef = new TypeReference<List<Row>>() {
        };
        groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if (cmd.hasOption("v"))
        System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if (groupBy) {
        List<Row> rows = (List<Row>) res;
        Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(),
                new Function<DimensionSpec, String>() {
                    @Override
                    public String apply(@Nullable DimensionSpec input) {
                        return input.getOutputName();
                    }
                });

        System.out.println(
                tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), dimensions, parser.fields)));
        for (final Row r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(
                    Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                    Iterables.transform(parser.groupByDimensions.values(),
                            new Function<DimensionSpec, String>() {
                                @Override
                                public String apply(@Nullable DimensionSpec input) {
                                    return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                                }
                            }),
                    Iterables.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getFloatMetric(input);
                        }
                    }))));
        }
    } else {
        List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>) res;
        System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), parser.fields)));
        for (final Result<TimeseriesResultValue> r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList(r.getTimestamp()),
                    Lists.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getValue().getMetric(input);
                        }
                    }))));
        }
    }

    CloseQuietly.close(stdInput);
}