Example usage for java.lang NullPointerException getClass

List of usage examples for java.lang NullPointerException getClass

Introduction

In this page you can find the example usage for java.lang NullPointerException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:eu.project.ttc.utils.JCasUtils.java

public static void showJCas(JCas jcas) {
    FSIterator<Annotation> it = jcas.getAnnotationIndex().iterator();
    Map<String, MutableInt> counters = new TreeMap<String, MutableInt>();
    int total = 0;
    while (it.hasNext()) {
        total += 1;/*from  www.j a v  a 2 s . com*/
        String annoType = "rien";
        try {
            Annotation annotation = (Annotation) it.next();
            annoType = annotation.getType().getName();
        } catch (NullPointerException e) {
            it.moveToNext();
            annoType = e.getClass().getCanonicalName();
        }
        if (counters.get(annoType) == null) {
            counters.put(annoType, new MutableInt(1));
        } else {
            counters.get(annoType).increment();
        }
    }
    System.out.println("Total annotation in JCas (ID: " + System.identityHashCode(jcas) + "): " + total);
    for (String annoType : counters.keySet()) {
        System.out.println(annoType + ": " + counters.get(annoType));
    }
}

From source file:com.poscoict.license.web.controller.ExceptionControllerAdvice.java

@ExceptionHandler(NullPointerException.class)
public ModelAndView handleNullPointerException(NullPointerException ex) {
    logger.error(ex.toString());//from w ww  . j  a va2 s  .  c o m
    ModelAndView mv = new ModelAndView(DEFAULT_ERROR_VIEW);
    mv.addObject("name", ex.getClass().getSimpleName());
    mv.addObject("message", "?? ?. ?? ? .");
    return mv;
}

From source file:de.innovationgate.wgpublisher.lucene.LuceneManager.java

