Example usage for java.lang String subSequence

List of usage examples for java.lang String subSequence

Introduction

In this page you can find the example usage for java.lang String subSequence.

Prototype

public CharSequence subSequence(int beginIndex, int endIndex) 

Source Link

Document

Returns a character sequence that is a subsequence of this sequence.

Usage

From source file:org.opentestsystem.shared.test.interactioncontext.FastInteractionContext.java

public FastInteractionResponse buildResponse(String method, URL url, Map<String, List<String>> headers,
        Reader body, long timeout) throws IOException {

    URI uri = null;//from  ww w .  ja va2s . com
    try {
        uri = url.toURI();
    } catch (URISyntaxException e) {
        synchronized (this) {
            getActiveTimingRecord().fail(String.format("Invalid URL: %s", url.toString()), e);
        }
    }

    int iTimeout = (int) Math.min(Integer.MAX_VALUE, timeout);

    FastInteractionResponse response = null;
    HttpURLConnection connection = null;

    // This value is only used if an error causes things to fail before the connection is created.
    long t_start = System.currentTimeMillis();
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(iTimeout);
        connection.setReadTimeout(iTimeout);

        // Expect to send ouptut if a body has been supplied
        connection.setDoOutput(body != null);

        // Set headers (except cookies)
        if (headers != null) {
            for (Entry<String, List<String>> header_i : headers.entrySet()) {
                connection.setRequestProperty(header_i.getKey(), StringUtils.join(header_i.getValue(), ','));
            }
        } else {
            headers = new HashMap<String, List<String>>();
        }

        // Set cookies
        for (Entry<String, List<String>> header_i : _cookies.get(uri, headers).entrySet()) {
            for (String cookie_j : header_i.getValue()) {
                connection.addRequestProperty(header_i.getKey(), cookie_j);
            }
        }

        // Log the request, if desired
        if (_logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder("Posted HTTP request:\r\n\r\n");
            msg.append(method).append("\r\n");
            msg.append(uri.toString()).append("\r\n");
            for (Entry<String, List<String>> header_i : connection.getRequestProperties().entrySet()) {
                for (String value_j : header_i.getValue())
                    msg.append(header_i.getKey()).append(": ").append(value_j).append("\r\n");
            }
            msg.append("\r\n");

            if (body != null) {
                String bodyString = IOUtils.toString(body);
                IOUtils.closeQuietly(body);
                body = new StringReader(bodyString);
                msg.append(bodyString);
            }

            _logger.debug(msg.toString());
        }

        // Start timing
        // We update here because we don't really want to count time spent above.
        t_start = System.currentTimeMillis();

        // Send the request
        connection.connect();

        // Send the body
        if (body != null) {
            try (OutputStream os = connection.getOutputStream();) {
                IOUtils.copy(body, os, "UTF-8");
            } finally {
                IOUtils.closeQuietly(body);
            }
        }

        // Record the cookies
        // SB-547 workaround: multiple set-cookie headers are sent for the same
        // cookie. Process the last.
        Map<String, String> cookieMap = new HashMap<>();
        for (Entry<String, List<String>> header_i : connection.getHeaderFields().entrySet()) {
            if (StringUtils.equals(header_i.getKey(), "Set-Cookie")) {
                for (String value_j : header_i.getValue()) {
                    for (String value_k : StringUtils.split(value_j, ',')) {
                        String[] cookieParts = StringUtils.split(value_k, "=", 2);
                        if (cookieParts.length > 0) {
                            String oldValue = cookieMap.get(cookieParts[0]);
                            if (oldValue == null || oldValue.length() < value_k.length()) {
                                cookieMap.put(cookieParts[0], value_k);
                            }
                        }
                    }
                }
            }
        }
        List<String> cookieValues = new ArrayList<>(cookieMap.values());
        Map<String, List<String>> cookieHeaders = new HashMap<>();
        cookieHeaders.put("Set-Cookie", cookieValues);
        _cookies.put(uri, cookieHeaders);

        // Retrieve the response
        InputStream is = connection.getInputStream();
        response = new FastInteractionResponse(this, is, connection, timeout, t_start + timeout);
        IOUtils.closeQuietly(is);
        connection.disconnect();

        // Stop timing
        long t_end = System.currentTimeMillis();
        synchronized (this) {
            InteractionTimingRecord timingRecord = getActiveTimingRecord();
            if (timingRecord != null) {
                timingRecord.accumulate("REMOTE_TIME", t_end - t_start);
                timingRecord.accumulate("N_REQ", 1);
            }
        }

        // Log the response, if desired
        if (_logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder("Response from HTTP request:\r\n\r\n");
            msg.append(uri.toString()).append("\r\n\r\n");
            for (Entry<String, List<String>> header_i : connection.getHeaderFields().entrySet()) {
                for (String value_j : header_i.getValue()) {
                    msg.append(header_i.getKey()).append(": ").append(value_j).append("\r\n");
                }
            }
            msg.append("\r\n");
            String bodyString = response.getResponseBodyAsString();
            if (bodyString != null) {
                if (bodyString.length() <= 1024) {
                    msg.append(bodyString);
                } else {
                    msg.append(String.format("Body length %d. Showing first 1024 characters\r\n\r\n",
                            bodyString.length()));
                    msg.append(bodyString.subSequence(0, 1024));
                }
            }
            _logger.debug(msg.toString());
        }

        return response;
    } catch (IOException e) {
        synchronized (this) {
            failActiveInteraction(String.format("IO Error trying to fill request to %s", url.toString()), e);
            InputStream es = null;
            es = connection.getErrorStream();
            response = new FastInteractionResponse(this, es, connection, timeout, t_start + timeout);
            IOUtils.closeQuietly(es);
        }
    }
    return response;
}

From source file:com.laxser.blitz.web.instruction.InstructionExecutorImpl.java

protected Object parseInstruction(Invocation inv, Object ins) {
    if (logger.isDebugEnabled()) {
        logger.debug("parset instruction:" + ins.getClass().getName() + ": '" + ins + "'");
    }//from w  w w .  ja  v a2  s.  c om
    if (ClassUtils.isPrimitiveOrWrapper(ins.getClass())) {
        return Text.text(ins);
    } else if (ins instanceof CharSequence) {
        String str = ins.toString();
        if (str.length() == 0 || str.equals("@")) {
            return null;
        }
        if (str.charAt(0) == '@') {
            return Text.text(str.substring(1)); // content-type?@HttpFeatures
        }
        if (str.charAt(0) == '/') {
            return new ViewInstruction(str);
        }
        if (str.startsWith("r:") || str.startsWith("redirect:")) {
            StringInstruction si = new StringInstruction(false, str.substring(str.indexOf(':') + 1));
            if (si.innerInstruction.startsWith("http://") || si.innerInstruction.startsWith("https://")) {
                return Redirect.location(si.innerInstruction);
            }
            return si;
        }
        if (str.startsWith("pr:") || str.startsWith("perm-redirect:")) {
            StringInstruction si = new StringInstruction(false, str.substring(str.indexOf(':') + 1));
            si.permanentlyWhenRedirect = true;
            if (si.innerInstruction.startsWith("http://") || si.innerInstruction.startsWith("https://")) {
                return si.permanentlyIfNecessary(Redirect.location(si.innerInstruction));
            }
            return si;
        }
        if (str.startsWith("f:") || str.startsWith("forward:")) {
            return new StringInstruction(true, str.substring(str.indexOf(':') + 1));
        }
        if (str.startsWith("e:") || str.startsWith("error:")) {
            int begin = str.indexOf(':') + 1;
            int codeEnd = str.indexOf(';');
            if (codeEnd == -1) {
                String text = str.substring(begin);
                if (text.length() > 0 && NumberUtils.isNumber(text)) {
                    return HttpError.code(Integer.parseInt(text));
                }
                return HttpError.code(500, text);
            } else {
                return HttpError.code(Integer.parseInt(str.substring(begin, codeEnd)),
                        str.substring(codeEnd + 1).trim());
            }
        }
        if (str.startsWith("s:") || str.startsWith("status:")) {
            int begin = str.indexOf(':') + 1;
            int codeEnd = str.indexOf(';', begin);
            if (codeEnd == -1) {
                inv.getResponse().setStatus(Integer.parseInt(str.substring(begin)));
                return null;
            } else {
                // setStatus(int, String)???';'??msg
                // sendError?
                inv.getResponse().setStatus(Integer.parseInt(str.substring(begin, codeEnd)));
                for (int i = codeEnd; i < str.length(); i++) {
                    if (str.charAt(i) != ' ') {
                        str = str.substring(i + 1);
                        break;
                    }
                }
            }
        }
        if (str.equals(":continue")) {
            return null;
        }
        return new StringInstruction(null, str);
    } else if (ins.getClass() == StringInstruction.class) {
        StringInstruction fr = (StringInstruction) ins;
        String str = fr.innerInstruction;
        int queryIndex = str.indexOf('?');
        for (int i = (queryIndex == -1) ? str.length() - 1 : queryIndex - 1; i >= 0; i--) {
            if (str.charAt(i) != ':') {
                continue;
            }
            if (i > 0 && str.charAt(i - 1) == '\\') { // ?
                str = str.substring(0, i - 1) + str.substring(i);
                i--;
                continue;
            }
            int cmdEnd = i;
            int cmdBeforeBegin = i - 1;
            while (cmdBeforeBegin >= 0 && str.charAt(cmdBeforeBegin) != ':') {
                cmdBeforeBegin--;
            }
            String prefix = str.subSequence(cmdBeforeBegin + 1, cmdEnd).toString();
            String body = str.subSequence(i + 1, str.length()).toString();
            if ("a".equals(prefix) || "action".equals(prefix)) {
                if (fr.isReirect()) {
                    return fr.permanentlyIfNecessary(Redirect.action(body));
                } else {
                    return Forward.action(body);
                }
            }
            if ("c".equals(prefix) || "controller".equals(prefix)) {
                if (fr.isReirect()) {
                    return fr.permanentlyIfNecessary(Redirect.controller(body));
                } else {
                    return Forward.controller(body);
                }
            }
            if ("m".equals(prefix) || "module".equals(prefix)) {
                if (fr.isReirect()) {
                    return fr.permanentlyIfNecessary(Redirect.module(body));
                } else {
                    return Forward.module(body);
                }
            }
            logger.warn("skip the prefix '" + prefix + ":' of " + str);
            if (fr.isReirect()) {
                return fr.permanentlyIfNecessary(Redirect.location(str));
            } else if (fr.isForward()) {
                return Forward.path(str);
            } else {
                return new ViewInstruction(str);
            }
        }
        if (fr.isReirect()) {
            return fr.permanentlyIfNecessary(Redirect.location(str));
        } else if (fr.isForward()) {
            return Forward.path(str);
        }
        return new ViewInstruction(str);
    } else if (ins instanceof InputStream) {
        return new InputStreamInstruction((InputStream) ins);
    } else if (ins instanceof byte[]) {
        return new InputStreamInstruction(new ByteArrayInputStream((byte[]) ins));
    } else {
        return Text.text(ins.toString());
    }
}

From source file:com.sinosoft.one.mvc.web.instruction.InstructionExecutorImpl.java

