Example usage for com.fasterxml.jackson.core JsonFactory JsonFactory

List of usage examples for com.fasterxml.jackson.core JsonFactory JsonFactory

Introduction

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

Prototype

public JsonFactory() 

Source Link

Document

Default constructor used to create factory instances.

Usage

From source file:com.ntsync.shared.ContactGroup.java

/**
 * Creates and returns an instance of the RawContact from encrypted data
 * /*from  w  w w . j a v  a2 s.c om*/
 * */
public static ContactGroup valueOf(String rowId, Map<Byte, ByteBuffer> values, Key privateKey)
        throws InvalidKeyException {
    try {
        String sourceId = null;
        Long rawId = null;

        if (values.containsKey(GroupConstants.SERVERROW_ID)) {
            sourceId = readRawString(values.get(GroupConstants.SERVERROW_ID));
        }

        if (sourceId == null || !sourceId.equals(rowId)) {
            // If ServerContactId is different, then rowId is the clientId
            rawId = Long.parseLong(rowId);
        }

        if (sourceId == null && rawId < 0) {
            throw new IllegalArgumentException("Missing RowId in data");
        }

        AEADBlockCipher cipher = CryptoHelper.getCipher();

        final boolean deleted = values.containsKey(GroupConstants.DELETED);

        final String textData = CryptoHelper.decodeStringValue(GroupConstants.TEXTDATA, values, cipher,
                privateKey);

        if (textData == null && !deleted) {
            LOG.error("No textdata found for row with Id:" + rowId);
            return null;
        }

        String title = null;
        String notes = null;

        if (!isEmpty(textData)) {
            JsonFactory fac = new JsonFactory();
            JsonParser jp = fac.createParser(textData);
            jp.nextToken();
            while (jp.nextToken() != JsonToken.END_OBJECT) {
                String fieldname = jp.getCurrentName();
                // move to value, or START_OBJECT/START_ARRAY
                jp.nextToken();
                if (GroupConstants.TITLE.equals(fieldname)) {
                    title = jp.getValueAsString();
                } else if (GroupConstants.NOTES.equals(fieldname)) {
                    notes = jp.getValueAsString();
                } else {
                    LOG.error("Unrecognized field for row with Id:" + rowId + " Fieldname:" + fieldname);
                }
            }
            jp.close();
        }

        String modStr = readRawString(values.get(GroupConstants.MODIFIED));
        Date lastModified = null;
        if (!isEmpty(modStr)) {
            lastModified = new Date(Long.parseLong(modStr));
        }

        return new ContactGroup(rawId, sourceId, title, notes, deleted, lastModified, -1);
    } catch (InvalidCipherTextException ex) {
        throw new InvalidKeyException("Invalid key detected.", ex);
    } catch (final Exception ex) {
        LOG.info("Error parsing contactgroup data. Reason:" + ex.toString(), ex);
    }
    return null;
}

From source file:de.qaware.cloud.deployer.commons.config.util.ContentTreeUtil.java

/**
 * Returns the object mapper for the specified content type.
 *
 * @param contentType The content type./*ww  w .j  a va2 s .co  m*/
 * @return The object mapper.
 * @throws ResourceConfigException If the specified content type is unsupported.
 */
private static ObjectMapper retrieveObjectMapper(ContentType contentType) throws ResourceConfigException {
    ObjectMapper mapper;
    switch (contentType) {
    case YAML:
        mapper = new ObjectMapper(new YAMLFactory());
        break;
    case JSON:
        mapper = new ObjectMapper(new JsonFactory());
        break;
    default:
        throw new ResourceConfigException(
                COMMONS_MESSAGE_BUNDLE.getMessage("DEPLOYER_COMMONS_ERROR_UNSUPPORTED_CONTENT_TYPE"));
    }
    return mapper;
}

From source file:DAO.BestellingDAOJson.java

