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.marklogic.client.functionaltest.TestBulkReadWriteWithJacksonParserHandle.java

@Test
public void testBulkSearchQBEWithJSONResponseFormat()
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    int count;/*ww  w  .  ja v  a  2 s.  c o  m*/
    String docId[] = { "/a.json", "/b.json", "/c.json" };
    String json1 = new String("{\"animal\":\"dog\", \"says\":\"woof\"}");
    String json2 = new String("{\"animal\":\"cat\", \"says\":\"meow\"}");
    String json3 = new String("{\"animal\":\"rat\", \"says\":\"keek\"}");

    JsonFactory f = new JsonFactory();

    JSONDocumentManager docMgr1 = client.newJSONDocumentManager();
    docMgr1.setMetadataCategories(Metadata.ALL);
    DocumentWriteSet writeset = docMgr1.newWriteSet();

    JacksonParserHandle jacksonParserHandle1 = new JacksonParserHandle();
    JacksonParserHandle jacksonParserHandle2 = new JacksonParserHandle();
    JacksonParserHandle jacksonParserHandle3 = new JacksonParserHandle();

    jacksonParserHandle1.set(f.createParser(json1));
    jacksonParserHandle2.set(f.createParser(json2));
    jacksonParserHandle3.set(f.createParser(json3));

    writeset.add(docId[0], jacksonParserHandle1);
    writeset.add(docId[1], jacksonParserHandle2);
    writeset.add(docId[2], jacksonParserHandle3);
    // Write to database.
    docMgr1.write(writeset);

    //Creating a xml document manager for bulk search
    XMLDocumentManager docMgr = client.newXMLDocumentManager();
    //using QBE for query definition and set the search criteria

    QueryManager queryMgr = client.newQueryManager();
    String queryAsString = "{\"$query\": { \"says\": {\"$word\":\"woof\",\"$exact\": false}}}";
    RawQueryByExampleDefinition qd = queryMgr
            .newRawQueryByExampleDefinition(new StringHandle(queryAsString).withFormat(Format.JSON));

    // set  document manager level settings for search response
    docMgr.setPageLength(25);
    docMgr.setSearchView(QueryView.RESULTS);
    docMgr.setNonDocumentFormat(Format.JSON);

    // Search for documents where content has bar and get first result record, get search handle on it,Use DOMHandle to read results
    JacksonParserHandle sh = new JacksonParserHandle();
    DocumentPage page;

    long pageNo = 1;
    do {
        count = 0;
        page = docMgr.search(qd, pageNo, sh);
        if (pageNo > 1) {
            assertFalse("Is this first Page", page.isFirstPage());
            assertTrue("Is page has previous page ?", page.hasPreviousPage());
        }
        while (page.hasNext()) {
            DocumentRecord rec = page.next();
            rec.getFormat();
            validateRecord(rec, Format.JSON);
            System.out.println(rec.getContent(new StringHandle()).get().toString());
            count++;
        }

        // Add additional asserts once JacksonParserHandle is ready to handle bulk Search set.

        //assertTrue("Page start in results and on page",sh.get().get("start").asLong() == page.getStart());
        assertEquals("document count", page.size(), count);
        //         assertEquals("Page Number #",pageNo,page.getPageNumber());
        pageNo = pageNo + page.getPageSize();
    } while (!page.isLastPage() && page.hasContent());

    assertEquals("page count is  ", 1, page.getTotalPages());
    assertFalse("Page has previous page ?", page.hasPreviousPage());
    assertEquals("page size", 25, page.getPageSize());
    assertEquals("document count", 1, page.getTotalSize());
    // Close handles.
    jacksonParserHandle1.close();
    jacksonParserHandle2.close();
    jacksonParserHandle3.close();
}

From source file:com.adobe.communities.ugc.migration.importer.ImportFileUploadServlet.java