protected Object parseInstruction(Invocation inv, Object ins) {
    if (ClassUtils.isPrimitiveOrWrapper(ins.getClass())) {
        return Text.text(ins);
    } else if (ins instanceof CharSequence) {
        String str = ins.toString();
        if (str.length() == 0 || str.equals("@")) {
            return null;
        }/*from ww  w.  j a v  a  2  s. c o m*/
        if (str.charAt(0) == '@') {
            return Text.text(str.substring(1)); // content-type?@HttpFeatures
        }
        if (str.charAt(0) == '/') {
            return new ViewInstruction(str);
        }
        if (str.startsWith("r:") || str.startsWith("redirect:")) {
            StringInstruction si = new StringInstruction(false, str.substring(str.indexOf(':') + 1));
            if (si.innerInstruction.startsWith("http://") || si.innerInstruction.startsWith("https://")) {
                return Redirect.location(si.innerInstruction);
            }
            return si;
        }
        if (str.startsWith("pr:") || str.startsWith("perm-redirect:")) {
            StringInstruction si = new StringInstruction(false, str.substring(str.indexOf(':') + 1));
            si.permanentlyWhenRedirect = true;
            if (si.innerInstruction.startsWith("http://") || si.innerInstruction.startsWith("https://")) {
                return si.permanentlyIfNecessary(Redirect.location(si.innerInstruction));
            }
            return si;
        }
        if (str.startsWith("f:") || str.startsWith("forward:")) {
            return new StringInstruction(true, str.substring(str.indexOf(':') + 1));
        }
        if (str.startsWith("e:") || str.startsWith("error:")) {
            int begin = str.indexOf(':') + 1;
            int codeEnd = str.indexOf(';');
            if (codeEnd == -1) {
                String text = str.substring(begin);
                if (text.length() > 0 && NumberUtils.isNumber(text)) {
                    return HttpError.code(Integer.parseInt(text));
                }
                return HttpError.code(500, text);
            } else {
                return HttpError.code(Integer.parseInt(str.substring(begin, codeEnd)),
                        str.substring(codeEnd + 1).trim());
            }
        }
        if (str.startsWith("s:") || str.startsWith("status:")) {
            int begin = str.indexOf(':') + 1;
            int codeEnd = str.indexOf(';', begin);
            if (codeEnd == -1) {
                inv.getResponse().setStatus(Integer.parseInt(str.substring(begin)));
                return null;
            } else {
                // setStatus(int, String)???';'??msg
                // sendError?
                inv.getResponse().setStatus(Integer.parseInt(str.substring(begin, codeEnd)));
                for (int i = codeEnd; i < str.length(); i++) {
                    if (str.charAt(i) != ' ') {
                        str = str.substring(i + 1);
                        break;
                    }
                }
            }
        }
        if (str.equals(":continue")) {
            return null;
        }
        return new StringInstruction(null, str);
    } else if (ins.getClass() == StringInstruction.class) {
        StringInstruction fr = (StringInstruction) ins;
        String str = fr.innerInstruction;
        int queryIndex = str.indexOf('?');
        for (int i = (queryIndex == -1) ? str.length() - 1 : queryIndex - 1; i >= 0; i--) {
            if (str.charAt(i) != ':') {
                continue;
            }
            if (i > 0 && str.charAt(i - 1) == '\\') { // ?
                str = str.substring(0, i - 1) + str.substring(i);
                i--;
                continue;
            }
            int cmdEnd = i;
            int cmdBeforeBegin = i - 1;
            while (cmdBeforeBegin >= 0 && str.charAt(cmdBeforeBegin) != ':') {
                cmdBeforeBegin--;
            }
            String prefix = str.subSequence(cmdBeforeBegin + 1, cmdEnd).toString();
            String body = str.subSequence(i + 1, str.length()).toString();
            if ("a".equals(prefix) || "action".equals(prefix)) {
                if (fr.isReirect()) {
                    return fr.permanentlyIfNecessary(Redirect.action(body));
                } else {
                    return Forward.action(body);
                }
            }
            if ("c".equals(prefix) || "controller".equals(prefix)) {
                if (fr.isReirect()) {
                    return fr.permanentlyIfNecessary(Redirect.controller(body));
                } else {
                    return Forward.controller(body);
                }
            }
            if ("m".equals(prefix) || "module".equals(prefix)) {
                if (fr.isReirect()) {
                    return fr.permanentlyIfNecessary(Redirect.module(body));
                } else {
                    return Forward.module(body);
                }
            }
            logger.warn("skip the prefix '" + prefix + ":' of " + str);
            if (fr.isReirect()) {
                return fr.permanentlyIfNecessary(Redirect.location(str));
            } else if (fr.isForward()) {
                return Forward.path(str);
            } else {
                return new ViewInstruction(str);
            }
        }
        if (fr.isReirect()) {
            return fr.permanentlyIfNecessary(Redirect.location(str));
        } else if (fr.isForward()) {
            return Forward.path(str);
        }
        return new ViewInstruction(str);
    } else if (ins instanceof InputStream) {
        return new InputStreamInstruction((InputStream) ins);
    } else if (ins instanceof byte[]) {
        return new InputStreamInstruction(new ByteArrayInputStream((byte[]) ins));
    } else if (ins instanceof Reply) {
        return new ReplyInstruction((Reply) ins);
    } else {
        return Text.text(ins.toString());
    }
}

From source file:org.dasein.cloud.nimbula.network.Vethernet.java