public WGResultSet search(WGDatabase db, List<String> fields, String phrase, Map parameters, WGA wga)
        throws WGQueryException {

    if (wga == null) {
        wga = WGA.get(_core);//from  w w  w.  ja  va  2 s  .  c o m
    }

    // set max clause count for boolean queries
    BooleanQuery.setMaxClauseCount(_booleanQueryMaxClauseCount);

    if (this.isRebuildingIndex()) {
        throw new WGQueryException(phrase, "Lucene search temporary disabled. Rebuilding lucene index ...");
    }

    // Registering problem in that case but not cancelling the query, as this is old, expected behaviour. The query will just return no results.
    if (!_core.getLuceneManager().indexIsEnabled(db.getDbReference())) {
        _core.getProblemRegistry().addProblem(
                Problem.create(new TMLContext.WebTMLOccasion(), new DatabaseScope(db.getDbReference()),
                        "webtmlProblem.luceneIndexExpected", ProblemSeverity.LOW));
    }

    if (phrase == null || phrase.trim().equals("")) {
        return null;
    }

    try {
        BooleanQuery wholeQuery = new BooleanQuery();

        int max = WGACore.DEFAULT_QUERY_MAXRESULTS;
        Integer maxResults = (Integer) parameters.get(WGDatabase.QUERYOPTION_MAXRESULTS);
        if (maxResults != null) {
            if (maxResults == 0 || maxResults == -1) {
                max = Integer.MAX_VALUE;
            } else {
                max = maxResults;
            }
        }

        // handle dboption EXCLUDEDOCUMENT
        WGContent excludeContent = (WGContent) parameters.get(WGDatabase.QUERYOPTION_EXCLUDEDOCUMENT);
        if (excludeContent != null) {
            String uniqueKey = buildUniqueIndexKey(excludeContent.getDatabase().getDbReference(),
                    excludeContent.getDocumentKey());
            wholeQuery.add(new TermQuery(new Term(INDEXFIELD_UNIQUEKEY, uniqueKey)),
                    BooleanClause.Occur.MUST_NOT);
            wholeQuery.add(new TermQuery(new Term(INDEXFIELD_PARENTKEY, uniqueKey)),
                    BooleanClause.Occur.MUST_NOT);
        }

        // list of dbs to search in
        String searchScope = (String) parameters.get(LuceneManager.QUERYOPTION_SEARCHSCOPE);
        List searchDBKeys = new ArrayList();
        if (searchScope.equals(LuceneManager.SEARCHSCOPE_DB)) {
            searchDBKeys.add(db.getDbReference());
        }
        if (searchScope.equals(LuceneManager.SEARCHSCOPE_DOMAIN)) {
            Iterator<WGDatabase> dbs = _core
                    .getDatabasesForDomain((String) db.getAttribute(WGACore.DBATTRIB_DOMAIN)).iterator();
            while (dbs.hasNext()) {
                WGDatabase currentDB = dbs.next();
                if (wga.openDatabase(currentDB)) {
                    searchDBKeys.add(currentDB.getDbReference());
                }
            }
        }
        if (searchScope.equals(LuceneManager.SEARCHSCOPE_WGA)) {
            Iterator dbs = _core.getContentdbs().values().iterator();
            while (dbs.hasNext()) {
                WGDatabase currentDB = (WGDatabase) dbs.next();
                if (wga.openDatabase(currentDB)) {
                    searchDBKeys.add(currentDB.getDbReference());
                }
            }
        }
        if (searchScope.equals(LuceneManager.SEARCHSCOPE_DB_LIST)) {
            String dbListCSV = (String) parameters.get(QUERYOPTION_SEARCHDBKEYS);
            if (dbListCSV == null || dbListCSV.trim().equals("")) {
                throw new WGQueryException(phrase, "Search scope is 'dblist' but no db keys given.");
            } else {
                Iterator dbkeys = WGUtils.deserializeCollection(dbListCSV, ",").iterator();
                while (dbkeys.hasNext()) {
                    String dbkey = (String) dbkeys.next();
                    WGDatabase currentDB = wga.db(dbkey);
                    if (currentDB.isSessionOpen()) {
                        searchDBKeys.add(dbkey.trim().toLowerCase());
                    }
                }
            }
        }

        // Handle language selection;
        List<WGLanguage> languagesPriorityList = null;
        boolean filterLanguages = false;
        if (parameters.containsKey(WGDatabase.QUERYOPTION_LANGUAGES)) {
            List<WGLanguage> langs = (List<WGLanguage>) parameters.get(WGDatabase.QUERYOPTION_LANGUAGES);
            if (langs.size() > 1) {
                BooleanQuery langQuery = new BooleanQuery();
                for (WGLanguage lang : langs) {
                    langQuery.add(new TermQuery(new Term(WGContent.META_LANGUAGE, lang.getName())),
                            BooleanClause.Occur.SHOULD);
                }
                wholeQuery.add(langQuery, BooleanClause.Occur.MUST);
                languagesPriorityList = langs;
                filterLanguages = true;
            } else if (langs.size() == 1) {
                wholeQuery.add(new TermQuery(new Term(WGContent.META_LANGUAGE, langs.get(0).getName())),
                        BooleanClause.Occur.MUST);
                languagesPriorityList = Collections.singletonList(langs.get(0));
            }
        } else if (parameters.containsKey(WGDatabase.QUERYOPTION_ONLYLANGUAGE)) {
            String language = (String) parameters.get(WGDatabase.QUERYOPTION_ONLYLANGUAGE);
            wholeQuery.add(new TermQuery(new Term(WGContent.META_LANGUAGE, language)),
                    BooleanClause.Occur.MUST);
            languagesPriorityList = Collections.singletonList(db.getLanguage(language));
        }

        if (languagesPriorityList == null) {
            languagesPriorityList = getLanguagesForSearchDBKeys(searchDBKeys);
            ;
        }

        // Handle visibility selection
        if (!parameters.containsKey(WGDatabase.QUERYOPTION_ENHANCE)
                || parameters.get(WGDatabase.QUERYOPTION_ENHANCE).equals(new Boolean(true))) {

            wholeQuery.add(new TermQuery(new Term(WGContent.META_VISIBLE, "true")), BooleanClause.Occur.MUST);

            String role = (String) parameters.get(WGDatabase.QUERYOPTION_ROLE);
            if (role != null) {
                if (!role.equalsIgnoreCase(WGContent.DISPLAYTYPE_NONE)) {
                    wholeQuery.add(new TermQuery(new Term("HIDDENIN" + role.toUpperCase(), "false")),
                            BooleanClause.Occur.MUST);
                }
            }
        }

        if (parameters.containsKey(WGDatabase.QUERYOPTION_ONLYRELEASED)) {
            wholeQuery.add(new TermQuery(new Term(WGContent.META_STATUS, WGContent.STATUS_RELEASE)),
                    BooleanClause.Occur.MUST);
        }

        // build dbQuery (OR combination of all searchDbs indexed by lucene)
        BooleanQuery dbQuery = new BooleanQuery();
        Iterator itSearchDBKeys = searchDBKeys.iterator();
        while (itSearchDBKeys.hasNext()) {
            String currentDBKey = (String) itSearchDBKeys.next();
            if (_indexedDbs.containsKey(currentDBKey)) {
                dbQuery.add(new TermQuery(new Term(INDEXFIELD_DBKEY, currentDBKey)),
                        BooleanClause.Occur.SHOULD);
            }
        }
        wholeQuery.add(dbQuery, BooleanClause.Occur.MUST);

        // Add parsed search phrase.
        // Search in allcontent for each language using the configured analyzer
        // if no analyzer is configured for a language search at least with one
        // default analyzer
        boolean searchWithDefaultAnalyzer = false;

        //if no languages found search at least with DefaultAnalyzer
        if (languagesPriorityList.size() <= 0) {
            searchWithDefaultAnalyzer = true;
        }

        // parse native options
        Sort sort = null;
        String sortFieldName = "";
        Operator defaultOperator = QueryParser.AND_OPERATOR;
        String nativeOptionsStr = (String) parameters.get(WGDatabase.QUERYOPTION_NATIVEOPTIONS);
        boolean includeVirtualContent = false;
        String doctype = DOCTYPE_CONTENT;
        if (nativeOptionsStr != null) {
            Iterator nativeOptions = WGUtils.deserializeCollection(nativeOptionsStr, ",", true).iterator();
            while (nativeOptions.hasNext()) {
                String option = (String) nativeOptions.next();
                if (option.startsWith("sort:")) {
                    sortFieldName = option.substring(5).trim();
                    boolean reverse = false;
                    if (sortFieldName.toLowerCase().endsWith("(asc)")) {
                        sortFieldName = sortFieldName.substring(0, sortFieldName.length() - 5).trim();
                    } else if (sortFieldName.toLowerCase().endsWith("(desc)")) {
                        sortFieldName = sortFieldName.substring(0, sortFieldName.length() - 6).trim();
                        reverse = true;
                    }

                    if (sortFieldName.length() > 0) {
                        char first = sortFieldName.charAt(0);
                        if (first >= 'A' && first <= 'Z') {
                            // meta sort
                            sortFieldName = sortFieldName.toUpperCase();
                        } else {
                            // item sort
                            sortFieldName = sortFieldName.toLowerCase();
                        }
                    }

                    // sort order currently only german
                    sort = new Sort(new SortField(SORTITEM_PREFIX + sortFieldName, Locale.GERMANY, reverse));
                } else if (option.equalsIgnoreCase(NATIVE_QUERYOPTION_INCLUDEVIRTUALCONTENT)) {
                    includeVirtualContent = true;
                } else if (option.startsWith("doctype:")) {
                    doctype = option.substring("doctype:".length()).trim();
                } else if (option.startsWith("operator:")) {
                    String op = option.substring("operator:".length()).trim();
                    if (op.equalsIgnoreCase("or"))
                        defaultOperator = QueryParser.OR_OPERATOR;
                }

            }
        }

        if (!includeVirtualContent) {
            wholeQuery.add(new TermQuery(new Term(INDEXFIELD_ISVIRTUALCONTENT, String.valueOf(true))),
                    BooleanClause.Occur.MUST_NOT);
        }

        // handle doctype option
        // we cannot be sure that all documents in index already contains the field DOCTYPE (introduced with OpenWGA 7.1) therefore we have to perform some excludes
        if (doctype.equals(DOCTYPE_CONTENT)) {
            wholeQuery.add(new TermQuery(new Term(INDEXFIELD_DOCTYPE, DOCTYPE_ATTACHMENT)),
                    BooleanClause.Occur.MUST_NOT);
        } else if (!doctype.equals(DOCTYPE_ALL)) {
            wholeQuery.add(new TermQuery(new Term(INDEXFIELD_DOCTYPE, doctype)), BooleanClause.Occur.MUST);
        }

        //build phrase query                
        BooleanQuery phraseQuery = new BooleanQuery();
        phraseQuery.setBoost(10);
        Iterator languageList = languagesPriorityList.iterator();

        List<String> searchFields = new ArrayList<String>();
        Map<String, Float> searchBoosts = new HashMap<String, Float>();
        for (String field : fields) {
            String[] parts = field.split("\\^");
            searchFields.add(parts[0]);
            if (parts.length == 2) {
                searchBoosts.put(parts[0], Float.parseFloat(parts[1]));
            }
        }
        if (!searchFields.contains("allcontent"))
            searchFields.add("allcontent");
        if (!searchFields.contains("TITLE"))
            searchFields.add("TITLE");
        if (!searchFields.contains("DESCRIPTION"))
            searchFields.add("DESCRIPTION");
        if (!searchFields.contains("KEYWORDS"))
            searchFields.add("KEYWORDS");

        while (languageList.hasNext()) {
            WGLanguage languageItem = (WGLanguage) languageList.next();
            Analyzer analyzer = _core.getAnalyzerForLanguageCode(languageItem.getName().substring(0, 2));
            if (analyzer != null) {
                QueryParser parser = new IndexingRuleBasedQueryParser(searchFields.toArray(new String[0]),
                        analyzer, searchBoosts, _indexedDbs, searchDBKeys, _metaKeywordFields);
                parser.setDefaultOperator(defaultOperator);
                Query query = parser.parse(phrase);
                if (filterLanguages) {
                    BooleanQuery testPhraseAndLangQuery = new BooleanQuery();
                    testPhraseAndLangQuery.add(query, BooleanClause.Occur.MUST);
                    testPhraseAndLangQuery.add(
                            new TermQuery(new Term(WGContent.META_LANGUAGE, languageItem.getName())),
                            BooleanClause.Occur.MUST);
                    phraseQuery.add(testPhraseAndLangQuery, BooleanClause.Occur.SHOULD);
                } else {
                    phraseQuery.add(query, BooleanClause.Occur.SHOULD);
                }
            } else {
                searchWithDefaultAnalyzer = true;
            }
        }

        if (searchWithDefaultAnalyzer) {
            QueryParser parser = new IndexingRuleBasedQueryParser(searchFields.toArray(new String[0]),
                    _core.getDefaultAnalyzer(), searchBoosts, _indexedDbs, searchDBKeys, _metaKeywordFields);
            parser.setDefaultOperator(defaultOperator);
            Query query = parser.parse(phrase);
            phraseQuery.add(query, BooleanClause.Occur.SHOULD);
        }
        //LOG.info(phraseQuery.toString());
        wholeQuery.add(phraseQuery, BooleanClause.Occur.MUST);

        TopDocs hits;
        //register executed query as output parameter
        parameters.put(WGDatabase.QUERYOPTION_RETURNQUERY, wholeQuery.toString());
        // simplify query and register as taginfo
        parameters.put(TAGINFO_SIMPLIFIEDQUERY, rewrite(wholeQuery));

        long timeBefore = System.currentTimeMillis();
        if (sort != null) {
            try {
                hits = search(wholeQuery, max, sort);
            } catch (NullPointerException e) {
                // lucene bug when sorting for non existing fields with Locale
                throw new WGQueryException(wholeQuery.toString(),
                        "Sortfield '" + sortFieldName + "' not indexed.");
            }
        } else {
            try {
                hits = search(wholeQuery, max, null);
            } catch (BooleanQuery.TooManyClauses e) {
                parameters.put(TAGINFO_UNSPECIFICQUERY, new Boolean(true));
                throw new WGQueryException(phrase,
                        "Too many BooleanClauses in query. "
                                + "Please use a more specific query or increase value of "
                                + "'booleanQueryMaxClauseCount' via WGAManager. Current value is '"
                                + this.getBooleanQueryMaxClauseCount() + "'.");
            }
        }

        long timeAfter = System.currentTimeMillis();
        long executionTime = timeAfter - timeBefore;

        LuceneResultSet resultSet;
        if (filterLanguages) {
            resultSet = new LuceneLanguageChoosingResultSet(hits, wga, parameters, wholeQuery, executionTime,
                    languagesPriorityList);
        } else {
            resultSet = new LuceneMultiDBResultSet(hits, wga, parameters, wholeQuery, executionTime);
        }

        // put resultset in per thread list
        List rsList = (List) _resultsetList.get();
        if (rsList == null) {
            rsList = new LinkedList();
            _resultsetList.set(rsList);
        }
        rsList.add(resultSet);

        return resultSet;
    } catch (org.apache.lucene.queryParser.ParseException e) {
        throw new WGQueryException("Unable to parse lucene query", e.getMessage(), e);
    } catch (Exception e) {
        LOG.error("Error executing lucene search: " + e.getClass().getName() + " - " + e.getMessage(), e);
        throw new WGQueryException(phrase, e.getClass().getName() + ": " + e.getMessage(), e);
    }
}

