Search in sources :

Example 6 with JsonGenerationException

use of com.fasterxml.jackson.core.JsonGenerationException in project platformlayer by platformlayer.

the class MetricTreeSerializer method serialize.

public void serialize(MetricTreeBase tree, OutputStream os) throws IOException {
    final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(os);
    tree.accept(new MetricTreeVisitor() {

        private void writeKey(MetricTreeBase o) throws JsonGenerationException, IOException {
            if (o.getKey() != null) {
                jsonGenerator.writeFieldName(o.getKey());
            }
        }

        @Override
        public void visit(MetricTreeObject o) {
            try {
                writeKey(o);
                jsonGenerator.writeStartObject();
                o.visitChildren(this);
                jsonGenerator.writeEndObject();
            } catch (IOException e) {
                throw new IllegalStateException("Error serializing to JSON", e);
            }
        }

        @Override
        public void visit(MetricTreeString o) {
            try {
                writeKey(o);
                jsonGenerator.writeString(o.getValue());
            } catch (IOException e) {
                throw new IllegalStateException("Error serializing to JSON", e);
            }
        }

        @Override
        public void visit(MetricTreeArray o) {
            try {
                writeKey(o);
                jsonGenerator.writeStartArray();
                o.visitItems(this);
                jsonGenerator.writeEndArray();
            } catch (IOException e) {
                throw new IllegalStateException("Error serializing to JSON", e);
            }
        }

        @Override
        public void visit(MetricTreeInteger o) {
            try {
                writeKey(o);
                jsonGenerator.writeNumber(o.getValue());
            } catch (IOException e) {
                throw new IllegalStateException("Error serializing to JSON", e);
            }
        }

        @Override
        public void visit(MetricTreeFloat o) {
            try {
                writeKey(o);
                jsonGenerator.writeNumber(o.getValue());
            } catch (IOException e) {
                throw new IllegalStateException("Error serializing to JSON", e);
            }
        }
    });
    jsonGenerator.close();
}
Also used : MetricTreeString(org.platformlayer.metrics.MetricTreeBase.MetricTreeString) MetricTreeVisitor(org.platformlayer.metrics.MetricTreeVisitor) MetricTreeObject(org.platformlayer.metrics.MetricTreeObject) MetricTreeInteger(org.platformlayer.metrics.MetricTreeBase.MetricTreeInteger) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) MetricTreeBase(org.platformlayer.metrics.MetricTreeBase) MetricTreeFloat(org.platformlayer.metrics.MetricTreeBase.MetricTreeFloat) IOException(java.io.IOException) MetricTreeArray(org.platformlayer.metrics.MetricTreeBase.MetricTreeArray) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException)

Example 7 with JsonGenerationException

use of com.fasterxml.jackson.core.JsonGenerationException in project ORCID-Source by ORCID.

the class OrcidInfo method publicPreview.