protected void doPut(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    final String path = request.getRequestParameter("path").getString();
    final ResourceResolver resolver = request.getResourceResolver();
    UGCImportHelper.checkUserPrivileges(resolver, rrf);

    final Resource resource = resolver.getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for import");
    }//from  ww  w.  java2  s .  c  o  m
    final String filePath = request.getRequestParameter("filePath").getString();
    if (!filePath.startsWith(ImportFileUploadServlet.UPLOAD_DIR)) {
        throw new ServletException("Path to file resource lies outside migration import path");
    }
    final Resource fileResource = resolver.getResource(filePath);
    if (fileResource == null) {
        throw new ServletException("Could not find a valid file resource to read");
    }
    // get the input stream from the file resource
    Resource file = fileResource.getChild("file");
    if (null != file && !(file instanceof NonExistingResource)) {
        file = file.getChild(JcrConstants.JCR_CONTENT);
        if (null != file && !(file instanceof NonExistingResource)) {
            final ValueMap contentVM = file.getValueMap();
            InputStream inputStream = (InputStream) contentVM.get(JcrConstants.JCR_DATA);
            if (inputStream != null) {
                final JsonParser jsonParser = new JsonFactory().createParser(inputStream);
                jsonParser.nextToken(); // get the first token

                importFile(jsonParser, resource, resolver);
                deleteResource(fileResource);
                return;
            }
        }
    }
    throw new ServletException("Unable to read file in provided file resource path");
}

From source file:org.apache.drill.exec.store.parquet.Metadata.java

/**
 * Serialize parquet metadata to json and write to a file
 *
 * @param parquetTableMetadata//from ww  w.ja  va 2s.c  o  m
 * @param p
 * @throws IOException
 */
private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer());
    mapper.registerModule(module);
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata);
    os.flush();
    os.close();
}

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

