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.acentera.utils.ProjectsHelpers.java

public static String updateServer(Long projectId, Long serverId, JSONObject updatedServer)
        throws JsonProcessingException {

    SecurityController.checkPermission(projectId, PermisionTagConstants.SERVER, serverId,
            PermissionActionConstats.EDIT);

    ProjectDevices device = DeviceImpl.getProjectDevice(projectId, serverId);

    //Device device = projectDevice.getDevice();

    Session s = HibernateSessionFactory.getSession();

    if (updatedServer.containsKey("tags")) {
        JSONArray listOfTags = updatedServer.getJSONArray("tags");

        final Set<ProjectDevicesTags> tags = device.getTags();
        Set<ProjectDevicesTags> newTags = new HashSet<ProjectDevicesTags>();

        for (ProjectDevicesTags tag : tags) {
            tag.disable();//from   www .ja v  a  2  s.  c  o m
        }

        int len = listOfTags.size();
        for (int i = 0; i < len; i++) {
            JSONObject jsoData = listOfTags.getJSONObject(i);
            String data = jsoData.getString("name");

            List<ProjectDevicesTags> foundItem = select(tags,
                    having(on(ProjectDevicesTags.class).getName(), equalTo(data)));

            ProjectDevicesTags projectTags = null;
            if (foundItem.size() == 1) {
                //We found it..
                projectTags = foundItem.get(0);
            } else {
                //This tag is not in this object yet.
                projectTags = new ProjectDevicesTags();
            }
            projectTags.setProjectTags(
                    ProjectTagsImpl.getOrCreateTags(device.getProject(), data, TagConstants.ANY));
            projectTags.enable();

            tags.add(projectTags);
            s.saveOrUpdate(projectTags);
            newTags.add(projectTags);
        }

        //Set the new Tags
        device.setTags(tags);

        s.saveOrUpdate(device);

        //Since we disabled all data now.. lets return the object.
        device.setTags(newTags);

        //Do not return the provider object as someone will potentially call "save on the object"

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        ObjectWriter ow = mapper.writer();
        JSONObject jsoRes = new JSONObject();
        jsoRes.put("servers", ow.writeValueAsString(device));
        //return device;//ProjectsHelpers.getProjectProvidersAsJson(provider);
        return jsoRes.toString();
    }

    return null;
}

From source file:org.lambdamatic.internal.elasticsearch.codec.ObjectMapperFactory.java

/**
 * Initializes an {@link ObjectMapper} configured with mixins to support serialization and
 * deserialization of all built-in and user-defined domain types.
 * <p>//  w ww.  j  a va2 s.c om
 * <strong>Note:</strong>The {@link ObjectMapper} is instantiated and initialized once and then
 * kept in cache, so multiple calls will retrieve the same instance.
 * </p>
 * 
 * @return the {@link ObjectMapper}
 * 
 */
public static ObjectMapper getObjectMapper() {
    if (instance.objectMapper == null) {
        LOGGER.info("Initializing the ObjectMapper");
        final ObjectMapper mapper = new ObjectMapper();
        final ExecutorService availableProcessorsThreadPool = Executors
                .newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        final Reflections reflections = new Reflections(new ConfigurationBuilder()

                // TODO: allow for configuration settings to reduce the scope of searching, using package
                // names instead of a classloader
                .setUrls(ClasspathHelper.forJavaClassPath())
                // .setUrls(ClasspathHelper.forClassLoader())
                .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())
                .setExecutorService(availableProcessorsThreadPool));
        // thread pool must be closed after it has been used, to avoid leaking threads in the JVM.
        availableProcessorsThreadPool.shutdown();
        // final Reflections reflections = new Reflections();
        reflections.getTypesAnnotatedWith(Mixin.class).stream().forEach(mixin -> {
            final Mixin mixinAnnotation = mixin.getAnnotation(Mixin.class);
            LOGGER.info("Adding mixin {} to {}", mixin, mixinAnnotation.target());
            mapper.addMixIn(mixinAnnotation.target(), mixin);
        });
        mapper.registerModule(new JavaTimeModule());
        // configure LocalDate serialization as string with pattern: YYYY-mm-dd
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        instance.objectMapper = mapper;
    }
    return instance.objectMapper;
}

