Example usage for org.apache.commons.lang StringUtils substringAfter

List of usage examples for org.apache.commons.lang StringUtils substringAfter

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringAfter.

Prototype

public static String substringAfter(String str, String separator) 

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:org.apache.archiva.rest.services.DefaultRedbackRuntimeConfigurationService.java

@Override
public List<RBACManagerImplementationInformation> getRbacManagerImplementationInformations()
        throws ArchivaRestServiceException {
    Map<String, RBACManager> beans = applicationContext.getBeansOfType(RBACManager.class);

    if (beans.isEmpty()) {
        return Collections.emptyList();
    }//from  w  w w.ja  va  2  s. c o  m

    List<RBACManagerImplementationInformation> informations = new ArrayList<>(beans.size());

    for (Map.Entry<String, RBACManager> entry : beans.entrySet()) {
        RBACManager rbacManager = applicationContext.getBean(entry.getKey(), RBACManager.class);
        if (rbacManager.isFinalImplementation()) {
            RBACManagerImplementationInformation information = new RBACManagerImplementationInformation();
            information.setBeanId(StringUtils.substringAfter(entry.getKey(), "#"));
            information.setDescriptionKey(rbacManager.getDescriptionKey());
            information.setReadOnly(rbacManager.isReadOnly());
            informations.add(information);
        }
    }

    return informations;
}

From source file:org.apache.archiva.web.rss.RssFeedServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    String repoId = null;/*from  www. j  ava  2 s  .c  o  m*/
    String groupId = null;
    String artifactId = null;

    String url = StringUtils.removeEnd(req.getRequestURL().toString(), "/");

    if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") > 0) {
        artifactId = StringUtils.substringAfterLast(url, "/");
        groupId = StringUtils.substringBeforeLast(StringUtils.substringAfter(url, "feeds/"), "/");
        groupId = StringUtils.replaceChars(groupId, '/', '.');
    } else if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") == 0) {
        // we receive feeds?babla=ded which is not correct
        if (StringUtils.countMatches(url, "feeds?") > 0) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url.");
            return;
        }
        repoId = StringUtils.substringAfterLast(url, "/");
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url.");
        return;
    }

    RssFeedProcessor processor = null;

    try {
        Map<String, String> map = new HashMap<>();
        SyndFeed feed = null;

        if (isAllowed(req, repoId, groupId, artifactId)) {
            if (repoId != null) {
                // new artifacts in repo feed request
                processor = newArtifactsprocessor;
                map.put(RssFeedProcessor.KEY_REPO_ID, repoId);
            } else if ((groupId != null) && (artifactId != null)) {
                // TODO: this only works for guest - we could pass in the list of repos
                // new versions of artifact feed request
                processor = newVersionsprocessor;
                map.put(RssFeedProcessor.KEY_GROUP_ID, groupId);
                map.put(RssFeedProcessor.KEY_ARTIFACT_ID, artifactId);
            }
        } else {
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED);
            return;
        }

        RepositorySession repositorySession = repositorySessionFactory.createSession();
        try {
            feed = processor.process(map, repositorySession.getRepository());
        } finally {
            repositorySession.close();
        }
        if (feed == null) {
            res.sendError(HttpServletResponse.SC_NO_CONTENT, "No information available.");
            return;
        }

        res.setContentType(MIME_TYPE);

        if (repoId != null) {
            feed.setLink(req.getRequestURL().toString());
        } else if ((groupId != null) && (artifactId != null)) {
            feed.setLink(req.getRequestURL().toString());
        }

        SyndFeedOutput output = new SyndFeedOutput();
        output.output(feed, res.getWriter());
    } catch (UserNotFoundException unfe) {
        log.debug(COULD_NOT_AUTHENTICATE_USER, unfe);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (AccountLockedException acce) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (AuthenticationException authe) {
        log.debug(COULD_NOT_AUTHENTICATE_USER, authe);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (FeedException ex) {
        log.debug(COULD_NOT_GENERATE_FEED_ERROR, ex);
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR);
    } catch (MustChangePasswordException e) {
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
    } catch (UnauthorizedException e) {
        log.debug(e.getMessage());
        if (repoId != null) {
            res.setHeader("WWW-Authenticate",
                    "Basic realm=\"Repository Archiva Managed " + repoId + " Repository");
        } else {
            res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId);
        }

        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED);
    }
}

From source file:org.apache.camel.component.avro.AvroConfiguration.java

public void parseURI(URI uri, Map<String, Object> parameters, AvroComponent component) throws Exception {
    transport = uri.getScheme();/*w w  w .  jav a 2 s.co  m*/

    if ((!AVRO_HTTP_TRANSPORT.equalsIgnoreCase(transport))
            && (!AVRO_NETTY_TRANSPORT.equalsIgnoreCase(transport))) {
        throw new IllegalArgumentException("Unrecognized Avro IPC transport: " + protocol + " for uri: " + uri);
    }

    setHost(uri.getHost());
    setPort(uri.getPort());

    if ((uri.getPath() != null) && (StringUtils.indexOf(uri.getPath(), AVRO_MESSAGE_NAME_SEPARATOR) != -1)) {
        String path = StringUtils.substringAfter(uri.getPath(), AVRO_MESSAGE_NAME_SEPARATOR);
        if (!path.contains(AVRO_MESSAGE_NAME_SEPARATOR)) {
            setMessageName(path);
        } else {
            throw new IllegalArgumentException("Unrecognized Avro message name: " + path + " for uri: " + uri);
        }
    }

    setUriAuthority(uri.getAuthority());
}