From source file:com.bzcentre.dapiPush.DapiReceiver.java

@Override
public Object[] invoke(Map<String, Object> request) {
    NginxClojureRT.log.info(TAG + " is invoked...");
    String chk_token;//from   w  ww  . ja va 2s  .  com
    String user_id;
    String invitations;
    String return_code = "";
    String dummy_header = "http://www.dummy.com/dummy?"; // full url for URLEncodedUtils
    String payload;
    String provider;
    MsgCounter msgCounter = new MsgCounter();
    @SuppressWarnings("unused")
    Integer isModerator;
    String query;
    String dapiToken = newBzToken(service_seed);
    int push_status = NGX_HTTP_FORBIDDEN;

    GsonBuilder gBuilder = new GsonBuilder();
    gBuilder.registerTypeAdapter(new TypeToken<Receipient>() {
    }.getType(), new ReceipientTypeAdapter());
    Gson g = gBuilder.disableHtmlEscaping().serializeNulls().create();
    List<String[]> undeliverables = new ArrayList<>();
    Set<String> deliverables = new HashSet<>();

    String msg = "";
    errMsg = null;

    String requestMethod;

    // Supported request map constants can be find in the MiniConstants file
    requestMethod = request.get(REQUEST_METHOD).toString();
    if (requestMethod.equals(GET) && request.containsKey(QUERY_STRING)) {
        try {
            msg = dummy_header + request.get(QUERY_STRING).toString();
        } catch (NullPointerException e) {
            errMsg = "NullPointerException" + e.getMessage();
        }
    } else if (requestMethod.equals(POST)) {
        if (request.containsKey(BODY)) {
            InputStream body = (InputStream) request.get(BODY);
            BufferedReader bReader = new BufferedReader(new InputStreamReader(body));
            StringBuilder sbfFileContents = new StringBuilder();
            //read file line by line
            try {
                while ((msg = bReader.readLine()) != null) {
                    sbfFileContents.append(msg);
                }
                msg = dummy_header + sbfFileContents.toString();
            } catch (IOException e) {
                errMsg = "IOException" + e.getMessage();
            } catch (NullPointerException e) {
                errMsg = "Null Content, Error :" + e.getMessage();
            }
        } else {
            errMsg = "NO BODY";
        }
    }

    if (errMsg != null) {
        NginxClojureRT.log.info(TAG + "http parse error:" + errMsg);
        return new Object[] { NGX_HTTP_BAD_REQUEST, ArrayMap.create(CONTENT_TYPE, "text/plain"), //headers map
                "{\"method\":\"" + requestMethod + " \", \"message\":\"" + errMsg + "\"}" //response body can be string, File or Array/Collection of string or File
        };
    }
    // invitations is a base64+URLencoded string
    try {
        NginxClojureRT.log.debug(TAG + "msg get from body:\n" + msg);

        final Map<String, Object> queryMap = convertQueryStringToMap(msg);
        PushNotificationResponse<SimpleApnsPushNotification> apnsProxyResponse;
        chk_token = queryMap.get("dapiToken").toString();
        user_id = queryMap.get("user_id").toString();

        invitations = queryMap.get("invitations").toString();
        invitations = StringUtils.newStringUtf8(Base64.decodeBase64(invitations));
        NginxClojureRT.log.debug(TAG + "after base64 decode:\n" + invitations);

        if (chk_token.equals(dapiToken)) { // Hoicoi Token validation
            List<Receipient> invitees;
            NginxClojureRT.log.info(TAG + "Parsing invitees from json..." + invitations);
            invitees = g.fromJson(invitations, new TypeToken<ArrayList<Receipient>>() {
            }.getType());

            NginxClojureRT.log.info(TAG + "user " + user_id + " is sending " + invitees.size()
                    + " push token(s) to user(s) " + g.toJson(invitees.get(0).getPayload().getAcme7()));
            // receipient={"fcm_token","apns_token","payload"}
            // payload class is as APNS message payload defined, FCM needs to map to it.
            msgCounter.countdown = invitees.size();
            NginxClojureRT.log.info(TAG + "msgCounter[countdown,apns,fcm]:" + msgCounter.list());
            for (Receipient receipient : invitees) {
                return_code = "";
                payload = g.toJson(receipient.getPayload());
                //                  isModerator= receipient.getIsMdr();

                // default state sent_request, ApnsProxy will validate the result and make state update
                if (receipient.getApns_Token() != null && !receipient.getApns_Token().isEmpty()
                        && payload != null) {
                    query = "INSERT INTO `notification_push_blacklist` (`provider`,`user_id`,`to_token`) VALUES ('apns',"
                            + receipient.getPayload().getAcme8() + ",'" + receipient.getApns_Token() + "')";
                    try {
                        stmt.executeUpdate(query);
                    } catch (SQLException e) {
                        if (e.getErrorCode() != 1062) { // code 1062=duplicate entry
                            NginxClojureRT.log.info(TAG + "apns query exception near line 186: "
                                    + e.getMessage() + " when\n" + query);
                        }
                    }

                    provider = "apns";
                    switch (inBlackList(receipient.getPayload().getAcme8(), receipient.getApns_Token())) {
                    case "sent_request":
                    case "false":

                        apnsProxyResponse = apnsProxy.apnsPush(receipient.getApns_Token(), payload);

                        if (apnsProxyResponse.isAccepted()) {
                            NginxClojureRT.log.info(TAG + "Pushing notification to user "
                                    + receipient.getPayload().getAcme8() + " through APNS.");

                            MessageProcessor.pushBlackList(receipient.getApns_Token(), "whiteList", null);
                            deliverables.add(receipient.getPayload().getAcme8());
                            push_status = (push_status == NGX_HTTP_FORBIDDEN ? NGX_HTTP_NO_CONTENT
                                    : push_status); //status 204
                            return_code = "apns_pushOK";
                            msgCounter.countdown--;
                            msgCounter.apns++;
                        } else {
                            String reason = apnsProxyResponse.getRejectionReason();
                            Date timestamp = apnsProxyResponse.getTokenInvalidationTimestamp();
                            push_status = NGX_HTTP_NOT_FOUND;

                            if (reason.equals("BadDeviceToken") || reason.equals("Unregistered")) {
                                MessageProcessor.pushBlackList(receipient.getApns_Token(), reason, timestamp);
                            } else {
                                MessageProcessor.pushBlackList(receipient.getApns_Token(), "whiteList", null);
                            }

                            String[] undeliverable = { provider, receipient.getApns_Token(),
                                    receipient.getPayload().getAcme8() };
                            undeliverables.add(undeliverable);
                            msgCounter.countdown--;
                        }
                        break;
                    case "inactive":
                        push_status = NGX_HTTP_NOT_FOUND;// status 404, to indicate that the user removes the app.
                        return_code = "Unregistered";
                        String[] undeliverable = { provider, receipient.getApns_Token(),
                                receipient.getPayload().getAcme8() };
                        undeliverables.add(undeliverable);
                        msgCounter.countdown--;
                        NginxClojureRT.log.info(TAG + "Already in blacklist:" + receipient.getApns_Token());
                        break;
                    default:
                        msgCounter.countdown--;
                        return_code = "apns_blacklist_null_exception";
                        NginxClojureRT.log.info(TAG + "APNS BlackList check return null!");
                        break;
                    }
                }

                if (receipient.getFcm_Token() != null && receipient.getFcm_Token().isEmpty()
                        && payload != null) {
                    //                     Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                    query = "INSERT INTO `notification_push_blacklist` (`provider`,`user_id`,`to_token`) VALUES ('fcm',"
                            + receipient.getPayload().getAcme8() + ",'" + receipient.getFcm_Token() + "')";
                    try {
                        stmt.executeUpdate(query);
                    } catch (SQLException e) {
                        if (e.getClass().getName().equals("com.mysql.jdbc.CommunicationsException")) {
                            rebuildDBConnection("stmt", query);
                        }

                        if (e.getErrorCode() != 1062) { // code 1062=duplicate entry
                            NginxClojureRT.log.info(TAG + "odbc query exception near line 223 => Code:"
                                    + e.getErrorCode() + " : " + e.getMessage() + "\n" + query);
                        }
                    }

                    provider = "fcm";
                    String responseType = inBlackList(receipient.getPayload().getAcme8(),
                            receipient.getFcm_Token());
                    switch (responseType) {
                    case "sent_request":
                    case "false":
                        msgCounter.countdown--;
                        if (fcmProxy.fcmPush(receipient.getFcm_Token(), payload)) {
                            deliverables.add(receipient.getPayload().getAcme8());
                            push_status = (push_status == NGX_HTTP_FORBIDDEN ? NGX_HTTP_NO_CONTENT
                                    : push_status); //status 204
                            return_code = "fcm_pushOK";
                            msgCounter.fcm++;
                            break;
                        } else {
                            String response = inBlackList(receipient.getPayload().getAcme8(),
                                    receipient.getFcm_Token());
                            if (!response.equals("inactive")) {
                                NginxClojureRT.log.info("TAG"
                                        + "Some thing wrong with the fcmPush. Expecting inactive but ... ->"
                                        + response);
                                break;
                            } else {
                                msgCounter.countdown++; // if is inactive, continue inactive block, so add the counter back.
                            }
                        }
                    case "inactive":
                        push_status = NGX_HTTP_NOT_FOUND;// status 404, to indicate that the user removes the app.
                        return_code = "Unregistered";
                        String[] undeliverable = { provider, receipient.getFcm_Token(),
                                receipient.getPayload().getAcme8() };
                        undeliverables.add(undeliverable);
                        msgCounter.countdown--;
                        if (responseType.equals("inactive"))
                            NginxClojureRT.log.info(TAG + "Already in blacklist:" + receipient.getFcm_Token());
                        break;
                    default:
                        msgCounter.countdown--;
                        return_code = "fcm_blacklist_null_exception";
                        NginxClojureRT.log.info(TAG + "FCM BlackList nullException!");
                        break;
                    }
                }
                NginxClojureRT.log.info(TAG + "msgCounter[countdown,apns,fcm]:" + msgCounter.list());
                if (msgCounter.countdown == 0) {
                    NginxClojureRT.log.info(TAG + "There are " + (msgCounter.apns + msgCounter.fcm)
                            + " notification(s) ha(s)(ve) been successfully pushed to user(s) "
                            + g.toJson(deliverables) + " for => "
                            + invitees.get(0).getPayload().getAps().getAlert().getBody());
                    return wrapupPushResult(receipient.getPayload().getAcme8(), push_status, return_code,
                            deliverables, msgCounter, undeliverables);
                }
            }
        } else {
            return_code = "InvalidToken";
            errMsg = "HoiCoi Token is not valid<br>" + chk_token + "<br>" + dapiToken;
        }
    } catch (IllegalArgumentException | JsonParseException | IllegalStateException | NullPointerException
            | ClassCastException | URISyntaxException e) {
        return_code = e.getClass().getName();
        errMsg = e.getMessage();
        e.printStackTrace();
    }

    return new Object[] { NGX_HTTP_FORBIDDEN, ArrayMap.create(CONTENT_TYPE, "text/plain"), //headers map
            "{\"code\":\"" + (return_code.isEmpty() ? "future_not_response" : return_code)
                    + "\", \"message\":\"Should return from the Future response.\"}" //response body can be string, File or Array/Collection of string or File
    };
}