@Override
public @Nonnull VLAN createVlan(@Nonnull String cidr, @Nonnull String name, @Nonnull String description,
        @Nonnull String domainName, @Nonnull String[] dnsServers, @Nonnull String[] ntpServers)
        throws CloudException, InternalException {
    ProviderContext ctx = cloud.getContext();

    if (ctx == null) {
        throw new CloudException("No context was set for this request");
    }//from  w w  w . j ava2 s  .  c  om
    if (!"root".equals(ctx.getAccountNumber())) {
        throw new OperationNotSupportedException("VLAN creation is not yet supported for non-root");
    }
    int id = findId();

    int[] parts = new int[4];
    int idx = cidr.indexOf('/');
    int mask = 32;

    if (idx > -1) {
        mask = Integer.parseInt(cidr.substring(idx + 1));
        cidr = cidr.substring(0, idx);
    }

    String[] dotted = cidr.split("\\.");
    if (dotted.length != 4) {
        throw new CloudException("Invalid IP address: " + cidr);
    }
    int i = 0;

    for (String dot : dotted) {
        try {
            parts[i++] = Integer.parseInt(dot);
        } catch (NumberFormatException e) {
            throw new CloudException("Invalid IP address: " + cidr);
        }
    }
    HashMap<String, Object> state = new HashMap<String, Object>();

    state.put("id", id);
    state.put("description", description);
    state.put("type", "vlan");
    state.put("uri", null);
    try {
        state.put("name", "/" + cloud.getContext().getAccountNumber() + "/"
                + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vnet" + id);
    } catch (UnsupportedEncodingException e) {
        if (logger.isDebugEnabled()) {
            logger.error("Failed UTF-8 encoding: " + e.getMessage());
            e.printStackTrace();
        }
        throw new InternalException(e);
    }
    NimbulaMethod method = new NimbulaMethod(cloud, "vethernet");

    method.post(state);

    VLAN vlan;

    try {
        vlan = toVlan(method.getResponseBody());
    } catch (JSONException e) {
        if (logger.isDebugEnabled()) {
            logger.error("Error parsing JSON: " + e.getMessage());
            e.printStackTrace();
        }
        throw new CloudException(e);
    }
    state.clear();

    String ipStop;
    if (mask == 32 || mask == 31) {
        ipStop = cidr;
    } else {
        if (mask >= 24) {
            int count = ((int) Math.pow(2, (32 - mask)) - 1);

            if (count > 4) {
                count = count - 4;
            }
            parts[3] = parts[3] + count;
        } else if (mask >= 16) {
            int count = ((int) Math.pow(2, (24 - mask)) - 1);

            if (count > 4) {
                count = count - 4;
            }
            parts[2] = parts[2] + count;
        } else if (mask >= 8) {
            int count = ((int) Math.pow(2, (16 - mask)) - 1);

            if (count > 4) {
                count = count - 4;
            }
            parts[1] = parts[1] + count;
        } else {
            int count = ((int) Math.pow(2, (8 - mask)) - 1);

            if (count > 4) {
                count = count - 4;
            }
            parts[0] = parts[0] + count;
        }
        ipStop = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
    }
    state.put("iprange_mask", mask);
    state.put("dns_server", dnsServers[0]);
    state.put("dns_server_standby", dnsServers[1]);
    state.put("iprange_start", cidr);
    state.put("iprange_stop", ipStop);
    state.put("uri", null);
    try {
        state.put("vethernet", "/" + cloud.getContext().getAccountNumber() + "/"
                + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vnet" + id);
        state.put("name", "/" + cloud.getContext().getAccountNumber() + "/"
                + new String(cloud.getContext().getAccessPublic(), "utf-8") + "/vdhcpd" + id);
    } catch (UnsupportedEncodingException e) {
        if (logger.isDebugEnabled()) {
            logger.error("Encoding error: " + e.getMessage());
            e.printStackTrace();
        }
        throw new InternalException(e);
    }
    int slash = cidr.indexOf('/');
    state.put("iprouter", cidr.subSequence(0, slash));
    method = new NimbulaMethod(cloud, VDHCPD);

    method.post(state);
    return vlan;
}

From source file:de.tu_dortmund.ub.api.daia.DaiaOpenUrlEndpoint.java

private void provideService(HttpServletRequest request, HttpServletResponse response, String format,
        HashMap<String, String> latinParameters, boolean isTUintern, boolean isUBintern, boolean is52bIBA)
        throws IOException {

    String openurl = "";

    try {// ww  w. ja  v  a2  s.co  m

        // build openurl
        for (String k : latinParameters.keySet()) {

            // repeat input-openurl
            if (!k.equals("format") && !k.equals("system") && !latinParameters.get(k).equals("")) {

                if (latinParameters.get(k).contains("/>")) {
                    latinParameters.put(k, latinParameters.get(k).replaceAll("/>", ""));
                }
                if (latinParameters.get(k).contains(">")) {
                    latinParameters.put(k, latinParameters.get(k).replaceAll(">", ""));
                }

                String prefix = "";
                if (!k.startsWith("rft")) {
                    prefix = "rft.";
                }

                String value = "";

                if (k.contains("title") || k.contains("au")) {
                    value = latinParameters.get(k);
                } else if (k.contains("issn") && !latinParameters.get(k).equals("")) {

                    if (latinParameters.get(k).contains("-")) {
                        value = latinParameters.get(k);
                    } else {
                        value = latinParameters.get(k).subSequence(0, 4) + "-"
                                + latinParameters.get(k).subSequence(4, 8);
                    }
                } else {
                    value = latinParameters.get(k);
                }

                openurl += "&" + prefix + k + "=" + URLEncoder.encode(value, "UTF-8");
            }
        }
        this.logger.debug("\n" + "\tOpenURL-Parameter = " + this.config.getProperty("linkresolver.baseurl")
                + this.config.getProperty("linkresolver.parameters") + openurl);

        ArrayList<Document> daiaDocuments = new ArrayList<Document>();

        // falls OpenURL contains isbn: Anfrage an "normalen DaiaService Endpoint
        String isbn = "";
        if (latinParameters.get("rft.isbn") != null && !latinParameters.get("rft.isbn").equals("")) {
            isbn = latinParameters.get("rft.isbn");
        } else if (latinParameters.get("isbn") != null && !latinParameters.get("isbn").equals("")) {
            isbn = latinParameters.get("isbn");
        } else if (latinParameters.get("id") != null && latinParameters.get("id").contains("isbn:")) {
            isbn = latinParameters.get("id").split(":")[1];
        }
        this.logger.debug("ISBN = " + isbn);

        if (!isbn.equals("")) {

            if (Lookup.lookupAll(IntegratedLibrarySystem.class).size() > 0) {
                // erst DAIA isbn fragen
                if (isbn.contains("; ")) {
                    isbn = isbn.replaceAll("; ", ",");
                }
                String daiaUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                        + "/daia/?id=isbn:" + isbn;
                this.logger.debug("daiaUrl = " + daiaUrl);
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(daiaUrl);
                httpGet.addHeader("Accept", "application/xml");

                CloseableHttpResponse httpResponse = httpclient.execute(httpGet);

                try {

                    int statusCode = httpResponse.getStatusLine().getStatusCode();
                    HttpEntity httpEntity = httpResponse.getEntity();

                    switch (statusCode) {

                    case 200: {

                        JAXBContext jaxbContext = JAXBContext.newInstance(Daia.class);
                        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                        Daia daia = (Daia) unmarshaller.unmarshal(httpEntity.getContent());

                        if (daia.getDocument() != null) {

                            daiaDocuments.addAll(daia.getDocument());
                        }

                        break;
                    }
                    default: {

                        // TODO Evaluieren: Das mssten die Flle sein, in denen E-Books in der Knowledgebase eingetragen sind
                        if (Lookup.lookupAll(LinkResolver.class).size() > 0) {

                            Document daiaDocument = null;

                            LinkResolver linkResolver = Lookup.lookup(LinkResolver.class);
                            // init Linkresolver
                            linkResolver.init(this.config);

                            // get items
                            ArrayList<Document> linkresolverDocument = linkResolver.items("openurl", openurl);

                            if (linkresolverDocument != null && linkresolverDocument.size() > 0) {

                                daiaDocument = new Document();

                                daiaDocument.setId("urn:isbn:" + isbn);

                                if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) {

                                    daiaDocument.setItem(linkresolverDocument.get(0).getItem());
                                } else {
                                    daiaDocument.getItem().addAll(linkresolverDocument.get(0).getItem());
                                }

                                if (daiaDocument != null) {

                                    daiaDocuments.add(daiaDocument);
                                }
                            }
                        }
                    }
                    }

                    EntityUtils.consume(httpEntity);
                } finally {
                    httpResponse.close();
                }
            }
        } else {

            // Wenn JOP registriert ist
            if (Lookup.lookupAll(JournalOnlinePrintService.class).size() > 0) {

                // build OpenURL for JOP
                String issn = "";
                if (latinParameters.get("rft.issn") != null && !latinParameters.get("rft.issn").equals("")) {
                    issn = latinParameters.get("rft.issn");
                } else if (latinParameters.get("issn") != null && !latinParameters.get("issn").equals("")) {
                    issn = latinParameters.get("issn");
                }
                if (latinParameters.get("rft.eissn") != null && !latinParameters.get("rft.eissn").equals("")) {
                    issn = latinParameters.get("rft.eissn");
                } else if (latinParameters.get("eissn") != null && !latinParameters.get("eissn").equals("")) {
                    issn = latinParameters.get("eissn");
                } else if (latinParameters.get("id") != null && latinParameters.get("id").contains("issn:")) {
                    issn = latinParameters.get("id").split(":")[1];
                }
                this.logger.debug("ISSN = " + issn);

                String jop_openurl = "";

                for (String k : latinParameters.keySet()) {

                    // mit rft
                    if ((latinParameters.keySet().contains("rft.atitle")
                            || latinParameters.keySet().contains("atitle")) && k.equals("rft.date")
                            && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&date=" + latinParameters.get(k);
                    }
                    if (k.equals("rft.volume") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&volume=" + latinParameters.get(k);
                    }
                    if (k.equals("rft.issue") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&issue=" + latinParameters.get(k);
                    }

                    // ohne rft
                    if ((latinParameters.keySet().contains("rft.atitle")
                            || latinParameters.keySet().contains("atitle")) && k.equals("date")
                            && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&date=" + latinParameters.get(k);
                    }
                    if (k.equals("volume") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&volume=" + latinParameters.get(k);
                    }
                    if (k.equals("issue") && !latinParameters.get(k).equals("")) {
                        jop_openurl += "&issue=" + latinParameters.get(k);
                    }
                }

                if (!issn.equals("")) {

                    if (issn.contains("-")) {
                        jop_openurl += "&issn=" + issn;
                    } else {
                        jop_openurl += "&issn=" + issn.subSequence(0, 4) + "-" + issn.subSequence(4, 8);
                    }
                }

                if (latinParameters.keySet().contains("rft.atitle")
                        || latinParameters.keySet().contains("atitle")) {
                    jop_openurl += "&genre=article";
                } else {
                    jop_openurl += "&genre=journal";
                }

                this.logger.debug("\n" + jop_openurl + "\tOpenURL-Parameter (JOP) = "
                        + this.config.getProperty("jop.url.openurl") + jop_openurl);

                if (!jop_openurl.equals("&genre=journal")
                        && (jop_openurl.contains("&title=") || jop_openurl.contains("&issn="))) {

                    // get data
                    try {

                        JournalOnlinePrintService journalOnlinePrintService = Lookup
                                .lookup(JournalOnlinePrintService.class);
                        // init JOP
                        journalOnlinePrintService.init(this.config);

                        // get items
                        ArrayList<de.tu_dortmund.ub.api.daia.jop.model.Document> jopDocuments = journalOnlinePrintService
                                .items("openurl", jop_openurl);

                        if (jopDocuments != null && jopDocuments.size() > 0) {

                            Document daiaDocument = new Document();

                            this.logger.debug("JOP hits: " + jopDocuments.size());

                            if (jopDocuments.get(0).getId() != null && jopDocuments.get(0).getHref() != null) {
                                daiaDocument.setId(jopDocuments.get(0).getId());
                                daiaDocument.setHref(jopDocuments.get(0).getHref());
                            } else {
                                daiaDocument.setId("urn:issn:" + issn);
                            }

                            // print
                            if (jopDocuments.get(0).getItem() != null
                                    && jopDocuments.get(0).getItem().size() > 0) {
                                daiaDocument.setItem(jopDocuments.get(0).getItem());
                            }

                            // digital
                            if (jopDocuments.get(0).isExistsDigitalItems()
                                    && Lookup.lookupAll(LinkResolver.class).size() > 0) {

                                // TODO define a boolean variable for executing a linkresolver request
                                // TODO auslagern!
                                LinkResolver linkResolver = Lookup.lookup(LinkResolver.class);
                                // init Linkresolver
                                linkResolver.init(this.config);

                                // get items
                                ArrayList<Document> linkresolverDocument = linkResolver.items("openurl",
                                        openurl);

                                if (linkresolverDocument != null && linkresolverDocument.size() > 0
                                        && linkresolverDocument.get(0).getItem().size() >= jopDocuments.get(0)
                                                .getCountDigitlItems()) {

                                    if (daiaDocument.getItem() == null || daiaDocument.getItem().size() == 0) {
                                        daiaDocument.setItem(linkresolverDocument.get(0).getItem());
                                    } else {
                                        daiaDocument.getItem().addAll(linkresolverDocument.get(0).getItem());
                                    }
                                } else {

                                    // TODO Ticket 11679

                                    // E-Mail an katalogplus@ub.tu-dortmund.de mit Betreff-Prefix [Content]

                                    boolean isNatLic = true;

                                    if (isNatLic) {

                                        if (!issn.equals("")) {

                                            // request JOP again with only ISSN
                                            jopDocuments = journalOnlinePrintService.eonly("issn", issn);

                                            if (jopDocuments != null && jopDocuments.size() > 0) {

                                                this.logger.debug("JOP hits: " + jopDocuments.size());

                                                if (daiaDocument.getItem() == null
                                                        || daiaDocument.getItem().size() == 0) {
                                                    daiaDocument.setItem(jopDocuments.get(0).getItem());
                                                } else {
                                                    if (jopDocuments.get(0).getItem() != null) {
                                                        daiaDocument.getItem()
                                                                .addAll(jopDocuments.get(0).getItem());
                                                    } else {

                                                        // Error-E-Mail "JOP<>LinkResolver: Not an NatLic"
                                                        Mailer mailer = new Mailer(
                                                                this.config.getProperty("service.mailer.conf"));

                                                        try {

                                                            int cnt = 0;
                                                            if (linkresolverDocument != null) {
                                                                cnt = linkresolverDocument.get(0).getItem()
                                                                        .size();
                                                            }

                                                            mailer.postMail(
                                                                    "[DAIAopenurl] JOP-Document ohne Items ",
                                                                    "JOP-Link "
                                                                            + jopDocuments.get(0)
                                                                                    .getCountDigitlItems()
                                                                            + ": "
                                                                            + this.config.getProperty(
                                                                                    "jop.url.openurl")
                                                                            + jop_openurl + ".\n");

                                                        } catch (MessagingException e) {

                                                            this.logger.error(e.getMessage(), e.getCause());
                                                            this.logger.debug("[DAIAopenurl] CONTENT-ERROR");
                                                            this.logger.debug("OpenUrl: " + openurl
                                                                    + "\n\n\tJOP-URL: " + jop_openurl);
                                                        }

                                                        if (daiaDocument.getItem() == null
                                                                || daiaDocument.getItem().size() == 0) {
                                                            daiaDocument = null;
                                                        }
                                                    }
                                                }

                                            }
                                        } else {

                                            // Error-E-Mail "JOP<>LinkResolver: Not an NatLic"
                                            Mailer mailer = new Mailer(
                                                    this.config.getProperty("service.mailer.conf"));

                                            try {

                                                int cnt = 0;
                                                if (linkresolverDocument != null) {
                                                    cnt = linkresolverDocument.get(0).getItem().size();
                                                }

                                                mailer.postMail(
                                                        "[DAIAopenurl] JOP<>LinkResolver: NatLic without ISSN ",
                                                        "Laut ZDB/EZB gibt es "
                                                                + jopDocuments.get(0).getCountDigitlItems()
                                                                + "-mal elektronischen Bestand (vgl. "
                                                                + this.config.getProperty("jop.url.openurl")
                                                                + jop_openurl + ").\n" + "Laut 360 Link aber "
                                                                + cnt + "-mal (vgl. "
                                                                + this.config
                                                                        .getProperty("linkresolver.baseurl")
                                                                + this.config
                                                                        .getProperty("linkresolver.parameters")
                                                                + openurl + ").");

                                            } catch (MessagingException e) {

                                                this.logger.error(e.getMessage(), e.getCause());
                                                this.logger.debug("[DAIAopenurl] CONTENT-ERROR");
                                                this.logger.debug("OpenUrl: " + openurl + "\n\n\tJOP-URL: "
                                                        + jop_openurl);
                                            }

                                            if (daiaDocument.getItem() == null
                                                    || daiaDocument.getItem().size() == 0) {
                                                daiaDocument = null;
                                            }
                                        }
                                    } else {
                                        // Hier kann man nix machen!
                                    }
                                }
                            }

                            if (daiaDocument != null) {

                                daiaDocuments.add(daiaDocument);
                            }
                        }

                    } catch (LinkResolverException e) {

                        // daiaDocuments bleibt leer
                        this.logger.error("[DaiaService OpenUrl Endpoint] Exception: "
                                + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                + " Service unavailable (LinkResolver).");
                        this.logger.error(e.getMessage(), e.getCause());
                        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                            this.logger.error("\t" + stackTraceElement.toString());
                        }

                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {
                            mailer.postMail(
                                    "[DaiaService OpenUrl Endpoint] Exception: "
                                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                            + " Service unavailable (LinkResolver).",
                                    e.getMessage() + "\n" + this.config.getProperty("linkresolver.baseurl")
                                            + this.config.getProperty("linkresolver.parameters") + openurl);

                        } catch (MessagingException e1) {

                            this.logger.error(e1.getMessage(), e1.getCause());
                        }

                    } catch (JOPException e) {

                        // daiaDocuments bleibt leer
                        this.logger.error("[DaiaService OpenUrl Endpoint] Exception: "
                                + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                + " Service unavailable (Journals Online & Print).");
                        this.logger.error(e.getMessage(), e.getCause());
                        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                            this.logger.error("\t" + stackTraceElement.toString());
                        }

                        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

                        try {
                            mailer.postMail(
                                    "[DaiaService OpenUrl Endpoint] Exception: "
                                            + HttpServletResponse.SC_SERVICE_UNAVAILABLE
                                            + " Service unavailable (Journals Online & Print).",
                                    e.getMessage() + "\n" + this.config.getProperty("jop.url.openurl")
                                            + jop_openurl);

                        } catch (MessagingException e1) {

                            this.logger.error(e1.getMessage(), e1.getCause());
                        }
                    }
                } else {

                    // tue nix: daiaDocuments bleibt leer
                }
            }
        }

        // Abschlusskorrektur fr ACM, IEEE und LNCS vor dem response
        // LNCS
        if (Lookup.lookupAll(LncsResolver.class).size() > 0
                && Boolean.parseBoolean(this.config.getProperty("licenced.lncs"))) {

            if (daiaDocuments.size() > 0) {

                for (Document daiaDocument : daiaDocuments) {

                    if (daiaDocument != null && daiaDocument.getId() != null
                            && daiaDocument.getId().contains("urn:issn:03029743")
                            && ((latinParameters.keySet().contains("id")
                                    && latinParameters.get("id").startsWith("doi:10.1007"))
                                    || (latinParameters.keySet().contains("rft.id")
                                            && latinParameters.get("rft.id").startsWith("doi:10.1145")))) {

                        daiaDocument.setItem(null);

                        LncsResolver lncsResolver = Lookup.lookup(LncsResolver.class);
                        lncsResolver.init(this.config);

                        Document lncsDocument = lncsResolver.items(latinParameters);

                        daiaDocument.setId(lncsDocument.getId());
                        daiaDocument.setHref(lncsDocument.getHref());
                        daiaDocument.setItem(lncsDocument.getItem());
                    }
                }
            }
        }

        // ACM
        if (Lookup.lookupAll(AcmResolver.class).size() > 0
                && Boolean.parseBoolean(this.config.getProperty("licenced.acm"))) {

            if ((latinParameters.keySet().contains("id") && latinParameters.get("id").contains("10.1145"))
                    || (latinParameters.keySet().contains("rft.id")
                            && latinParameters.get("rft.id").contains("10.1145"))) {

                if (daiaDocuments.size() > 0) {

                    for (Document daiaDocument : daiaDocuments) {

                        daiaDocument.setItem(null);

                        AcmResolver acmResolver = Lookup.lookup(AcmResolver.class);
                        acmResolver.init(this.config);

                        Document acmDocument = acmResolver.items(latinParameters);

                        daiaDocument.setId(acmDocument.getId());
                        daiaDocument.setHref(acmDocument.getHref());

                        if (daiaDocument.getItem() == null) {
                            daiaDocument.setItem(acmDocument.getItem());
                        } else {
                            daiaDocument.getItem().addAll(acmDocument.getItem());
                        }
                    }
                } else {

                    Document daiaDocument = new Document();

                    AcmResolver acmResolver = Lookup.lookup(AcmResolver.class);
                    acmResolver.init(this.config);

                    Document acmDocument = acmResolver.items(latinParameters);

                    daiaDocument.setId(acmDocument.getId());
                    daiaDocument.setHref(acmDocument.getHref());

                    if (daiaDocument.getItem() == null) {
                        daiaDocument.setItem(acmDocument.getItem());
                    } else {
                        daiaDocument.getItem().addAll(acmDocument.getItem());
                    }

                    daiaDocuments.add(daiaDocument);
                }
            }
        }

        // IEEE
        if (Lookup.lookupAll(IeeeResolver.class).size() > 0
                && Boolean.parseBoolean(this.config.getProperty("licenced.ieee"))) {

            if ((latinParameters.keySet().contains("id") && latinParameters.get("id").contains("10.1109"))
                    || (latinParameters.keySet().contains("rft.id")
                            && latinParameters.get("rft.id").contains("10.1109"))) {

                if (daiaDocuments.size() > 0) {

                    for (Document daiaDocument : daiaDocuments) {

                        daiaDocument.setItem(null);

                        IeeeResolver ieeeResolver = Lookup.lookup(IeeeResolver.class);
                        ieeeResolver.init(this.config);

                        Document ieeeDocument = ieeeResolver.items(latinParameters);

                        daiaDocument.setId(ieeeDocument.getId());
                        daiaDocument.setHref(ieeeDocument.getHref());

                        if (daiaDocument.getItem() == null) {
                            daiaDocument.setItem(ieeeDocument.getItem());
                        } else {
                            daiaDocument.getItem().addAll(ieeeDocument.getItem());
                        }
                    }
                } else {

                    Document daiaDocument = new Document();

                    IeeeResolver ieeeResolver = Lookup.lookup(IeeeResolver.class);
                    ieeeResolver.init(this.config);

                    Document ieeeDocument = ieeeResolver.items(latinParameters);

                    daiaDocument.setId(ieeeDocument.getId());
                    daiaDocument.setHref(ieeeDocument.getHref());

                    if (daiaDocument.getItem() == null) {
                        daiaDocument.setItem(ieeeDocument.getItem());
                    } else {
                        daiaDocument.getItem().addAll(ieeeDocument.getItem());
                    }

                    daiaDocuments.add(daiaDocument);
                }
            }
        }

        if (daiaDocuments.size() > 0) {

            this.logger.debug("200 Document Found");

            // TODO query footnotes from ils if configured

            // Ausgabe
            Daia daia = new Daia();
            daia.setVersion(this.config.getProperty("daia.version"));
            daia.setSchema(this.config.getProperty("daia.schema"));

            GregorianCalendar gc = new GregorianCalendar();
            gc.setTimeInMillis(new Date().getTime());
            try {
                DatatypeFactory df = DatatypeFactory.newInstance();

                daia.setTimestamp(df.newXMLGregorianCalendar(gc).toString());

            } catch (DatatypeConfigurationException dce) {
                this.logger.error("ERROR: Service unavailable.", dce.getCause());
            }

            Institution institution = new Institution();
            institution.setId(this.config.getProperty("daia.institution.id"));
            institution.setHref(this.config.getProperty("daia.institution.href"));
            institution.setContent(this.config.getProperty("daia.institution.content"));
            daia.setInstitution(institution);

            daia.setDocument(daiaDocuments);

            // Ausgabe
            if (daia.getDocument() == null || daia.getDocument().size() == 0) {

                // HTML-Ausgabe via XSLT
                if (format.equals("html")) {

                    try {

                        JAXBContext context = JAXBContext.newInstance(Daia.class);
                        Marshaller m = context.createMarshaller();
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                        // Write to HttpResponse
                        StringWriter stringWriter = new StringWriter();
                        m.marshal(daia, stringWriter);

                        org.jdom2.Document doc = new org.jdom2.Document();
                        doc.setRootElement(new Element("daia"));

                        HashMap<String, String> parameters = new HashMap<String, String>();
                        parameters.put("lang", "de");
                        parameters.put("isTUintern", Boolean.toString(isTUintern));
                        parameters.put("isUBintern", Boolean.toString(isUBintern));
                        parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                        parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8"));

                        ObjectMapper mapper = new ObjectMapper();
                        StringWriter json = new StringWriter();
                        mapper.writeValue(json, daia);
                        parameters.put("json", json.toString());

                        String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                                parameters);

                        response.setContentType("text/html;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);
                        response.getWriter().println(html);
                    } catch (PropertyException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                    }
                } else {

                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "Document not found.");
                }
            } else {

                this.logger.debug("format = " + format);

                // HTML-Ausgabe via XSLT
                if (format.equals("html")) {

                    try {

                        JAXBContext context = JAXBContext.newInstance(Daia.class);
                        Marshaller m = context.createMarshaller();
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                        // Write to HttpResponse
                        StringWriter stringWriter = new StringWriter();
                        m.marshal(daia, stringWriter);

                        org.jdom2.Document doc = new SAXBuilder()
                                .build(new StringReader(this.cleanup(stringWriter.toString())));

                        HashMap<String, String> parameters = new HashMap<String, String>();
                        parameters.put("lang", "de");
                        parameters.put("isTUintern", Boolean.toString(isTUintern));
                        parameters.put("isUBintern", Boolean.toString(isUBintern));
                        parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                        parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8"));

                        ObjectMapper mapper = new ObjectMapper();
                        StringWriter json = new StringWriter();
                        mapper.writeValue(json, daia);
                        parameters.put("json", json.toString());

                        String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                                parameters);

                        response.setContentType("text/html;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);
                        response.getWriter().println(html);
                    } catch (PropertyException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (JDOMException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (IOException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    }
                }

                // XML-Ausgabe mit JAXB
                if (format.equals("xml")) {

                    try {

                        JAXBContext context = JAXBContext.newInstance(Daia.class);
                        Marshaller m = context.createMarshaller();
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                        // Write to HttpResponse
                        response.setContentType("application/xml;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);
                        m.marshal(daia, response.getWriter());
                    } catch (PropertyException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    }
                }

                // JSON-Ausgabe mit Jackson
                if (format.equals("json")) {

                    ObjectMapper mapper = new ObjectMapper();

                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_OK);

                    mapper.writeValue(response.getWriter(), daia);
                }

                // RDF-Ausgabe mit XSLT auf XML-Ausgabe
                if (format.equals("rdf")) {

                    try {
                        JAXBContext context = JAXBContext.newInstance(Daia.class);
                        Marshaller m = context.createMarshaller();
                        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                        // Write to HttpResponse
                        response.setContentType("application/xml;charset=UTF-8");
                        response.setStatus(HttpServletResponse.SC_OK);

                        StringWriter xml = new StringWriter();
                        m.marshal(daia, xml);

                        XMLOutputter out = new XMLOutputter();
                        out.output(
                                new SAXBuilder().build(new StringReader(
                                        xmlOutputter(new SAXBuilder().build(new StringReader(xml.toString())),
                                                config.getProperty("xslt_xml2rdf"), null))),
                                response.getWriter());

                    } catch (JDOMException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (PropertyException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    } catch (JAXBException e) {
                        this.logger.error(e.getMessage(), e.getCause());
                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Internal Server Error: Error while rendering the results.");
                    }
                }
            }
        } else {

            this.logger.debug("404 Document Not Found + (format=" + format + ")");

            if (format.equals("html")) {

                try {

                    JAXBContext context = JAXBContext.newInstance(Daia.class);
                    Marshaller m = context.createMarshaller();
                    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                    // Write to HttpResponse
                    org.jdom2.Document doc = new org.jdom2.Document();
                    doc.setRootElement(new Element("daia"));

                    HashMap<String, String> parameters = new HashMap<String, String>();
                    parameters.put("lang", "de");
                    parameters.put("isTUintern", Boolean.toString(isTUintern));
                    parameters.put("isUBintern", Boolean.toString(isUBintern));
                    parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                    parameters.put("id", "openurl:" + URLDecoder.decode(openurl, "UTF-8"));

                    String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                            parameters);

                    response.setContentType("text/html;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.getWriter().println(html);
                } catch (PropertyException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                } catch (JAXBException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Internal Server Error: Error while rendering a HTML message. Message is 'Document not found'.");
                }
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Document not found.");
            }
        }
    } catch (Exception e) {

        this.logger.error("[DaiaService OpenUrl Endpoint] Exception: "
                + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable.");
        this.logger.error(e.getMessage(), e.getCause());
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            this.logger.error("\t" + stackTraceElement.toString());
        }

        Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf"));

        try {
            mailer.postMail("[DaiaService OpenUrl Endpoint] Exception: "
                    + HttpServletResponse.SC_SERVICE_UNAVAILABLE + " Service unavailable.",
                    e.getMessage() + "\n" + request.getRequestURL());

        } catch (MessagingException e1) {

            this.logger.error(e1.getMessage(), e1.getCause());
        }

        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Service unavailable.");
    }
}

From source file:base.BasePlayer.Main.java

public static void writeToConfig(String attribute) {
    Main.configChanged = true;/*from  w ww  .j a v  a  2  s. com*/
    Boolean found = false;

    for (int i = 0; i < Launcher.config.size(); i++) {

        if (Launcher.config.get(i).contains(attribute.subSequence(0, attribute.indexOf("=")))) {
            found = true;

            Launcher.config.set(i, attribute);
            break;
        }
    }
    if (!found) {
        Launcher.config.add(attribute);
    }

}

From source file:OSFFM_ORC.FederationActionManager.java

/**
 * This function is prepared for future usage it has the scope to add a
 * network segment inside Openstack in order to absolve at a FEDSDN calls.
 *
 * @param fu//from  ww  w.j av  a  2 s .co  m
 * @param OSF_network_segment_id
 * @param OSF_cloud
 * @param netParameter
 * @param federationTenant
 * @return
 * @throws Exception
 */
public JSONObject networkSegmentAdd(FederationUser fu, String OSF_network_segment_id, String OSF_cloud,
        HashMap netParameter, String federationTenant) throws Exception {
    DBMongo db = new DBMongo();
    JSONObject reply = new JSONObject();
    db.init();
    db.setDbName(federationTenant);
    db.connectLocale(db.getMdbIp());
    HashMap fum = this.getAllFederatedCloudCreds(fu);
    JSONObject network_info = new JSONObject(), network_infoGLOBAL = new JSONObject();
    JSONArray ja = new JSONArray();

    Set s = fum.keySet();
    OpenstackInfoContainer credential = null;
    NeutronTest neutron = null;
    Iterator i = s.iterator();
    FederatedUser fed_U = null;
    while (i.hasNext()) {
        try {
            //Momentaneamente viene implementata una gestione singola del cloud federato.
            //nel caso in cui si decider di gestire globalmente l'insieme dei cloud federati fare come indicato sotto, rimuovendo 
            ////l'if che controlla il cloud
            //////>>>BEACON: inserire gestione con array di thread ogni thread dovr:
            JSONObject fdu = (JSONObject) fum.get(i.next());
            if (!((String) fdu.get("federatedCloud")).equals(OSF_cloud)) {
                continue;
            }
            fed_U = new FederatedUser(fdu.toString());
            String federated_cmp_endp = (String) db
                    .getDatacenterFromId(fu.getUser(), (String) fdu.get("federatedCloud")).get("idmEndpoint");//TO BE VERIFIED
            credential = new OpenstackInfoContainer((String) fdu.get("federatedCloud"), federated_cmp_endp,
                    fu.getUser(), (String) fdu.get("federatedUser"), (String) fdu.get("federatedPassword"),
                    fed_U.getRegion());
            neutron = new NeutronTest(credential.getEndpoint(), credential.getTenant(), credential.getUser(),
                    credential.getPassword(), credential.getRegion());
        } catch (Exception e) {
            reply.put("returncode", 1);
            reply.put("errormesg", "USER_AUTHENTICATION_EXCEPTION: OPERATION ABORTED");
            reply.put("network_info", "null");
            LOGGER.error("USER_AUTHENTICATION_EXCEPTION: OPERATION ABORTED >>>[Token:" + fu.getToken()
                    + "]; No federated credential has found for selected parameters.");
            throw new Exception(reply.toString());
        }

        String cidr = "";
        boolean found = false, cidrPresent = false;
        String internalNetId = db.getInternalNetworkID(fu.getUser(), OSF_network_segment_id, fed_U.getCloud());
        if (internalNetId != null) {
            Networks N = neutron.listNetworks();
            Iterator<Network> iN = N.iterator();
            found = false;
            while (i.hasNext() && !found) {
                Network n = iN.next();
                if (internalNetId.equals(n.getId())) {
                    found = true;//nothing to do
                }
            }
            if (!found) {
                //this is the case when some info aren't aligned, the internal ID for netsegment are present but 
                //// no network is retrieved for tenant inside the cloud match it.
                //Inserire qui la chiamata relativa al Network Segment verso l'API "/fednet/{fednetId}/{site_id}/netsegment/{netsegment_id}"
                ////da cui ritrovare tutte le varie 
                //in alternativa creare le informazioni qui:
                HashMap th = new HashMap();
                th.put("netsegments", OSF_network_segment_id);
                org.json.JSONObject j = db.getcidrInfoes(fu.getUser(), th);
                if (j != null) {
                    //this is the case when a cidr is already defined for this fednet and FederationUser. That would mean that we have to create the 
                    ////other netsegments of the fednet with ther same parameters.                         
                    th = new HashMap();
                    th.put("netsegments", OSF_network_segment_id);
                    th.put("cloudId", fed_U.getCloud());
                    org.json.JSONObject j2 = db.getcidrInfoes(fu.getUser(), th);
                    if (j2 == null) {
                        //on mongo the netsegments searched is not found for this cloud then we will take the federation cidr
                        cidr = (String) j.get("cidr");
                    } else {
                        //disallineamento  presente un cidr ma non c' un internalId che corrisponda al netsegments
                        //sarebbe giusto creare un eccezione
                        throw new Exception(
                                "A problematic situation is founded! MongoDB information aren't alingned Contact the administrator!");
                    }
                } else {
                    //this is the case when on mongo the cidr for netsegments indicated is not found. This case represent first istantiation of the
                    ////netsegment for this fednet and FederationUser.   
                    cidrPresent = true;
                }
            } else {
                //match
                //nothing to do
            }

        } else {
            internalNetId = java.util.UUID.randomUUID().toString();
        }
        //prepare and retrieve information for creation of network
        Boolean dhcp = (Boolean) netParameter.get("dhcpEnable");
        if (dhcp == null) {
            dhcp = false;
        }
        Boolean shared = (Boolean) netParameter.get("shared");
        if (shared == null) {
            shared = false;
        }
        Boolean external = (Boolean) netParameter.get("external");
        if (external == null) {
            external = false;
        }
        Boolean adminStateUp = (Boolean) netParameter.get("adminStateUp");
        if (adminStateUp == null) {
            adminStateUp = false;
        }
        String subnetId = java.util.UUID.randomUUID().toString();
        if (!cidrPresent) {
            cidr = this.cidrgen();
        }
        HashMap allpo = this.calculateAllocationPool(cidr);
        SubnetUtils su = new SubnetUtils(cidr);
        SubnetInfo si = su.getInfo();
        String gwadd = si.getLowAddress();
        String fednets = "";//fednet;
        try {
            FunctionResponseContainer frc = neutron.createCompleteNetw(fed_U.getRegion(), internalNetId, cidr,
                    (String) allpo.get("allocationPoolStart"), (String) allpo.get("allocationPoolEnd"),
                    subnetId, gwadd, dhcp, fu.getUser(), shared, external, adminStateUp, fednets);

            //da frc. si possono ottenere le informazioni qui presenti 
            /*
             Network{id=258453f7-b655-4fbd-bee6-d1ac2d9fe7bc, 
             status=ACTIVE, 
             subnets=[], 
             name=ert, 
             adminStateUp=true, 
             shared=true, 
             tenantId=demo, 
             networkType=null,
             physicalNetworkName=null,
             segmentationId=null, 
             external=true, 
             portSecurity=null, 
             profileId=null,
             multicastIp=null, 
             segmentAdd=null, 
             segmentDel=null, 
             memberSegments=null, 
             segments=null, 
             networkFlavor=null}
             */
        } catch (Exception e) {
            LOGGER.error("Exception occurred in network creation operation!");
        }
        db.storeInternalNetworkID(fu.getUser(), OSF_network_segment_id, fed_U.getCloud(), internalNetId);
        db.insertcidrInfoes(fu.getUser(), cidr, fednets, OSF_network_segment_id, fed_U.getCloud());
        network_info = new JSONObject();
        network_info.put("cloudId", fed_U.getCloud());
        network_info.put("internalId", internalNetId);
        network_info.put("FedSDN_netSegId", OSF_network_segment_id);
        network_info.put("network_address", cidr.subSequence(0, cidr.indexOf("/")));
        network_info.put("network_mask", si.getNetmask());
        network_info.put("size", si.getAddressCount());
        ja.put(network_info);

    }
    network_infoGLOBAL.put("ResponseArray", ja);
    ///DECIDERE COME GESTIRE LE INFORMAZIONI: COSA RESTITUIRE AL FEDSDN 
    ////momentaneamente viene restituito un JSONarray con un solo elemento, quello della cloud indicata da OSF_cloud
    reply.put("returncode", 0);
    reply.put("errormesg", "None");
    reply.put("network_info", network_infoGLOBAL);

    return reply;

}

From source file:kr.wdream.storyshop.NotificationsController.java

private String getStringForMessage(MessageObject messageObject, boolean shortMessage) {
    long dialog_id = messageObject.messageOwner.dialog_id;
    int chat_id = messageObject.messageOwner.to_id.chat_id != 0 ? messageObject.messageOwner.to_id.chat_id
            : messageObject.messageOwner.to_id.channel_id;
    int from_id = messageObject.messageOwner.to_id.user_id;
    if (from_id == 0) {
        if (messageObject.isFromUser() || messageObject.getId() < 0) {
            from_id = messageObject.messageOwner.from_id;
        } else {// w ww.j ava 2s. c o m
            from_id = -chat_id;
        }
    } else if (from_id == UserConfig.getClientUserId()) {
        from_id = messageObject.messageOwner.from_id;
    }

    if (dialog_id == 0) {
        if (chat_id != 0) {
            dialog_id = -chat_id;
        } else if (from_id != 0) {
            dialog_id = from_id;
        }
    }

    String name = null;
    if (from_id > 0) {
        TLRPC.User user = MessagesController.getInstance().getUser(from_id);
        if (user != null) {
            name = UserObject.getUserName(user);
        }
    } else {
        TLRPC.Chat chat = MessagesController.getInstance().getChat(-from_id);
        if (chat != null) {
            name = chat.title;
        }
    }

    if (name == null) {
        return null;
    }
    TLRPC.Chat chat = null;
    if (chat_id != 0) {
        chat = MessagesController.getInstance().getChat(chat_id);
        if (chat == null) {
            return null;
        }
    }

    String msg = null;
    if ((int) dialog_id == 0 || AndroidUtilities.needShowPasscode(false)
            || UserConfig.isWaitingForPasscodeEnter) {
        msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
    } else {
        if (chat_id == 0 && from_id != 0) {
            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
            if (preferences.getBoolean("EnablePreviewAll", true)) {
                if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
                    if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined) {
                        msg = LocaleController.formatString("NotificationContactJoined",
                                R.string.NotificationContactJoined, name);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) {
                        msg = LocaleController.formatString("NotificationContactNewPhoto",
                                R.string.NotificationContactNewPhoto, name);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
                        String date = LocaleController.formatString("formatDateAtTime",
                                R.string.formatDateAtTime,
                                LocaleController.getInstance().formatterYear
                                        .format(((long) messageObject.messageOwner.date) * 1000),
                                LocaleController.getInstance().formatterDay
                                        .format(((long) messageObject.messageOwner.date) * 1000));
                        msg = LocaleController.formatString("NotificationUnrecognizedDevice",
                                R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name,
                                date, messageObject.messageOwner.action.title,
                                messageObject.messageOwner.action.address);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) {
                        msg = messageObject.messageText.toString();
                    }
                } else {
                    if (messageObject.isMediaEmpty()) {
                        if (!shortMessage) {
                            if (messageObject.messageOwner.message != null
                                    && messageObject.messageOwner.message.length() != 0) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        messageObject.messageOwner.message);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageNoText",
                                        R.string.NotificationMessageNoText, name);
                            }
                        } else {
                            msg = LocaleController.formatString("NotificationMessageNoText",
                                    R.string.NotificationMessageNoText, name);
                        }
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                        if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                            msg = LocaleController.formatString("NotificationMessageText",
                                    R.string.NotificationMessageText, name,
                                    "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                        } else {
                            msg = LocaleController.formatString("NotificationMessagePhoto",
                                    R.string.NotificationMessagePhoto, name);
                        }
                    } else if (messageObject.isVideo()) {
                        if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                            msg = LocaleController.formatString("NotificationMessageText",
                                    R.string.NotificationMessageText, name,
                                    "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                        } else {
                            msg = LocaleController.formatString("NotificationMessageVideo",
                                    R.string.NotificationMessageVideo, name);
                        }
                    } else if (messageObject.isGame()) {
                        msg = LocaleController.formatString("NotificationMessageGame",
                                R.string.NotificationMessageGame, name,
                                messageObject.messageOwner.media.game.title);
                    } else if (messageObject.isVoice()) {
                        msg = LocaleController.formatString("NotificationMessageAudio",
                                R.string.NotificationMessageAudio, name);
                    } else if (messageObject.isMusic()) {
                        msg = LocaleController.formatString("NotificationMessageMusic",
                                R.string.NotificationMessageMusic, name);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                        msg = LocaleController.formatString("NotificationMessageContact",
                                R.string.NotificationMessageContact, name);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                            || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                        msg = LocaleController.formatString("NotificationMessageMap",
                                R.string.NotificationMessageMap, name);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                        if (messageObject.isSticker()) {
                            String emoji = messageObject.getStickerEmoji();
                            if (emoji != null) {
                                msg = LocaleController.formatString("NotificationMessageStickerEmoji",
                                        R.string.NotificationMessageStickerEmoji, name, emoji);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageSticker",
                                        R.string.NotificationMessageSticker, name);
                            }
                        } else if (messageObject.isGif()) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGif",
                                        R.string.NotificationMessageGif, name);
                            }
                        } else {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageDocument",
                                        R.string.NotificationMessageDocument, name);
                            }
                        }
                    }
                }
            } else {
                msg = LocaleController.formatString("NotificationMessageNoText",
                        R.string.NotificationMessageNoText, name);
            }
        } else if (chat_id != 0) {
            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
            if (preferences.getBoolean("EnablePreviewGroup", true)) {
                if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
                    if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) {
                        int singleUserId = messageObject.messageOwner.action.user_id;
                        if (singleUserId == 0 && messageObject.messageOwner.action.users.size() == 1) {
                            singleUserId = messageObject.messageOwner.action.users.get(0);
                        }
                        if (singleUserId != 0) {
                            if (messageObject.messageOwner.to_id.channel_id != 0 && !chat.megagroup) {
                                msg = LocaleController.formatString("ChannelAddedByNotification",
                                        R.string.ChannelAddedByNotification, name, chat.title);
                            } else {
                                if (singleUserId == UserConfig.getClientUserId()) {
                                    msg = LocaleController.formatString("NotificationInvitedToGroup",
                                            R.string.NotificationInvitedToGroup, name, chat.title);
                                } else {
                                    TLRPC.User u2 = MessagesController.getInstance().getUser(singleUserId);
                                    if (u2 == null) {
                                        return null;
                                    }
                                    if (from_id == u2.id) {
                                        if (chat.megagroup) {
                                            msg = LocaleController.formatString("NotificationGroupAddSelfMega",
                                                    R.string.NotificationGroupAddSelfMega, name, chat.title);
                                        } else {
                                            msg = LocaleController.formatString("NotificationGroupAddSelf",
                                                    R.string.NotificationGroupAddSelf, name, chat.title);
                                        }
                                    } else {
                                        msg = LocaleController.formatString("NotificationGroupAddMember",
                                                R.string.NotificationGroupAddMember, name, chat.title,
                                                UserObject.getUserName(u2));
                                    }
                                }
                            }
                        } else {
                            StringBuilder names = new StringBuilder("");
                            for (int a = 0; a < messageObject.messageOwner.action.users.size(); a++) {
                                TLRPC.User user = MessagesController.getInstance()
                                        .getUser(messageObject.messageOwner.action.users.get(a));
                                if (user != null) {
                                    String name2 = UserObject.getUserName(user);
                                    if (names.length() != 0) {
                                        names.append(", ");
                                    }
                                    names.append(name2);
                                }
                            }
                            msg = LocaleController.formatString("NotificationGroupAddMember",
                                    R.string.NotificationGroupAddMember, name, chat.title, names.toString());
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByLink) {
                        msg = LocaleController.formatString("NotificationInvitedToGroupByLink",
                                R.string.NotificationInvitedToGroupByLink, name, chat.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditTitle) {
                        msg = LocaleController.formatString("NotificationEditedGroupName",
                                R.string.NotificationEditedGroupName, name,
                                messageObject.messageOwner.action.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto
                            || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeletePhoto) {
                        if (messageObject.messageOwner.to_id.channel_id != 0 && !chat.megagroup) {
                            msg = LocaleController.formatString("ChannelPhotoEditNotification",
                                    R.string.ChannelPhotoEditNotification, chat.title);
                        } else {
                            msg = LocaleController.formatString("NotificationEditedGroupPhoto",
                                    R.string.NotificationEditedGroupPhoto, name, chat.title);
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) {
                        if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) {
                            msg = LocaleController.formatString("NotificationGroupKickYou",
                                    R.string.NotificationGroupKickYou, name, chat.title);
                        } else if (messageObject.messageOwner.action.user_id == from_id) {
                            msg = LocaleController.formatString("NotificationGroupLeftMember",
                                    R.string.NotificationGroupLeftMember, name, chat.title);
                        } else {
                            TLRPC.User u2 = MessagesController.getInstance()
                                    .getUser(messageObject.messageOwner.action.user_id);
                            if (u2 == null) {
                                return null;
                            }
                            msg = LocaleController.formatString("NotificationGroupKickMember",
                                    R.string.NotificationGroupKickMember, name, chat.title,
                                    UserObject.getUserName(u2));
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatCreate) {
                        msg = messageObject.messageText.toString();
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChannelCreate) {
                        msg = messageObject.messageText.toString();
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                        msg = LocaleController.formatString("ActionMigrateFromGroupNotify",
                                R.string.ActionMigrateFromGroupNotify, chat.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom) {
                        msg = LocaleController.formatString("ActionMigrateFromGroupNotify",
                                R.string.ActionMigrateFromGroupNotify, messageObject.messageOwner.action.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) {
                        if (messageObject.replyMessageObject == null) {
                            if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                msg = LocaleController.formatString("NotificationActionPinnedNoText",
                                        R.string.NotificationActionPinnedNoText, name, chat.title);
                            } else {
                                msg = LocaleController.formatString("NotificationActionPinnedNoTextChannel",
                                        R.string.NotificationActionPinnedNoTextChannel, name, chat.title);
                            }
                        } else {
                            MessageObject object = messageObject.replyMessageObject;
                            if (object.isMusic()) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedMusic",
                                            R.string.NotificationActionPinnedMusic, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedMusicChannel",
                                            R.string.NotificationActionPinnedMusicChannel, chat.title);
                                }
                            } else if (object.isVideo()) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83D\uDCF9 " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedVideo",
                                                R.string.NotificationActionPinnedVideo, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedVideoChannel",
                                                R.string.NotificationActionPinnedVideoChannel, chat.title);
                                    }
                                }
                            } else if (object.isGif()) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83C\uDFAC " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedGif",
                                                R.string.NotificationActionPinnedGif, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedGifChannel",
                                                R.string.NotificationActionPinnedGifChannel, chat.title);
                                    }
                                }
                            } else if (object.isVoice()) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedVoice",
                                            R.string.NotificationActionPinnedVoice, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedVoiceChannel",
                                            R.string.NotificationActionPinnedVoiceChannel, chat.title);
                                }
                            } else if (object.isSticker()) {
                                String emoji = messageObject.getStickerEmoji();
                                if (emoji != null) {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedStickerEmoji",
                                                R.string.NotificationActionPinnedStickerEmoji, name, chat.title,
                                                emoji);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedStickerEmojiChannel",
                                                R.string.NotificationActionPinnedStickerEmojiChannel,
                                                chat.title, emoji);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedSticker",
                                                R.string.NotificationActionPinnedSticker, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedStickerChannel",
                                                R.string.NotificationActionPinnedStickerChannel, chat.title);
                                    }
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83D\uDCCE " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedFile",
                                                R.string.NotificationActionPinnedFile, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedFileChannel",
                                                R.string.NotificationActionPinnedFileChannel, chat.title);
                                    }
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedGeo",
                                            R.string.NotificationActionPinnedGeo, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedGeoChannel",
                                            R.string.NotificationActionPinnedGeoChannel, chat.title);
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedContact",
                                            R.string.NotificationActionPinnedContact, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString(
                                            "NotificationActionPinnedContactChannel",
                                            R.string.NotificationActionPinnedContactChannel, chat.title);
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83D\uDDBC " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedPhoto",
                                                R.string.NotificationActionPinnedPhoto, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedPhotoChannel",
                                                R.string.NotificationActionPinnedPhotoChannel, chat.title);
                                    }
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedGame",
                                            R.string.NotificationActionPinnedGame, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedGameChannel",
                                            R.string.NotificationActionPinnedGameChannel, chat.title);
                                }
                            } else if (object.messageText != null && object.messageText.length() > 0) {
                                CharSequence message = object.messageText;
                                if (message.length() > 20) {
                                    message = message.subSequence(0, 20) + "...";
                                }
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedText",
                                            R.string.NotificationActionPinnedText, name, message, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedTextChannel",
                                            R.string.NotificationActionPinnedTextChannel, chat.title, message);
                                }
                            } else {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedNoText",
                                            R.string.NotificationActionPinnedNoText, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedNoTextChannel",
                                            R.string.NotificationActionPinnedNoTextChannel, chat.title);
                                }
                            }
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) {
                        msg = messageObject.messageText.toString();
                    }
                } else {
                    if (ChatObject.isChannel(chat) && !chat.megagroup) {
                        if (messageObject.messageOwner.post) {
                            if (messageObject.isMediaEmpty()) {
                                if (!shortMessage && messageObject.messageOwner.message != null
                                        && messageObject.messageOwner.message.length() != 0) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            messageObject.messageOwner.message);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageNoText",
                                            R.string.ChannelMessageNoText, name, chat.title);
                                }
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessagePhoto",
                                            R.string.ChannelMessagePhoto, name, chat.title);
                                }
                            } else if (messageObject.isVideo()) {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageVideo",
                                            R.string.ChannelMessageVideo, name, chat.title);
                                }
                            } else if (messageObject.isVoice()) {
                                msg = LocaleController.formatString("ChannelMessageAudio",
                                        R.string.ChannelMessageAudio, name, chat.title);
                            } else if (messageObject.isMusic()) {
                                msg = LocaleController.formatString("ChannelMessageMusic",
                                        R.string.ChannelMessageMusic, name, chat.title);
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                                msg = LocaleController.formatString("ChannelMessageContact",
                                        R.string.ChannelMessageContact, name, chat.title);
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                                    || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                                msg = LocaleController.formatString("ChannelMessageMap",
                                        R.string.ChannelMessageMap, name, chat.title);
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                                if (messageObject.isSticker()) {
                                    String emoji = messageObject.getStickerEmoji();
                                    if (emoji != null) {
                                        msg = LocaleController.formatString("ChannelMessageStickerEmoji",
                                                R.string.ChannelMessageStickerEmoji, name, chat.title, emoji);
                                    } else {
                                        msg = LocaleController.formatString("ChannelMessageSticker",
                                                R.string.ChannelMessageSticker, name, chat.title);
                                    }
                                } else if (messageObject.isGif()) {
                                    if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                            && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                        msg = LocaleController.formatString("NotificationMessageGroupText",
                                                R.string.NotificationMessageGroupText, name, chat.title,
                                                "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                                    } else {
                                        msg = LocaleController.formatString("ChannelMessageGIF",
                                                R.string.ChannelMessageGIF, name, chat.title);
                                    }
                                } else {
                                    if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                            && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                        msg = LocaleController.formatString("NotificationMessageGroupText",
                                                R.string.NotificationMessageGroupText, name, chat.title,
                                                "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                                    } else {
                                        msg = LocaleController.formatString("ChannelMessageDocument",
                                                R.string.ChannelMessageDocument, name, chat.title);
                                    }
                                }
                            }
                        } else {
                            if (messageObject.isMediaEmpty()) {
                                if (!shortMessage && messageObject.messageOwner.message != null
                                        && messageObject.messageOwner.message.length() != 0) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            messageObject.messageOwner.message);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageGroupNoText",
                                            R.string.ChannelMessageGroupNoText, name, chat.title);
                                }
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageGroupPhoto",
                                            R.string.ChannelMessageGroupPhoto, name, chat.title);
                                }
                            } else if (messageObject.isVideo()) {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageGroupVideo",
                                            R.string.ChannelMessageGroupVideo, name, chat.title);
                                }
                            } else if (messageObject.isVoice()) {
                                msg = LocaleController.formatString("ChannelMessageGroupAudio",
                                        R.string.ChannelMessageGroupAudio, name, chat.title);
                            } else if (messageObject.isMusic()) {
                                msg = LocaleController.formatString("ChannelMessageGroupMusic",
                                        R.string.ChannelMessageGroupMusic, name, chat.title);
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                                msg = LocaleController.formatString("ChannelMessageGroupContact",
                                        R.string.ChannelMessageGroupContact, name, chat.title);
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                                    || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                                msg = LocaleController.formatString("ChannelMessageGroupMap",
                                        R.string.ChannelMessageGroupMap, name, chat.title);
                            } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                                if (messageObject.isSticker()) {
                                    String emoji = messageObject.getStickerEmoji();
                                    if (emoji != null) {
                                        msg = LocaleController.formatString("ChannelMessageGroupStickerEmoji",
                                                R.string.ChannelMessageGroupStickerEmoji, name, chat.title,
                                                emoji);
                                    } else {
                                        msg = LocaleController.formatString("ChannelMessageGroupSticker",
                                                R.string.ChannelMessageGroupSticker, name, chat.title);
                                    }
                                } else if (messageObject.isGif()) {
                                    if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                            && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                        msg = LocaleController.formatString("NotificationMessageGroupText",
                                                R.string.NotificationMessageGroupText, name, chat.title,
                                                "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                                    } else {
                                        msg = LocaleController.formatString("ChannelMessageGroupGif",
                                                R.string.ChannelMessageGroupGif, name, chat.title);
                                    }
                                } else {
                                    if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                            && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                        msg = LocaleController.formatString("NotificationMessageGroupText",
                                                R.string.NotificationMessageGroupText, name, chat.title,
                                                "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                                    } else {
                                        msg = LocaleController.formatString("ChannelMessageGroupDocument",
                                                R.string.ChannelMessageGroupDocument, name, chat.title);
                                    }
                                }
                            }
                        }
                    } else {
                        if (messageObject.isMediaEmpty()) {
                            if (!shortMessage && messageObject.messageOwner.message != null
                                    && messageObject.messageOwner.message.length() != 0) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        messageObject.messageOwner.message);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGroupNoText",
                                        R.string.NotificationMessageGroupNoText, name, chat.title);
                            }
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGroupPhoto",
                                        R.string.NotificationMessageGroupPhoto, name, chat.title);
                            }
                        } else if (messageObject.isVideo()) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGroupVideo",
                                        R.string.NotificationMessageGroupVideo, name, chat.title);
                            }
                        } else if (messageObject.isVoice()) {
                            msg = LocaleController.formatString("NotificationMessageGroupAudio",
                                    R.string.NotificationMessageGroupAudio, name, chat.title);
                        } else if (messageObject.isMusic()) {
                            msg = LocaleController.formatString("NotificationMessageGroupMusic",
                                    R.string.NotificationMessageGroupMusic, name, chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                            msg = LocaleController.formatString("NotificationMessageGroupContact",
                                    R.string.NotificationMessageGroupContact, name, chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                            msg = LocaleController.formatString("NotificationMessageGroupGame",
                                    R.string.NotificationMessageGroupGame, name, chat.title,
                                    messageObject.messageOwner.media.game.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                                || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                            msg = LocaleController.formatString("NotificationMessageGroupMap",
                                    R.string.NotificationMessageGroupMap, name, chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                            if (messageObject.isSticker()) {
                                String emoji = messageObject.getStickerEmoji();
                                if (emoji != null) {
                                    msg = LocaleController.formatString("NotificationMessageGroupStickerEmoji",
                                            R.string.NotificationMessageGroupStickerEmoji, name, chat.title,
                                            emoji);
                                } else {
                                    msg = LocaleController.formatString("NotificationMessageGroupSticker",
                                            R.string.NotificationMessageGroupSticker, name, chat.title);
                                }
                            } else if (messageObject.isGif()) {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("NotificationMessageGroupGif",
                                            R.string.NotificationMessageGroupGif, name, chat.title);
                                }
                            } else {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("NotificationMessageGroupDocument",
                                            R.string.NotificationMessageGroupDocument, name, chat.title);
                                }
                            }
                        }
                    }
                }
            } else {
                if (ChatObject.isChannel(chat) && !chat.megagroup) {
                    msg = LocaleController.formatString("ChannelMessageNoText", R.string.ChannelMessageNoText,
                            name, chat.title);
                } else {
                    msg = LocaleController.formatString("NotificationMessageGroupNoText",
                            R.string.NotificationMessageGroupNoText, name, chat.title);
                }
            }
        }
    }
    return msg;
}