From source file:org.apache.cocoon.components.source.impl.QDoxSource.java

/**
 * Method outputLink.//from ww  w  . j a  v  a  2s. c om
 *
 * @param handler
 * @param ref
 * @param display
 */
private void outputLink(ContentHandler handler, String ref, String display) throws SAXException {
    String classPart = resolveClassNameFromLink(ref);
    String memberPart = StringUtils.substringAfter(ref, "#");
    String displayPart = display;

    List attrs = new ArrayList();

    if (StringUtils.isNotEmpty(classPart)) {
        attrs.add(new String[] { LINK_CLASS_ATTRIBUTE, classPart });
    }

    if (StringUtils.isNotEmpty(memberPart)) {
        attrs.add(new String[] { LINK_MEMBER_ATTRIBUTE, memberPart });
    }

    if (StringUtils.isEmpty(display) && !ref.equals(classPart + "#" + memberPart)) {
        displayPart = ref.replace('#', '.');
    }

    saxStartElement(handler, LINK_ELEMENT, (String[][]) attrs.toArray(new String[][] { {} }));
    saxCharacters(handler, displayPart);
    saxEndElement(handler, LINK_ELEMENT);
}

From source file:org.apache.cocoon.generation.JXTemplateGenerator.java

private void execute(final XMLConsumer consumer, MyJexlContext jexlContext, JXPathContext jxpathContext,
        StartElement macroCall, Event startEvent, Event endEvent) throws SAXException {
    Event ev = startEvent;/*from w w  w . ja  va 2s.  co m*/
    LocationFacade loc = new LocationFacade(ev.location);
    consumer.setDocumentLocator(loc);
    while (ev != endEvent) {
        loc.setDocumentLocation(ev.location);
        if (ev instanceof Characters) {
            TextEvent text = (TextEvent) ev;
            Iterator iter = text.substitutions.iterator();
            while (iter.hasNext()) {
                Object subst = iter.next();
                char[] chars;
                if (subst instanceof char[]) {
                    chars = (char[]) subst;
                } else {
                    JXTExpression expr = (JXTExpression) subst;
                    try {
                        Object val = getNode(expr, jexlContext, jxpathContext);
                        if (val instanceof Node) {
                            executeDOM(consumer, jexlContext, jxpathContext, (Node) val);
                            continue;
                        } else if (val instanceof NodeList) {
                            NodeList nodeList = (NodeList) val;
                            int len = nodeList.getLength();
                            for (int i = 0; i < len; i++) {
                                Node n = nodeList.item(i);
                                executeDOM(consumer, jexlContext, jxpathContext, n);
                            }
                            continue;
                        } else if (val instanceof Node[]) {
                            Node[] nodeList = (Node[]) val;
                            int len = nodeList.length;
                            for (int i = 0; i < len; i++) {
                                Node n = nodeList[i];
                                executeDOM(consumer, jexlContext, jxpathContext, n);
                            }
                            continue;
                        } else if (val instanceof XMLizable) {
                            ((XMLizable) val).toSAX(new IncludeXMLConsumer(consumer));
                            continue;
                        }
                        chars = val != null ? val.toString().toCharArray() : ArrayUtils.EMPTY_CHAR_ARRAY;
                    } catch (Exception e) {
                        throw new JXTException(e.getMessage(), ev.location, e);
                    }
                }
                consumer.characters(chars, 0, chars.length);
            }
        } else if (ev instanceof EndElement) {
            EndElement endElement = (EndElement) ev;
            StartElement startElement = endElement.startElement;
            StartDefine def = (StartDefine) definitions.get(startElement.qname);
            if (def == null) {
                consumer.endElement(startElement.namespaceURI, startElement.localName, startElement.raw);
                namespaces.leaveScope(consumer);
            }
        } else if (ev instanceof EndPrefixMapping) {
            EndPrefixMapping endPrefixMapping = (EndPrefixMapping) ev;
            namespaces.removeDeclaration(endPrefixMapping.prefix);
        } else if (ev instanceof IgnorableWhitespace) {
            TextEvent text = (TextEvent) ev;
            characters(jexlContext, jxpathContext, text, new CharHandler() {
                public void characters(char[] ch, int offset, int len) throws SAXException {
                    consumer.ignorableWhitespace(ch, offset, len);
                }
            });
        } else if (ev instanceof SkippedEntity) {
            SkippedEntity skippedEntity = (SkippedEntity) ev;
            consumer.skippedEntity(skippedEntity.name);
        } else if (ev instanceof StartIf) {
            StartIf startIf = (StartIf) ev;
            Object val;
            try {
                val = getValue(startIf.test, jexlContext, jxpathContext, Boolean.TRUE);
            } catch (Exception e) {
                throw new JXTException(e.getMessage(), ev.location, e);
            }
            boolean result = false;
            if (val instanceof Boolean) {
                result = ((Boolean) val).booleanValue();
            } else {
                result = (val != null);
            }
            if (!result) {
                ev = startIf.endInstruction.next;
                continue;
            }
        } else if (ev instanceof StartForEach) {
            StartForEach startForEach = (StartForEach) ev;
            final Object items = startForEach.items;
            Iterator iter = null;
            int begin, end, step;
            String var, varStatus;
            try {
                if (items != null) {
                    JXTExpression expr = (JXTExpression) items;
                    if (expr.compiledExpression instanceof CompiledExpression) {
                        CompiledExpression compiledExpression = (CompiledExpression) expr.compiledExpression;
                        Object val = compiledExpression.getPointer(jxpathContext, expr.raw).getNode();
                        // FIXME: workaround for JXPath bug
                        iter = val instanceof NativeArray
                                ? new JSIntrospector.NativeArrayIterator((NativeArray) val)
                                : compiledExpression.iteratePointers(jxpathContext);
                    } else if (expr.compiledExpression instanceof Expression) {
                        Expression e = (Expression) expr.compiledExpression;
                        Object result = e.evaluate(jexlContext);
                        if (result != null) {
                            iter = Introspector.getUberspect().getIterator(result,
                                    new Info(ev.location.getURI(), ev.location.getLineNumber(),
                                            ev.location.getColumnNumber()));
                        }
                        if (iter == null) {
                            iter = EMPTY_ITER;
                        }
                    } else {
                        // literal value
                        iter = new Iterator() {
                            Object val = items;

                            public boolean hasNext() {
                                return val != null;
                            }

                            public Object next() {
                                Object res = val;
                                val = null;
                                return res;
                            }

                            public void remove() {
                                // EMPTY
                            }
                        };
                    }
                } else {
                    iter = NULL_ITER;
                }
                begin = startForEach.begin == null ? 0
                        : getIntValue(startForEach.begin, jexlContext, jxpathContext);
                end = startForEach.end == null ? Integer.MAX_VALUE
                        : getIntValue(startForEach.end, jexlContext, jxpathContext);
                step = startForEach.step == null ? 1
                        : getIntValue(startForEach.step, jexlContext, jxpathContext);
                var = getStringValue(startForEach.var, jexlContext, jxpathContext);
                varStatus = getStringValue(startForEach.varStatus, jexlContext, jxpathContext);
            } catch (Exception exc) {
                throw new JXTException(exc.getMessage(), ev.location, exc);
            }
            MyJexlContext localJexlContext = new MyJexlContext(jexlContext);
            MyVariables localJXPathVariables = new MyVariables((MyVariables) jxpathContext.getVariables());
            int i = 0;
            // Move to the begin row
            while (i < begin && iter.hasNext()) {
                iter.next();
                i++;
            }
            LoopTagStatus status = null;
            if (varStatus != null) {
                status = new LoopTagStatus();
                status.begin = begin;
                status.end = end;
                status.step = step;
                status.first = true;
                localJexlContext.put(varStatus, status);
                localJXPathVariables.declareVariable(varStatus, status);
            }
            int skipCounter, count = 1;
            JXPathContext localJXPathContext = null;
            while (i <= end && iter.hasNext()) {
                Object value = iter.next();
                if (value instanceof Pointer) {
                    Pointer ptr = (Pointer) value;
                    localJXPathContext = jxpathContext.getRelativeContext(ptr);
                    localJXPathContext.setNamespaceContextPointer(new NamespacesTablePointer(namespaces));
                    try {
                        value = ptr.getNode();
                    } catch (Exception exc) {
                        throw new JXTException(exc.getMessage(), ev.location, null);
                    }
                } else {
                    localJXPathContext = jxpathContextFactory.newContext(jxpathContext, value);
                    localJXPathContext.setNamespaceContextPointer(new NamespacesTablePointer(namespaces));
                }
                localJXPathContext.setVariables(localJXPathVariables);
                if (var != null) {
                    localJexlContext.put(var, value);
                }
                if (status != null) {
                    status.index = i;
                    status.count = count;
                    status.first = i == begin;
                    status.current = value;
                    status.last = (i == end || !iter.hasNext());
                }
                execute(consumer, localJexlContext, localJXPathContext, macroCall, startForEach.next,
                        startForEach.endInstruction);
                // Skip rows
                skipCounter = step;
                while (--skipCounter > 0 && iter.hasNext()) {
                    iter.next();
                }
                // Increase index
                i += step;
                count++;
            }
            ev = startForEach.endInstruction.next;
            continue;
        } else if (ev instanceof StartChoose) {
            StartChoose startChoose = (StartChoose) ev;
            StartWhen startWhen = startChoose.firstChoice;
            while (startWhen != null) {
                Object val;
                try {
                    val = getValue(startWhen.test, jexlContext, jxpathContext, Boolean.TRUE);
                } catch (Exception e) {
                    throw new JXTException(e.getMessage(), ev.location, e);
                }
                boolean result;
                if (val instanceof Boolean) {
                    result = ((Boolean) val).booleanValue();
                } else {
                    result = (val != null);
                }
                if (result) {
                    execute(consumer, jexlContext, jxpathContext, macroCall, startWhen.next,
                            startWhen.endInstruction);
                    break;
                }
                startWhen = startWhen.nextChoice;
            }
            if (startWhen == null && startChoose.otherwise != null) {
                execute(consumer, jexlContext, jxpathContext, macroCall, startChoose.otherwise.next,
                        startChoose.otherwise.endInstruction);
            }
            ev = startChoose.endInstruction.next;
            continue;
        } else if (ev instanceof StartSet) {
            StartSet startSet = (StartSet) ev;
            Object value = null;
            String var = null;
            try {
                if (startSet.var != null) {
                    var = getStringValue(startSet.var, jexlContext, jxpathContext);
                }
                if (startSet.value != null) {
                    value = getNode(startSet.value, jexlContext, jxpathContext);
                }
            } catch (Exception exc) {
                throw new JXTException(exc.getMessage(), ev.location, exc);
            }
            if (value == null) {
                NodeList nodeList = toDOMNodeList("set", startSet, jexlContext, macroCall);
                // JXPath doesn't handle NodeList, so convert it to an array
                int len = nodeList.getLength();
                Node[] nodeArr = new Node[len];
                for (int i = 0; i < len; i++) {
                    nodeArr[i] = nodeList.item(i);
                }
                value = nodeArr;
            }
            if (var != null) {
                jxpathContext.getVariables().declareVariable(var, value);
                jexlContext.put(var, value);
            }
            ev = startSet.endInstruction.next;
            continue;
        } else if (ev instanceof StartElement) {
            StartElement startElement = (StartElement) ev;
            StartDefine def = (StartDefine) definitions.get(startElement.qname);
            if (def != null) {
                Map attributeMap = new HashMap();
                Iterator i = startElement.attributeEvents.iterator();
                while (i.hasNext()) {
                    String attributeName;
                    Object attributeValue;
                    AttributeEvent attrEvent = (AttributeEvent) i.next();
                    attributeName = attrEvent.localName;
                    if (attrEvent instanceof CopyAttribute) {
                        CopyAttribute copy = (CopyAttribute) attrEvent;
                        attributeValue = copy.value;
                    } else if (attrEvent instanceof SubstituteAttribute) {
                        SubstituteAttribute substEvent = (SubstituteAttribute) attrEvent;
                        if (substEvent.substitutions.size() == 1
                                && substEvent.substitutions.get(0) instanceof JXTExpression) {
                            JXTExpression expr = (JXTExpression) substEvent.substitutions.get(0);
                            Object val;
                            try {
                                val = getNode(expr, jexlContext, jxpathContext);
                            } catch (Exception e) {
                                throw new JXTException(e.getMessage(), ev.location, e);
                            }
                            attributeValue = val != null ? val : "";
                        } else {
                            StringBuffer buf = new StringBuffer();
                            Iterator iterSubst = substEvent.substitutions.iterator();
                            while (iterSubst.hasNext()) {
                                Subst subst = (Subst) iterSubst.next();
                                if (subst instanceof Literal) {
                                    Literal lit = (Literal) subst;
                                    buf.append(lit.value);
                                } else if (subst instanceof JXTExpression) {
                                    JXTExpression expr = (JXTExpression) subst;
                                    Object val;
                                    try {
                                        val = getValue(expr, jexlContext, jxpathContext);
                                    } catch (Exception e) {
                                        throw new JXTException(e.getMessage(), ev.location, e);
                                    }
                                    buf.append(val != null ? val.toString() : "");
                                }
                            }
                            attributeValue = buf.toString();
                        }
                    } else {
                        throw new Error("this shouldn't have happened");
                    }
                    attributeMap.put(attributeName, attributeValue);
                }
                MyVariables parent = (MyVariables) jxpathContext.getVariables();
                MyVariables vars = new MyVariables(parent);
                MyJexlContext localJexlContext = new MyJexlContext(jexlContext);
                HashMap macro = new HashMap();
                macro.put("body", startElement);
                macro.put("arguments", attributeMap);
                localJexlContext.put("macro", macro);
                vars.declareVariable("macro", macro);
                Iterator iter = def.parameters.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry e = (Map.Entry) iter.next();
                    String key = (String) e.getKey();
                    StartParameter startParam = (StartParameter) e.getValue();
                    Object default_ = startParam.default_;
                    Object val = attributeMap.get(key);
                    if (val == null) {
                        val = default_;
                    }
                    localJexlContext.put(key, val);
                    vars.declareVariable(key, val);
                }
                JXPathContext localJXPathContext = jxpathContextFactory.newContext(null,
                        jxpathContext.getContextBean());
                localJXPathContext.setNamespaceContextPointer(new NamespacesTablePointer(namespaces));
                localJXPathContext.setVariables(vars);
                call(ev.location, startElement, consumer, localJexlContext, localJXPathContext, def.body,
                        def.endInstruction);
                ev = startElement.endElement.next;
                continue;
            }
            Iterator i = startElement.attributeEvents.iterator();
            AttributesImpl attrs = new AttributesImpl();
            while (i.hasNext()) {
                AttributeEvent attrEvent = (AttributeEvent) i.next();
                if (attrEvent instanceof CopyAttribute) {
                    CopyAttribute copy = (CopyAttribute) attrEvent;
                    attrs.addAttribute(copy.namespaceURI, copy.localName, copy.raw, copy.type, copy.value);
                } else if (attrEvent instanceof SubstituteAttribute) {
                    StringBuffer buf = new StringBuffer();
                    SubstituteAttribute substEvent = (SubstituteAttribute) attrEvent;
                    Iterator iterSubst = substEvent.substitutions.iterator();
                    while (iterSubst.hasNext()) {
                        Subst subst = (Subst) iterSubst.next();
                        if (subst instanceof Literal) {
                            Literal lit = (Literal) subst;
                            buf.append(lit.value);
                        } else if (subst instanceof JXTExpression) {
                            JXTExpression expr = (JXTExpression) subst;
                            Object val;
                            try {
                                val = getValue(expr, jexlContext, jxpathContext);
                            } catch (Exception e) {
                                throw new JXTException(e.getMessage(), ev.location, e);
                            }
                            buf.append(val != null ? val.toString() : "");
                        }
                    }
                    attrs.addAttribute(attrEvent.namespaceURI, attrEvent.localName, attrEvent.raw,
                            attrEvent.type, buf.toString());
                }
            }
            namespaces.enterScope(consumer);
            consumer.startElement(startElement.namespaceURI, startElement.localName, startElement.raw, attrs);
        } else if (ev instanceof StartFormatNumber) {
            StartFormatNumber startFormatNumber = (StartFormatNumber) ev;
            try {
                String result = startFormatNumber.format(jexlContext, jxpathContext);
                if (result != null) {
                    char[] chars = result.toCharArray();
                    consumer.characters(chars, 0, chars.length);
                }
            } catch (Exception e) {
                throw new JXTException(e.getMessage(), ev.location, e);
            }
        } else if (ev instanceof StartFormatDate) {
            StartFormatDate startFormatDate = (StartFormatDate) ev;
            try {
                String result = startFormatDate.format(jexlContext, jxpathContext);
                if (result != null) {
                    char[] chars = result.toCharArray();
                    consumer.characters(chars, 0, chars.length);
                }
            } catch (Exception e) {
                throw new JXTException(e.getMessage(), ev.location, e);
            }
        } else if (ev instanceof StartPrefixMapping) {
            StartPrefixMapping startPrefixMapping = (StartPrefixMapping) ev;
            namespaces.addDeclaration(startPrefixMapping.prefix, startPrefixMapping.uri);
        } else if (ev instanceof StartComment) {
            StartComment startJXComment = (StartComment) ev;
            // Parse the body of the comment
            NodeList nodeList = toDOMNodeList("comment", startJXComment, jexlContext, macroCall);
            // JXPath doesn't handle NodeList, so convert it to an array
            int len = nodeList.getLength();
            final StringBuffer buf = new StringBuffer();
            Properties omit = XMLUtils.createPropertiesForXML(true);
            for (int i = 0; i < len; i++) {
                try {
                    String str = XMLUtils.serializeNode(nodeList.item(i), omit);
                    buf.append(StringUtils.substringAfter(str, ">")); // cut the XML header
                } catch (Exception e) {
                    throw new JXTException(e.getMessage(), startJXComment.location, e);
                }
            }
            char[] chars = new char[buf.length()];
            buf.getChars(0, chars.length, chars, 0);
            consumer.comment(chars, 0, chars.length);
            ev = startJXComment.endInstruction.next;
            continue;
        } else if (ev instanceof EndCDATA) {
            consumer.endCDATA();
        } else if (ev instanceof EndDTD) {
            consumer.endDTD();
        } else if (ev instanceof EndEntity) {
            consumer.endEntity(((EndEntity) ev).name);
        } else if (ev instanceof StartCDATA) {
            consumer.startCDATA();
        } else if (ev instanceof StartDTD) {
            StartDTD startDTD = (StartDTD) ev;
            consumer.startDTD(startDTD.name, startDTD.publicId, startDTD.systemId);
        } else if (ev instanceof StartEntity) {
            consumer.startEntity(((StartEntity) ev).name);
        } else if (ev instanceof StartOut) {
            StartOut startOut = (StartOut) ev;
            Object val;
            try {
                val = getNode(startOut.compiledExpression, jexlContext, jxpathContext, startOut.lenient);
                if (val instanceof Node) {
                    executeDOM(consumer, jexlContext, jxpathContext, (Node) val);
                } else if (val instanceof NodeList) {
                    NodeList nodeList = (NodeList) val;
                    int len = nodeList.getLength();
                    for (int i = 0; i < len; i++) {
                        Node n = nodeList.item(i);
                        executeDOM(consumer, jexlContext, jxpathContext, n);
                    }
                } else if (val instanceof Node[]) {
                    Node[] nodeList = (Node[]) val;
                    int len = nodeList.length;
                    for (int i = 0; i < len; i++) {
                        Node n = nodeList[i];
                        executeDOM(consumer, jexlContext, jxpathContext, n);
                    }
                } else if (val instanceof XMLizable) {
                    ((XMLizable) val).toSAX(new IncludeXMLConsumer(consumer));
                } else {
                    char[] ch = val == null ? ArrayUtils.EMPTY_CHAR_ARRAY : val.toString().toCharArray();
                    consumer.characters(ch, 0, ch.length);
                }
            } catch (Exception e) {
                throw new JXTException(e.getMessage(), ev.location, e);
            }
        } else if (ev instanceof StartTemplate) {
            // EMPTY
        } else if (ev instanceof StartEval) {
            StartEval startEval = (StartEval) ev;
            JXTExpression expr = startEval.value;
            try {
                Object val = getNode(expr, jexlContext, jxpathContext);
                if (!(val instanceof StartElement)) {
                    throw new Exception("macro invocation required instead of: " + val);
                }
                StartElement call = (StartElement) val;
                execute(consumer, jexlContext, jxpathContext, call, call.next, call.endElement);
            } catch (Exception exc) {
                throw new JXTException(exc.getMessage(), ev.location, exc);
            }
            ev = startEval.endInstruction.next;
            continue;
        } else if (ev instanceof StartEvalBody) {
            StartEvalBody startEval = (StartEvalBody) ev;
            try {
                execute(consumer, jexlContext, jxpathContext, null, macroCall.next, macroCall.endElement);
            } catch (Exception exc) {
                throw new JXTException(exc.getMessage(), ev.location, exc);
            }
            ev = startEval.endInstruction.next;
            continue;
        } else if (ev instanceof StartDefine) {
            StartDefine startDefine = (StartDefine) ev;
            definitions.put(startDefine.qname, startDefine);
            ev = startDefine.endInstruction.next;
            continue;
        } else if (ev instanceof StartImport) {
            StartImport startImport = (StartImport) ev;
            String uri;
            AttributeEvent e = startImport.uri;
            if (e instanceof CopyAttribute) {
                CopyAttribute copy = (CopyAttribute) e;
                uri = copy.value;
            } else {
                StringBuffer buf = new StringBuffer();
                SubstituteAttribute substAttr = (SubstituteAttribute) e;
                Iterator i = substAttr.substitutions.iterator();
                while (i.hasNext()) {
                    Subst subst = (Subst) i.next();
                    if (subst instanceof Literal) {
                        Literal lit = (Literal) subst;
                        buf.append(lit.value);
                    } else if (subst instanceof JXTExpression) {
                        JXTExpression expr = (JXTExpression) subst;
                        Object val;
                        try {
                            val = getValue(expr, jexlContext, jxpathContext);
                        } catch (Exception exc) {
                            throw new JXTException(exc.getMessage(), ev.location, exc);
                        }
                        buf.append(val != null ? val.toString() : "");
                    }
                }
                uri = buf.toString();
            }
            Source input = null;
            StartDocument doc;
            try {
                input = resolver.resolveURI(uri);
                SourceValidity validity = null;
                synchronized (cache) {
                    doc = (StartDocument) cache.get(input.getURI());
                    if (doc != null) {
                        boolean recompile = false;
                        if (doc.compileTime == null) {
                            recompile = true;
                        } else {
                            int valid = doc.compileTime.isValid();
                            if (valid == SourceValidity.UNKNOWN) {
                                validity = input.getValidity();
                                valid = doc.compileTime.isValid(validity);
                            }
                            if (valid != SourceValidity.VALID) {
                                recompile = true;
                            }
                        }
                        if (recompile) {
                            doc = null; // recompile
                        }
                    }
                }
                if (doc == null) {
                    Parser parser = new Parser();
                    // call getValidity before using the stream is faster if the source is a SitemapSource
                    if (validity == null) {
                        validity = input.getValidity();
                    }
                    SourceUtil.parse(this.manager, input, parser);
                    doc = parser.getStartEvent();
                    doc.compileTime = validity;
                    synchronized (cache) {
                        cache.put(input.getURI(), doc);
                    }
                }
            } catch (Exception exc) {
                throw new JXTException(exc.getMessage(), ev.location, exc);
            } finally {
                resolver.release(input);
            }
            JXPathContext selectJXPath = jxpathContext;
            MyJexlContext selectJexl = jexlContext;
            if (startImport.select != null) {
                try {
                    Object obj = getValue(startImport.select, jexlContext, jxpathContext);
                    selectJXPath = jxpathContextFactory.newContext(null, obj);
                    selectJXPath.setNamespaceContextPointer(new NamespacesTablePointer(namespaces));
                    selectJXPath.setVariables(variables);
                    selectJexl = new MyJexlContext(jexlContext);
                    fillContext(obj, selectJexl);
                } catch (Exception exc) {
                    throw new JXTException(exc.getMessage(), ev.location, exc);
                }
            }
            try {
                execute(consumer, selectJexl, selectJXPath, macroCall, doc.next, doc.endDocument);
            } catch (Exception exc) {
                throw new JXTException(
                        "Exception occurred in imported template " + uri + ": " + exc.getMessage(), ev.location,
                        exc);
            }
            ev = startImport.endInstruction.next;
            continue;
        } else if (ev instanceof StartDocument) {
            if (((StartDocument) ev).endDocument != null) {
                // if this isn't a document fragment
                consumer.startDocument();
            }
        } else if (ev instanceof EndDocument) {
            consumer.endDocument();
        } else if (ev instanceof ProcessingInstruction) {
            ProcessingInstruction pi = (ProcessingInstruction) ev;
            consumer.processingInstruction(pi.target, pi.data);
        }
        ev = ev.next;
    }
}