@Override
public List<ArtikelBestelling> readArtikelBestelling(Bestelling bestelling) throws SQLException {
    //create.put("artikellijst", list);
    //create.put("bestelling_id", bestelling.getBestelling_id());
    //create.put("klant_id", bestelling.getKlant_id());       
    List<ArtikelBestelling> artikelBestellingen = new ArrayList<>();
    ArtikelBestelling artikelBestelling;
    ArtikelPOJO artikelpojo;//  w w  w.ja  v  a2  s .c o  m
    HashMap<Integer, Bestelling> catalogus = new HashMap<>();
    //catalogus = bestelling;
    try (FileReader read = new FileReader("C:\\Users\\maurice\\Desktop\\Workshoptest.json");) {

        catalogus = gson.fromJson(read, artikelType);

        //je hoeft de arraylist Artikelbestelling niet in een hashmap te stoppen (waarvan de integer dan zou corresponderen
        // met de bestelling ID) omdat de bestelling ID standaard al in het bestelling object opgeslagen wordt..
        // dus je kunt met een hasNext for each loop alle elementen van catalogus doorlopen en met een if statement bekijken of
        // het overeenkomt. Ik bedenk me net dat de key telkens uniek hoort te zijn, je zou dus niet meerdere keren dezelfde klantID
        // als key kunnen opgeven... Je zult een unieke key moeten maken van zowel de klantID plus het bestellingID erachter geplakt.
        // en een "_" ertussen. Zo kun je ook zeer gemakkelijk de juist bestelling vinden.
        catalogus = gson.fromJson(read, artikelType);
        bestelling = catalogus.get(bestelling.getKlant_id());
    } catch (IOException ex) {
        logger.error("read input/output " + ex);
    }

    JSONParser jsonParser = new JSONParser();
    String jsonFilePath = "C:\\Users\\maurice\\Desktop\\Workshoptest.json";
    try {
        JsonFactory jfactory = new JsonFactory();
        JsonParser jParser = jfactory
                .createJsonParser(new File("C:\\Users\\maurice\\Desktop\\Workshoptest.json"));
        //ObjectMapper mapper = new ObjectMapper();
        //ObjectNode node = (ObjectNode) mapper.readTree(jParser);
        //node.get(jsonFilePath)
    } catch (JsonGenerationException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    return artikelBestellingen;
}

From source file:io.fabric8.cxf.endpoint.jaxrs.RestJsonSchemaJMXTest.java

private void parseJson(String json) throws Exception {
    JsonParser parser = new JsonFactory().createParser(json);
    while (parser.nextToken() != null) {
        //if it's an invalidate json will throw exception 
        //which could be caught by the test
    }/*w  w  w  .j a  v a2  s .  co  m*/
}

From source file:eu.project.ttc.models.index.JsonTermIndexIO.java

/**
 * Loads the json-serialized term index into the param {@link TermIndex} object.
 * // w  w w .ja va  2s.c o  m
 * @param reader
 * @param options
 *          The deserialization {@link IOOptions}.
 * @return
 * @throws JsonParseException
 * @throws IOException
 */
public static TermIndex load(Reader reader, JsonOptions options) throws JsonParseException, IOException {
    TermIndex termIndex = null;
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(reader); // or Stream, Reader
    jp.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    jp.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
    String fieldname;
    String compLemma = null;
    int fileSource = -1;
    String wordLemma = null;
    String syntacticLabel = null;
    int begin = -1;
    int end = -1;
    int nbWordAnnos = -1;
    int nbSpottedTerms = -1;
    Term b;
    Term v;
    String text;
    String base;
    String variant;
    //      String rule;
    String infoToken;
    String variantType;
    double variantScore;

    Map<Integer, String> inputSources = Maps.newTreeMap();

    Map<Integer, List<TempVecEntry>> contextVectors = Maps.newHashMap();

    OccurrenceStore occurrenceStore = null;

    // useful var for debug
    JsonToken tok;

    while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {

        fieldname = jp.getCurrentName();
        if (METADATA.equals(fieldname)) {
            jp.nextToken();
            String termIndexName = null;
            Lang lang = null;
            String corpusID = null;
            String occurrenceStorage = null;
            String occurrenceStoreURI = null;

            while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                fieldname = jp.getCurrentName();
                if (LANG.equals(fieldname)) {
                    lang = Lang.forName(jp.nextTextValue());
                } else if (NAME.equals(fieldname)) {
                    termIndexName = jp.nextTextValue();
                } else if (NB_WORD_ANNOTATIONS.equals(fieldname)) {
                    nbWordAnnos = jp.nextIntValue(-1);
                } else if (NB_SPOTTED_TERMS.equals(fieldname)) {
                    nbSpottedTerms = jp.nextIntValue(-1);
                } else if (CORPUS_ID.equals(fieldname)) {
                    corpusID = jp.nextTextValue();
                } else if (OCCURRENCE_STORAGE.equals(fieldname)) {
                    occurrenceStorage = jp.nextTextValue();
                } else if (OCCURRENCE_MONGODB_STORE_URI.equals(fieldname)) {
                    occurrenceStoreURI = jp.nextTextValue();
                }
            }
            Preconditions.checkState(lang != null, "The property meta.lang must be defined");
            Preconditions.checkState(termIndexName != null, "The property meta.name must be defined");

            if (occurrenceStorage != null && occurrenceStorage.equals(OCCURRENCE_STORAGE_MONGODB)) {
                Preconditions.checkNotNull(occurrenceStoreURI,
                        "Missing attribute " + OCCURRENCE_MONGODB_STORE_URI);
                occurrenceStore = new MongoDBOccurrenceStore(occurrenceStoreURI, OccurrenceStore.State.INDEXED);
            } else
                occurrenceStore = new MemoryOccurrenceStore();

            termIndex = new MemoryTermIndex(termIndexName, lang, occurrenceStore);
            if (corpusID != null)
                termIndex.setCorpusId(corpusID);
            if (nbWordAnnos != -1)
                termIndex.setWordAnnotationsNum(nbWordAnnos);
            if (nbSpottedTerms != -1)
                termIndex.setSpottedTermsNum(nbSpottedTerms);

            if (options.isMetadataOnly())
                return termIndex;

        } else if (WORDS.equals(fieldname)) {
            jp.nextToken();
            while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
                WordBuilder wordBuilder = WordBuilder.start();
                while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                    fieldname = jp.getCurrentName();
                    if (LEMMA.equals(fieldname))
                        wordBuilder.setLemma(jp.nextTextValue());
                    else if (COMPOUND_TYPE.equals(fieldname))
                        wordBuilder.setCompoundType(CompoundType.fromName(jp.nextTextValue()));
                    else if (STEM.equals(fieldname))
                        wordBuilder.setStem(jp.nextTextValue());
                    else if (COMPONENTS.equals(fieldname)) {
                        while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
                            while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                                fieldname = jp.getCurrentName();
                                if (LEMMA.equals(fieldname))
                                    compLemma = jp.nextTextValue();
                                else if (BEGIN.equals(fieldname))
                                    begin = jp.nextIntValue(-2);
                                else if (END.equals(fieldname))
                                    end = jp.nextIntValue(-2);
                            }
                            wordBuilder.addComponent(begin, end, compLemma);
                        }
                    }
                }
                try {
                    termIndex.addWord(wordBuilder.create());
                } catch (Exception e) {
                    LOGGER.error("Could not add word " + wordBuilder.getLemma() + " to term index", e);
                    LOGGER.warn("Error ignored, trying ton continue the loading of TermIndex");
                }
            }
        } else if (TERMS.equals(fieldname)) {
            jp.nextToken();
            while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
                TermBuilder builder = TermBuilder.start(termIndex);
                List<TempVecEntry> currentContextVector = Lists.newArrayList();
                int currentTermId = -1;
                while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                    fieldname = jp.getCurrentName();
                    if (GROUPING_KEY.equals(fieldname))
                        builder.setGroupingKey(jp.nextTextValue());
                    else if (SPOTTING_RULE.equals(fieldname))
                        builder.setSpottingRule(jp.nextTextValue());
                    else if (ID.equals(fieldname)) {
                        currentTermId = jp.nextIntValue(-2);
                        builder.setId(currentTermId);
                    } else if (RANK.equals(fieldname)) {
                        builder.setRank(jp.nextIntValue(-1));
                    } else if (FREQUENCY.equals(fieldname)) {
                        builder.setFrequency(jp.nextIntValue(-1));
                    } else {
                        if (FREQ_NORM.equals(fieldname)) {
                            jp.nextToken();
                            builder.setFrequencyNorm((double) jp.getFloatValue());
                        } else if (SPECIFICITY.equals(fieldname)) {
                            jp.nextToken();
                            builder.setSpecificity((double) jp.getDoubleValue());
                        } else if (GENERAL_FREQ_NORM.equals(fieldname)) {
                            jp.nextToken();
                            builder.setGeneralFrequencyNorm((double) jp.getFloatValue());
                        } else if (WORDS.equals(fieldname)) {
                            while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
                                wordLemma = null;
                                syntacticLabel = null;
                                while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                                    fieldname = jp.getCurrentName();
                                    if (LEMMA.equals(fieldname))
                                        wordLemma = jp.nextTextValue();
                                    else if (SYN.equals(fieldname))
                                        syntacticLabel = jp.nextTextValue();
                                }
                                Preconditions.checkArgument(wordLemma != null, MSG_EXPECT_PROP_FOR_TERM_WORD,
                                        LEMMA);
                                Preconditions.checkArgument(syntacticLabel != null,
                                        MSG_EXPECT_PROP_FOR_TERM_WORD, SYN);
                                builder.addWord(termIndex.getWord(wordLemma), syntacticLabel);
                            } // end words

                        } else if (OCCURRENCES.equals(fieldname)) {
                            tok = jp.nextToken();
                            if (tok == JsonToken.START_ARRAY) {

                                while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
                                    begin = -1;
                                    end = -1;
                                    fileSource = -1;
                                    text = null;
                                    while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                                        fieldname = jp.getCurrentName();
                                        if (BEGIN.equals(fieldname))
                                            begin = jp.nextIntValue(-1);
                                        else if (TEXT.equals(fieldname))
                                            text = jp.nextTextValue();
                                        else if (END.equals(fieldname))
                                            end = jp.nextIntValue(-1);
                                        else if (FILE.equals(fieldname)) {
                                            fileSource = jp.nextIntValue(-1);
                                        }
                                    }

                                    Preconditions.checkArgument(begin != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE,
                                            BEGIN);
                                    Preconditions.checkArgument(end != -1, MSG_EXPECT_PROP_FOR_OCCURRENCE, END);
                                    Preconditions.checkArgument(fileSource != -1,
                                            MSG_EXPECT_PROP_FOR_OCCURRENCE, FILE);
                                    Preconditions.checkNotNull(inputSources.get(fileSource),
                                            "No file source with id: %s", fileSource);
                                    Preconditions.checkNotNull(text, MSG_EXPECT_PROP_FOR_OCCURRENCE, TEXT);
                                    if (occurrenceStore.getStoreType() == OccurrenceStore.Type.MEMORY)
                                        builder.addOccurrence(begin, end,
                                                termIndex.getDocument(inputSources.get(fileSource)), text);
                                }
                            }
                            // end occurrences
                        } else if (CONTEXT.equals(fieldname)) {
                            @SuppressWarnings("unused")
                            int totalCooccs = 0;
                            while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                                fieldname = jp.getCurrentName();
                                if (TOTAL_COOCCURRENCES.equals(fieldname))
                                    /*
                                     * value never used since the total will 
                                     * be reincremented in the contextVector
                                     */
                                    totalCooccs = jp.nextIntValue(-1);
                                else if (CO_OCCURRENCES.equals(fieldname)) {
                                    jp.nextToken();
                                    while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
                                        TempVecEntry entry = new TempVecEntry();
                                        while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                                            fieldname = jp.getCurrentName();
                                            if (NB_COCCS.equals(fieldname))
                                                entry.setNbCooccs(jp.nextIntValue(-1));
                                            else if (ASSOC_RATE.equals(fieldname)) {
                                                jp.nextToken();
                                                entry.setAssocRate(jp.getFloatValue());
                                            } else if (CO_TERM.equals(fieldname))
                                                entry.setTermGroupingKey(jp.nextTextValue());
                                            else if (FILE.equals(fieldname)) {
                                                fileSource = jp.nextIntValue(-1);
                                            }
                                        }
                                        currentContextVector.add(entry);
                                    }
                                }
                            }
                        }
                    } //end if fieldname

                } // end term object
                try {
                    builder.createAndAddToIndex();
                } catch (Exception e) {
                    LOGGER.error("Could not add term " + builder.getGroupingKey() + " to term index", e);
                    LOGGER.warn("Error ignored, trying ton continue the loading of TermIndex");
                }

                if (options.isWithContexts())
                    contextVectors.put(currentTermId, currentContextVector);

            } // end array of terms

        } else if (INPUT_SOURCES.equals(fieldname)) {
            jp.nextToken();
            while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                String id = jp.getCurrentName();
                try {
                    inputSources.put(Integer.parseInt(id), jp.nextTextValue());
                } catch (NumberFormatException e) {
                    IOUtils.closeQuietly(jp);
                    throw new IllegalArgumentException("Bad format for input source key: " + id);
                }
            }
        } else if (TERM_VARIATIONS.equals(fieldname)) {
            jp.nextToken();
            while ((tok = jp.nextToken()) != JsonToken.END_ARRAY) {
                base = null;
                variant = null;
                infoToken = null;
                variantType = null;
                variantScore = 0;
                while ((tok = jp.nextToken()) != JsonToken.END_OBJECT) {
                    fieldname = jp.getCurrentName();
                    if (BASE.equals(fieldname))
                        base = jp.nextTextValue();
                    else if (VARIANT.equals(fieldname))
                        variant = jp.nextTextValue();
                    else if (VARIANT_TYPE.equals(fieldname))
                        variantType = jp.nextTextValue();
                    else if (VARIANT_SCORE.equals(fieldname)) {
                        jp.nextToken();
                        variantScore = jp.getDoubleValue();
                    } else if (INFO.equals(fieldname))
                        infoToken = jp.nextTextValue();
                } // end syntactic variant object
                Preconditions.checkNotNull(base, MSG_EXPECT_PROP_FOR_VAR, BASE);
                Preconditions.checkNotNull(variant, MSG_EXPECT_PROP_FOR_VAR, VARIANT);
                Preconditions.checkNotNull(infoToken, MSG_EXPECT_PROP_FOR_VAR, INFO);
                b = termIndex.getTermByGroupingKey(base);
                v = termIndex.getTermByGroupingKey(variant);
                if (b != null && v != null) {

                    VariationType vType = VariationType.fromShortName(variantType);

                    TermVariation tv = new TermVariation(vType, b, v,
                            vType == VariationType.GRAPHICAL ? Double.parseDouble(infoToken) : infoToken);
                    tv.setScore(variantScore);
                    b.addTermVariation(tv);
                } else {
                    if (b == null)
                        LOGGER.warn("Could not build variant because term \"{}\" was not found.", base);
                    if (v == null)
                        LOGGER.warn("Could not build variant because term \"{}\" was not found.", variant);
                }

                //               Preconditions.checkNotNull(b, MSG_TERM_DOES_NOT_EXIST, base);
                //               Preconditions.checkNotNull(v, MSG_TERM_DOES_NOT_EXIST, variant);

            } // end syntactic variations array
        }
    }
    jp.close();

    if (options.isWithContexts()) {
        /*
         *  map term ids with terms in context vectors and
         *  set context vectors
         */
        List<TempVecEntry> currentTempVecList;
        Term term = null;
        Term coTerm = null;
        ContextVector contextVector;
        for (int termId : contextVectors.keySet()) {
            currentTempVecList = contextVectors.get(termId);
            term = termIndex.getTermById(termId);
            contextVector = new ContextVector(term);
            for (TempVecEntry tempVecEntry : currentTempVecList) {
                coTerm = termIndex.getTermByGroupingKey(tempVecEntry.getTermGroupingKey());
                contextVector.addEntry(coTerm, tempVecEntry.getNbCooccs(), tempVecEntry.getAssocRate());
            }
            if (!contextVector.getEntries().isEmpty())
                term.setContextVector(contextVector);
        }
    }

    return termIndex;
}

