Create a Document in Zanata.

@param resource  The resource data to be used by Zanata to create the Document.
@param copyTrans Run copytrans on the server
@return True if the document was successfully created, otherwise false.
168129
public boolean createFile(final Resource resource, boolean copyTrans) throws UnauthorizedException {
        ClientResponse<String> response = null;
        try {
            final ISourceDocResource client = proxyFactory.getSourceDocResource(details.getProject(), details.getVersion());
            response = client.post(resource, null, false);

            final Status status = Response.Status.fromStatusCode(response.getStatus());

            if (status == Response.Status.CREATED) {
                final String entity = response.getEntity();
                if (entity.trim().length() != 0) log.info(entity);

                // Run copytrans if requested
                if (copyTrans) {
                    runCopyTrans(resource.getName(), true);
                }

                return true;
            } else if (status == Status.UNAUTHORIZED) {
                throw new UnauthorizedException();
            } else {
                log.error("REST call to createResource() did not complete successfully. HTTP response code was " + status.getStatusCode() +
                        ". Reason was " + status.getReasonPhrase());
            }

        } catch (final Exception ex) {
            log.error("Failed to create the Zanata Document", ex);
            if (ex instanceof UnauthorizedException) {
                throw (UnauthorizedException) ex;
            }
        } finally {
            /*
             * If you are using RESTEasy client framework, and returning a Response from your service method, you will
             * explicitly need to release the connection.
             */
            if (response != null) response.releaseConnection();

            /* Perform a small wait to ensure zanata isn't overloaded */
            performZanataRESTCallWaiting();
        }

        return false;
    }
357994
public static final void copyResource(String source, Path target, Class<?> cls) throws IOException
    {
        try (InputStream is = cls.getResourceAsStream(source))
        {
            Files.copy(is, target, REPLACE_EXISTING);
        }
    }
295387
public void copy(CopyRequest request) {
    call(
      new PostRequest(path("copy"))
        .setParam("id", request.getId())
        .setParam("name", request.getName())
        .setParam("organization", request.getOrganization())
        .setMediaType(MediaTypes.JSON)
    ).content();
  }
1036708
public static boolean isJavaArchive(IResource resource) {
        if (resource == null || (resource.getType() != IResource.FILE)) {
            return false;
        }
        String name = resource.getName();
        return Archive.isArchiveFileName(name);
    }
7433
@NotNull
    public static DocumentBuilder createDocumentBuilder() {
        try {
            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            return factory.newDocumentBuilder();
        } catch (final ParserConfigurationException ex) {
            throw new RuntimeException("Couldn't create document builder", ex);
        }
    }
1031441
public static BsonDocument copyOfDocument(final BsonDocument document) {
    final BsonDocument newDocument = new BsonDocument();
    for (final Map.Entry<String, BsonValue> kv : document.entrySet()) {
      newDocument.put(kv.getKey(), kv.getValue());
    }
    return newDocument;
  }
848264
public boolean copyMessageToResult( javax.xml.transform.Result resultTarget)
    {
        Object root = m_message.getRawData();
        try {
            String strSOAPPackage = (String)((TrxMessageHeader)this.getMessage().getMessageHeader()).get(SOAPMessageTransport.SOAP_PACKAGE);

            Marshaller m = JaxbContexts.getJAXBContexts().getMarshaller(strSOAPPackage);
            if (m != null)
            {
                synchronized(m)
                {   // Since the marshaller is shared (may want to tweek this for multi-cpu implementations)
                    m.marshal( root, resultTarget );
                }
                return true;    // Success
            }
        } catch (JAXBException ex)   {
            ex.printStackTrace();
        } catch (java.lang.IllegalArgumentException ex)   {
            ex.printStackTrace();
        }
        return super.copyMessageToResult(resultTarget);        
    }
750881
public boolean deleteResource(final String id) {
        performZanataRESTCallWaiting();
        ClientResponse<String> response = null;
        try {
            final ISourceDocResource client = proxyFactory.getSourceDocResource(details.getProject(), details.getVersion());
            response = client.deleteResource(id);

            final Status status = Response.Status.fromStatusCode(response.getStatus());

            if (status == Response.Status.OK) {
                final String entity = response.getEntity();
                if (entity.trim().length() != 0) log.info(entity);
                return true;
            } else {
                log.error("REST call to deleteResource() did not complete successfully. HTTP response code was " + status.getStatusCode() +
                        ". Reason was " + status.getReasonPhrase());
            }
        } catch (final Exception ex) {
            log.error("Failed to delete the Zanata Source Document", ex);
        } finally {
            /*
             * If you are using RESTEasy client framework, and returning a Response from your service method, you will
             * explicitly need to release the connection.
             */
            if (response != null) response.releaseConnection();
        }

        return false;
    }
1198138
public static boolean copyTreeToResult(Node tree, Result result)
    {
        try {
            // Use a Transformer for output
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();

            DOMSource source = new DOMSource(tree);
            transformer.transform(source, result);
            return true;    // Success
        } catch (TransformerConfigurationException tce) {
            // Error generated by the parser
            tce.printStackTrace();
        } catch (TransformerException te) {
            // Error generated by the parser
            te.printStackTrace();
        }
        return false;   // Failure
    }
990579
@Override
    public Document newDocument(Namespace namespace,
                                Collection<Statement> statements,
                                Collection<Bundle> bundles) {
	Document res = of.createDocument();
	res.setNamespace(namespace);
	res.getStatementOrBundle()
	   .addAll(statements);
	res.getStatementOrBundle()
	   .addAll(bundles);
	return res;
    }
