Search in sources :

Example 1 with InputStreamContent

use of com.google.api.client.http.InputStreamContent in project camel by apache.

the class GoogleDriveFilesConverter method genericFileToGoogleDriveFile.

@Converter
public static com.google.api.services.drive.model.File genericFileToGoogleDriveFile(GenericFile<?> file, Exchange exchange) throws Exception {
    if (file.getFile() instanceof File) {
        File f = (File) file.getFile();
        com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();
        fileMetadata.setTitle(f.getName());
        FileContent mediaContent = new FileContent(null, f);
        if (exchange != null) {
            exchange.getIn().setHeader("CamelGoogleDrive.content", fileMetadata);
            exchange.getIn().setHeader("CamelGoogleDrive.mediaContent", mediaContent);
        }
        return fileMetadata;
    }
    if (exchange != null) {
        // body wasn't a java.io.File so let's try to convert it
        file.getBinding().loadContent(exchange, file);
        InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, file.getBody());
        com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();
        fileMetadata.setTitle(file.getFileName());
        InputStreamContent mediaContent = new InputStreamContent(null, is);
        if (exchange != null) {
            exchange.getIn().setHeader("CamelGoogleDrive.content", fileMetadata);
            exchange.getIn().setHeader("CamelGoogleDrive.mediaContent", mediaContent);
        }
        return fileMetadata;
    }
    return null;
}
Also used : FileContent(com.google.api.client.http.FileContent) InputStream(java.io.InputStream) InputStreamContent(com.google.api.client.http.InputStreamContent) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) Converter(org.apache.camel.Converter)

Example 2 with InputStreamContent

use of com.google.api.client.http.InputStreamContent in project druid by druid-io.

the class GoogleDataSegmentPusher method insert.

public void insert(final File file, final String contentType, final String path) throws IOException {
    LOG.info("Inserting [%s] to [%s]", file, path);
    FileInputStream fileSteam = new FileInputStream(file);
    InputStreamContent mediaContent = new InputStreamContent(contentType, fileSteam);
    mediaContent.setLength(file.length());
    storage.insert(config.getBucket(), path, mediaContent);
}
Also used : InputStreamContent(com.google.api.client.http.InputStreamContent) FileInputStream(java.io.FileInputStream)

Example 3 with InputStreamContent

use of com.google.api.client.http.InputStreamContent in project api-samples by youtube.

the class UploadVideo method main.

/**
     * Upload the user-selected video to the user's YouTube channel. The code
     * looks for the video in the application's project folder and uses OAuth
     * 2.0 to authorize the API request.
     *
     * @param args command line args (not used).
     */
public static void main(String[] args) {
    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");
        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName("youtube-cmdline-uploadvideo-sample").build();
        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);
        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();
        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);
        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();
        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());
        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);
        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);
        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT, UploadVideo.class.getResourceAsStream("/sample-video.mp4"));
        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", videoObjectDefiningMetadata, mediaContent);
        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);
        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {

            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch(uploader.getUploadState()) {
                    case INITIATION_STARTED:
                        System.out.println("Initiation Started");
                        break;
                    case INITIATION_COMPLETE:
                        System.out.println("Initiation Completed");
                        break;
                    case MEDIA_IN_PROGRESS:
                        System.out.println("Upload in progress");
                        System.out.println("Upload percentage: " + uploader.getProgress());
                        break;
                    case MEDIA_COMPLETE:
                        System.out.println("Upload Completed!");
                        break;
                    case NOT_STARTED:
                        System.out.println("Upload Not Started!");
                        break;
                }
            }
        };
        uploader.setProgressListener(progressListener);
        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();
        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}
Also used : VideoSnippet(com.google.api.services.youtube.model.VideoSnippet) Credential(com.google.api.client.auth.oauth2.Credential) MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) VideoStatus(com.google.api.services.youtube.model.VideoStatus) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) MediaHttpUploaderProgressListener(com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener) IOException(java.io.IOException) YouTube(com.google.api.services.youtube.YouTube) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Video(com.google.api.services.youtube.model.Video) InputStreamContent(com.google.api.client.http.InputStreamContent)

