gerlowskija commented on a change in pull request #39:
URL: https://github.com/apache/solr/pull/39#discussion_r616882290



##########
File path: 
solr/contrib/gcs-repository/src/java/org/apache/solr/gcs/GCSBackupRepository.java
##########
@@ -0,0 +1,466 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.solr.gcs;
+
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.cloud.ReadChannel;
+import com.google.cloud.WriteChannel;
+import com.google.cloud.storage.Blob;
+import com.google.cloud.storage.BlobId;
+import com.google.cloud.storage.BlobInfo;
+import com.google.cloud.storage.Storage;
+import com.google.cloud.storage.StorageException;
+import com.google.cloud.storage.StorageOptions;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.store.BufferedIndexInput;
+import org.apache.lucene.store.ChecksumIndexInput;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.core.DirectoryFactory;
+import org.apache.solr.core.backup.repository.BackupRepository;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.invoke.MethodHandles;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.ByteBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.WritableByteChannel;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.NoSuchFileException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import static java.net.HttpURLConnection.HTTP_PRECON_FAILED;
+
+/**
+ * {@link BackupRepository} implementation that stores files in Google Cloud 
Storage ("GCS").
+ */
+public class GCSBackupRepository implements BackupRepository {
+    private static final Logger log = 
LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+    private static final int LARGE_BLOB_THRESHOLD_BYTE_SIZE = 5 * 1024 * 1024;
+    private static final int BUFFER_SIZE = 16 * 1024 * 1024;
+    protected Storage storage;
+
+    private NamedList<Object> config = null;
+    protected String bucketName = null;
+    protected String credentialPath = null;
+    protected StorageOptions.Builder storageOptionsBuilder = null;
+
+    protected Storage initStorage() {
+        if (storage != null)
+            return storage;
+
+        try {
+            if (credentialPath == null) {
+                throw new 
IllegalArgumentException(GCSConfigParser.missingCredentialErrorMsg());
+            }
+
+            log.info("Creating GCS client using credential at {}", 
credentialPath);
+            GoogleCredentials credential = GoogleCredentials.fromStream(new 
FileInputStream(credentialPath));
+            storageOptionsBuilder.setCredentials(credential);
+            storage = storageOptionsBuilder.build().getService();
+        } catch (IOException e) {
+            throw new IllegalStateException(e);
+        }
+        return storage;
+    }
+
+    @Override
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    public void init(NamedList args) {
+        this.config = (NamedList<Object>) args;
+        final GCSConfigParser configReader = new GCSConfigParser();
+        final GCSConfigParser.GCSConfig parsedConfig = 
configReader.parseConfiguration(config);
+
+        this.bucketName = parsedConfig.getBucketName();
+        this.credentialPath = parsedConfig.getCredentialPath();
+        this.storageOptionsBuilder = parsedConfig.getStorageOptionsBuilder();
+
+        initStorage();
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public <T> T getConfigProperty(String name) {
+        return (T) this.config.get(name);
+    }
+
+    @Override
+    public URI createURI(String location) {
+        Objects.requireNonNull(location);
+
+        URI result;
+        try {
+            result = new URI(location);
+        } catch (URISyntaxException e) {
+            throw new IllegalArgumentException("Error on creating URI", e);
+        }
+
+        return result;
+    }
+
+    @Override
+    public URI resolve(URI baseUri, String... pathComponents) {
+        StringBuilder builder = new StringBuilder(baseUri.toString());
+        for (String path : pathComponents) {
+            if (path != null && !path.isEmpty()) {
+                if (builder.charAt(builder.length()-1) != '/') {
+                    builder.append('/');
+                }
+                builder.append(path);
+            }
+        }
+
+        return URI.create(builder.toString());
+    }
+
+    @Override
+    public boolean exists(URI path) throws IOException {
+        if (path.toString().equals(getConfigProperty("location"))) {
+            return true;
+        }
+
+        if (path.toString().endsWith("/")) {
+            return storage.get(bucketName, path.toString(), 
Storage.BlobGetOption.fields()) != null;
+        } else {
+            final String filePath = path.toString();
+            final String directoryPath = path.toString() + "/";
+            return storage.get(bucketName, filePath, 
Storage.BlobGetOption.fields()) != null ||
+                    storage.get(bucketName, directoryPath, 
Storage.BlobGetOption.fields()) != null;
+        }
+
+    }
+
+    @Override
+    public PathType getPathType(URI path) throws IOException {
+        if (path.toString().endsWith("/"))
+            return PathType.DIRECTORY;
+
+        Blob blob = storage.get(bucketName, path.toString()+"/", 
Storage.BlobGetOption.fields());
+        if (blob != null)
+            return PathType.DIRECTORY;
+
+        return PathType.FILE;
+    }
+
+    private String toBlobName(URI path) {
+        return path.toString();
+    }
+
+    @Override
+    public String[] listAll(URI path) throws IOException {
+        String blobName = path.toString();
+        if (!blobName.endsWith("/"))
+            blobName += "/";
+
+        final String pathStr = blobName;
+        final LinkedList<String> result = new LinkedList<>();
+        storage.list(
+                bucketName,
+                Storage.BlobListOption.currentDirectory(),
+                Storage.BlobListOption.prefix(pathStr),
+                Storage.BlobListOption.fields())
+        .iterateAll().forEach(
+                blob -> {
+                    assert blob.getName().startsWith(pathStr);
+                    final String suffixName = 
blob.getName().substring(pathStr.length());
+                    if (!suffixName.isEmpty()) {
+                        // Remove trailing '/' if present
+                        if (suffixName.endsWith("/")) {
+                            result.add(suffixName.substring(0, 
suffixName.length() - 1));
+                        } else {
+                            result.add(suffixName);
+                        }
+                    }
+                });
+
+        return result.toArray(new String[0]);

Review comment:
       Gonna respectfully pass on this one - maybe when my work has me more in 
Java 11 codebases I'll prefer this too, but to my uncultured Java 8 eyes 
`String[]::new` makes me stop and think too long haha.  And it's one more thing 
to fix if I try an 8.x backport.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to