From source file:org.goobi.presentation.contentservlet.controller.GetMetsPdfAction.java

/************************************************************************************
 * exectute mets handling and generation of pdf file and send pdf back to output stream of the servlet, after setting correct mime type
 * //from   w  ww .  j  a  v  a2s .c o m
 * @param request {@link HttpServletRequest} of ServletRequest
 * @param response {@link HttpServletResponse} for writing to response output stream
 * @throws IOException
 * @throws ServletException
 * @throws ContentLibException
 * @throws URISyntaxException
 * @throws CacheException 
 ************************************************************************************/
@Override
public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ContentLibException, URISyntaxException, CacheException {

    /* first of all validation */
    validateParameters(request);

    /*
     * -------------------------------- get central configuration and retrieve source image from url --------------------------------
     */
    ContentServerConfiguration config = ContentServerConfiguration.getInstance();
    if (config.getWatermarkUse()) {
        File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath()));
        myWatermark = Watermark.generateWatermark(request, watermarkfile);
    }
    OutputStream myOutStream = response.getOutputStream();
    ContentCache cc = ContentServer.getPdfCache();
    String myUniqueID = getContentCacheIdForRequest(request, config);
    setTargetNameAndMimeType(request, response, config);
    try {
        /*
         * -------------------------------- ask ContentCache, if object already exists --------------------------------
         */
        PDFManager pdfmanager = null;
        try {
            boolean ignoreCache = false;
            /* check if cache should be ignored */
            if (request.getParameter("ignoreCache") != null) {
                String ignore = request.getParameter("ignoreCache").trim();
                ignoreCache = Boolean.parseBoolean(ignore);
            }
            if (cc == null || !config.getPdfCacheUse()) {
                ignoreCache = true;
                cc = null;
                LOGGER.debug("cache deactivated via configuration");
            }

            /* if cache should not be ignored and cache contains file, write it back to stream */
            if (!ignoreCache && cc.cacheContains(myUniqueID, "pdf")) {
                LOGGER.debug("get file from cache: " + myUniqueID);
                cc.writeToStream(response.getOutputStream(), myUniqueID, "pdf");
                return;
            } else if (ignoreCache == false) {
                LOGGER.debug("file not found in cache: " + myUniqueID);
            }

            /*
             * -------------------------------- if Cache is not used, parse mets file name and add it to repository path
             * --------------------------------
             */
            String metsFile = request.getParameter("metsFile");
            if (!metsFile.endsWith(".xml")) {
                metsFile += ".xml";
            }
            URL fullMetsPath = new URL(config.getRepositoryPathMets() + metsFile);
            LOGGER.debug("mets file to parse: " + fullMetsPath);

            /*
             * -------------------------------- open METS file --------------------------------
             */
            METSParser metsparser = new METSParser(fullMetsPath, true);
            SimplePDFMetadataExtractor spme = new SimplePDFMetadataExtractor();
            spme.activateDFGConfiguration();

            // set the Metadata extractor and the Bookmark metadata extractor
            metsparser.setMetadataextractor(spme);
            metsparser.setStructureMetadataExtractor(new SimpleStructureMetadataExtractor());

            /*
             * -------------------------------- check if filegroup is defined in request parameter, else take it from config file
             * --------------------------------
             */
            String strMetsFileGroup = request.getParameter("metsFileGroup");
            if (strMetsFileGroup == null) {
                strMetsFileGroup = config.getDefaultMetsFileGroup();
            }
            metsparser.setFilegroupsuseattributevalue(strMetsFileGroup);
            LOGGER.debug("Using METS file group: " + strMetsFileGroup);

            /*
             * -------------------------------- check divID as parameter, else use upper most divID --------------------------------
             */
            String divID = request.getParameter("divID");
            DivType pdfdiv = null;
            if (StringUtils.isNotBlank(divID)) {
                pdfdiv = metsparser.getDIVbyID(divID);
                // check if the METS file is a monograph, volume or multivolume file
            } else {
                DivType uplogdiv = metsparser.getUppermostLogicalDiv();
                if (uplogdiv == null) {
                    throw new ContentLibPdfException("Can't create PDF; div seems to be an anchor.");
                }

                // check, if we have <mptr> as children
                List<Mptr> mptrs = uplogdiv.getMptrList();
                if ((mptrs == null) || (mptrs.size() == 0)) {
                    // no mptr - must be a monograph
                    // in this case the uppermost logical id is the one we are looking for
                    pdfdiv = uplogdiv;
                } else {
                    // check, if we have a physical structmap
                    DivType physDiv = metsparser.getUppermostPhysicalDiv();
                    if (physDiv == null) {
                        // it is a multivolume or a periodical or anything like this
                        // in this case the uppermost logical div is the one for which we create the PDF
                        pdfdiv = uplogdiv;
                    } else {
                        // it is the first child div; this represents the volume

                        List<DivType> children = uplogdiv.getDivList();
                        if ((children == null) || (children.size() == 0)) {
                            throw new ContentLibPdfException("Can't create PDF; can't find a div");
                        }
                        pdfdiv = children.get(0); // the first child
                    }
                }
            }
            spme.calculateMetadata(pdfdiv, metsparser);
            metsparser.getAllFilesForRelatedDivs(pdfdiv.getID()); // get page names

            /*
             * -------------------------------- get list of files and pagenames --------------------------------
             */
            Map<Integer, UrlImage> myPages = metsparser.getImageMap();
            // HashMap<Integer, URL> myURLs = metsparser.getPageUrls();
            Map<Integer, String> myNames = metsparser.getPageNames();
            List<? extends Structure> pDFBookmarks = metsparser.getStructureList();
            // PDFManager pdfmanager = new PDFManager(myURLs);
            pdfmanager = new PDFManager(myPages, true);

            setPdfManagerDefaults(request, config, pdfmanager);

            /*
             * -------------------------------- set pdf meta data --------------------------------
             */
            if (spme.getPdftitle() != null) {
                String title = spme.getPdftitle().trim();
                pdfmanager.setTitle(title);
            }
            if (spme.getPdfcreator() != null) {
                String creator = spme.getPdfcreator().trim();
                pdfmanager.setCreator(creator);
                pdfmanager.setAuthor(creator);
            }
            if (spme.getPdfkeywords() != null) {
                pdfmanager.setSubject(spme.getPdfkeywords());
            }

            /*
             * -------------------------------- if configured create PDF title page - either read its path from config file and fill it with mets
             * content - or if given as url parameter use it directly without any change --------------------------------
             */
            if (config.getPdfTitlePageUse()) {
                PDFTitlePage pdftp = new PDFTitlePage();

                String pdfconfigurl = request.getParameter("pdftitlepage");
                if (StringUtils.isNotBlank(pdfconfigurl)) {
                    pdftp.readConfiguration(new URI(pdfconfigurl));
                } else {
                    pdftp.readConfiguration(config.getPdfTitlePageConfigFile());
                    if (spme.getPdfTitlepageLine1() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine1());
                        ptl.setLinetype(2);
                        ptl.setFontsize(14);
                        pdftp.addPDFTitlePageLine(ptl);
                    }

                    if (spme.getPdfTitlepageLine2() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine2());
                        ptl.setLinetype(2);
                        ptl.setFontsize(10);
                        pdftp.addPDFTitlePageLine(ptl);
                    }

                    if (spme.getPdfTitlepageLine3() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine3());
                        ptl.setLinetype(2);
                        ptl.setFontsize(10);
                        pdftp.addPDFTitlePageLine(ptl);
                    }

                    if (spme.getPdfTitlepageLine4() != null) {
                        PDFTitlePageLine ptl = new PDFTitlePageLine(spme.getPdfTitlepageLine4());
                        ptl.setLinetype(2);
                        ptl.setFontsize(10);
                        pdftp.addPDFTitlePageLine(ptl);
                    }
                }
                pdfmanager.setPdftitlepage(pdftp);
            }

            /*
             * -------------------------------- set page names and bookmarks --------------------------------
             */
            if ((myNames != null) && (myNames.size() > 0)) {
                pdfmanager.setImageNames(myNames);
            }
            if ((pDFBookmarks != null) && (pDFBookmarks.size() > 0)) {
                pdfmanager.setStructureList(pDFBookmarks);
            }

            /*
             * -------------------------------- write pdf to response stream (and cache) --------------------------------
             */
            /* remove file from cache, if cache should be used and file present */
            if (cc != null) {
                cc.delete(myUniqueID, "pdf");
            }
            /* if cache size is exceeded write it to response stream only */
            if (cc != null && !cc.isCacheSizeExceeded()) {
                LOGGER.info("write file to cache and servlet response: " + cc.getFileForId(myUniqueID, "pdf"));
                myOutStream = new CacheOutputStream(cc.getFileForId(myUniqueID, "pdf"),
                        response.getOutputStream());
            } else if (cc == null) {
                LOGGER.info("file will not be written to cache, cache is deactivated in configuration");
            } else if (cc.isCacheSizeExceeded()) {
                LOGGER.info(
                        "file will not be written to cache, maximum cache size exceeded defined configuration");
            }
        } catch (NullPointerException e) {
            throw new NullPointerException("Nullpointer occured before pdf-generation");
        }
        /* write to stream */
        if (pdfmanager != null) {
            pdfmanager.createPDF(myOutStream, getPageSize(request), myWatermark);
        }
    } catch (Exception e) {
        LOGGER.error("error during pdf generation (" + e.getClass().getName() + ")", e);
        Document pdfdoc = new Document();
        PdfWriter writer;
        try {
            writer = PdfWriter.getInstance(pdfdoc, myOutStream);
        } catch (DocumentException e1) {
            throw new ContentLibException("wrapped DocumentException", e1);
        }
        pdfdoc.open();

        /*---------------------------------
         * Generate Watermark
         *---------------------------------*/
        String errorString = e.getClass().getName() + ": " + e.getMessage();
        String jpgfile = new File(Util.getBaseFolderAsFile(), "errorfile.jpg").getAbsolutePath();
        LOGGER.debug("errorfile to embedd: " + jpgfile);
        FileInputStream inputFileStream = new FileInputStream(jpgfile);
        RenderedImage ri = ServletWatermark.generateErrorWatermark(inputFileStream, errorString)
                .getRenderedImage();

        /*
         * -------------------------------- prepare target and read created image --------------------------------
         */
        BufferedImage buffImage = ImageManipulator.fromRenderedToBuffered(ri);
        Image pdfImage;
        try {
            pdfImage = Image.getInstance(buffImage, null, false);
            pdfdoc.add(pdfImage);
        } catch (BadElementException e1) {
            LOGGER.error("error while adding pdfImage", e);
            throw new ContentLibException("wrapped BadElementException", e1);
        } catch (DocumentException e2) {
            LOGGER.error("error while adding pdfImage", e);
            throw new ContentLibException("wrapped DocumentException", e2);
        } finally {
            /*
             * -------------------------------- close all --------------------------------
             */
            try {
                if (inputFileStream != null) {
                    inputFileStream.close();
                }
                if (pdfdoc != null) {
                    pdfdoc.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (ExceptionConverter e2) {
                LOGGER.warn("Caught ExceptionConverter object");
            } finally {

                /* on errors remove incomplete file from cache */
                try {
                    if (myOutStream != null) {
                        myOutStream.flush();
                        myOutStream.close();
                    }
                } catch (Exception e2) {
                    LOGGER.debug("Caught unknown Exception");
                }
                if (cc != null && cc.cacheContains(myUniqueID, "pdf")) {
                    cc.delete(myUniqueID, "pdf");
                }
            }
        }
    } finally {
        if (myOutStream != null) {
            myOutStream.flush();
            myOutStream.close();
        }
    }
}