From source file:ijfx.service.ui.ImageJInfoService.java

@AngularMethod(sync = true, description = "Return the list of all widgets", inputDescription = "No input")
public JSObject getModuleList() {
    try {// ww  w  .  j  ava  2  s.c  o  m
        ObjectMapper mapper = new ObjectMapper();
        logger.fine("Getting module list");
        SimpleModule simpleModule = new SimpleModule("ModuleSerializer");
        // simpleModule.addSerializer(ModuleItem<?>.class,new ModuleItemSerializer());
        simpleModule.addSerializer(ModuleInfo.class, new ModuleSerializer());
        simpleModule.addSerializer(ModuleItem.class, new ModuleItemSerializer());
        mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(simpleModule);

        ArrayNode arrayNode = mapper.createArrayNode();

        moduleService.getModules().forEach(module -> {

            //System.out.println("Adding "+module.getName());
            arrayNode.add(mapper.convertValue(module, JsonNode.class));

        });

        //String json = mapper.writeValueAsString(moduleService.getModules());
        logger.fine("JSON done !");

        return JSONUtils.parseToJSON(appService.getCurrentWebEngine(), arrayNode.toString());
        //return JSONUtils.parseToJSON(appService.getCurrentWebEngine(), json);

    } catch (Exception ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    logger.warning("Returning null");
    return null;
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException {

    try (CloseableHttpResponse httpResponse = httpClient.execute(req);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }// w  ww .  java  2s.  c  om
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.readValue(responseContent, clazz);
    }
}

From source file:com.jivesoftware.os.amza.sync.deployable.AmzaSyncMain.java

public void run(String[] args) throws Exception {
    ServiceStartupHealthCheck serviceStartupHealthCheck = new ServiceStartupHealthCheck();
    try {/*from w  w  w.j  ava 2 s. com*/
        final Deployable deployable = new Deployable(args);
        InstanceConfig instanceConfig = deployable.config(InstanceConfig.class);
        HealthFactory.initialize(deployable::config, new DeployableHealthCheckRegistry(deployable));
        deployable.addManageInjectables(HasUI.class, new HasUI(Arrays.asList(new UI("Sync", "main", "/ui"))));
        deployable.addHealthCheck(new GCPauseHealthChecker(
                deployable.config(GCPauseHealthChecker.GCPauseHealthCheckerConfig.class)));
        deployable.addHealthCheck(new GCLoadHealthChecker(
                deployable.config(GCLoadHealthChecker.GCLoadHealthCheckerConfig.class)));
        deployable.addHealthCheck(new SystemCpuHealthChecker(
                deployable.config(SystemCpuHealthChecker.SystemCpuHealthCheckerConfig.class)));
        deployable.addHealthCheck(new LoadAverageHealthChecker(
                deployable.config(LoadAverageHealthChecker.LoadAverageHealthCheckerConfig.class)));
        deployable.addHealthCheck(new FileDescriptorCountHealthChecker(deployable
                .config(FileDescriptorCountHealthChecker.FileDescriptorCountHealthCheckerConfig.class)));
        deployable.addHealthCheck(serviceStartupHealthCheck);
        deployable.addErrorHealthChecks(deployable.config(ErrorHealthCheckConfig.class));
        deployable.addManageInjectables(FullyOnlineVersion.class, (FullyOnlineVersion) () -> {
            if (serviceStartupHealthCheck.startupHasSucceeded()) {
                return instanceConfig.getVersion();
            } else {
                return null;
            }
        });
        deployable.buildManageServer().start();

        HttpDeliveryClientHealthProvider clientHealthProvider = new HttpDeliveryClientHealthProvider(
                instanceConfig.getInstanceKey(), HttpRequestHelperUtils.buildRequestHelper(false, false, null,
                        instanceConfig.getRoutesHost(), instanceConfig.getRoutesPort()),
                instanceConfig.getConnectionsHealth(), 5_000, 100);

        TenantRoutingProvider tenantRoutingProvider = deployable.getTenantRoutingProvider();

        TenantsServiceConnectionDescriptorProvider syncDescriptorProvider = tenantRoutingProvider
                .getConnections(instanceConfig.getServiceName(), "main", 10_000); // TODO config

        TenantRoutingHttpClientInitializer<String> tenantRoutingHttpClientInitializer = deployable
                .getTenantRoutingHttpClientInitializer();

        TenantAwareHttpClient<String> amzaClient = tenantRoutingHttpClientInitializer
                .builder(deployable.getTenantRoutingProvider().getConnections("amza", "main", 10_000), // TODO config
                        clientHealthProvider)
                .deadAfterNErrors(10).checkDeadEveryNMillis(10_000).socketTimeoutInMillis(60_000).build(); // TODO expose to conf

        deployable.addHealthCheck(new TenantAwareHttpClientHealthCheck("amzaClient", amzaClient));

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        AmzaSyncConfig syncConfig = deployable.config(AmzaSyncConfig.class);

        TailAtScaleStrategy tailAtScaleStrategy = new TailAtScaleStrategy(
                deployable.newBoundedExecutor(1024, "tas"), 100, // TODO config
                95, // TODO config
                1000 // TODO config
        );

        AmzaInterner amzaInterner = new AmzaInterner();
        AmzaClientProvider<HttpClient, HttpClientException> amzaClientProvider = new AmzaClientProvider<>(
                new HttpPartitionClientFactory(),
                new HttpPartitionHostsProvider(amzaClient, tailAtScaleStrategy, mapper),
                new RingHostHttpClientProvider(amzaClient),
                deployable.newBoundedExecutor(syncConfig.getAmzaCallerThreadPoolSize(), "amza-client"),
                syncConfig.getAmzaAwaitLeaderElectionForNMillis(), -1, -1);

        TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(
                new ConstantWriterIdProvider(instanceConfig.getInstanceName()), new SnowflakeIdPacker(),
                new JiveEpochTimestampProvider());
        AmzaClientAquariumProvider amzaClientAquariumProvider = new AmzaClientAquariumProvider(
                new AquariumStats(), instanceConfig.getServiceName(), amzaClientProvider, orderIdProvider,
                new Member(instanceConfig.getInstanceKey().getBytes(StandardCharsets.UTF_8)), count -> {
                    ConnectionDescriptors descriptors = syncDescriptorProvider.getConnections("");
                    int ringSize = descriptors.getConnectionDescriptors().size();
                    return count > ringSize / 2;
                }, () -> {
                    Set<Member> members = Sets.newHashSet();
                    ConnectionDescriptors descriptors = syncDescriptorProvider.getConnections("");
                    for (ConnectionDescriptor connectionDescriptor : descriptors.getConnectionDescriptors()) {
                        members.add(new Member(connectionDescriptor.getInstanceDescriptor().instanceKey
                                .getBytes(StandardCharsets.UTF_8)));
                    }
                    return members;
                }, 128, //TODO config
                128, //TODO config
                5_000L, //TODO config
                100L, //TODO config
                60_000L, //TODO config
                10_000L, //TODO config
                Executors.newSingleThreadExecutor(), 100L, //TODO config
                1_000L, //TODO config
                10_000L, //TODO config
                syncConfig.getAquariumUseSolutionLog());

        ObjectMapper miruSyncMapper = new ObjectMapper();
        miruSyncMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        miruSyncMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        AmzaMarshaller<String> stringMarshaller = new AmzaMarshaller<String>() {
            @Override
            public String fromBytes(byte[] bytes) throws Exception {
                return new String(bytes, StandardCharsets.UTF_8);
            }

            @Override
            public byte[] toBytes(String value) throws Exception {
                return value == null ? null : value.getBytes(StandardCharsets.UTF_8);
            }
        };

        AmzaMarshaller<AmzaSyncSenderConfig> amzaSyncSenderConfigMarshaller = new AmzaMarshaller<AmzaSyncSenderConfig>() {
            @Override
            public AmzaSyncSenderConfig fromBytes(byte[] bytes) throws Exception {
                return mapper.readValue(bytes, AmzaSyncSenderConfig.class);
            }

            @Override
            public byte[] toBytes(AmzaSyncSenderConfig value) throws Exception {
                return mapper.writeValueAsBytes(value);
            }
        };

        AmzaSyncSenderMap senderConfigStorage = new AmzaSyncSenderMap(amzaClientProvider,
                "amza-sync-sender-config",
                new PartitionProperties(Durability.fsync_async, 0, 0, 0, 0, 0, 0, 0, 0, false,
                        Consistency.leader_quorum, true, true, false, RowType.snappy_primary, "lab", -1, null,
                        -1, -1),
                stringMarshaller, amzaSyncSenderConfigMarshaller);

        AmzaMarshaller<AmzaSyncPartitionTuple> tupleMarshaller = new AmzaMarshaller<AmzaSyncPartitionTuple>() {
            @Override
            public AmzaSyncPartitionTuple fromBytes(byte[] bytes) throws Exception {
                return AmzaSyncPartitionTuple.fromBytes(bytes, 0, amzaInterner);
            }

            @Override
            public byte[] toBytes(AmzaSyncPartitionTuple value) throws Exception {
                return AmzaSyncPartitionTuple.toBytes(value);
            }
        };

        AmzaMarshaller<AmzaSyncPartitionConfig> partitionConfigMarshaller = new AmzaMarshaller<AmzaSyncPartitionConfig>() {
            @Override
            public AmzaSyncPartitionConfig fromBytes(byte[] bytes) throws Exception {
                return mapper.readValue(bytes, AmzaSyncPartitionConfig.class);
            }

            @Override
            public byte[] toBytes(AmzaSyncPartitionConfig value) throws Exception {
                return mapper.writeValueAsBytes(value);
            }
        };

        AmzaSyncPartitionConfigStorage syncPartitionConfigStorage = new AmzaSyncPartitionConfigStorage(
                amzaClientProvider, "amza-sync-partitions-config-",
                new PartitionProperties(Durability.fsync_async, 0, 0, 0, 0, 0, 0, 0, 0, false,
                        Consistency.leader_quorum, true, true, false, RowType.snappy_primary, "lab", -1, null,
                        -1, -1),
                tupleMarshaller, partitionConfigMarshaller);

        AmzaSyncStats stats = new AmzaSyncStats();

        AmzaSyncReceiver syncReceiver = new AmzaSyncReceiver(amzaClientProvider,
                syncConfig.getSyncReceiverUseSolutionLog());

        AmzaSyncSenders syncSenders = null;
        if (syncConfig.getSyncSenderEnabled()) {
            ScheduledExecutorService executorService = Executors
                    .newScheduledThreadPool(syncConfig.getSyncSendersThreadCount());
            syncSenders = new AmzaSyncSenders(stats, syncConfig, syncReceiver, executorService,
                    amzaClientProvider, amzaClientAquariumProvider, amzaInterner, mapper, orderIdProvider,
                    senderConfigStorage, syncPartitionConfigStorage, 30_000); // TODO config
        }

        amzaClientAquariumProvider.start();
        if (syncSenders != null) {
            syncSenders.start();
        }

        SoyRendererConfig rendererConfig = deployable.config(SoyRendererConfig.class);

        File staticResourceDir = new File(System.getProperty("user.dir"));
        System.out.println("Static resources rooted at " + staticResourceDir.getAbsolutePath());
        Resource sourceTree = new Resource(staticResourceDir)
                .addResourcePath(rendererConfig.getPathToStaticResources()).setDirectoryListingAllowed(false)
                .setContext("/ui/static");
        deployable.addResource(sourceTree);

        SoyRenderer renderer = new SoyRendererInitializer().initialize(rendererConfig);

        AmzaSyncUIService amzaSyncUIService = new AmzaSyncUIServiceInitializer().initialize(renderer,
                syncSenders, stats, syncConfig.getSyncSenderEnabled(), syncConfig.getSyncReceiverEnabled(),
                mapper);

        deployable.addEndpoints(LoadBalancerHealthCheckEndpoints.class);
        deployable.addNoAuth("/health/check");
        if (instanceConfig.getMainServiceAuthEnabled()) {
            if (syncConfig.getSyncReceiverEnabled()) {
                AmzaSyncOAuthValidatorConfig oAuthValidatorConfig = deployable
                        .config(AmzaSyncOAuthValidatorConfig.class);
                AuthValidator<OAuth1Signature, OAuth1Request> syncOAuthValidator = new AmzaSyncOAuthValidatorInitializer()
                        .initialize(oAuthValidatorConfig);
                deployable.addCustomOAuth(syncOAuthValidator, "/api/*");
            }
            deployable.addRouteOAuth("/amza/*", "/api/*");
            deployable.addSessionAuth("/ui/*", "/amza/*", "/api/*");
        } else {
            deployable.addNoAuth("/amza/*", "/api/*");
            deployable.addSessionAuth("/ui/*");
        }

        deployable.addEndpoints(AmzaSyncEndpoints.class);
        deployable.addInjectables(AmzaInterner.class, amzaInterner);
        if (syncSenders != null) {
            deployable.addInjectables(AmzaSyncSenders.class, syncSenders);
        }

        deployable.addEndpoints(AmzaSyncUIEndpoints.class);
        deployable.addInjectables(AmzaSyncUIService.class, amzaSyncUIService);

        if (syncConfig.getSyncReceiverEnabled()) {
            deployable.addEndpoints(AmzaSyncApiEndpoints.class);
            deployable.addInjectables(AmzaSyncReceiver.class, syncReceiver);
        }
        deployable.addInjectables(ObjectMapper.class, mapper);
        deployable.addInjectables(AmzaSyncSenderMap.class, senderConfigStorage);
        deployable.addInjectables(AmzaSyncPartitionConfigStorage.class, syncPartitionConfigStorage);

        deployable.buildServer().start();
        clientHealthProvider.start();
        serviceStartupHealthCheck.success();

    } catch (Throwable t) {
        serviceStartupHealthCheck.info("Encountered the following failure during startup.", t);
    }
}

From source file:com.esri.geoportal.harvester.rest.TaskController.java

/**
 * Gets task by id.//from w ww. ja  v  a  2  s. c  om
 *
 * @param taskId task id
 * @return task info or <code>null</code> if no task found
 */
@RequestMapping(value = "/rest/harvester/tasks/{taskId}/export", method = RequestMethod.GET)
public ResponseEntity<String> export(@PathVariable UUID taskId) {
    try {
        LOG.debug(formatForLog("GET /rest/harvester/tasks/%s", taskId));
        TaskDefinition taskDefinition = engine.getTasksService().readTaskDefinition(taskId);
        if (taskDefinition == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-disposition", String.format("attachment; filename=\"%s.json\"", taskId));
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        ResponseEntity<String> responseEntity = new ResponseEntity<>(mapper.writeValueAsString(taskDefinition),
                headers, HttpStatus.OK);
        return responseEntity;
    } catch (DataProcessorException | JsonProcessingException ex) {
        LOG.error(formatForLog("Error getting task: %s", taskId), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.superbiz.javaee.providers.ObjectMapperProvider.java

@Override
public ObjectMapper getContext(Class<?> type) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.setVisibilityChecker(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    objectMapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    objectMapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
}

From source file:sg.yeefan.searchenginewrapper.clients.TwitterClient.java

/**
 * Makes a query to Twitter Search by URL and returns its results.
 *
 * @param query Search engine query./*from www.j a v  a  2 s  . co m*/
 */
private SearchEngineResults getResults(NextQuery query) throws SearchEngineException {
    String keyString = query.getKey();
    String[] keyStrings = keyString.split("\\$", 0);
    if (keyStrings.length != 4)
        throw new SearchEngineFatalException(
                "Key must be of the form: consumer_key + \"$\" + consumer_secret + \"$\" + token_key + \"$\" + token_secret");
    String consumerKey = keyStrings[0];
    String consumerSecret = keyStrings[1];
    String tokenKey = keyStrings[2];
    String tokenSecret = keyStrings[3];
    long startTime = System.currentTimeMillis();
    OAuthConsumer consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret);
    consumer.setTokenWithSecret(tokenKey, tokenSecret);
    OAuthConnectionHandler connectionHandler = new OAuthConnectionHandler(consumer);
    FileDownloader downloader = new FileDownloader();
    String jsonString = null;
    try {
        downloader.setUserAgent(
                "Search Engine Wrapper (http://wing.comp.nus.edu.sg/~tanyeefa/downloads/searchenginewrapper/)");
        downloader.setConnectionHandler(connectionHandler);
        String requestUrl = query.getUrl();
        byte[] bytes = downloader.download(requestUrl);
        jsonString = new String(bytes, "UTF-8");
    } catch (FileDownloaderException e) {
        if (e.getReason() == FileDownloaderException.Reason.DOWNLOAD_ABORTED) {
            OAuthException exception = connectionHandler.getException();
            if (exception != null)
                throw new SearchEngineFatalException(exception);
            throw new SearchEngineException(e);
        } else {
            int code = downloader.getResponseCode();
            if (code == 429)
                throw new SearchEngineQuotaException(e);
            if (code % 100 == 4)
                throw new SearchEngineFatalException(e);
            throw new SearchEngineException(e);
        }
    } catch (UnsupportedEncodingException e) {
        throw new SearchEngineException(e);
    }
    long endTime = System.currentTimeMillis();
    Response response = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        response = mapper.readValue(jsonString, Response.class);
    } catch (IOException e) {
        throw new SearchEngineException(e);
    }
    SearchEngineResults results = new SearchEngineResults();
    results.setLabel(query.getLabel());
    results.setQuery(query.getQuery());
    results.setTotalResults(Long.MAX_VALUE);
    results.setStartIndex(query.getStartIndex());
    Status[] items = response.getStatuses();
    SearchEngineResult[] resultArray = new SearchEngineResult[items.length];
    for (int i = 0; i < items.length; i++) {
        User user = items[i].getUser();
        String url = "https://twitter.com/" + items[i].getUser().getScreenName().trim() + "/status/"
                + items[i].getId();
        String title = processTitle(user.getName().trim() + " (" + user.getScreenName().trim() + ")");
        String snippet = getStatusText(items[i]); // Use this instead of items[i].getText().
        resultArray[i] = new SearchEngineResult();
        resultArray[i].setURL(url);
        resultArray[i].setTitle(title);
        resultArray[i].setSnippet(processSnippet(snippet));
    }
    results.setResults(resultArray);
    results.setStartTime(startTime);
    results.setEndTime(endTime);
    String nextUrlString = response.getSearchMetadata().getNextResults();
    if (nextUrlString != null) {
        nextUrlString = "https://api.twitter.com/1.1/search/tweets.json" + nextUrlString;
        NextQuery nextQuery = new NextQuery();
        nextQuery.setKey(query.getKey());
        nextQuery.setLabel(query.getLabel());
        nextQuery.setQuery(query.getQuery());
        nextQuery.setStartIndex(query.getStartIndex() + items.length);
        nextQuery.setUrl(nextUrlString);
        results.setNextQuery(nextQuery);
    }
    return results;
}

From source file:gr.abiss.calipso.test.AbstractControllerIT.java

@BeforeClass
public void setup() {

    // log request/response in errors
    RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

    // pickup from the command line if given for the jetty-maven-plugin
    String port = System.getProperty("jetty.http.port");
    RestAssured.port = port != null ? Integer.parseInt(port) : 8080;

    this.WEBSOCKET_URI = new StringBuffer("ws://localhost:").append(RestAssured.port).append("/calipso/ws")
            .toString();/*  w ww  . j a  va 2 s. c  om*/
    // TODO:
    // String basePath = System.getProperty("server.base");
    // if (basePath == null) {
    // basePath = "/rest-garage-sample/";
    // }
    // RestAssured.basePath = basePath;
    //
    // String baseHost = System.getProperty("server.host");
    // if (baseHost == null) {
    // baseHost = "http://localhost";
    // }
    // RestAssured.baseURI = baseHost;

    // configure our object mapper
    RestAssured.config = RestAssuredConfig.config().objectMapperConfig(
            // config object mapper
            new ObjectMapperConfig().jackson2ObjectMapperFactory(new Jackson2ObjectMapperFactory() {
                @Override
                public ObjectMapper create(Class aClass, String s) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    // support joda classes<->JSON
                    objectMapper.registerModule(new JodaModule());
                    // ignore unknown properties
                    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                    return objectMapper;
                }
            }));

}