简体   繁体   中英

Impossible to Upload file to rest api with jersey

My nexus exposes a REST API to upload file. With curl I can upload with this command :

curl -X POST " http://myurl:9086/service/rest/v1/components?repository=ebooks-store " -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "raw.directory=test" -F "raw.asset1=@billet.pdf;type=application/pdf" -F "raw.asset1.filename=billet.pdf"

The documentation says that only 3 informations are required : https://help.sonatype.com/repomanager3/rest-and-integration-api/components-api

raw.directory (String = Destination for upload files (e.g. /path/to/files)) 
raw.assetN  (File   = at least one  Binary asset) 
raw.assetN.filename (String = Filename to be used for the corresponding assetN asset)

So in my java code I try to do the same thing using Jersey:

FileDataBodyPart filePart = new FileDataBodyPart("file", new File("C:\\Users\\tpolo\Documents\\article.pdf"));
        FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
        FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
                .field("format","raw")
                .field("raw.asset1.filename","article.pdf")
                .field("raw.directory", "test")
                .field("raw.asset1","article.pdf")
                .bodyPart(filePart);

        String url = nexusBaseUrl+"v1/components?repository="+repositoryName;
        WebTarget target = client.target(url);
        //Very important to do, we have to register this
        target.register(MultiPartFeature.class);
        final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType()));

        //Use response object to verify upload success

        formDataMultiPart.close();
        multipart.close();

In the log of my nexus, I have this error :

2019-08-22 21:43:32,122+0000 INFO [qtp969575574-7812] admin org.sonatype.nexus.repository.upload.internal.UploadManagerImpl - Uploading component with parameters: repository="ebooks-store" format="raw" directory="test" 2019-08-22 21:43:32,122+0000 INFO [qtp969575574-7812] admin org.sonatype.nexus.repository.upload.internal.UploadManagerImpl - Asset with parameters: file="null" filename="article.pdf" 2019-08-22 21:43:32,122+0000 INFO [qtp969575574-7812] admin org.sonatype.nexus.repository.upload.internal.UploadManagerImpl - Asset with parameters: file="article.pdf" 2019-08-22 21:43:32,124+0000 WARN [qtp969575574-7812] admin org.sonatype.nexus.siesta.internal.ValidationErrorsExceptionMapper - (ID 678c48c7-d7fc-438d-94ab-df54977fed23) Failed to map exception org.jboss.resteasy.spi.BadRequestException: RESTEASY003520: Malformed quality value. at org.jboss.resteasy.core.request.QualityValue.parseAsInteger(QualityValue.java:112) ... 2019-08-22 21:43:32,125+0000 WARN [qtp969575574-7812] admin org.sonatype.nexus.siesta.internal.ValidationErrorsExceptionMapper - (ID 678c48c7-d7fc-438d-94ab-df54977fed23) Response: [500] 'FaultXO{id='678c48c7-d7fc-438d-94ab-df54977fed23', message='org.jboss.resteasy.spi.BadRequestException: RESTEASY003520: Malformed quality value.'}'; mapped from: org.sonatype.nexus.rest.ValidationErrorsException: Missing required asset field 'Filename' on '2'

What did I do wrong ? When I change raw.asset1.filename by just Filename I got

2019-08-22 21:48:51,653+0000 INFO [qtp969575574-7831] admin org.sonatype.nexus.repository.upload.internal.UploadManagerImpl - Uploading component with parameters: repository="ebooks-store" format="raw" Filename="article.pdf" directory="test" 2019-08-22 21:48:51,653+0000 INFO [qtp969575574-7831] admin org.sonatype.nexus.repository.upload.internal.UploadManagerImpl - Asset with parameters: file="null" 2019-08-22 21:48:51,653+0000 INFO [qtp969575574-7831] admin org.sonatype.nexus.repository.upload.internal.UploadManagerImpl - Asset with parameters: file="article.pdf" 2019-08-22 21:48:51,655+0000 WARN [qtp969575574-7831] admin org.sonatype.nexus.siesta.internal.ValidationErrorsExceptionMapper - (ID 2e179b6c-7c6a-486d-bb17-41a86da08103) Failed to map exception org.jboss.resteasy.spi.BadRequestException: RESTEASY003520: Malformed quality value. message='org.jboss.resteasy.spi.BadRequestException: RESTEASY003520: Malformed quality value.'}'; mapped from: org.sonatype.nexus.rest.ValidationErrorsException: Unknown component field 'Filename', Missing required asset field 'Filename' on '1', Missing required asset field 'Filename' on '2', The assets 1 and 2 have identical coordinates

I really don't know what to do.

If you have a maven repo it seems that you have to use the Maven values to upload. Raw didn't work for me. But this worked with my Maven repo.


import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

class Authenticator implements ClientRequestFilter
{
    private final String user;
    private final String password;

    Authenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public void filter(ClientRequestContext requestContext) throws IOException {
        MultivaluedMap<String, Object> headers = requestContext.getHeaders();
        final String basicAuthentication = getBasicAuthentication();
        headers.add("Authorization", basicAuthentication);
    }

    private String getBasicAuthentication() {
        String token = this.user + ":" + this.password;
        try {
            return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new IllegalStateException("Cannot encode with UTF-8", ex);
        }
    }
}
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.glassfish.jersey.media.multipart.internal.MultiPartWriter;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;

public class NexusFacade
{
    public Response uploadFile(File file, String repository, String groupId, String artifactId, String extension, String version)
    {
        String user = "XXXXX";
        String password = "XXXXX";
        ClientConfig configuration = new ClientConfig();
        configuration.register(MultiPartWriter.class);
        Client client = ClientBuilder.newClient(configuration).register(new Authenticator(user, password));

        FormDataMultiPart multipartEntity = new FormDataMultiPart();
        multipartEntity.bodyPart(new FileDataBodyPart("maven2.asset1", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
        multipartEntity.bodyPart(new FormDataBodyPart("maven2.asset1.extension", extension, MediaType.TEXT_PLAIN_TYPE));
        multipartEntity.bodyPart(new FormDataBodyPart("maven2.groupId", groupId, MediaType.TEXT_PLAIN_TYPE));
        multipartEntity.bodyPart(new FormDataBodyPart("maven2.artifactId", artifactId, MediaType.TEXT_PLAIN_TYPE));
        multipartEntity.bodyPart(new FormDataBodyPart("maven2.version", version, MediaType.TEXT_PLAIN_TYPE));
        multipartEntity.bodyPart(new FormDataBodyPart("maven2.generate-pom", "false", MediaType.TEXT_PLAIN_TYPE));

        return client.target(baseURL)
                .path("/service/rest/v1/components")
                .queryParam("repository", repository)
                .request()
                .post(Entity.entity(multipartEntity, MediaType.MULTIPART_FORM_DATA));
    }

    private String baseURL = "http://my-nexus.localhost";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM