Example usage for com.google.common.io Resources asByteSource

List of usage examples for com.google.common.io Resources asByteSource

Introduction

In this page you can find the example usage for com.google.common.io Resources asByteSource.

Prototype

public static ByteSource asByteSource(URL url) 

Source Link

Document

Returns a ByteSource that reads from the given URL.

Usage

From source file:org.locationtech.geogig.cli.app.Logging.java

@Nullable
private static URL getOrCreateLoggingConfigFile(final File geogigdir) {

    final File logsDir = new File(geogigdir, "log");
    if (!logsDir.exists() && !logsDir.mkdir()) {
        return null;
    }/*from  ww  w . j a  v a2  s .  com*/
    final File configFile = new File(logsDir, "logback.xml");
    if (configFile.exists()) {
        try {
            return configFile.toURI().toURL();
        } catch (MalformedURLException e) {
            throw Throwables.propagate(e);
        }
    }
    ByteSource from;
    final URL resource = CLI.class.getResource("logback_default.xml");
    try {
        from = Resources.asByteSource(resource);
    } catch (NullPointerException npe) {
        LOGGER.warn("Couldn't obtain default logging configuration file");
        return null;
    }
    try {
        from.copyTo(Files.asByteSink(configFile));
        return configFile.toURI().toURL();
    } catch (Exception e) {
        LOGGER.warn("Error copying logback_default.xml to {}. Using default configuration.", configFile, e);
        return resource;
    }
}

From source file:org.apache.drill.exec.expr.fn.FunctionInitializer.java

private CompilationUnit get(Class<?> c) throws IOException {
    String path = c.getName();//from  w w  w.j a v a2s.c  om
    path = path.replaceFirst("\\$.*", "");
    path = path.replace(".", FileUtils.separator);
    path = "/" + path + ".java";
    CompilationUnit cu = functionUnits.get(path);
    if (cu != null) {
        return cu;
    }

    URL u = Resources.getResource(c, path);
    try (InputStream is = Resources.asByteSource(u).openStream()) {
        if (is == null) {
            throw new IOException(String.format(
                    "Failure trying to located source code for Class %s, tried to read on classpath location %s",
                    c.getName(), path));
        }
        String body = IO.toString(is);

        // TODO: Hack to remove annotations so Janino doesn't choke. Need to reconsider this problem...
        body = body.replaceAll("@\\w+(?:\\([^\\\\]*?\\))?", "");
        try {
            cu = new Parser(new Scanner(null, new StringReader(body))).parseCompilationUnit();
            functionUnits.put(path, cu);
            return cu;
        } catch (CompileException e) {
            logger.warn("Failure while parsing function class:\n{}", body, e);
            return null;
        }

    }

}

From source file:org.glowroot.agent.weaving.PluginDetailBuilder.java

@OnlyUsedByTests
static MixinClass buildMixinClass(Class<?> clazz) throws IOException {
    URL url = checkNotNull(// w w w .j av  a  2 s.  c om
            PluginDetailBuilder.class.getResource("/" + ClassNames.toInternalName(clazz.getName()) + ".class"));
    byte[] bytes = Resources.asByteSource(url).read();
    MemberClassVisitor mcv = new MemberClassVisitor();
    new ClassReader(bytes).accept(mcv, ClassReader.SKIP_CODE);
    return mcv.buildMixinClass(false, bytes);
}

From source file:de.unima.core.io.file.BPMN20Exporter.java

@SuppressWarnings("unchecked")
@Override// ww w .j  a  v  a2s .  com
public File exportToFile(Model data, File location) {
    OntModel dataOntModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, data);
    //Preparing jena models
    OntModel schemaModel = ModelFactory.createOntologyModel(new OntModelSpec(OntModelSpec.OWL_MEM));
    try (InputStream schemaInputStream = Resources.asByteSource(Resources.getResource(SCHEMAPATH))
            .openBufferedStream()) {
        schemaModel.read(schemaInputStream, null);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    schemaModel.addSubModel(data);

    //Preparing camunda 
    BpmnModelInstanceImpl bpmnMI = (BpmnModelInstanceImpl) Bpmn.createEmptyModel();

    Definitions definitions = bpmnMI.newInstance(Definitions.class);
    definitions.setTargetNamespace("");
    bpmnMI.setDefinitions(definitions);

    ExtendedIterator<Individual> processIndividuals = (ExtendedIterator<Individual>) schemaModel
            .getOntClass(SCHEMA_NAMESPACE + "process").listInstances();
    List<Individual> processIndividualsList = processIndividuals.toList();
    for (Individual processInd : processIndividualsList) {
        Process process = bpmnMI.newInstance(Process.class);
        definitions.addChildElement(process);

        String processId = processInd.getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id"))
                .toString();
        process.setId(processId);

        boolean isExecutable = Boolean.parseBoolean(processInd
                .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "isExecutable")).toString());
        process.setExecutable(isExecutable);

        boolean isClosed = Boolean.parseBoolean(
                processInd.getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "isClosed")).toString());
        process.setClosed(isClosed);

        String processType = processInd
                .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "processType")).toString();
        process.setProcessType(ProcessType.valueOf(processType));

        RDFNode processNameNode = processInd
                .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "name"));
        if (processNameNode != null) {
            process.setName(processNameNode.toString());
        }

        //flowNodes
        NodeIterator flowNodeIterator = processInd
                .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_flowNode"));

        for (RDFNode flowNode : flowNodeIterator.toList()) {
            String flowNodeId = flowNode.asResource()
                    .getProperty(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).getObject().toString();
            Individual flowNodeInd = schemaModel.getIndividual(individualNameSpace + flowNodeId);
            String type = flowNodeInd.getRDFType().getLocalName();
            type = type.substring(0, 1).toUpperCase() + type.substring(1);
            Class typeClass = null;
            try {
                typeClass = Class.forName("org.camunda.bpm.model.bpmn.instance." + type);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            FlowNode bpmnFlowNode = (FlowNode) bpmnMI.newInstance(typeClass);
            bpmnFlowNode.setId(flowNodeId);

            if (flowNodeInd.getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "name")) != null) {
                String name = flowNodeInd.getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "name"))
                        .toString();
                bpmnFlowNode.setName(name);
            }

            for (RDFNode outgoingNode : flowNodeInd
                    .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_outgoing")).toList()) {
                //dirtyfix since one sequence does not get recognized as a node. Should use .asNode.getLocalName() on outgoingNode object
                String outgoingId = outgoingNode.asNode().getLocalName();
                Outgoing outgoingSeqFlow = bpmnMI.newInstance(Outgoing.class);
                outgoingSeqFlow.setTextContent(outgoingId);
                bpmnFlowNode.addChildElement(outgoingSeqFlow);
            }

            for (RDFNode incomingNode : flowNodeInd
                    .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_incoming")).toList()) {
                //dirtyfix since one sequence does not get recognized as a node. Should use .asNode.getLocalName() on incomingNode object
                String incomingId = incomingNode.asNode().getLocalName();
                Incoming incomingSeqFlow = bpmnMI.newInstance(Incoming.class);
                incomingSeqFlow.setTextContent(incomingId);
                bpmnFlowNode.addChildElement(incomingSeqFlow);
            }

            if (bpmnFlowNode instanceof Activity) {
                int completionQuantity = Integer.parseInt(flowNodeInd
                        .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "completionQuantity"))
                        .asLiteral().getValue().toString());
                ((Activity) bpmnFlowNode).setCompletionQuantity(completionQuantity);
                int startQuantity = Integer.parseInt(flowNodeInd
                        .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "startQuantity"))
                        .asLiteral().getValue().toString());
                ((Activity) bpmnFlowNode).setStartQuantity(startQuantity);
                boolean isForCompensation = Boolean.parseBoolean(flowNodeInd
                        .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "isForCompensation"))
                        .toString());
                ((Activity) bpmnFlowNode).setForCompensation(isForCompensation);
            }

            if (bpmnFlowNode instanceof Gateway) {
                String gatewayDirection = flowNodeInd
                        .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "gatewayDirection"))
                        .toString();
                ((Gateway) bpmnFlowNode).setGatewayDirection(GatewayDirection.valueOf(gatewayDirection));
                if (bpmnFlowNode instanceof EventBasedGateway) {
                    boolean isInstantiate = Boolean.parseBoolean(flowNodeInd
                            .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "instantiate"))
                            .toString());
                    ((EventBasedGateway) bpmnFlowNode).setInstantiate(isInstantiate);
                    String eventBasedGatewayType = flowNodeInd
                            .getPropertyValue(
                                    schemaModel.getProperty(SCHEMA_NAMESPACE + "eventBasedGatewayType"))
                            .toString();
                    ((EventBasedGateway) bpmnFlowNode)
                            .setEventGatewayType(EventBasedGatewayType.valueOf(eventBasedGatewayType));
                }
            }

            if (bpmnFlowNode instanceof Event) {
                if (bpmnFlowNode instanceof CatchEvent) {
                    NodeIterator eventDefinitionIterator = flowNodeInd.listPropertyValues(
                            schemaModel.getProperty(SCHEMA_NAMESPACE + "has_eventDefinition"));
                    for (RDFNode eventDefinitionNode : eventDefinitionIterator.toList()) {
                        Individual eventDefinitionInd = dataOntModel
                                .getIndividual(eventDefinitionNode.asNode().getURI());
                        String eventDefintionClassType = eventDefinitionInd.getRDFType().getLocalName();
                        eventDefintionClassType = eventDefintionClassType.substring(0, 1).toUpperCase()
                                + eventDefintionClassType.substring(1);
                        Class eventDefinitionClass = null;
                        try {
                            eventDefinitionClass = Class
                                    .forName("org.camunda.bpm.model.bpmn.instance." + eventDefintionClassType);
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        EventDefinition bpmnEventDef = (EventDefinition) bpmnMI
                                .newInstance(eventDefinitionClass);
                        System.out.println(eventDefinitionInd);
                        String eventDefinitionId = eventDefinitionInd
                                .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).toString();
                        bpmnEventDef.setId(eventDefinitionId);

                        bpmnFlowNode.addChildElement(bpmnEventDef);
                    }

                    if (bpmnFlowNode instanceof StartEvent) {
                        boolean isInterrupting = flowNodeInd
                                .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "isInterrupting"))
                                .asLiteral().getBoolean();
                        ((StartEvent) bpmnFlowNode).setInterrupting(isInterrupting);
                    }
                }
            }

            process.addChildElement(bpmnFlowNode);
        }

        //LaneSet has to be done when all flownodes of a process are initialized because of the ref.

        NodeIterator laneSetIterator = processInd
                .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_laneSet"));

        for (RDFNode laneSetNode : laneSetIterator.toList()) {
            String laneSetId = laneSetNode.asNode().getLocalName();
            LaneSet bpmnLaneSet = bpmnMI.newInstance(LaneSet.class);
            Individual laneSetInd = schemaModel.getIndividual(individualNameSpace + laneSetId);
            bpmnLaneSet.setId(laneSetId);

            for (RDFNode laneNode : laneSetInd
                    .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_lane")).toList()) {
                String laneId = laneNode.asNode().getLocalName();
                Lane bpmnLane = bpmnMI.newInstance(Lane.class);
                Individual laneInd = schemaModel.getIndividual(individualNameSpace + laneId);
                bpmnLane.setId(laneId);

                for (RDFNode flowNodeRef : laneInd
                        .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_flowNode"))
                        .toList()) {
                    FlowNodeRef bpmnFlowNodeRef = bpmnMI.newInstance(FlowNodeRef.class);
                    String flowNodeRefId = flowNodeRef.asNode().getLocalName();
                    bpmnFlowNodeRef.setTextContent(flowNodeRefId);
                    bpmnLane.addChildElement(bpmnFlowNodeRef);
                }

                bpmnLaneSet.addChildElement(bpmnLane);
            }

            process.addChildElement(bpmnLaneSet);
        }

    }

    //Has to be done after FlowNodes have been initialized because of the sourceRef and targetRef attribute.

    for (Individual processInd : processIndividualsList) {
        String processId = processInd.getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id"))
                .toString();
        Process process = bpmnMI.getModelElementById(processId);

        //SequenceFlow
        NodeIterator sequenceIterator = processInd
                .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_sequenceFlow"));

        for (RDFNode sequenceFlow : sequenceIterator.toList()) {

            String sequenceFlowId = sequenceFlow.asNode().getLocalName();
            SequenceFlow bpmnSeqFlow = bpmnMI.newInstance(SequenceFlow.class);
            bpmnSeqFlow.setId(sequenceFlowId);
            Individual seqFlowInd = schemaModel.getIndividual(individualNameSpace + sequenceFlowId);

            RDFNode nameProperty = seqFlowInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "name"));
            if (nameProperty != null) {
                bpmnSeqFlow.setName(nameProperty.toString());
            }

            String sourceRefUri = seqFlowInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_sourceRef")).toString();
            String sourceRef = dataOntModel.getIndividual(sourceRefUri)
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).toString();
            FlowNode bpmnSource = bpmnMI.getModelElementById(sourceRef);
            bpmnSeqFlow.setSource(bpmnSource);

            String targetRefUri = seqFlowInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_targetRef")).toString();
            String targetRef = dataOntModel.getIndividual(targetRefUri)
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).toString();
            FlowNode bpmnTarget = bpmnMI.getModelElementById(targetRef);
            bpmnSeqFlow.setTarget(bpmnTarget);

            process.addChildElement(bpmnSeqFlow);
        }

    }

    ExtendedIterator<Individual> collaborationIndividuals = (ExtendedIterator<Individual>) schemaModel
            .getOntClass(SCHEMA_NAMESPACE + "collaboration").listInstances();
    for (Individual collaborationInd : collaborationIndividuals.toList()) {
        String collaborationId = collaborationInd
                .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).toString();
        Collaboration bpmnCollaboration = bpmnMI.newInstance(Collaboration.class);
        bpmnCollaboration.setId(collaborationId);

        List<RDFNode> participants = collaborationInd
                .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_participant")).toList();

        for (RDFNode participantNode : participants) {
            String participantId = dataOntModel
                    .getProperty(participantNode.asResource(), schemaModel.getProperty(SCHEMA_NAMESPACE + "id"))
                    .getObject().toString();
            Individual participantInd = dataOntModel.getIndividual(participantNode.asResource().getURI());
            Participant bpmnParticipant = bpmnMI.newInstance(Participant.class);
            bpmnParticipant.setId(participantId);

            RDFNode nameNode = participantInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "name"));

            if (nameNode != null) {
                bpmnParticipant.setName(nameNode.toString());
            }

            String processRefUri = participantInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_processRef")).toString();
            String processRefId = dataOntModel.getIndividual(processRefUri)
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).toString();
            Process processRef = (Process) bpmnMI.getModelElementById(processRefId);
            bpmnParticipant.setProcess(processRef);

            bpmnCollaboration.addChildElement(bpmnParticipant);
        }

        List<RDFNode> messageFlows = collaborationInd
                .listPropertyValues(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_messageFlow")).toList();
        for (RDFNode messageFlowNode : messageFlows) {
            String messageFlowId = dataOntModel
                    .getProperty(messageFlowNode.asResource(), schemaModel.getProperty(SCHEMA_NAMESPACE + "id"))
                    .getObject().toString();
            Individual messageFlowInd = dataOntModel.getIndividual(messageFlowNode.asResource().getURI());
            MessageFlow bpmnMessageFlow = bpmnMI.newInstance(MessageFlow.class);
            bpmnMessageFlow.setId(messageFlowId);

            RDFNode nameNode = messageFlowInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "name"));
            if (nameNode != null) {
                bpmnMessageFlow.setName(nameNode.toString());
            }

            String sourceUri = messageFlowInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_sourceRef")).toString();
            String sourceId = dataOntModel.getIndividual(sourceUri)
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).toString();
            InteractionNode source = (InteractionNode) bpmnMI.getModelElementById(sourceId);
            bpmnMessageFlow.setSource(source);

            String targetUri = messageFlowInd
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "has_targetRef")).toString();
            String targetId = dataOntModel.getIndividual(targetUri)
                    .getPropertyValue(schemaModel.getProperty(SCHEMA_NAMESPACE + "id")).toString();
            InteractionNode target = (InteractionNode) bpmnMI.getModelElementById(targetId);
            bpmnMessageFlow.setTarget(target);

            bpmnCollaboration.addChildElement(bpmnMessageFlow);
        }

        definitions.addChildElement(bpmnCollaboration);
    }

    Bpmn.writeModelToFile(location, bpmnMI);
    return location;

}