610435
public Task createDocument(Task task) {
        DocumentRevision rev = new DocumentRevision();
        rev.setBody(DocumentBodyFactory.create(task.asMap()));
        try {
            DocumentRevision created = this.mDocumentStore.database().create(rev);
            return Task.fromRevision(created);
        } catch (DocumentException de) {
            return null;
        } catch (DocumentStoreException de) {
            return null;
        }
    }
788533
@Override
    void copyTransients(JsMessageImpl copy) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "copyTransients");
        super.copyTransients(copy);

        JsJmsObjectMessageImpl other = (JsJmsObjectMessageImpl) copy;
        // Copy the real object reference, soft reference & booleans across
        other.realObject = realObject;
        other.hasRealObject = hasRealObject;
        other.hasSerializedRealObject = hasSerializedRealObject;
        other.softRefToRealObject = softRefToRealObject;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "copyTransients");
    }
1312338
@COPY
    @Timed
    public void copyResource(@Suspended final AsyncResponse response, @Context final Request request,
            @Context final UriInfo uriInfo, @Context final HttpHeaders headers,
            @Context final SecurityContext security) {
        final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
        final Session session = getSession(req.getPrincipalName());
        final IRI destination = getDestination(headers, getBaseUrl(req));
        final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
        // Default is recursive copy as per RFC-4918
        final Depth.DEPTH depth = getDepth(headers.getHeaderString("Depth"));
        getParent(destination).thenCombine(services.getResourceService().get(destination), this::checkResources)
            .thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier()))
            .thenCompose(future -> services.getResourceService().get(identifier))
            .thenApply(this::checkResource)
            .thenCompose(res -> copyTo(res, session, depth, destination, getBaseUrl(req)))
            .thenApply(future -> status(NO_CONTENT).build())
            .exceptionally(this::handleException).thenApply(response::resume);
    }
228835
@SuppressWarnings({"unchecked"})
    public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException {
        acl.checkPermission(Item.CREATE);
        src.checkPermission(Item.EXTENDED_READ);
        XmlFile srcConfigFile = Items.getConfigFile(src);
        if (!src.hasPermission(Item.CONFIGURE)) {
            Matcher matcher = AbstractItem.SECRET_PATTERN.matcher(srcConfigFile.asString());
            while (matcher.find()) {
                if (Secret.decrypt(matcher.group(1)) != null) {
                    // AccessDeniedException2 does not permit a custom message, and anyway redirecting the user to the login screen is obviously pointless.
                    throw new AccessDeniedException(Messages.ItemGroupMixIn_may_not_copy_as_it_contains_secrets_and_(src.getFullName(), Jenkins.getAuthentication().getName(), Item.PERMISSIONS.title, Item.EXTENDED_READ.name, Item.CONFIGURE.name));
                }
            }
        }
        src.getDescriptor().checkApplicableIn(parent);
        acl.getACL().checkCreatePermission(parent, src.getDescriptor());
        ItemListener.checkBeforeCopy(src, parent);

        T result = (T)createProject(src.getDescriptor(),name,false);

        // copy config
        Files.copy(Util.fileToPath(srcConfigFile.getFile()), Util.fileToPath(Items.getConfigFile(result).getFile()),
                StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);

        // reload from the new config
        final File rootDir = result.getRootDir();
        result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<T,IOException>() {
            @Override public T call() throws IOException {
                return (T) Items.load(parent, rootDir);
            }
        });
        result.onCopiedFrom(src);

        add(result);
        ItemListener.fireOnCopied(src,result);
        Jenkins.getInstance().rebuildDependencyGraphAsync();

        return result;
    }
1062346
@RequirePOST
    public synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp,
                                           @QueryParameter String name, @QueryParameter String mode,
                                           @QueryParameter String from ) throws IOException, ServletException {
        final Jenkins app = Jenkins.getInstance();
        app.checkPermission(Computer.CREATE);

        if(mode!=null && mode.equals("copy")) {
            name = checkName(name);

            Node src = app.getNode(from);
            if(src==null) {
                if (Util.fixEmpty(from) == null) {
                    throw new Failure(Messages.ComputerSet_SpecifySlaveToCopy());
                } else {
                    throw new Failure(Messages.ComputerSet_NoSuchSlave(from));
                }
            }

            // copy through XStream
            String xml = Jenkins.XSTREAM.toXML(src);
            Node result = (Node) Jenkins.XSTREAM.fromXML(xml);
            result.setNodeName(name);
            if(result instanceof Slave){ //change userId too
                User user = User.current();
                ((Slave)result).setUserId(user==null ? "anonymous" : user.getId());
             }
            result.holdOffLaunchUntilSave = true;

            app.addNode(result);

            // send the browser to the config page
            rsp.sendRedirect2(result.getNodeName()+"/configure");
        } else {
            // proceed to step 2
            if (mode == null) {
                throw new Failure("No mode given");
            }

            NodeDescriptor d = NodeDescriptor.all().findByName(mode);
            if (d == null) {
                throw new Failure("No node type ‘" + mode + "’ is known");
            }
            d.handleNewNodePage(this,name,req,rsp);
        }
    }
1196258
static void createFileFromResource(String resource, Resource file, String password) throws IOException {
	SystemOut.printDate(SystemUtil.getPrintWriter(SystemUtil.OUT), "write file:" + file);
	file.delete();

	InputStream is = InfoImpl.class.getResourceAsStream(resource);
	if (is == null) throw new IOException("file [" + resource + "] does not exist.");
	file.createNewFile();
	IOUtil.copy(is, file, true);
    }
544606
@SuppressWarnings("static-method")
	protected boolean isSourceFile(Resource resource) {
		if (resource instanceof BatchLinkableResource) {
			return !((BatchLinkableResource) resource).isLoadedFromStorage();
		}
		return false;
	}