io.proximax.xpx.service.local.LocalUploadApi Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of xpx-java-sdk Show documentation
Show all versions of xpx-java-sdk Show documentation
Proximax P2P File Storage Java SDK (NIS1 Compatible)
/*
* Copyright 2018 ProximaX Limited
*
* Licensed 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.
*/
/*
* Proximax P2P Storage REST API
* Proximax P2P Storage REST API
*
* OpenAPI spec version: v0.0.1
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.proximax.xpx.service.local;
import com.google.flatbuffers.FlatBufferBuilder;
import io.ipfs.api.IPFS;
import io.ipfs.api.MerkleNode;
import io.ipfs.api.NamedStreamable;
import io.ipfs.multihash.Multihash;
import io.proximax.xpx.exceptions.ApiException;
import io.proximax.xpx.model.PublishResult;
import io.proximax.xpx.service.intf.UploadApi;
import io.proximax.xpx.service.model.buffers.ResourceHashMessage;
import io.proximax.xpx.utils.ContentTypeUtils;
import io.proximax.xpx.utils.StringUtils;
import org.apache.commons.codec.binary.Base64;
import org.pmw.tinylog.Logger;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.bouncycastle.util.encoders.Hex.encode;
/**
* The Class LocalUploadApi.
*/
@SuppressWarnings("unchecked")
public class LocalUploadApi implements UploadApi {
/** The proximax ifps connection. */
private final IPFS proximaxIfpsConnection;
/**
* Instantiates a new local upload api.
*
* @param proximaxIfpsConnection the proximax ifps connection
*/
public LocalUploadApi(final IPFS proximaxIfpsConnection) {
this.proximaxIfpsConnection = proximaxIfpsConnection;
}
/*
* (non-Javadoc)
*
* @see
* io.proximax.xpx.service.intf.UploadApi#deletePinnedContent(java.lang.
* String)
*/
@Override
public String deletePinnedContent(String multihash) throws ApiException, IOException {
return proximaxIfpsConnection.pin.rm(Multihash.fromBase58(multihash)).toString();
}
/*
* (non-Javadoc)
*
* @see
* io.proximax.xpx.service.intf.UploadApi#uploadBytesBinary(io.proximax.xpx.model
* .UploadBytesBinaryRequestParameter)
*/
@Override
public byte[] uploadBytesBinary(byte[] binaryData, String name, String contentType, String keywords, String metadata)
throws IOException, NoSuchAlgorithmException {
final String nameOrDefault = StringUtils.isEmpty(name) ? String.valueOf(Math.abs(System.currentTimeMillis())) : name;
final String contentTypeOrDetected = ContentTypeUtils.contentTypeLookup(contentType, binaryData);
final String keywordsOrDefault = keywords == null ? "" : keywords;
final String metadataOrDefault = metadata == null ? "" : metadata;
PublishResult spfsBlockResult = exposeAndPinBinary(nameOrDefault, binaryData);
String multiHashString = spfsBlockResult.getMerkleNode().get(0).hash.toBase58();
FlatBufferBuilder builder = new FlatBufferBuilder(1024);
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
int digest = builder.createString(new String(encode(messageDigest.digest(binaryData))));
int hash = builder.createString(multiHashString);
int keywordsRes = builder.createString(keywordsOrDefault);
int metadataRes = builder.createString(metadataOrDefault);
int nameint = builder.createString(nameOrDefault);
int type = builder.createString(contentTypeOrDetected);
ResourceHashMessage.startResourceHashMessage(builder);
ResourceHashMessage.addDigest(builder, digest);
ResourceHashMessage.addHash(builder, hash);
ResourceHashMessage.addKeywords(builder, keywordsRes);
ResourceHashMessage.addMetaData(builder, metadataRes);
ResourceHashMessage.addName(builder, nameint);
ResourceHashMessage.addTimestamp(builder, System.currentTimeMillis());
ResourceHashMessage.addType(builder, type);
builder.finish(ResourceHashMessage.endResourceHashMessage(builder));
return Base64.encodeBase64(builder.sizedByteArray());
}
/*
* (non-Javadoc)
*
* @see
* io.proximax.xpx.service.intf.UploadApi#uploadText(io.proximax.xpx.model.
* UploadTextRequestParameter)
*/
@Override
public byte[] uploadText(byte[] textInBytes, String name, String contentType, String encoding, String keywords, String metadata)
throws IOException, NoSuchAlgorithmException {
final String nameOrDefault = StringUtils.isEmpty(name) ? String.valueOf(Math.abs(System.currentTimeMillis())) : name;
final String contentTypeOrDefault = StringUtils.isEmpty(contentType) ? "text/plain" : contentType;
final String encodingOrDefault = StringUtils.isEmpty(encoding) ? "UTF-8" : encoding;
final String keywordsOrDefault = keywords == null ? "" : keywords;
final String metadataOrDefault = metadata == null ? "" : metadata;
PublishResult spfsBlockResult = exposeAndPinBinary(nameOrDefault, textInBytes);
String multiHashString = spfsBlockResult.getMerkleNode().get(0).hash.toBase58();
FlatBufferBuilder builder = new FlatBufferBuilder(1024);
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
int digest = builder.createString(new String(encode(messageDigest.digest(textInBytes))));
int hash = builder.createString(multiHashString);
int keywordsRes = builder.createString(keywordsOrDefault);
int metadataRes = builder.createString(metadataOrDefault);
int nameint = builder.createString(nameOrDefault);
int type = builder.createString(contentTypeOrDefault);
ResourceHashMessage.startResourceHashMessage(builder);
ResourceHashMessage.addDigest(builder, digest);
ResourceHashMessage.addHash(builder, hash);
ResourceHashMessage.addKeywords(builder, keywordsRes);
ResourceHashMessage.addMetaData(builder, metadataRes);
ResourceHashMessage.addName(builder, nameint);
ResourceHashMessage.addTimestamp(builder, System.currentTimeMillis());
ResourceHashMessage.addType(builder, type);
builder.finish(ResourceHashMessage.endResourceHashMessage(builder));
// return base64 encoded bytearray.
return Base64.encodeBase64(builder.sizedByteArray());
}
/* (non-Javadoc)
* @see io.proximax.xpx.service.intf.UploadApi#uploadPath(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public byte[] uploadPath(String path, String name, String keywords, String metadata) throws NoSuchAlgorithmException {
final String nameOrDefault = StringUtils.isEmpty(name) ? String.valueOf(Math.abs(System.currentTimeMillis())) : name;
final String keywordsOrDefault = keywords == null ? "" : keywords;
final String metadataOrDefault = metadata == null ? "" : metadata;
final String contentType = "Directory";
// Expose/load the file.
PublishResult spfsBlockResult = exposeAndPinPath(path);
String multiHashString = "";
Iterator merkleNodeIter = spfsBlockResult.getMerkleNode().iterator();
// log it.
spfsBlockResult.getMerkleNode().stream().forEach(n -> {
Logger.error(n);
});
while (merkleNodeIter.hasNext()) {
MerkleNode merkleNode = (MerkleNode) merkleNodeIter.next();
String namePath = "/" + merkleNode.name.get();
if (namePath.equals(path)) {
multiHashString = merkleNode.hash.toBase58();
break;
}
}
if (multiHashString == null || multiHashString.equals("")) {
multiHashString = spfsBlockResult.getMerkleNode().get(spfsBlockResult.getMerkleNode().size() - 1).hash
.toBase58();
}
// Serialize
FlatBufferBuilder builder = new FlatBufferBuilder(1024);
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
int digest = builder.createString(new String(encode(messageDigest.digest(path.getBytes()))));
int hash = builder.createString(multiHashString);
int keywordsRes = builder.createString(keywordsOrDefault);
int metadataRes = builder.createString(metadataOrDefault);
int nameint = builder.createString(nameOrDefault);
int type = builder.createString(contentType);
ResourceHashMessage.startResourceHashMessage(builder);
ResourceHashMessage.addDigest(builder, digest);
ResourceHashMessage.addHash(builder, hash);
ResourceHashMessage.addKeywords(builder, keywordsRes);
ResourceHashMessage.addMetaData(builder, metadataRes);
ResourceHashMessage.addName(builder, nameint);
ResourceHashMessage.addTimestamp(builder, System.currentTimeMillis());
ResourceHashMessage.addType(builder, type);
builder.finish(ResourceHashMessage.endResourceHashMessage(builder));
// return base64 encoded bytearray.
return Base64.encodeBase64(builder.sizedByteArray());
}
/**
* Expose and pin binary.
*
* @param name
* the name
* @param binary
* the binary
* @return the publish result
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ApiException
* the api exception
*/
private PublishResult exposeAndPinBinary(String name, byte[] binary) throws IOException {
PublishResult result = new PublishResult();
NamedStreamable.ByteArrayWrapper byteArrayWrapper = new NamedStreamable.ByteArrayWrapper(name, binary);
List node = proximaxIfpsConnection.add(byteArrayWrapper);
List pinned = proximaxIfpsConnection.pin.add(node.get(0).hash);
result.setMerkleNode(node);
result.setMultiHash(pinned);
return result;
}
/**
* Expose and pin path.
*
* @param path the path
* @return the publish result
*/
public PublishResult exposeAndPinPath(String path) {
PublishResult result = new PublishResult();
try {
List streamables = new ArrayList();
NamedStreamable.FileWrapper fileWrapper = new NamedStreamable.FileWrapper(new File(path));
streamables
.add(new NamedStreamable.DirWrapper(new File(path).getAbsolutePath(), fileWrapper.getChildren()));
// recursePathToBeAdded(streamables, path);
List merkleNode = proximaxIfpsConnection.add(streamables, true, false);
result.setMerkleNode(merkleNode);
} catch (Exception e) {
Logger.error("Error on decoding NEM Transaction Message." + e.getMessage());
}
return result;
}
/**
* Recurse path to be added.
*
* @param streamables
* the streamables
* @param path
* the path
*/
private void recursePathToBeAdded(List streamables, String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isDirectory()) {
NamedStreamable.FileWrapper fileWrapper = new NamedStreamable.FileWrapper(file);
streamables.add(new NamedStreamable.DirWrapper(file.getAbsolutePath(), fileWrapper.getChildren()));
recursePathToBeAdded(streamables, file.getAbsolutePath());
} else {
streamables.add(new NamedStreamable.FileWrapper(file));
}
}
}
/**
* Expose binary.
*
* @param name
* the name
* @param binary
* the binary
* @return the publish result
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ApiException
* the api exception
*/
private PublishResult exposeBinary(String name, byte[] binary) throws IOException {
PublishResult result = new PublishResult();
NamedStreamable.ByteArrayWrapper byteArrayWrapper = new NamedStreamable.ByteArrayWrapper(name, binary);
List node = proximaxIfpsConnection.add(byteArrayWrapper);
result.setMerkleNode(node);
return result;
}
/**
* Gets the binary hash only.
*
* @param name
* the name
* @param binary
* the binary
* @return the binary hash only
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ApiException
* the api exception
*/
private PublishResult getBinaryHashOnly(String name, byte[] binary) throws IOException {
PublishResult result = null;
// store it in ipfs
result = new PublishResult();
NamedStreamable.ByteArrayWrapper byteArrayWrapper = new NamedStreamable.ByteArrayWrapper(name, binary);
List node = proximaxIfpsConnection.add(byteArrayWrapper, false, true);
result.setMerkleNode(node);
return result;
}
/**
* Grab dirs.
*
* @param path
* the path
* @param node
* the node
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ApiException
* the api exception
*/
private void grabDirs(String path, List node) throws IOException {
File[] directories = new File(path).listFiles(File::isDirectory);
for (File f : directories) {
NamedStreamable.FileWrapper fileWrapper = new NamedStreamable.FileWrapper(f);
NamedStreamable.DirWrapper dirWrapper = new NamedStreamable.DirWrapper(f.getName().toString(),
fileWrapper.getChildren());
node.addAll(proximaxIfpsConnection.add(dirWrapper, true, false));
grabDirs(f.getAbsolutePath(), node);
}
}
}