From source file:org.usrz.libs.webtools.resources.ServeResource.java

/**
 * Create a new {@link ServeResource} instance with the specified
 * {@link Configurations}.//from w ww .j a va2s  .  c  om
 */
@Inject
public ServeResource(Configurations configurations) throws IOException {
    charset = Charset.forName(configurations.get("charset", UTF8.name()));
    charsetName = charset.name();

    manager = new ResourceManager(configurations.requireFile("root_path"), charset);

    minify = configurations.get("minify", false);

    cacheDuration = configurations.get("cache", Duration.ZERO);
    cacheControl = new CacheControl();
    cacheControl.setMaxAge((int) cacheDuration.getSeconds());
    cacheControl.setNoCache(Duration.ZERO.equals(cacheDuration));

    jsonMediaType = new MediaType("application", "json").withCharset(charsetName);
    styleMediaType = new MediaType("text", "css").withCharset(charsetName);
    scriptMediaType = new MediaType("application", "javascript").withCharset(charsetName);

    executor = new KeyedExecutor<String>(SimpleExecutorProvider.create(configurations.strip("executor")));

    /* Our Json factory, able to read all sorts of weird schtuff */
    json = new JsonFactory()
            /* Factory features */
            .disable(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES)
            .disable(JsonFactory.Feature.INTERN_FIELD_NAMES)
            /* Parser features */
            .enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)
            .enable(JsonParser.Feature.ALLOW_COMMENTS).enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS)
            .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS)
            .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .disable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS)
            .disable(JsonParser.Feature.ALLOW_YAML_COMMENTS)
            .disable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
            /* Generator features */
            .disable(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT)
            .enable(JsonGenerator.Feature.ESCAPE_NON_ASCII).enable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)
            .enable(JsonGenerator.Feature.QUOTE_FIELD_NAMES)
            .enable(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN)
            .disable(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS)
            .disable(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION)
            .disable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
}