@RequestMapping(value = { "/{orcid:(?:\\d{4}-){3,}\\d{3}[\\dX]}", "/{orcid:(?:\\d{4}-){3,}\\d{3}[\\dX]}/print" })
public ModelAndView publicPreview(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int pageNo, @RequestParam(value = "v", defaultValue = "0") int v, @RequestParam(value = "maxResults", defaultValue = "15") int maxResults, @PathVariable("orcid") String orcid) {
    ProfileEntity profile = null;
    try {
        profile = profileEntityCacheManager.retrieve(orcid);
    } catch (Exception e) {
        return new ModelAndView("error-404");
    }
    try {
        // Check if the profile is deprecated, non claimed or locked
        orcidSecurityManager.checkProfile(orcid);
    } catch (OrcidDeprecatedException | OrcidNotClaimedException | LockedException e) {
        ModelAndView mav = new ModelAndView("public_profile_unavailable");
        mav.addObject("effectiveUserOrcid", orcid);
        String displayName = "";
        if (e instanceof OrcidDeprecatedException) {
            PersonalDetails publicPersonalDetails = personalDetailsManager.getPublicPersonalDetails(orcid);
            if (publicPersonalDetails.getName() != null) {
                Name name = publicPersonalDetails.getName();
                if (name.getVisibility().equals(org.orcid.jaxb.model.common_v2.Visibility.PUBLIC)) {
                    if (name.getCreditName() != null && !PojoUtil.isEmpty(name.getCreditName().getContent())) {
                        displayName = name.getCreditName().getContent();
                    } else {
                        if (name.getGivenNames() != null && !PojoUtil.isEmpty(name.getGivenNames().getContent())) {
                            displayName = name.getGivenNames().getContent() + " ";
                        }
                        if (name.getFamilyName() != null && !PojoUtil.isEmpty(name.getFamilyName().getContent())) {
                            displayName += name.getFamilyName().getContent();
                        }
                    }
                }
            }
            mav.addObject("deprecated", true);
            mav.addObject("primaryRecord", profile.getPrimaryRecord().getId());
        } else if (e instanceof OrcidNotClaimedException) {
            displayName = localeManager.resolveMessage("orcid.reserved_for_claim");
        } else {
            mav.addObject("locked", true);
            mav.addObject("isPublicProfile", true);
            displayName = localeManager.resolveMessage("public_profile.deactivated.given_names") + " " + localeManager.resolveMessage("public_profile.deactivated.family_name");
        }
        if (!PojoUtil.isEmpty(displayName)) {
            mav.addObject("title", getMessage("layout.public-layout.title", displayName, orcid));
            mav.addObject("displayName", displayName);
        }
        return mav;
    }
    long lastModifiedTime = getLastModifiedTime(orcid);
    ModelAndView mav = null;
    if (request.getRequestURI().contains("/print")) {
        mav = new ModelAndView("print_public_record");
        mav.addObject("hideUserVoiceScript", true);
    } else {
        mav = new ModelAndView("public_profile_v3");
    }
    mav.addObject("isPublicProfile", true);
    mav.addObject("effectiveUserOrcid", orcid);
    mav.addObject("lastModifiedTime", lastModifiedTime);
    boolean isProfileEmtpy = true;
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.removeAttribute(PUBLIC_WORKS_RESULTS_ATTRIBUTE);
    }
    PersonalDetails publicPersonalDetails = personalDetailsManager.getPublicPersonalDetails(orcid);
    // Fill personal details
    if (publicPersonalDetails != null) {
        // Get display name
        String displayName = "";
        if (publicPersonalDetails.getName() != null) {
            Name name = publicPersonalDetails.getName();
            if (name.getVisibility().equals(org.orcid.jaxb.model.common_v2.Visibility.PUBLIC)) {
                if (name.getCreditName() != null && !PojoUtil.isEmpty(name.getCreditName().getContent())) {
                    displayName = name.getCreditName().getContent();
                } else {
                    if (name.getGivenNames() != null && !PojoUtil.isEmpty(name.getGivenNames().getContent())) {
                        displayName = name.getGivenNames().getContent() + " ";
                    }
                    if (name.getFamilyName() != null && !PojoUtil.isEmpty(name.getFamilyName().getContent())) {
                        displayName += name.getFamilyName().getContent();
                    }
                }
            }
        }
        if (!PojoUtil.isEmpty(displayName)) {
            // <Published Name> (<ORCID iD>) - ORCID | Connecting Research
            // and Researchers
            mav.addObject("title", getMessage("layout.public-layout.title", displayName.trim(), orcid));
            mav.addObject("displayName", displayName);
        }
        // Get biography
        if (publicPersonalDetails.getBiography() != null) {
            Biography bio = publicPersonalDetails.getBiography();
            if (org.orcid.jaxb.model.common_v2.Visibility.PUBLIC.equals(bio.getVisibility()) && !PojoUtil.isEmpty(bio.getContent())) {
                isProfileEmtpy = false;
                mav.addObject("biography", bio);
            }
        }
        // Fill other names
        OtherNames publicOtherNames = publicPersonalDetails.getOtherNames();
        if (publicOtherNames != null && publicOtherNames.getOtherNames() != null) {
            Iterator<OtherName> it = publicOtherNames.getOtherNames().iterator();
            while (it.hasNext()) {
                OtherName otherName = it.next();
                if (!org.orcid.jaxb.model.common_v2.Visibility.PUBLIC.equals(otherName.getVisibility())) {
                    it.remove();
                }
            }
        }
        Map<String, List<OtherName>> groupedOtherNames = groupOtherNames(publicOtherNames);
        mav.addObject("publicGroupedOtherNames", groupedOtherNames);
    }
    // Fill biography elements
    // Fill country
    Addresses publicAddresses = addressManager.getPublicAddresses(orcid, lastModifiedTime);
    Map<String, String> countryNames = new HashMap<String, String>();
    if (publicAddresses != null && publicAddresses.getAddress() != null) {
        Address publicAddress = null;
        // The primary address will be the one with the lowest display index
        for (Address address : publicAddresses.getAddress()) {
            countryNames.put(address.getCountry().getValue().value(), getcountryName(address.getCountry().getValue().value()));
            if (publicAddress == null) {
                publicAddress = address;
            }
        }
        if (publicAddress != null) {
            mav.addObject("publicAddress", publicAddress);
            mav.addObject("countryNames", countryNames);
            Map<String, List<Address>> groupedAddresses = groupAddresses(publicAddresses);
            mav.addObject("publicGroupedAddresses", groupedAddresses);
        }
    }
    // Fill keywords
    Keywords publicKeywords = keywordManager.getPublicKeywords(orcid, lastModifiedTime);
    Map<String, List<Keyword>> groupedKeywords = groupKeywords(publicKeywords);
    mav.addObject("publicGroupedKeywords", groupedKeywords);
    // Fill researcher urls
    ResearcherUrls publicResearcherUrls = researcherUrlManager.getPublicResearcherUrls(orcid, lastModifiedTime);
    Map<String, List<ResearcherUrl>> groupedResearcherUrls = groupResearcherUrls(publicResearcherUrls);
    mav.addObject("publicGroupedResearcherUrls", groupedResearcherUrls);
    // Fill emails
    Emails publicEmails = emailManager.getPublicEmails(orcid, lastModifiedTime);
    Map<String, List<Email>> groupedEmails = groupEmails(publicEmails);
    mav.addObject("publicGroupedEmails", groupedEmails);
    // Fill external identifiers
    PersonExternalIdentifiers publicPersonExternalIdentifiers = externalIdentifierManager.getPublicExternalIdentifiers(orcid, lastModifiedTime);
    Map<String, List<PersonExternalIdentifier>> groupedExternalIdentifiers = groupExternalIdentifiers(publicPersonExternalIdentifiers);
    mav.addObject("publicGroupedPersonExternalIdentifiers", groupedExternalIdentifiers);
    LinkedHashMap<Long, WorkForm> minimizedWorksMap = new LinkedHashMap<>();
    LinkedHashMap<Long, Affiliation> affiliationMap = new LinkedHashMap<>();
    LinkedHashMap<Long, Funding> fundingMap = new LinkedHashMap<>();
    LinkedHashMap<Long, PeerReview> peerReviewMap = new LinkedHashMap<>();
    minimizedWorksMap = activityCacheManager.pubMinWorksMap(orcid, lastModifiedTime);
    if (minimizedWorksMap.size() > 0) {
        isProfileEmtpy = false;
    } else {
        mav.addObject("worksEmpty", true);
    }
    affiliationMap = affiliationMap(orcid, lastModifiedTime);
    if (affiliationMap.size() > 0) {
        isProfileEmtpy = false;
    } else {
        mav.addObject("affiliationsEmpty", true);
    }
    fundingMap = fundingMap(orcid, lastModifiedTime);
    if (fundingMap.size() > 0)
        isProfileEmtpy = false;
    else {
        mav.addObject("fundingEmpty", true);
    }
    peerReviewMap = peerReviewMap(orcid, lastModifiedTime);
    if (peerReviewMap.size() > 0) {
        isProfileEmtpy = false;
    } else {
        mav.addObject("peerReviewsEmpty", true);
    }
    ObjectMapper mapper = new ObjectMapper();
    try {
        String worksIdsJson = mapper.writeValueAsString(minimizedWorksMap.keySet());
        String affiliationIdsJson = mapper.writeValueAsString(affiliationMap.keySet());
        String fundingIdsJson = mapper.writeValueAsString(fundingMap.keySet());
        String peerReviewIdsJson = mapper.writeValueAsString(peerReviewMap.keySet());
        mav.addObject("workIdsJson", StringEscapeUtils.escapeEcmaScript(worksIdsJson));
        mav.addObject("affiliationIdsJson", StringEscapeUtils.escapeEcmaScript(affiliationIdsJson));
        mav.addObject("fundingIdsJson", StringEscapeUtils.escapeEcmaScript(fundingIdsJson));
        mav.addObject("peerReviewIdsJson", StringEscapeUtils.escapeEcmaScript(peerReviewIdsJson));
        mav.addObject("isProfileEmpty", isProfileEmtpy);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (!profile.isReviewed()) {
        if (isProfileValidForIndex(profile)) {
            int countTokens = orcidOauth2TokenService.findCountByUserName(orcid, lastModifiedTime);
            if (!profile.isAccountNonLocked() || countTokens == 0 || (!CreationMethod.WEBSITE.value().equals(profile.getCreationMethod()) && !CreationMethod.DIRECT.value().equals(profile.getCreationMethod()))) {
                mav.addObject("noIndex", true);
            }
        } else {
            mav.addObject("noIndex", true);
        }
    }
    return mav;
}
Also used : Keywords(org.orcid.jaxb.model.record_v2.Keywords) Address(org.orcid.jaxb.model.record_v2.Address) OtherNames(org.orcid.jaxb.model.record_v2.OtherNames) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Funding(org.orcid.jaxb.model.record_v2.Funding) ModelAndView(org.springframework.web.servlet.ModelAndView) OtherName(org.orcid.jaxb.model.record_v2.OtherName) Name(org.orcid.jaxb.model.record_v2.Name) LinkedHashMap(java.util.LinkedHashMap) Addresses(org.orcid.jaxb.model.record_v2.Addresses) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) Biography(org.orcid.jaxb.model.record_v2.Biography) ResearcherUrls(org.orcid.jaxb.model.record_v2.ResearcherUrls) List(java.util.List) ArrayList(java.util.ArrayList) Emails(org.orcid.jaxb.model.record_v2.Emails) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Affiliation(org.orcid.jaxb.model.record_v2.Affiliation) LockedException(org.orcid.core.security.aop.LockedException) HttpSession(javax.servlet.http.HttpSession) OtherName(org.orcid.jaxb.model.record_v2.OtherName) IOException(java.io.IOException) PersonalDetails(org.orcid.jaxb.model.record_v2.PersonalDetails) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) OrcidNotClaimedException(org.orcid.core.exception.OrcidNotClaimedException) OrcidDeprecatedException(org.orcid.core.exception.OrcidDeprecatedException) LockedException(org.orcid.core.security.aop.LockedException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException) IOException(java.io.IOException) WorkForm(org.orcid.pojo.ajaxForm.WorkForm) PersonExternalIdentifiers(org.orcid.jaxb.model.record_v2.PersonExternalIdentifiers) OrcidDeprecatedException(org.orcid.core.exception.OrcidDeprecatedException) OrcidNotClaimedException(org.orcid.core.exception.OrcidNotClaimedException) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException) PeerReview(org.orcid.jaxb.model.record_v2.PeerReview) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with JsonGenerationException