From source file:org.apache.cocoon.template.instruction.Comment.java

public Event execute(final XMLConsumer consumer, ExpressionContext expressionContext,
        ExecutionContext executionContext, MacroContext macroContext, Event startEvent, Event endEvent)
        throws SAXException {
    // Parse the body of the comment
    NodeList nodeList = Invoker.toDOMNodeList("comment", this, expressionContext, executionContext,
            macroContext);//from  w w  w  .j av a2  s .  c  o m
    // JXPath doesn't handle NodeList, so convert it to an array
    int len = nodeList.getLength();
    final StringBuffer buf = new StringBuffer();
    Properties omit = XMLUtils.createPropertiesForXML(true);
    for (int i = 0; i < len; i++) {
        try {
            String str = XMLUtils.serializeNode(nodeList.item(i), omit);
            buf.append(StringUtils.substringAfter(str, ">")); // cut
            // the XML header
        } catch (ProcessingException e) {
            throw new SAXParseException(e.getMessage(), getLocation(), e);
        }
    }
    char[] chars = new char[buf.length()];
    buf.getChars(0, chars.length, chars, 0);
    consumer.comment(chars, 0, chars.length);
    return getEndInstruction().getNext();
}

From source file:org.apache.gobblin.data.management.conversion.hive.converter.HiveAvroToOrcConverterTest.java