From source file:com.ferdi2005.secondgram.NotificationsController.java

private String getStringForMessage(MessageObject messageObject, boolean shortMessage) {
    long dialog_id = messageObject.messageOwner.dialog_id;
    int chat_id = messageObject.messageOwner.to_id.chat_id != 0 ? messageObject.messageOwner.to_id.chat_id
            : messageObject.messageOwner.to_id.channel_id;
    int from_id = messageObject.messageOwner.to_id.user_id;
    if (from_id == 0) {
        if (messageObject.isFromUser() || messageObject.getId() < 0) {
            from_id = messageObject.messageOwner.from_id;
        } else {/*from  www . ja va2 s  .  com*/
            from_id = -chat_id;
        }
    } else if (from_id == UserConfig.getClientUserId()) {
        from_id = messageObject.messageOwner.from_id;
    }

    if (dialog_id == 0) {
        if (chat_id != 0) {
            dialog_id = -chat_id;
        } else if (from_id != 0) {
            dialog_id = from_id;
        }
    }

    String name = null;
    if (from_id > 0) {
        TLRPC.User user = MessagesController.getInstance().getUser(from_id);
        if (user != null) {
            name = UserObject.getUserName(user);
        }
    } else {
        TLRPC.Chat chat = MessagesController.getInstance().getChat(-from_id);
        if (chat != null) {
            name = chat.title;
        }
    }

    if (name == null) {
        return null;
    }
    TLRPC.Chat chat = null;
    if (chat_id != 0) {
        chat = MessagesController.getInstance().getChat(chat_id);
        if (chat == null) {
            return null;
        }
    }

    String msg = null;
    if ((int) dialog_id == 0 || AndroidUtilities.needShowPasscode(false)
            || UserConfig.isWaitingForPasscodeEnter) {
        msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
    } else {
        if (chat_id == 0 && from_id != 0) {
            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
            if (preferences.getBoolean("EnablePreviewAll", true)) {
                if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
                    if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserJoined) {
                        msg = LocaleController.formatString("NotificationContactJoined",
                                R.string.NotificationContactJoined, name);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) {
                        msg = LocaleController.formatString("NotificationContactNewPhoto",
                                R.string.NotificationContactNewPhoto, name);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
                        String date = LocaleController.formatString("formatDateAtTime",
                                R.string.formatDateAtTime,
                                LocaleController.getInstance().formatterYear
                                        .format(((long) messageObject.messageOwner.date) * 1000),
                                LocaleController.getInstance().formatterDay
                                        .format(((long) messageObject.messageOwner.date) * 1000));
                        msg = LocaleController.formatString("NotificationUnrecognizedDevice",
                                R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name,
                                date, messageObject.messageOwner.action.title,
                                messageObject.messageOwner.action.address);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore
                            || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPaymentSent) {
                        msg = messageObject.messageText.toString();
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPhoneCall) {
                        TLRPC.PhoneCallDiscardReason reason = messageObject.messageOwner.action.reason;
                        if (!messageObject.isOut()
                                && (reason instanceof TLRPC.TL_phoneCallDiscardReasonMissed)) {
                            msg = LocaleController.getString("CallMessageIncomingMissed",
                                    R.string.CallMessageIncomingMissed);
                        }
                    }
                } else {
                    if (messageObject.isMediaEmpty()) {
                        if (!shortMessage) {
                            if (messageObject.messageOwner.message != null
                                    && messageObject.messageOwner.message.length() != 0) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        messageObject.messageOwner.message);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageNoText",
                                        R.string.NotificationMessageNoText, name);
                            }
                        } else {
                            msg = LocaleController.formatString("NotificationMessageNoText",
                                    R.string.NotificationMessageNoText, name);
                        }
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                        if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                            msg = LocaleController.formatString("NotificationMessageText",
                                    R.string.NotificationMessageText, name,
                                    "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                        } else {
                            msg = LocaleController.formatString("NotificationMessagePhoto",
                                    R.string.NotificationMessagePhoto, name);
                        }
                    } else if (messageObject.isVideo()) {
                        if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                            msg = LocaleController.formatString("NotificationMessageText",
                                    R.string.NotificationMessageText, name,
                                    "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                        } else {
                            msg = LocaleController.formatString("NotificationMessageVideo",
                                    R.string.NotificationMessageVideo, name);
                        }
                    } else if (messageObject.isGame()) {
                        msg = LocaleController.formatString("NotificationMessageGame",
                                R.string.NotificationMessageGame, name,
                                messageObject.messageOwner.media.game.title);
                    } else if (messageObject.isVoice()) {
                        msg = LocaleController.formatString("NotificationMessageAudio",
                                R.string.NotificationMessageAudio, name);
                    } else if (messageObject.isMusic()) {
                        msg = LocaleController.formatString("NotificationMessageMusic",
                                R.string.NotificationMessageMusic, name);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                        msg = LocaleController.formatString("NotificationMessageContact",
                                R.string.NotificationMessageContact, name);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                            || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                        msg = LocaleController.formatString("NotificationMessageMap",
                                R.string.NotificationMessageMap, name);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                        if (messageObject.isSticker()) {
                            String emoji = messageObject.getStickerEmoji();
                            if (emoji != null) {
                                msg = LocaleController.formatString("NotificationMessageStickerEmoji",
                                        R.string.NotificationMessageStickerEmoji, name, emoji);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageSticker",
                                        R.string.NotificationMessageSticker, name);
                            }
                        } else if (messageObject.isGif()) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGif",
                                        R.string.NotificationMessageGif, name);
                            }
                        } else {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageDocument",
                                        R.string.NotificationMessageDocument, name);
                            }
                        }
                    }
                }
            } else {
                msg = LocaleController.formatString("NotificationMessageNoText",
                        R.string.NotificationMessageNoText, name);
            }
        } else if (chat_id != 0) {
            SharedPreferences preferences = ApplicationLoader.applicationContext
                    .getSharedPreferences("Notifications", Context.MODE_PRIVATE);
            if (preferences.getBoolean("EnablePreviewGroup", true)) {
                if (messageObject.messageOwner instanceof TLRPC.TL_messageService) {
                    if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser) {
                        int singleUserId = messageObject.messageOwner.action.user_id;
                        if (singleUserId == 0 && messageObject.messageOwner.action.users.size() == 1) {
                            singleUserId = messageObject.messageOwner.action.users.get(0);
                        }
                        if (singleUserId != 0) {
                            if (messageObject.messageOwner.to_id.channel_id != 0 && !chat.megagroup) {
                                msg = LocaleController.formatString("ChannelAddedByNotification",
                                        R.string.ChannelAddedByNotification, name, chat.title);
                            } else {
                                if (singleUserId == UserConfig.getClientUserId()) {
                                    msg = LocaleController.formatString("NotificationInvitedToGroup",
                                            R.string.NotificationInvitedToGroup, name, chat.title);
                                } else {
                                    TLRPC.User u2 = MessagesController.getInstance().getUser(singleUserId);
                                    if (u2 == null) {
                                        return null;
                                    }
                                    if (from_id == u2.id) {
                                        if (chat.megagroup) {
                                            msg = LocaleController.formatString("NotificationGroupAddSelfMega",
                                                    R.string.NotificationGroupAddSelfMega, name, chat.title);
                                        } else {
                                            msg = LocaleController.formatString("NotificationGroupAddSelf",
                                                    R.string.NotificationGroupAddSelf, name, chat.title);
                                        }
                                    } else {
                                        msg = LocaleController.formatString("NotificationGroupAddMember",
                                                R.string.NotificationGroupAddMember, name, chat.title,
                                                UserObject.getUserName(u2));
                                    }
                                }
                            }
                        } else {
                            StringBuilder names = new StringBuilder("");
                            for (int a = 0; a < messageObject.messageOwner.action.users.size(); a++) {
                                TLRPC.User user = MessagesController.getInstance()
                                        .getUser(messageObject.messageOwner.action.users.get(a));
                                if (user != null) {
                                    String name2 = UserObject.getUserName(user);
                                    if (names.length() != 0) {
                                        names.append(", ");
                                    }
                                    names.append(name2);
                                }
                            }
                            msg = LocaleController.formatString("NotificationGroupAddMember",
                                    R.string.NotificationGroupAddMember, name, chat.title, names.toString());
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatJoinedByLink) {
                        msg = LocaleController.formatString("NotificationInvitedToGroupByLink",
                                R.string.NotificationInvitedToGroupByLink, name, chat.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditTitle) {
                        msg = LocaleController.formatString("NotificationEditedGroupName",
                                R.string.NotificationEditedGroupName, name,
                                messageObject.messageOwner.action.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto
                            || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeletePhoto) {
                        if (messageObject.messageOwner.to_id.channel_id != 0 && !chat.megagroup) {
                            msg = LocaleController.formatString("ChannelPhotoEditNotification",
                                    R.string.ChannelPhotoEditNotification, chat.title);
                        } else {
                            msg = LocaleController.formatString("NotificationEditedGroupPhoto",
                                    R.string.NotificationEditedGroupPhoto, name, chat.title);
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser) {
                        if (messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()) {
                            msg = LocaleController.formatString("NotificationGroupKickYou",
                                    R.string.NotificationGroupKickYou, name, chat.title);
                        } else if (messageObject.messageOwner.action.user_id == from_id) {
                            msg = LocaleController.formatString("NotificationGroupLeftMember",
                                    R.string.NotificationGroupLeftMember, name, chat.title);
                        } else {
                            TLRPC.User u2 = MessagesController.getInstance()
                                    .getUser(messageObject.messageOwner.action.user_id);
                            if (u2 == null) {
                                return null;
                            }
                            msg = LocaleController.formatString("NotificationGroupKickMember",
                                    R.string.NotificationGroupKickMember, name, chat.title,
                                    UserObject.getUserName(u2));
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatCreate) {
                        msg = messageObject.messageText.toString();
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChannelCreate) {
                        msg = messageObject.messageText.toString();
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                        msg = LocaleController.formatString("ActionMigrateFromGroupNotify",
                                R.string.ActionMigrateFromGroupNotify, chat.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChannelMigrateFrom) {
                        msg = LocaleController.formatString("ActionMigrateFromGroupNotify",
                                R.string.ActionMigrateFromGroupNotify, messageObject.messageOwner.action.title);
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) {
                        if (messageObject.replyMessageObject == null) {
                            if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                msg = LocaleController.formatString("NotificationActionPinnedNoText",
                                        R.string.NotificationActionPinnedNoText, name, chat.title);
                            } else {
                                msg = LocaleController.formatString("NotificationActionPinnedNoTextChannel",
                                        R.string.NotificationActionPinnedNoTextChannel, name, chat.title);
                            }
                        } else {
                            MessageObject object = messageObject.replyMessageObject;
                            if (object.isMusic()) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedMusic",
                                            R.string.NotificationActionPinnedMusic, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedMusicChannel",
                                            R.string.NotificationActionPinnedMusicChannel, chat.title);
                                }
                            } else if (object.isVideo()) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83D\uDCF9 " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedVideo",
                                                R.string.NotificationActionPinnedVideo, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedVideoChannel",
                                                R.string.NotificationActionPinnedVideoChannel, chat.title);
                                    }
                                }
                            } else if (object.isGif()) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83C\uDFAC " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedGif",
                                                R.string.NotificationActionPinnedGif, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedGifChannel",
                                                R.string.NotificationActionPinnedGifChannel, chat.title);
                                    }
                                }
                            } else if (object.isVoice()) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedVoice",
                                            R.string.NotificationActionPinnedVoice, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedVoiceChannel",
                                            R.string.NotificationActionPinnedVoiceChannel, chat.title);
                                }
                            } else if (object.isSticker()) {
                                String emoji = messageObject.getStickerEmoji();
                                if (emoji != null) {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedStickerEmoji",
                                                R.string.NotificationActionPinnedStickerEmoji, name, chat.title,
                                                emoji);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedStickerEmojiChannel",
                                                R.string.NotificationActionPinnedStickerEmojiChannel,
                                                chat.title, emoji);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedSticker",
                                                R.string.NotificationActionPinnedSticker, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedStickerChannel",
                                                R.string.NotificationActionPinnedStickerChannel, chat.title);
                                    }
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83D\uDCCE " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedFile",
                                                R.string.NotificationActionPinnedFile, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedFileChannel",
                                                R.string.NotificationActionPinnedFileChannel, chat.title);
                                    }
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaGeo) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedGeo",
                                            R.string.NotificationActionPinnedGeo, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedGeoChannel",
                                            R.string.NotificationActionPinnedGeoChannel, chat.title);
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedContact",
                                            R.string.NotificationActionPinnedContact, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString(
                                            "NotificationActionPinnedContactChannel",
                                            R.string.NotificationActionPinnedContactChannel, chat.title);
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                                if (Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(object.messageOwner.media.caption)) {
                                    String message = "\uD83D\uDDBC " + object.messageOwner.media.caption;
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedText",
                                                R.string.NotificationActionPinnedText, name, message,
                                                chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedTextChannel",
                                                R.string.NotificationActionPinnedTextChannel, chat.title,
                                                message);
                                    }
                                } else {
                                    if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                        msg = LocaleController.formatString("NotificationActionPinnedPhoto",
                                                R.string.NotificationActionPinnedPhoto, name, chat.title);
                                    } else {
                                        msg = LocaleController.formatString(
                                                "NotificationActionPinnedPhotoChannel",
                                                R.string.NotificationActionPinnedPhotoChannel, chat.title);
                                    }
                                }
                            } else if (object.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedGame",
                                            R.string.NotificationActionPinnedGame, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedGameChannel",
                                            R.string.NotificationActionPinnedGameChannel, chat.title);
                                }
                            } else if (object.messageText != null && object.messageText.length() > 0) {
                                CharSequence message = object.messageText;
                                if (message.length() > 20) {
                                    message = message.subSequence(0, 20) + "...";
                                }
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedText",
                                            R.string.NotificationActionPinnedText, name, message, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedTextChannel",
                                            R.string.NotificationActionPinnedTextChannel, chat.title, message);
                                }
                            } else {
                                if (!ChatObject.isChannel(chat) || chat.megagroup) {
                                    msg = LocaleController.formatString("NotificationActionPinnedNoText",
                                            R.string.NotificationActionPinnedNoText, name, chat.title);
                                } else {
                                    msg = LocaleController.formatString("NotificationActionPinnedNoTextChannel",
                                            R.string.NotificationActionPinnedNoTextChannel, chat.title);
                                }
                            }
                        }
                    } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) {
                        msg = messageObject.messageText.toString();
                    }
                } else if (ChatObject.isChannel(chat) && !chat.megagroup) {
                    if (messageObject.messageOwner.post) {
                        if (messageObject.isMediaEmpty()) {
                            if (!shortMessage && messageObject.messageOwner.message != null
                                    && messageObject.messageOwner.message.length() != 0) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        messageObject.messageOwner.message);
                            } else {
                                msg = LocaleController.formatString("ChannelMessageNoText",
                                        R.string.ChannelMessageNoText, name);
                            }
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("ChannelMessagePhoto",
                                        R.string.ChannelMessagePhoto, name);
                            }
                        } else if (messageObject.isVideo()) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageText",
                                        R.string.NotificationMessageText, name,
                                        "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("ChannelMessageVideo",
                                        R.string.ChannelMessageVideo, name);
                            }
                        } else if (messageObject.isVoice()) {
                            msg = LocaleController.formatString("ChannelMessageAudio",
                                    R.string.ChannelMessageAudio, name);
                        } else if (messageObject.isMusic()) {
                            msg = LocaleController.formatString("ChannelMessageMusic",
                                    R.string.ChannelMessageMusic, name);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                            msg = LocaleController.formatString("ChannelMessageContact",
                                    R.string.ChannelMessageContact, name);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                                || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                            msg = LocaleController.formatString("ChannelMessageMap", R.string.ChannelMessageMap,
                                    name);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                            if (messageObject.isSticker()) {
                                String emoji = messageObject.getStickerEmoji();
                                if (emoji != null) {
                                    msg = LocaleController.formatString("ChannelMessageStickerEmoji",
                                            R.string.ChannelMessageStickerEmoji, name, emoji);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageSticker",
                                            R.string.ChannelMessageSticker, name);
                                }
                            } else if (messageObject.isGif()) {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageText",
                                            R.string.NotificationMessageText, name,
                                            "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageGIF",
                                            R.string.ChannelMessageGIF, name);
                                }
                            } else {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageText",
                                            R.string.NotificationMessageText, name,
                                            "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageDocument",
                                            R.string.ChannelMessageDocument, name);
                                }
                            }
                        }
                    } else {
                        if (messageObject.isMediaEmpty()) {
                            if (!shortMessage && messageObject.messageOwner.message != null
                                    && messageObject.messageOwner.message.length() != 0) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        messageObject.messageOwner.message);
                            } else {
                                msg = LocaleController.formatString("ChannelMessageGroupNoText",
                                        R.string.ChannelMessageGroupNoText, name, chat.title);
                            }
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("ChannelMessageGroupPhoto",
                                        R.string.ChannelMessageGroupPhoto, name, chat.title);
                            }
                        } else if (messageObject.isVideo()) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("ChannelMessageGroupVideo",
                                        R.string.ChannelMessageGroupVideo, name, chat.title);
                            }
                        } else if (messageObject.isVoice()) {
                            msg = LocaleController.formatString("ChannelMessageGroupAudio",
                                    R.string.ChannelMessageGroupAudio, name, chat.title);
                        } else if (messageObject.isMusic()) {
                            msg = LocaleController.formatString("ChannelMessageGroupMusic",
                                    R.string.ChannelMessageGroupMusic, name, chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                            msg = LocaleController.formatString("ChannelMessageGroupContact",
                                    R.string.ChannelMessageGroupContact, name, chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                                || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                            msg = LocaleController.formatString("ChannelMessageGroupMap",
                                    R.string.ChannelMessageGroupMap, name, chat.title);
                        } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                            if (messageObject.isSticker()) {
                                String emoji = messageObject.getStickerEmoji();
                                if (emoji != null) {
                                    msg = LocaleController.formatString("ChannelMessageGroupStickerEmoji",
                                            R.string.ChannelMessageGroupStickerEmoji, name, chat.title, emoji);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageGroupSticker",
                                            R.string.ChannelMessageGroupSticker, name, chat.title);
                                }
                            } else if (messageObject.isGif()) {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageGroupGif",
                                            R.string.ChannelMessageGroupGif, name, chat.title);
                                }
                            } else {
                                if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                        && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                    msg = LocaleController.formatString("NotificationMessageGroupText",
                                            R.string.NotificationMessageGroupText, name, chat.title,
                                            "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                                } else {
                                    msg = LocaleController.formatString("ChannelMessageGroupDocument",
                                            R.string.ChannelMessageGroupDocument, name, chat.title);
                                }
                            }
                        }
                    }
                } else {
                    if (messageObject.isMediaEmpty()) {
                        if (!shortMessage && messageObject.messageOwner.message != null
                                && messageObject.messageOwner.message.length() != 0) {
                            msg = LocaleController.formatString("NotificationMessageGroupText",
                                    R.string.NotificationMessageGroupText, name, chat.title,
                                    messageObject.messageOwner.message);
                        } else {
                            msg = LocaleController.formatString("NotificationMessageGroupNoText",
                                    R.string.NotificationMessageGroupNoText, name, chat.title);
                        }
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
                        if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                            msg = LocaleController.formatString("NotificationMessageGroupText",
                                    R.string.NotificationMessageGroupText, name, chat.title,
                                    "\uD83D\uDDBC " + messageObject.messageOwner.media.caption);
                        } else {
                            msg = LocaleController.formatString("NotificationMessageGroupPhoto",
                                    R.string.NotificationMessageGroupPhoto, name, chat.title);
                        }
                    } else if (messageObject.isVideo()) {
                        if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                            msg = LocaleController.formatString("NotificationMessageGroupText",
                                    R.string.NotificationMessageGroupText, name, chat.title,
                                    "\uD83D\uDCF9 " + messageObject.messageOwner.media.caption);
                        } else {
                            msg = LocaleController.formatString("NotificationMessageGroupVideo",
                                    R.string.NotificationMessageGroupVideo, name, chat.title);
                        }
                    } else if (messageObject.isVoice()) {
                        msg = LocaleController.formatString("NotificationMessageGroupAudio",
                                R.string.NotificationMessageGroupAudio, name, chat.title);
                    } else if (messageObject.isMusic()) {
                        msg = LocaleController.formatString("NotificationMessageGroupMusic",
                                R.string.NotificationMessageGroupMusic, name, chat.title);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
                        msg = LocaleController.formatString("NotificationMessageGroupContact",
                                R.string.NotificationMessageGroupContact, name, chat.title);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGame) {
                        msg = LocaleController.formatString("NotificationMessageGroupGame",
                                R.string.NotificationMessageGroupGame, name, chat.title,
                                messageObject.messageOwner.media.game.title);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo
                            || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
                        msg = LocaleController.formatString("NotificationMessageGroupMap",
                                R.string.NotificationMessageGroupMap, name, chat.title);
                    } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
                        if (messageObject.isSticker()) {
                            String emoji = messageObject.getStickerEmoji();
                            if (emoji != null) {
                                msg = LocaleController.formatString("NotificationMessageGroupStickerEmoji",
                                        R.string.NotificationMessageGroupStickerEmoji, name, chat.title, emoji);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGroupSticker",
                                        R.string.NotificationMessageGroupSticker, name, chat.title);
                            }
                        } else if (messageObject.isGif()) {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        "\uD83C\uDFAC " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGroupGif",
                                        R.string.NotificationMessageGroupGif, name, chat.title);
                            }
                        } else {
                            if (!shortMessage && Build.VERSION.SDK_INT >= 19
                                    && !TextUtils.isEmpty(messageObject.messageOwner.media.caption)) {
                                msg = LocaleController.formatString("NotificationMessageGroupText",
                                        R.string.NotificationMessageGroupText, name, chat.title,
                                        "\uD83D\uDCCE " + messageObject.messageOwner.media.caption);
                            } else {
                                msg = LocaleController.formatString("NotificationMessageGroupDocument",
                                        R.string.NotificationMessageGroupDocument, name, chat.title);
                            }
                        }
                    }
                }
            } else {
                if (ChatObject.isChannel(chat) && !chat.megagroup) {
                    msg = LocaleController.formatString("ChannelMessageNoText", R.string.ChannelMessageNoText,
                            name, chat.title);
                } else {
                    msg = LocaleController.formatString("NotificationMessageGroupNoText",
                            R.string.NotificationMessageGroupNoText, name, chat.title);
                }
            }
        }
    }
    return msg;
}