use of com.fasterxml.jackson.core.JsonGenerationException in project Java-Mandrill-Wrapper by cribbstechnologies.

the class MandrillRESTRequest method performPostRequest.

private BaseMandrillResponse performPostRequest(BaseMandrillRequest request, String serviceMethod, Object responseClass, TypeReference reference) throws RequestFailedException {
    try {
        request.setKey(config.getApiKey());
        HttpPost postRequest = new HttpPost(config.getServiceUrl() + serviceMethod);
        String postData = getPostData(request);
        StringEntity input = new StringEntity(postData, "UTF-8");
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        StringBuffer sb = new StringBuffer();
        String output;
        // System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            sb.append(output);
        // System.out.println(output);
        }
        String responseString = sb.toString();
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            //throw new RequestFailedException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + responseString);
            throw new RequestFailedException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " " + responseString, objectMapper.readValue(responseString, MandrillError.class));
        }
        // for whatever reason the ping response isn't well-formed
        if (ServiceMethods.Users.PING.equals(serviceMethod) && responseString.indexOf("PONG!") > -1) {
            return new BaseMandrillStringResponse(responseString);
        }
        if (reference == null) {
            return convertResponseData(responseString, responseClass);
        } else {
            return convertAnonymousListResponseData(responseString, responseClass, reference);
        }
    } catch (MalformedURLException mURLE) {
        throw new RequestFailedException("Malformed url", mURLE);
    } catch (JsonGenerationException jge) {
        throw new RequestFailedException("Json Generation Exception", jge);
    } catch (JsonMappingException jme) {
        throw new RequestFailedException("Json Mapping Exception", jme);
    } catch (IOException ioe) {
        throw new RequestFailedException("IOException", ioe);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MalformedURLException(java.net.MalformedURLException) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) StringEntity(org.apache.http.entity.StringEntity) BaseMandrillStringResponse(com.cribbstechnologies.clients.mandrill.model.response.BaseMandrillStringResponse) RequestFailedException(com.cribbstechnologies.clients.mandrill.exception.RequestFailedException) MandrillError(com.cribbstechnologies.clients.mandrill.model.MandrillError) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) BufferedReader(java.io.BufferedReader) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException)