/***
 * Test flattened DDL and DML generation
 * @throws IOException/*from  w  w  w.j ava2s  .c o m*/
 */
@Test
public void testFlattenSchemaDDLandDML() throws Exception {
    String dbName = "testdb";
    String tableName = "testtable";
    String tableSdLoc = "/tmp/testtable";

    this.hiveMetastoreTestUtils.getLocalMetastoreClient().dropDatabase(dbName, false, true, true);

    Table table = this.hiveMetastoreTestUtils.createTestAvroTable(dbName, tableName, tableSdLoc,
            Optional.<String>absent());
    Schema schema = ConversionHiveTestUtils.readSchemaFromJsonFile(resourceDir,
            "recordWithinRecordWithinRecord_nested.json");
    WorkUnitState wus = ConversionHiveTestUtils.createWus(dbName, tableName, 0);

    try (HiveAvroToFlattenedOrcConverter converter = new HiveAvroToFlattenedOrcConverter();) {

        Config config = ConfigFactory.parseMap(ImmutableMap.<String, String>builder()
                .put("destinationFormats", "flattenedOrc").put("flattenedOrc.destination.dbName", dbName)
                .put("flattenedOrc.destination.tableName", tableName + "_orc")
                .put("flattenedOrc.destination.dataPath", "file:" + tableSdLoc + "_orc").build());

        ConvertibleHiveDataset cd = ConvertibleHiveDatasetTest.createTestConvertibleDataset(config);

        List<QueryBasedHiveConversionEntity> conversionEntities = Lists
                .newArrayList(converter.convertRecord(converter.convertSchema(schema, wus),
                        new QueryBasedHiveConversionEntity(cd, new SchemaAwareHiveTable(table, schema)), wus));

        Assert.assertEquals(conversionEntities.size(), 1, "Only one query entity should be returned");

        QueryBasedHiveConversionEntity queryBasedHiveConversionEntity = conversionEntities.get(0);
        List<String> queries = queryBasedHiveConversionEntity.getQueries();

        Assert.assertEquals(queries.size(), 4, "4 DDL and one DML query should be returned");

        // Ignoring part before first bracket in DDL and 'select' clause in DML because staging table has
        // .. a random name component
        String actualDDLQuery = StringUtils.substringAfter("(", queries.get(0).trim());
        String actualDMLQuery = StringUtils.substringAfter("SELECT", queries.get(0).trim());
        String expectedDDLQuery = StringUtils.substringAfter("(", ConversionHiveTestUtils
                .readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_flattened.ddl"));
        String expectedDMLQuery = StringUtils.substringAfter("SELECT", ConversionHiveTestUtils
                .readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_flattened.dml"));

        Assert.assertEquals(actualDDLQuery, expectedDDLQuery);
        Assert.assertEquals(actualDMLQuery, expectedDMLQuery);
    }

}

From source file:org.apache.gobblin.data.management.conversion.hive.converter.HiveAvroToOrcConverterTest.java

/***
 * Test nested DDL and DML generation/*  ww w. jav  a2  s .  co  m*/
 * @throws IOException
 */
@Test
public void testNestedSchemaDDLandDML() throws Exception {
    String dbName = "testdb";
    String tableName = "testtable";
    String tableSdLoc = "/tmp/testtable";

    this.hiveMetastoreTestUtils.getLocalMetastoreClient().dropDatabase(dbName, false, true, true);

    Table table = this.hiveMetastoreTestUtils.createTestAvroTable(dbName, tableName, tableSdLoc,
            Optional.<String>absent());
    Schema schema = ConversionHiveTestUtils.readSchemaFromJsonFile(resourceDir,
            "recordWithinRecordWithinRecord_nested.json");
    WorkUnitState wus = ConversionHiveTestUtils.createWus(dbName, tableName, 0);
    wus.getJobState().setProp("orc.table.flatten.schema", "false");

    try (HiveAvroToNestedOrcConverter converter = new HiveAvroToNestedOrcConverter();) {

        Config config = ConfigFactory
                .parseMap(ImmutableMap.<String, String>builder().put("destinationFormats", "nestedOrc")
                        .put("nestedOrc.destination.tableName", "testtable_orc_nested")
                        .put("nestedOrc.destination.dbName", dbName)
                        .put("nestedOrc.destination.dataPath", "file:/tmp/testtable_orc_nested").build());

        ConvertibleHiveDataset cd = ConvertibleHiveDatasetTest.createTestConvertibleDataset(config);

        List<QueryBasedHiveConversionEntity> conversionEntities = Lists
                .newArrayList(converter.convertRecord(converter.convertSchema(schema, wus),
                        new QueryBasedHiveConversionEntity(cd, new SchemaAwareHiveTable(table, schema)), wus));

        Assert.assertEquals(conversionEntities.size(), 1, "Only one query entity should be returned");

        QueryBasedHiveConversionEntity queryBasedHiveConversionEntity = conversionEntities.get(0);
        List<String> queries = queryBasedHiveConversionEntity.getQueries();

        Assert.assertEquals(queries.size(), 4, "4 DDL and one DML query should be returned");

        // Ignoring part before first bracket in DDL and 'select' clause in DML because staging table has
        // .. a random name component
        String actualDDLQuery = StringUtils.substringAfter("(", queries.get(0).trim());
        String actualDMLQuery = StringUtils.substringAfter("SELECT", queries.get(0).trim());
        String expectedDDLQuery = StringUtils.substringAfter("(", ConversionHiveTestUtils
                .readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_nested.ddl"));
        String expectedDMLQuery = StringUtils.substringAfter("SELECT", ConversionHiveTestUtils
                .readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_nested.dml"));

        Assert.assertEquals(actualDDLQuery, expectedDDLQuery);
        Assert.assertEquals(actualDMLQuery, expectedDMLQuery);
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.RowCounter.java

/**
 * Sets up the actual job.//from   w  w  w. j a va  2s  .  c  o  m
 *
 * @param conf  The current configuration.
 * @param args  The command line parameters.
 * @return The newly created job.
 * @throws IOException When setting up the job fails.
 */
public static Job createSubmittableJob(Configuration conf, String[] args) throws IOException {
    String tableName = args[0];
    String startKey = null;
    String endKey = null;
    StringBuilder sb = new StringBuilder();

    final String rangeSwitch = "--range=";

    // First argument is table name, starting from second
    for (int i = 1; i < args.length; i++) {
        if (args[i].startsWith(rangeSwitch)) {
            String[] startEnd = args[i].substring(rangeSwitch.length()).split(",", 2);
            if (startEnd.length != 2 || startEnd[1].contains(",")) {
                printUsage("Please specify range in such format as \"--range=a,b\" "
                        + "or, with only one boundary, \"--range=,b\" or \"--range=a,\"");
                return null;
            }
            startKey = startEnd[0];
            endKey = startEnd[1];
        } else {
            // if no switch, assume column names
            sb.append(args[i]);
            sb.append(" ");
        }
    }

    Job job = new Job(conf, NAME + "_" + tableName);
    job.setJarByClass(RowCounter.class);
    Scan scan = new Scan();
    scan.setCacheBlocks(false);
    Set<byte[]> qualifiers = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
    if (startKey != null && !startKey.equals("")) {
        scan.setStartRow(Bytes.toBytes(startKey));
    }
    if (endKey != null && !endKey.equals("")) {
        scan.setStopRow(Bytes.toBytes(endKey));
    }
    if (sb.length() > 0) {
        for (String columnName : sb.toString().trim().split(" ")) {
            String family = StringUtils.substringBefore(columnName, ":");
            String qualifier = StringUtils.substringAfter(columnName, ":");

            if (StringUtils.isBlank(qualifier)) {
                scan.addFamily(Bytes.toBytes(family));
            } else {
                scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier));
            }
        }
    }
    // specified column may or may not be part of first key value for the row.
    // Hence do not use FirstKeyOnlyFilter if scan has columns, instead use
    // FirstKeyValueMatchingQualifiersFilter.
    if (qualifiers.size() == 0) {
        scan.setFilter(new FirstKeyOnlyFilter());
    } else {
        scan.setFilter(new FirstKeyValueMatchingQualifiersFilter(qualifiers));
    }
    job.setOutputFormatClass(NullOutputFormat.class);
    TableMapReduceUtil.initTableMapperJob(tableName, scan, RowCounterMapper.class, ImmutableBytesWritable.class,
            Result.class, job);
    job.setNumReduceTasks(0);
    return job;
}

From source file:org.apache.hadoop.hive.ql.hooks.VerifySessionStateStackTracesHook.java

public void run(HookContext hookContext) {
    LogHelper console = SessionState.getConsole();

    for (Entry<String, List<List<String>>> entry : SessionState.get().getStackTraces().entrySet()) {

        for (List<String> stackTrace : entry.getValue()) {
            // Only print the first line of the stack trace as it contains the error message, and other
            // lines may contain line numbers which are volatile
            // Also only take the string after the first two spaces, because the prefix is a date and
            // and time stamp
            console.printError(/*from w ww  .j av a 2s.c  om*/
                    StringUtils.substringAfter(StringUtils.substringAfter(stackTrace.get(0), " "), " "));
        }
    }
}