public static void save(Writer writer, TermIndex termIndex, JsonOptions options) throws IOException {
    JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory 
    //      jsonFactory.configure(f, state)
    JsonGenerator jg = jsonFactory.createGenerator(writer); // or Stream, Reader
    jg.useDefaultPrettyPrinter();//from   w  w  w.  ja v  a  2 s  .co  m

    jg.writeStartObject();

    jg.writeFieldName(METADATA);
    jg.writeStartObject();
    jg.writeFieldName(NAME);
    jg.writeString(termIndex.getName());
    jg.writeFieldName(LANG);
    jg.writeString(termIndex.getLang().getCode());
    if (termIndex.getCorpusId() != null) {
        jg.writeFieldName(CORPUS_ID);
        jg.writeString(termIndex.getCorpusId());
    }

    jg.writeFieldName(OCCURRENCE_STORAGE);
    if (options.isMongoDBOccStore()) {
        jg.writeString(OCCURRENCE_STORAGE_MONGODB);
        jg.writeFieldName(OCCURRENCE_MONGODB_STORE_URI);
        jg.writeString(options.getMongoDBOccStore());
    } else if (options.isEmbeddedOccurrences())
        jg.writeString(OCCURRENCE_STORAGE_EMBEDDED);
    else
        throw new IllegalStateException("Unknown storage mode");

    jg.writeFieldName(NB_WORD_ANNOTATIONS);
    jg.writeNumber(termIndex.getWordAnnotationsNum());
    jg.writeFieldName(NB_SPOTTED_TERMS);
    jg.writeNumber(termIndex.getSpottedTermsNum());

    jg.writeEndObject();

    jg.writeFieldName(INPUT_SOURCES);
    int idCnt = 0;
    Map<String, Integer> inputSources = Maps.newTreeMap();
    for (Document d : termIndex.getDocuments())
        if (!inputSources.containsKey(d.getUrl()))
            inputSources.put(d.getUrl(), ++idCnt);
    jg.writeStartObject();
    for (String uri : inputSources.keySet()) {
        jg.writeFieldName(inputSources.get(uri).toString());
        jg.writeString(uri);
    }
    jg.writeEndObject();

    jg.writeFieldName(WORDS);
    jg.writeStartArray();
    for (Word w : termIndex.getWords()) {
        jg.writeStartObject();
        jg.writeFieldName(LEMMA);
        jg.writeString(w.getLemma());
        jg.writeFieldName(STEM);
        jg.writeString(w.getStem());
        if (w.isCompound()) {
            jg.writeFieldName(COMPOUND_TYPE);
            jg.writeString(w.getCompoundType().name());
            jg.writeFieldName(COMPONENTS);
            jg.writeStartArray();
            for (Component c : w.getComponents()) {
                jg.writeStartObject();
                jg.writeFieldName(LEMMA);
                jg.writeString(c.getLemma());
                jg.writeFieldName(BEGIN);
                jg.writeNumber(c.getBegin());
                jg.writeFieldName(END);
                jg.writeNumber(c.getEnd());
                jg.writeEndObject();
            }
            jg.writeEndArray();
        }

        jg.writeEndObject();
    }
    jg.writeEndArray();

    Set<TermVariation> termVariations = Sets.newHashSet();

    jg.writeFieldName(TERMS);
    jg.writeStartArray();
    for (Term t : termIndex.getTerms()) {
        termVariations.addAll(t.getVariations());

        jg.writeStartObject();
        jg.writeFieldName(ID);
        jg.writeNumber(t.getId());
        jg.writeFieldName(RANK);
        jg.writeNumber(t.getRank());
        jg.writeFieldName(GROUPING_KEY);
        jg.writeString(t.getGroupingKey());
        jg.writeFieldName(WORDS);
        jg.writeStartArray();
        for (TermWord tw : t.getWords()) {
            jg.writeStartObject();
            jg.writeFieldName(SYN);
            jg.writeString(tw.getSyntacticLabel());
            jg.writeFieldName(LEMMA);
            jg.writeString(tw.getWord().getLemma());
            jg.writeEndObject();
        }
        jg.writeEndArray();

        jg.writeFieldName(FREQUENCY);
        jg.writeNumber(t.getFrequency());
        jg.writeFieldName(FREQ_NORM);
        jg.writeNumber(t.getFrequencyNorm());
        jg.writeFieldName(GENERAL_FREQ_NORM);
        jg.writeNumber(t.getGeneralFrequencyNorm());
        jg.writeFieldName(SPECIFICITY);
        jg.writeNumber(t.getSpecificity());
        jg.writeFieldName(SPOTTING_RULE);
        jg.writeString(t.getSpottingRule());

        if (options.withOccurrences() && options.isEmbeddedOccurrences()) {
            jg.writeFieldName(OCCURRENCES);
            jg.writeStartArray();
            for (TermOccurrence termOcc : t.getOccurrences()) {
                jg.writeStartObject();
                jg.writeFieldName(BEGIN);
                jg.writeNumber(termOcc.getBegin());
                jg.writeFieldName(END);
                jg.writeNumber(termOcc.getEnd());
                jg.writeFieldName(TEXT);
                jg.writeString(termOcc.getCoveredText());
                jg.writeFieldName(FILE);
                jg.writeNumber(inputSources.get(termOcc.getSourceDocument().getUrl()));
                jg.writeEndObject();
            }
            jg.writeEndArray();
        }

        if (options.isWithContexts() && t.isContextVectorComputed()) {
            jg.writeFieldName(CONTEXT);
            jg.writeStartObject();

            jg.writeFieldName(TOTAL_COOCCURRENCES);
            jg.writeNumber(t.getContextVector().getTotalCoccurrences());
            jg.writeFieldName(CO_OCCURRENCES);
            jg.writeStartArray();
            if (t.isContextVectorComputed()) {
                for (ContextVector.Entry contextEntry : t.getContextVector().getEntries()) {
                    jg.writeStartObject();
                    jg.writeFieldName(CO_TERM);
                    jg.writeString(contextEntry.getCoTerm().getGroupingKey());
                    jg.writeFieldName(NB_COCCS);
                    jg.writeNumber(contextEntry.getNbCooccs());
                    jg.writeFieldName(ASSOC_RATE);
                    jg.writeNumber(contextEntry.getAssocRate());
                    jg.writeEndObject();
                }
            }
            jg.writeEndArray();
            jg.writeEndObject();
        }

        jg.writeEndObject();
    }
    jg.writeEndArray();

    /* Variants */
    jg.writeFieldName(TERM_VARIATIONS);
    jg.writeStartArray();
    for (TermVariation v : termVariations) {
        jg.writeStartObject();
        jg.writeFieldName(BASE);
        jg.writeString(v.getBase().getGroupingKey());
        jg.writeFieldName(VARIANT);
        jg.writeString(v.getVariant().getGroupingKey());
        jg.writeFieldName(VARIANT_TYPE);
        jg.writeString(v.getVariationType().getShortName());
        jg.writeFieldName(INFO);
        jg.writeString(v.getInfo().toString());
        jg.writeFieldName(VARIANT_SCORE);
        jg.writeNumber(v.getScore());
        jg.writeEndObject();
    }
    jg.writeEndArray();

    jg.writeEndObject();
    jg.close();
}