Example 9 with JsonGenerationException

use of com.fasterxml.jackson.core.JsonGenerationException in project elasticsearch by elastic.

the class BaseXContentTestCase method expectFieldException.

private static void expectFieldException(ThrowingRunnable runnable) {
    JsonGenerationException e = expectThrows(JsonGenerationException.class, runnable);
    assertThat(e.getMessage(), containsString("expecting field name"));
}
Also used : JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException)

Example 10 with JsonGenerationException

use of com.fasterxml.jackson.core.JsonGenerationException in project elasticsearch by elastic.

the class BaseXContentTestCase method expectObjectException.

private static void expectObjectException(ThrowingRunnable runnable) {
    JsonGenerationException e = expectThrows(JsonGenerationException.class, runnable);
    assertThat(e.getMessage(), containsString("Current context not Object"));
}
Also used : JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException)

Aggregations

JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)17 IOException (java.io.IOException)9 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)8 Test (org.junit.Test)3 RequestFailedException (com.cribbstechnologies.clients.mandrill.exception.RequestFailedException)2 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 BaseMandrillRequest (com.cribbstechnologies.clients.mandrill.model.BaseMandrillRequest)1 MandrillError (com.cribbstechnologies.clients.mandrill.model.MandrillError)1 BaseMandrillStringResponse (com.cribbstechnologies.clients.mandrill.model.response.BaseMandrillStringResponse)1 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)1 InvalidFormatException (com.fasterxml.jackson.databind.exc.InvalidFormatException)1 PropertyBindingException (com.fasterxml.jackson.databind.exc.PropertyBindingException)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 JaxbAnnotationModule (com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule)1 JsonLdError (com.github.jsonldjava.core.JsonLdError)1 ErrorMessage (io.dropwizard.jersey.errors.ErrorMessage)1 BufferedReader (java.io.BufferedReader)1 InputStreamReader (java.io.InputStreamReader)1 StringWriter (java.io.StringWriter)1