From source file:org.helm.notation2.wsadapter.MonomerWSLoader.java

/**
 * Loads the monomer categories using the URL configured in
 * {@code MonomerStoreConfiguration}.//from   w  w  w  .ja  va  2 s  . com
 *
 * @return List containing monomer categories
 *
 * @throws IOException
 * @throws URISyntaxException
 */
public static List<CategorizedMonomer> loadMonomerCategorization() throws IOException, URISyntaxException {
    List<CategorizedMonomer> config = new LinkedList<CategorizedMonomer>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    // There is no need to provide user credentials
    // HttpClient will attempt to access current user security context
    // through Windows platform specific methods via JNI.
    CloseableHttpResponse response = null;
    try {
        response = WSAdapterUtils.getResource(
                MonomerStoreConfiguration.getInstance().getWebserviceEditorCategorizationFullURL());

        LOG.debug(response.getStatusLine().toString());

        JsonFactory jsonf = new JsonFactory();
        InputStream instream = response.getEntity().getContent();

        JsonParser jsonParser = jsonf.createJsonParser(instream);
        config = deserializeEditorCategorizationConfig(jsonParser);
        LOG.debug(config.size() + " categorization info entries loaded");

        EntityUtils.consume(response.getEntity());

    } finally {
        if (response != null) {
            response.close();
        }
        if (httpclient != null) {
            httpclient.close();
        }
    }

    return config;
}