Example 4 with InputStreamContent

use of com.google.api.client.http.InputStreamContent in project ignite by apache.

the class TcpDiscoveryGoogleStorageIpFinder method registerAddresses.

/** {@inheritDoc} */
@Override
public void registerAddresses(Collection<InetSocketAddress> addrs) throws IgniteSpiException {
    assert !F.isEmpty(addrs);
    init();
    for (InetSocketAddress addr : addrs) {
        String key = keyFromAddr(addr);
        StorageObject object = new StorageObject();
        object.setBucket(bucketName);
        object.setName(key);
        InputStreamContent content = new InputStreamContent("application/octet-stream", OBJECT_CONTENT);
        content.setLength(OBJECT_CONTENT.available());
        try {
            Storage.Objects.Insert insertObject = storage.objects().insert(bucketName, object, content);
            insertObject.execute();
        } catch (Exception e) {
            throw new IgniteSpiException("Failed to put entry [bucketName=" + bucketName + ", entry=" + key + ']', e);
        }
    }
}
Also used : StorageObject(com.google.api.services.storage.model.StorageObject) InetSocketAddress(java.net.InetSocketAddress) InputStreamContent(com.google.api.client.http.InputStreamContent) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) GeneralSecurityException(java.security.GeneralSecurityException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) IOException(java.io.IOException)

Example 5 with InputStreamContent

use of com.google.api.client.http.InputStreamContent in project ddf by codice.

the class PaosInInterceptor method getHttpResponse.

HttpResponseWrapper getHttpResponse(String responseConsumerURL, String soapResponse, Message message) throws IOException {
    //This used to use the ApacheHttpTransport which appeared to not work with 2 way TLS auth but this one does
    HttpTransport httpTransport = new NetHttpTransport();
    HttpContent httpContent = new InputStreamContent(TEXT_XML, new ByteArrayInputStream(soapResponse.getBytes("UTF-8")));
    //this handles redirects for us
    ((InputStreamContent) httpContent).setRetrySupported(true);
    HttpRequest httpRequest = httpTransport.createRequestFactory().buildPostRequest(new GenericUrl(responseConsumerURL), httpContent);
    HttpUnsuccessfulResponseHandler httpUnsuccessfulResponseHandler = (request, response, supportsRetry) -> {
        String redirectLocation = response.getHeaders().getLocation();
        if (request.getFollowRedirects() && HttpStatusCodes.isRedirect(response.getStatusCode()) && redirectLocation != null) {
            String method = (String) message.get(Message.HTTP_REQUEST_METHOD);
            HttpContent content = null;
            if (!isRedirectable(method)) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                message.setContent(OutputStream.class, byteArrayOutputStream);
                BodyWriter bodyWriter = new BodyWriter();
                bodyWriter.handleMessage(message);
                content = new InputStreamContent((String) message.get(Message.CONTENT_TYPE), new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            }
            // resolve the redirect location relative to the current location
            request.setUrl(new GenericUrl(request.getUrl().toURL(redirectLocation)));
            request.setRequestMethod(method);
            request.setContent(content);
            // remove Authorization and If-* headers
            request.getHeaders().setAuthorization((String) null);
            request.getHeaders().setIfMatch(null);
            request.getHeaders().setIfNoneMatch(null);
            request.getHeaders().setIfModifiedSince(null);
            request.getHeaders().setIfUnmodifiedSince(null);
            request.getHeaders().setIfRange(null);
            request.getHeaders().setCookie((String) ((List) response.getHeaders().get("set-cookie")).get(0));
            return true;
        }
        return false;
    };
    httpRequest.setUnsuccessfulResponseHandler(httpUnsuccessfulResponseHandler);
    httpRequest.getHeaders().put(SOAP_ACTION, HTTP_WWW_OASIS_OPEN_ORG_COMMITTEES_SECURITY);
    //has 20 second timeout by default
    HttpResponse httpResponse = httpRequest.execute();
    HttpResponseWrapper httpResponseWrapper = new HttpResponseWrapper();
    httpResponseWrapper.statusCode = httpResponse.getStatusCode();
    httpResponseWrapper.content = httpResponse.getContent();
    return httpResponseWrapper;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) RestSecurity(org.codice.ddf.security.common.jaxrs.RestSecurity) StringUtils(org.apache.commons.lang.StringUtils) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) DOMUtils(org.apache.cxf.helpers.DOMUtils) ResponseBuilder(ddf.security.liberty.paos.impl.ResponseBuilder) SOAPException(javax.xml.soap.SOAPException) DOM2Writer(org.apache.wss4j.common.util.DOM2Writer) IDPList(org.opensaml.saml.saml2.core.IDPList) LoggerFactory(org.slf4j.LoggerFactory) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) AbstractPhaseInterceptor(org.apache.cxf.phase.AbstractPhaseInterceptor) HttpRequest(com.google.api.client.http.HttpRequest) SamlProtocol(ddf.security.samlp.SamlProtocol) HttpResponse(com.google.api.client.http.HttpResponse) IDPEntry(org.opensaml.saml.saml2.core.IDPEntry) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) Fault(org.apache.cxf.interceptor.Fault) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Document(org.w3c.dom.Document) Map(java.util.Map) XMLStreamException(javax.xml.stream.XMLStreamException) Node(org.w3c.dom.Node) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) GenericUrl(com.google.api.client.http.GenericUrl) OpenSAMLUtil(org.apache.wss4j.common.saml.OpenSAMLUtil) XMLObject(org.opensaml.core.xml.XMLObject) HttpContent(com.google.api.client.http.HttpContent) OutputStream(java.io.OutputStream) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Response(ddf.security.liberty.paos.Response) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Message(org.apache.cxf.message.Message) HttpTransport(com.google.api.client.http.HttpTransport) IOException(java.io.IOException) AccessDeniedException(org.apache.cxf.interceptor.security.AccessDeniedException) StandardCharsets(java.nio.charset.StandardCharsets) Request(org.opensaml.saml.saml2.ecp.Request) IOUtils(org.apache.commons.io.IOUtils) Base64(java.util.Base64) List(java.util.List) SOAPPart(javax.xml.soap.SOAPPart) Element(org.w3c.dom.Element) HttpStatusCodes(com.google.api.client.http.HttpStatusCodes) InputStreamContent(com.google.api.client.http.InputStreamContent) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) ByteArrayInputStream(java.io.ByteArrayInputStream) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) InputStreamContent(com.google.api.client.http.InputStreamContent) HttpContent(com.google.api.client.http.HttpContent)

Aggregations

InputStreamContent (com.google.api.client.http.InputStreamContent)13 IOException (java.io.IOException)6 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)5 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)5 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)5 Credential (com.google.api.client.auth.oauth2.Credential)4 YouTube (com.google.api.services.youtube.YouTube)4 FileInputStream (java.io.FileInputStream)4 Objects (com.google.api.services.storage.model.Objects)2 Caption (com.google.api.services.youtube.model.Caption)2 CaptionSnippet (com.google.api.services.youtube.model.CaptionSnippet)2 Video (com.google.api.services.youtube.model.Video)2 VideoSnippet (com.google.api.services.youtube.model.VideoSnippet)2 VideoStatus (com.google.api.services.youtube.model.VideoStatus)2 BufferedInputStream (java.io.BufferedInputStream)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 Calendar (java.util.Calendar)2 FileContent (com.google.api.client.http.FileContent)1 GenericUrl (com.google.api.client.http.GenericUrl)1