From source file:org.apache.drill.exec.store.parquet.Metadata.java

private void writeFile(ParquetTableMetadataDirs parquetTableMetadataDirs, Path p) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    mapper.registerModule(module);/*  w w  w  . j  a v  a2  s . co m*/
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadataDirs);
    os.flush();
    os.close();
}

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

/**
 * Creates and returns an instance of the RawContact from encrypted data
 * //from  w ww.j  a v  a 2  s  . co  m
 * */
public static RawContact valueOf(String rowId, Map<Byte, ByteBuffer> values, Key privateKey)
        throws InvalidKeyException {
    try {
        String serverContactId = null;
        long rawContactId = -1;
        if (values.containsKey(ContactConstants.SERVERROW_ID)) {
            serverContactId = readRawString(values.get(ContactConstants.SERVERROW_ID));
        }
        String lastModStr = readRawString(values.get(ContactConstants.MODIFIED));
        Date lastModified = null;
        if (lastModStr != null) {
            lastModified = new Date(Long.parseLong(lastModStr));
        }

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

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

        AEADBlockCipher cipher = CryptoHelper.getCipher();
        final boolean deleted = values.containsKey(ContactConstants.DELETED);

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

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

        String fullName = null;
        String firstName = null;
        String lastName = null;
        String middleName = null;
        String prefixName = null;
        String suffixName = null;
        String phonecticFirst = null;
        String phonecticMiddle = null;
        String phonecticLast = null;
        List<String> groupSourceIds = null;
        String note = null;
        List<ListRawData<PhoneType>> phones = null;
        List<ListRawData<EmailType>> emails = null;
        List<ListRawData<WebsiteType>> websites = null;
        List<ListRawData<EventType>> events = null;
        List<ListRawData<RelationType>> relations = null;
        List<ListRawData<SipAddressType>> sipaddresses = null;
        List<ListRawData<NicknameType>> nicknames = null;
        List<RawAddressData> addresses = null;
        List<RawImData> imAddresses = null;
        RawOrganizationData organization = null;
        boolean photoSuperPrimary = false;
        boolean starred = false;
        String customRingtone = null;
        boolean sendToVoiceMail = false;

        if (!SyncDataHelper.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 (ContactConstants.STRUCTUREDNAME.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                        String namefield = jp.getCurrentName();
                        // move to value
                        if (jp.nextToken() == null) {
                            throw new JsonParseException("Invalid JSON-Structure. End of Object missing.",
                                    jp.getCurrentLocation());
                        }
                        if (ContactConstants.DISPLAY_NAME.equals(namefield)) {
                            fullName = jp.getValueAsString();
                        } else if (ContactConstants.FAMILY_NAME.equals(namefield)) {
                            lastName = jp.getValueAsString();
                        } else if (ContactConstants.GIVEN_NAME.equals(namefield)) {
                            firstName = jp.getValueAsString();
                        } else if (ContactConstants.MIDDLE_NAME.equals(namefield)) {
                            middleName = jp.getValueAsString();
                        } else if (ContactConstants.SUFFIX_NAME.equals(namefield)) {
                            suffixName = jp.getValueAsString();
                        } else if (ContactConstants.PREFIX_NAME.equals(namefield)) {
                            prefixName = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_FAMILY.equals(namefield)) {
                            phonecticLast = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_GIVEN.equals(namefield)) {
                            phonecticFirst = jp.getValueAsString();
                        } else if (ContactConstants.PHONETIC_MIDDLE.equals(namefield)) {
                            phonecticMiddle = jp.getValueAsString();
                        } else {
                            LOG.error("Unrecognized structurednamefield for row with Id:" + rowId
                                    + " Fieldname:" + fieldname);
                            break;
                        }
                    }
                } else if (ContactConstants.STRUCTUREDPOSTAL.equals(fieldname)) {
                    addresses = readAddressList(rowId, addresses, jp);
                } else if (ContactConstants.PHONE.equals(fieldname)) {
                    phones = readJsonList(rowId, phones, jp, fieldname, PhoneType.TYPE_OTHER, PhoneType.class);
                } else if (ContactConstants.EMAIL.equals(fieldname)) {
                    emails = readJsonList(rowId, emails, jp, fieldname, EmailType.TYPE_OTHER, EmailType.class);
                } else if (ContactConstants.WEBSITE.equals(fieldname)) {
                    websites = readJsonList(rowId, websites, jp, fieldname, WebsiteType.TYPE_OTHER,
                            WebsiteType.class);
                } else if (ContactConstants.EVENT.equals(fieldname)) {
                    events = readJsonList(rowId, events, jp, fieldname, EventType.TYPE_OTHER, EventType.class);
                } else if (ContactConstants.RELATION.equals(fieldname)) {
                    relations = readJsonList(rowId, relations, jp, fieldname, RelationType.TYPE_CUSTOM,
                            RelationType.class);
                } else if (ContactConstants.SIPADDRESS.equals(fieldname)) {
                    sipaddresses = readJsonList(rowId, sipaddresses, jp, fieldname, SipAddressType.TYPE_OTHER,
                            SipAddressType.class);
                } else if (ContactConstants.NICKNAME.equals(fieldname)) {
                    nicknames = readJsonList(rowId, nicknames, jp, fieldname, NicknameType.TYPE_DEFAULT,
                            NicknameType.class);
                } else if (ContactConstants.IM.equals(fieldname)) {
                    imAddresses = readImList(rowId, imAddresses, jp);
                } else if (ContactConstants.NOTE.equals(fieldname)) {
                    note = jp.getValueAsString();
                } else if (ContactConstants.GROUPMEMBERSHIP.equals(fieldname)) {
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        String groupSourceId = jp.getValueAsString();
                        if (groupSourceIds == null) {
                            groupSourceIds = new ArrayList<String>();
                        }
                        groupSourceIds.add(groupSourceId);
                    }
                } else if (ContactConstants.ORGANIZATION.equals(fieldname)) {
                    organization = readOrg(rowId, jp);
                } else if (ContactConstants.PHOTO_SUPERPRIMARY.equals(fieldname)) {
                    photoSuperPrimary = jp.getValueAsBoolean();
                } else if (ContactConstants.STARRED.equals(fieldname)) {
                    starred = jp.getValueAsBoolean();
                } else if (ContactConstants.SEND_TO_VOICE_MAIL.equals(fieldname)) {
                    sendToVoiceMail = jp.getValueAsBoolean();
                } else if (ContactConstants.DROID_CUSTOM_RINGTONE.equals(fieldname)) {
                    customRingtone = jp.getValueAsString();
                } else {
                    LOG.error("Unrecognized field for row with Id:" + rowId + " Fieldname:" + fieldname);
                }
            }
            jp.close();
        }

        final byte[] photo = CryptoHelper.decodeValue(ContactConstants.PHOTO, values, cipher, privateKey);

        return new RawContact(fullName, firstName, lastName, middleName, prefixName, suffixName, phonecticFirst,
                phonecticMiddle, phonecticLast, phones, emails, websites, addresses, events, relations,
                sipaddresses, nicknames, imAddresses, note, organization, photo, photoSuperPrimary,
                groupSourceIds, null, starred, customRingtone, sendToVoiceMail, lastModified, deleted,
                serverContactId, rawContactId, false, -1);
    } catch (InvalidCipherTextException ex) {
        throw new InvalidKeyException("Invalid key detected.", ex);
    } catch (final IOException ex) {
        LOG.info("Error parsing contact data. Reason:" + ex.toString(), ex);
    } catch (IllegalArgumentException ex) {
        LOG.warn("Error parsing contact data. Reason:" + ex.toString(), ex);
    }

    return null;
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager.//from  www .  j av  a2s . c  o  m
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.SteeringTest.java