From source file:org.messic.server.api.tagwizard.discogs.DiscogsTAGWizardPlugin.java

private Album getAlbum(String id) {
    String baseURL = "http://api.discogs.com/releases/" + id;
    try {//  w ww .  j  a v  a2 s  . c o  m
        URL url = new URL(baseURL);
        Proxy proxy = getProxy();
        URLConnection uc = (proxy != null ? url.openConnection(proxy) : url.openConnection());
        uc.setRequestProperty("User-Agent", "Messic/1.0 +http://spheras.github.io/messic/");

        Album album = new Album();

        album.name = "";
        album.author = "";
        album.comments = "Info obtained by Discogs provider (http://www.discogs.com/)";
        album.year = 1900;
        album.genre = "";

        JsonFactory jsonFactory = new JsonFactory(); // or, for data binding,
        JsonParser jParser = jsonFactory.createParser(uc.getInputStream());
        while (jParser.nextToken() != null) {
            String fieldname = jParser.getCurrentName();
            if ("title".equals(fieldname)) {
                jParser.nextToken();
                album.name = jParser.getText();
            }
            if ("year".equals(fieldname)) {
                jParser.nextToken();
                try {
                    album.year = Integer.valueOf(jParser.getText());
                } catch (Exception e) {
                    album.year = 0;
                }
            }
            if ("notes".equals(fieldname)) {
                jParser.nextToken();
                album.comments = jParser.getText();
            }
            if ("genres".equals(fieldname)) {
                jParser.nextToken();
                jParser.nextToken();
                album.genre = jParser.getText();
                do {
                    jParser.nextToken();
                } while (!"genres".equals(jParser.getCurrentName()));
            }
            if ("artists".equals(fieldname)) {
                jParser.nextToken();
                while (!"name".equals(jParser.getCurrentName())) {
                    jParser.nextToken();
                }
                jParser.nextToken();
                album.author = jParser.getText();
                do {
                    jParser.nextToken();
                } while (!"artists".equals(jParser.getCurrentName()));
            }

            if ("tracklist".equals(fieldname)) {
                album.songs = new ArrayList<Song>();
                do {
                    Song newsong = new Song();
                    int tracknumber = 1;
                    while (jParser.nextToken() != JsonToken.END_OBJECT) {
                        String trackfieldname = jParser.getCurrentName();

                        if ("extraartists".equals(trackfieldname)) {
                            do {
                                while (jParser.nextToken() != JsonToken.END_OBJECT) {

                                }
                                jParser.nextToken();
                            } while (!"extraartists".equals(jParser.getCurrentName()));
                        }
                        if ("position".equals(trackfieldname)) {
                            jParser.nextToken();
                            try {
                                newsong.track = Integer.valueOf(jParser.getText());
                            } catch (Exception e) {
                                newsong.track = tracknumber;
                            }
                            tracknumber++;
                        }
                        if ("title".equals(trackfieldname)) {
                            jParser.nextToken();
                            newsong.name = jParser.getText();
                        }
                    }
                    album.songs.add(newsong);
                    jParser.nextToken();
                } while (!"tracklist".equals(jParser.getCurrentName()));
                jParser.nextToken();
            }
        }

        return album;
    } catch (Exception e) {
        log.error("failed!", e);
    }

    return null;
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.TelekomSMSTokenProvider.java

@Override
protected void sendSMS(String text, String recipientNumber) {
    recipientNumber = recipientNumber.replaceAll("^00", "\\+");

    try {/*from   ww  w  . j  a  v a  2s.  c om*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator jg = jsonFactory.createGenerator(baos, JsonEncoding.UTF8);

        jg.writeStartObject();
        jg.writeObjectFieldStart("outboundSMSMessageRequest");
        jg.writeArrayFieldStart("address");
        jg.writeString("tel:" + recipientNumber);
        jg.writeEndArray();
        jg.writeStringField("senderAddress", senderAddress);
        jg.writeObjectFieldStart("outboundSMSTextMessage");
        jg.writeStringField("message", text);
        jg.writeEndObject();
        jg.writeStringField("outboundEncoding", "7bitGSM");
        jg.writeStringField("clientCorrelator", "" + ((long) (Math.random() * Long.MAX_VALUE)));
        if (senderName != null)
            jg.writeStringField("senderName", senderName);
        jg.writeEndObject();
        jg.writeEndObject();

        jg.close();

        Exchange exc = new Request.Builder()
                .post("https://gateway.developer.telekom.com/plone/sms/rest/"
                        + environment.name().toLowerCase() + "/smsmessaging/v1/outbound/"
                        + URLEncoder.encode(senderAddress, "UTF-8") + "/requests")
                .header("Host", "gateway.developer.telekom.com")
                .header("Authorization",
                        "OAuth realm=\"developergarden.com\",oauth_token=\"" + getAccessToken() + "\"")
                .header("Accept", "application/json").header("Content-Type", "application/json")
                .body(baos.toByteArray()).buildExchange();

        exc.setRule(new NullRule() {
            @Override
            public SSLProvider getSslOutboundContext() {
                return new SSLContext(new SSLParser(), new ResolverMap(), null);
            }
        });
        hc.call(exc, false, true);

        if (exc.getResponse().getStatusCode() != 201)
            throw new RuntimeException("Could not send SMS: " + exc.getResponse());

        log.debug("sent SMS to " + recipientNumber);
    } catch (Exception e2) {
        throw new RuntimeException(e2);
    }
}

From source file:com.greplin.gec.GecLog4jAppender.java

/**
 * Writes a formatted msg for errors that don't have exceptions.
 *
 * @param message the log message//from   w w  w  .  j a  v  a  2 s  .  com
 * @param level   the error level
 * @param out     the destination
 * @throws IOException if there are IO errors in the destination
 */
void writeFormattedException(final String message, final Level level, final Writer out) throws IOException {
    JsonGenerator generator = new JsonFactory().createJsonGenerator(out);

    String backtrace = ExceptionUtils.getFullStackTrace(new Exception());
    String[] lines = backtrace.split("\n");
    StringBuilder builder = new StringBuilder();
    for (String line : lines) {
        if (!line.contains("com.greplin.gec.GecLog4jAppender.")) {
            builder.append(line);
            builder.append("\n");
        }
    }
    backtrace = builder.toString();

    generator.writeStartObject();
    generator.writeStringField("project", this.project);
    generator.writeStringField("environment", this.environment);
    generator.writeStringField("serverName", this.serverName);
    generator.writeStringField("backtrace", backtrace);
    generator.writeStringField("message", message);
    generator.writeStringField("logMessage", message);
    generator.writeStringField("type", "N/A");
    if (level != Level.ERROR) {
        generator.writeStringField("errorLevel", level.toString());
    }
    writeContext(generator);
    generator.writeEndObject();
    generator.close();
}