From source file:com.android.tools.idea.structure.services.DeveloperServiceCreator.java

public DeveloperServiceCreator() {
    try {//from w w  w.j av  a2  s . c om
        // TODO: Here, we copy all resources out from the initializer and create local File copies
        // of them, because our template code (see Template.java, RecipeXmlParser.java) requires
        // working with them. A longer term solution is to make our template code work with
        // InputStreams. The biggest obstacle is our template code currently supports recursive
        // directory operations (e.g. copy src/* to dest/), and InputStreams can't point to
        // directories or allow walking a directory.
        myRootPath = new File(FileUtil.generateRandomTemporaryPath(), getResourceRoot());
        myRootPath.deleteOnExit();

        for (String name : getResources()) {
            assert !name.contains("..") : "Initializer resource can't specify relative path";
            File file = new File(myRootPath, name);

            Files.createParentDirs(file);
            assert file.createNewFile();
            String fullName = String.format("%1$s/%2$s", getResourceRoot(), name);
            URL resource = getClass().getResource(fullName);
            if (resource == null) {
                throw new FileNotFoundException(String.format("Could not find service file %1$s", fullName));
            }
            Resources.asByteSource(resource).copyTo(Files.asByteSink(file));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.glowroot.agent.weaving.PluginDetailBuilder.java

@OnlyUsedByTests
private static PointcutClass buildAdviceClassLookAtSuperClass(String internalName) throws IOException {
    URL url = checkNotNull(PluginDetailBuilder.class.getResource("/" + internalName + ".class"));
    byte[] bytes = Resources.asByteSource(url).read();
    MemberClassVisitor mcv = new MemberClassVisitor();
    new ClassReader(bytes).accept(mcv, ClassReader.SKIP_CODE);
    ImmutablePointcutClass pointcutClass = mcv.buildPointcutClass(bytes, false, null);
    String superName = checkNotNull(mcv.superName);
    if (!"java/lang/Object".equals(superName)) {
        pointcutClass = ImmutablePointcutClass.builder().copyFrom(pointcutClass)
                .addAllMethods(buildAdviceClassLookAtSuperClass(superName).methods()).build();
    }/*from ww  w. j  a  v  a 2 s . c  o m*/
    return pointcutClass;
}

From source file:ratpack.config.internal.DefaultConfigDataBuilder.java

@Override
public ConfigDataBuilder props(URL url) {
    return add(new ByteSourcePropertiesConfigSource(Optional.empty(), Resources.asByteSource(url)));
}

From source file:ratpack.config.internal.DefaultConfigDataSpec.java

@Override
public ConfigDataSpec props(URL url) {
    return add(new ByteSourcePropertiesConfigSource(Optional.empty(), Resources.asByteSource(url)));
}

From source file:org.apache.isis.core.commons.lang.ClassExtensions.java

public static Properties resourceProperties(final Class<?> extendee, final String suffix) {
    try {//from  w  ww  .j a v a  2 s. c o  m
        final URL url = Resources.getResource(extendee, extendee.getSimpleName() + suffix);
        final ByteSource byteSource = Resources.asByteSource(url);
        final Properties properties = new Properties();
        properties.load(byteSource.openStream());
        return properties;
    } catch (Exception e) {
        return null;
    }
}

From source file:ratpack.util.internal.TypeCoercingProperties.java

/**
 * Gets a property value as a ByteSource. The property value can be any of:
 * <ul>/*  w  w w.j av  a  2  s. co  m*/
 *   <li>An absolute file path to a file that exists.</li>
 *   <li>A valid URI.</li>
 *   <li>A classpath resource path loaded via the ClassLoader passed to the constructor.</li>
 * </ul>
 *
 * @param  key the property key.
 * @return a ByteSource or {@code null} if the property does not exist.
 * @throws java.lang.IllegalArgumentException if the property value cannot be resolved to a byte source.
 */
public ByteSource asByteSource(String key) {
    ByteSource byteSource = null;
    String path = delegate.getProperty(key);
    if (path != null) {
        // try to treat it as a File path
        File file = new File(path);
        if (file.isFile()) {
            byteSource = Files.asByteSource(file);
        } else {
            // try to treat it as a URL
            try {
                URL url = new URL(path);
                byteSource = Resources.asByteSource(url);
            } catch (MalformedURLException e) {
                // try to treat it as a resource path
                byteSource = Resources.asByteSource(Resources.getResource(path));
            }
        }
    }
    return byteSource;
}