License:asdf

@Test
public void itUsesMultiLocationFormatWithMoreThanTwoEntries() throws Exception {
    final String path = "/qwerytuiop/asdfghjkl?fakeClientIpAddress=12.34.56.78";
    HttpGet httpGet = new HttpGet("http://localhost:" + routerHttpPort + path);
    httpGet.addHeader("Host", "tr.client-steering-test-2.thecdn.example.com");

    CloseableHttpResponse response = null;

    try {//w w  w.ja va2  s.  c o m
        response = httpClient.execute(httpGet);
        String location1 = ".steering-target-2.thecdn.example.com:8090" + path;
        String location2 = ".steering-target-1.thecdn.example.com:8090" + path;
        String location3 = ".client-steering-target-2.thecdn.example.com:8090" + path;
        String location4 = ".client-steering-target-4.thecdn.example.com:8090" + path;
        String location5 = ".client-steering-target-3.thecdn.example.com:8090" + path;
        String location6 = ".client-steering-target-1.thecdn.example.com:8090" + path;
        String location7 = ".steering-target-4.thecdn.example.com:8090" + path;
        String location8 = ".steering-target-3.thecdn.example.com:8090" + path;

        HttpEntity entity = response.getEntity();
        assertThat("Failed getting 302 for request " + httpGet.getFirstHeader("Host").getValue(),
                response.getStatusLine().getStatusCode(), equalTo(302));
        assertThat(response.getFirstHeader("Location").getValue(), endsWith(location1));

        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());

        assertThat(entity.getContent(), not(nullValue()));

        JsonNode json = objectMapper.readTree(entity.getContent());

        assertThat(json.has("locations"), equalTo(true));
        assertThat(json.get("locations").size(), equalTo(8));
        assertThat(json.get("locations").get(0).asText(),
                equalTo(response.getFirstHeader("Location").getValue()));
        assertThat(json.get("locations").get(1).asText(), endsWith(location2));
        assertThat(json.get("locations").get(2).asText(), endsWith(location3));
        assertThat(json.get("locations").get(3).asText(), endsWith(location4));
        assertThat(json.get("locations").get(4).asText(), endsWith(location5));
        assertThat(json.get("locations").get(5).asText(), endsWith(location6));
        assertThat(json.get("locations").get(6).asText(), endsWith(location7));
        assertThat(json.get("locations").get(7).asText(), endsWith(location8));
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.apache.drill.exec.store.parquet.metadata.Metadata.java

/**
 * Serialize parquet metadata to json and write to a file.
 *
 * @param parquetTableMetadata parquet table metadata
 * @param p file path/*ww  w  .  jav  a2  s  .c o  m*/
 */
private void writeFile(ParquetTableMetadata_v3 parquetTableMetadata, Path p, FileSystem fs) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ColumnMetadata_v3.class, new ColumnMetadata_v3.Serializer());
    mapper.registerModule(module);
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata);
    os.flush();
    os.close();
}