I actually have a problem, I want to know how to recover an image URL with his key in the Google Cloud Storage, here is the code.
StorageUtils.java
public class StorageUtils {
public static Storage storage;
private static final String DATETIME_FORMAT = "yyyyMMdd_HHmmss";
private static final String CAMERA_FILENAME_PREFIX = "IMG_";
/**
* Uploads a file to a bucket. Filename and content type will be based on
* the original file
* #param bucketName
* Bucket where file will be uploaded
* #param filePath
* Absolute path of the file to upload
* #throws Exception
*/
public static void uploadFile(String bucketName, String filePath)throws Exception {
Storage storage = getStorage();
String timeStamp = new SimpleDateFormat(DATETIME_FORMAT).format(new Date());
String imageFileName = CAMERA_FILENAME_PREFIX + timeStamp;
StorageObject object = new StorageObject();
object.setBucket(bucketName);
File file = new File(filePath);
InputStream stream = new FileInputStream(file);
try {
String contentType = URLConnection
.guessContentTypeFromStream(stream);
InputStreamContent content = new InputStreamContent(contentType,
stream);
Storage.Objects.Insert insert = storage.objects().insert(
bucketName, null, content);
insert.setName(imageFileName + file.getName());
insert.execute();
/////
/////
} finally {
stream.close();
}
}
public static void downloadFile(String bucketName, String fileName, String destinationDirectory) throws Exception {
File directory = new File(destinationDirectory);
if(!directory.isDirectory()) {
throw new Exception("Provided destinationDirectory path is not a directory");
}
File file = new File(directory.getAbsolutePath() + "/" + fileName);
Storage storage = getStorage();
Storage.Objects.Get get = storage.objects().get(bucketName, fileName);
FileOutputStream stream = new FileOutputStream(file);
try{
get.executeMediaAndDownloadTo(stream);
} finally {
stream.close();
}
}
/**
* Deletes a file within a bucket
*
* #param bucketName
* Name of bucket that contains the file
* #param fileName
* The file to delete
* #throws Exception
*/
public static void deleteFile(String bucketName, String fileName) throws Exception {
Storage storage = getStorage();
storage.objects().delete(bucketName, fileName).execute();
}
/**
* Creates a bucket
*
* #param bucketName
* Name of bucket to create
* #throws Exception
*/
public static void createBucket(String bucketName) throws Exception {
Storage storage = getStorage();
Bucket bucket = new Bucket();
bucket.setName(bucketName);
storage.buckets().insert(StorageConstants.PROJECT_ID_PROPERTY, bucket).execute();
}
/**
* Deletes a bucket
*
* #param bucketName
* Name of bucket to delete
* #throws Exception
*/
public static void deleteBucket(String bucketName) throws Exception {
Storage storage = getStorage();
storage.buckets().delete(bucketName).execute();
}
/**
* Lists the objects in a bucket
*
* #param bucketName bucket name to list
* #return Array of object names
* #throws Exception
*/
public static List<String> listBucket(String bucketName) throws Exception {
Storage storage = getStorage();
List<String> list = new ArrayList<String>();
List<StorageObject> objects = storage.objects().list(bucketName).execute().getItems();
if(objects != null) {
for(StorageObject o : objects) {
list.add(o.getName());
}
}
return list;
}
/**
* List the buckets with the project
* (Project is configured in properties)
*
* #return
* #throws Exception
*/
public static List<String> listBuckets() throws Exception {
Storage storage = getStorage();
List<String> list = new ArrayList<String>();
List<Bucket> buckets = storage.buckets().list(StorageConstants.PROJECT_ID_PROPERTY).execute().getItems();
if(buckets != null) {
for(Bucket b : buckets) {
list.add(b.getName());
}
}
return list;
}
private static Storage getStorage() throws Exception {
if (storage == null) {
ApacheHttpTransport httpTransport = new ApacheHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
Credential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(StorageConstants.ACCOUNT_ID_PROPERTY)
.setServiceAccountPrivateKeyFromP12File(getTempPkc12File())
.setServiceAccountScopes(scopes).build();
storage = new Storage.Builder(httpTransport, jsonFactory,
credential).setApplicationName(StorageConstants.APPLICATION_NAME_PROPERTY)
.build();
}
return storage;
}
private static File getTempPkc12File() throws IOException {
InputStream pkc12Stream = StorageConstants.CONTEXT.getAssets().open("key.p12");
File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
OutputStream tempFileStream = new FileOutputStream(tempPkc12File);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = pkc12Stream.read(bytes)) != -1) {
tempFileStream.write(bytes, 0, read);
}
return tempPkc12File;
}
}
Related
I have started the Docker containers and channels as per the "Build your First network" example
from the Hyperledger fabric docs .
I am trying to query a value from the ledger using Fabric Java SDK . The Fabric samples release version I am using is fabric-samples-release-1.0.
I get a certificate verification failed exception during channel initialize
Here is my Java code
public class javaSDKSample {
private static final Logger log = Logger.getLogger(HFJavaSDKBasicExample.class);
public static void main(String[] args) throws Exception {
// create fabric-ca client
HFCAClient caClient = getHfCaClient("http://{remotemachineURL}:7054", null);
// enroll or load admin
AppUser admin = getAdmin(caClient);
log.info(admin);
// register and enroll new user
// AppUser appUser = getUser(caClient, admin, "hfuser7");
// log.info(appUser);
// get HFC client instance
HFClient client = getHfClient();
// set user context
client.setUserContext(admin);
// get HFC channel using the client
Channel channel = getChannel(client);
log.info("Channel: " + channel.getName());
//createCar(client, channel, "CAR18", "MAKE7", "MODEL7", "BLACK", "JOHN", true);
// queryBlockChain(client);
}
/**
* Invoke blockchain query
*
* #param client The HF Client
* #throws ProposalException
* #throws InvalidArgumentException
*/
static void queryBlockChain(HFClient client) throws ProposalException, InvalidArgumentException {
// get channel instance from client
Channel channel = client.getChannel("mychannel");
// create chaincode request
QueryByChaincodeRequest qpr = client.newQueryProposalRequest();
// build cc id providing the chaincode name. Version is omitted here.
ChaincodeID fabcarCCId = ChaincodeID.newBuilder().setName("mycc").build();
qpr.setChaincodeID(fabcarCCId);
// CC function to be called
qpr.setFcn("query");
qpr.setArgs(new String[]{"a"});
Collection<ProposalResponse> res = channel.queryByChaincode(qpr);
// display response
for (ProposalResponse pres : res) {
String stringResponse = new String(pres.getChaincodeActionResponsePayload());
log.info(stringResponse);
}
}
static void createCar(HFClient client,Channel channel, String key, String make,String model,String color,String owner, Boolean doCommit)
throws Exception {
TransactionProposalRequest req = client.newTransactionProposalRequest();
ChaincodeID cid = ChaincodeID.newBuilder().setName("fabcar").build();
req.setChaincodeID(cid);
req.setFcn("createCar");
req.setArgs(new String[] { key, make,model,color,owner });
System.out.println("Executing for " + key);
Collection<ProposalResponse> resps = channel.sendTransactionProposal(req);
if (doCommit) {
channel.sendTransaction(resps);
}
}
/**
* Initialize and get HF channel
*
* #param client The HFC client
* #return Initialized channel
* #throws InvalidArgumentException
* #throws TransactionException
*/
static Channel getChannel(HFClient client) throws InvalidArgumentException, TransactionException {
// initialize channel
// peer name and endpoint in fabcar network
Properties peerProperties = new Properties();
peerProperties.setProperty("pemFile", "D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt");
peerProperties.setProperty("trustServerCertificate", "true"); //testing environment only NOT FOR PRODUCTION!
peerProperties.setProperty("hostnameOverride", "peer0.org1.example.com");
peerProperties.setProperty("sslProvider", "openSSL");
peerProperties.setProperty("negotiationType", "TLS");
peerProperties.put("grpc.NettyChannelBuilderOption.maxInboundMessageSize", 9000000);
Peer peer = client.newPeer("peer0.org1.example.com", "grpcs://{remotemachineURL}:7051");
// eventhub name and endpoint in fabcar network
final Properties eventHubProperties = new Properties();
eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] {5L, TimeUnit.MINUTES});
eventHubProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] {8L, TimeUnit.SECONDS});
EventHub eventHub = client.newEventHub("eventhub01", "grpcs://{remotemachineURL}:7053",eventHubProperties);
// orderer name and endpoint in fabcar network
Properties ordererProperties = new Properties();
ordererProperties.setProperty("pemFile", "D:/FabricCert/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt");
ordererProperties.setProperty("trustServerCertificate", "true"); //testing environment only NOT FOR PRODUCTION!
ordererProperties.setProperty("hostnameOverride", "orderer.example.com");
ordererProperties.setProperty("sslProvider", "openSSL");
ordererProperties.setProperty("negotiationType", "TLS");
ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTime", new Object[] {5L, TimeUnit.MINUTES});
ordererProperties.put("grpc.NettyChannelBuilderOption.keepAliveTimeout", new Object[] {8L, TimeUnit.SECONDS});
Orderer orderer = client.newOrderer("orderer.example.com", "grpcs://{remotemachineURL}:7050");
// channel name in fabcar network
Channel channel = client.newChannel("mychannel");
channel.addPeer(peer);
channel.addEventHub(eventHub);
channel.addOrderer(orderer);
channel.initialize();
return channel;
}
/**
* Create new HLF client
*
* #return new HLF client instance. Never null.
* #throws CryptoException
* #throws InvalidArgumentException
*/
static HFClient getHfClient() throws Exception {
// initialize default cryptosuite
CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
// setup the client
HFClient client = HFClient.createNewInstance();
client.setCryptoSuite(cryptoSuite);
return client;
}
/**
* Register and enroll user with userId.
* If AppUser object with the name already exist on fs it will be loaded and
* registration and enrollment will be skipped.
*
* #param caClient The fabric-ca client.
* #param registrar The registrar to be used.
* #param userId The user id.
* #return AppUser instance with userId, affiliation,mspId and enrollment set.
* #throws Exception
*/
static AppUser getUser(HFCAClient caClient, AppUser registrar, String userId) throws Exception {
AppUser appUser = tryDeserialize(userId);
System.out.println("appUser"+appUser);
if (appUser == null) {
RegistrationRequest rr = new RegistrationRequest(userId, "org1");
String enrollmentSecret = caClient.register(rr, registrar);
Enrollment enrollment = getEnrollment();
enrollment = caClient.enroll(userId, enrollmentSecret);
byte[] certFile = Base64.encodeBase64(enrollment.getCert().getBytes());
byte[] keyFile = Base64.encodeBase64(enrollment.getKey().toString().getBytes());
BufferedWriter bufferedWriter = null;
File myFile = new File("D:/keyfile.key");
// check if file exist, otherwise create the file before writing
if (!myFile.exists()) {
myFile.createNewFile();
}
Writer writer = new FileWriter(myFile);
bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write(enrollment.getKey().toString());
bufferedWriter.close();
appUser = new AppUser(userId, "org1", "Org1MSP", enrollment);
serialize(appUser);
}
return appUser;
}
public static Enrollment getEnrollment() {
return new Enrollment() {
public PrivateKey getKey() {
PrivateKey privateKey = null;
try {
File privateKeyFile = findFileSk("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin#org1.example.com/msp/keystore");
privateKey = getPrivateKeyFromBytes(IOUtils.toByteArray(new FileInputStream(privateKeyFile)));
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return privateKey;
}
public String getCert() {
String certificate = null;
try {
File certificateFile = new File("D:/FabricCert/crypto-config/peerOrganizations/org1.example.com/users/Admin#org1.example.com/msp/signcerts/Admin#org1.example.com-cert.pem");
certificate = new String(IOUtils.toByteArray(new FileInputStream(certificateFile)), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return certificate;
}
};
}
static PrivateKey getPrivateKeyFromBytes(byte[] data) throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
final Reader pemReader = new StringReader(new String(data));
final PrivateKeyInfo pemPair;
try (PEMParser pemParser = new PEMParser(pemReader)) {
pemPair = (PrivateKeyInfo) pemParser.readObject();
}
PrivateKey privateKey = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);
return privateKey;
}
/**
* Enroll admin into fabric-ca using {#code admin/adminpw} credentials.
* If AppUser object already exist serialized on fs it will be loaded and
* new enrollment will not be executed.
*
* #param caClient The fabric-ca client
* #return AppUser instance with userid, affiliation, mspId and enrollment set
* #throws Exception
*/
static AppUser getAdmin(HFCAClient caClient) throws Exception {
AppUser admin = tryDeserialize("admin");
if (admin == null) {
Enrollment adminEnrollment = caClient.enroll("admin", "adminpw");
admin = new AppUser("admin", "org1", "Org1MSP", adminEnrollment);
serialize(admin);
}
return admin;
}
/**
* Get new fabric-ca client
*
* #param caUrl The fabric-ca-server endpoint url
* #param caClientProperties The fabri-ca client properties. Can be null.
* #return new client instance. never null.
* #throws Exception
*/
static HFCAClient getHfCaClient(String caUrl, Properties caClientProperties) throws Exception {
CryptoSuite cryptoSuite = CryptoSuite.Factory.getCryptoSuite();
HFCAClient caClient = HFCAClient.createNewInstance(caUrl, caClientProperties);
caClient.setCryptoSuite(cryptoSuite);
return caClient;
}
// user serialization and deserialization utility functions
// files are stored in the base directory
/**
* Serialize AppUser object to file
*
* #param appUser The object to be serialized
* #throws IOException
*/
static void serialize(AppUser appUser) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(
Paths.get(appUser.getName() + ".jso")))) {
oos.writeObject(appUser);
}
}
/**
* Deserialize AppUser object from file
*
* #param name The name of the user. Used to build file name ${name}.jso
* #return
* #throws Exception
*/
static AppUser tryDeserialize(String name) throws Exception {
if (Files.exists(Paths.get(name + ".jso"))) {
return deserialize(name);
}
return null;
}
static AppUser deserialize(String name) throws Exception {
try (ObjectInputStream decoder = new ObjectInputStream(
Files.newInputStream(Paths.get(name + ".jso")))) {
return (AppUser) decoder.readObject();
}
}
static File findFileSk(String directorys) {
File directory = new File(directorys);
File[] matches = directory.listFiles((dir, name) -> name.endsWith("_sk"));
if (null == matches) {
throw new RuntimeException(format("Matches returned null does %s directory exist?", directory.getAbsoluteFile().getName()));
}
if (matches.length != 1) {
throw new RuntimeException(format("Expected in %s only 1 sk file but found %d", directory.getAbsoluteFile().getName(), matches.length));
}
return matches[0];
}}
And this is my error trace
DEBUG ReferenceCountedOpenSslContext - verification of certificate failed
java.security.cert.CertificateException: No subject alternative DNS name matching {remotemachineURL} found.
at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:191)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:93)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:455)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:436)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:252)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136)
at io.netty.handler.ssl.ReferenceCountedOpenSslClientContext$ExtendedTrustManagerVerifyCallback.verify(ReferenceCountedOpenSslClientContext.java:223)
at io.netty.handler.ssl.ReferenceCountedOpenSslContext$AbstractCertificateVerifier.verify(ReferenceCountedOpenSslContext.java:606)
at org.apache.tomcat.jni.SSL.readFromSSL(Native Method)
at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.readPlaintextData(ReferenceCountedOpenSslEngine.java:470)
at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:927)
at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1033)
at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1076)
at io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:206)
at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1117)
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1039)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:411)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:248)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:349)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:341)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:363)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:349)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:129)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:642)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:565)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:479)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:441)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:745)
I am trying to initialize "mychannel" with peer0 from org1 and orderer and query for a value from the "byfn" network .
Please ignore extra code if any or the comments .
Thanks
Code worked , apparently there was some problem with the Enrollment .
I had used a bad certificate . Changed certificate for enrollment and it worked
Solved .Thanks
Not able to download google sheet from google drive. Facing 403 Insufficient Permission issue.
Please check below code.
public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME = "Drive API Java Quickstart";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
".credentials/drive-java-quickstart");
/** Global instance of the {#link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/**
* Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials at
* ~/.credentials/drive-java-quickstart
*/
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
*
* #return an authorized Credential object.
* #throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in = Quickstart.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Drive client service.
*
* #return an authorized Drive client service
* #throws IOException
*/
public static Drive getDriveService() throws IOException {
Credential credential = authorize();
return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
}
public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Drive service = getDriveService();
// Print the names and IDs for up to 10 files.
FileList result = service.files().list().setPageSize(10).setFields("nextPageToken, files(id, name)").execute();
List<File> files = result.getFiles();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
downloadFile(service, "1l0dX1hOdk0xX5T2ruqnci-75sMwziwiih9BFGX6DcdA");
}
private static void downloadFile(Drive service, String fileId) {
try {
File file = service.files().get(fileId).execute();
System.out.println("Title: " + file.getName());
System.out.println("Description: " + file.getDescription());
System.out.println("MIME type: " + file.getMimeType());
OutputStream outputStream = new ByteArrayOutputStream();
service.files().export(fileId, "application/x-vnd.oasis.opendocument.spreadsheet")
.executeMediaAndDownloadTo(outputStream);
} catch (IOException e) {
System.out.println("An error occurred: " + e);
}
}
}
**Output:**
403 error is displayed after executing above code. Please check below output of above code.
Credentials saved to /home/nikhil/.credentials/drive-java-quickstart
Files:
nikhil (1zNmRFWe_HABvhP_HukQIcOVdUoLllKB49RpPK3_XXn4)
Test Sheet (1l0dX1hOdk0xX5T2ruqnci-75sMwziwiih9BFGX6DcdA)
Getting started (0Bx8dATp9NaeXc3RhcnRlcl9maWxlX2Rhc2hlclYw)
Title: Test Sheet
Description: null
MIME type: application/vnd.google-apps.spreadsheet
An error occurred: com.google.api.client.http.HttpResponseException: 403
Forbidden
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Change the scope and data store directory.
private static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
".credentials/drive-java-quickstart.json");
Added File path for saving the file to local machine.
public static void initialMethod() throws IOException {
// Build a new authorized API client service.
Drive service = getDriveService();
downloadFile(service, "1JYlTtznsCll16upwIIbgXjqDvjsAFO5krSiGjvciO70");
}
private static void downloadFile(Drive service, String fileId) {
try {
File file = service.files().get(fileId).execute();
System.out.println("Title: " + file.getName());
System.out.println("Description: " + file.getDescription());
System.out.println("MIME type: " + file.getMimeType());
OutputStream outputStream = new FileOutputStream(new java.io.File(Constant.DRIVE_EXCEL_PATH + "Test.xlsx"));
service.files().export(fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
.executeMediaAndDownloadTo(outputStream);
System.out.println(outputStream);
} catch (IOException e) {
System.out.println("An error occurred: " + e);
} catch (Exception e) {
System.out.println("An error occurred: " + e);
}
}
Above code helps for downloading file from google drive.
I'm having trouble using the firebase-server-sdk with java, and verifying tokens server side. I have a rest controller setup to take a token from a client, then I run the following code.
FirebaseAuthVerifier.java
#Service
public class FirebaseAuthVerifier implements AuthVerifier {
Logger logger = LoggerFactory.getLogger(this.getClass());
public boolean verify(AuthToken token) throws GeneralSecurityException, IOException {
Task<FirebaseToken> fbTask = FirebaseAuth.getInstance().verifyIdToken(token.getTokenId());
fbTask.getResult();
return fbTask.isSuccessful();
}
}
FirebaseAuthController
#RestController
#RequestMapping("/api/firebase/auth")
public class FirebaseAuthController {
#Autowired
private FirebaseAuthVerifier glAuthVerifier;
#ResponseBody
#CrossOrigin(origins = "http://localhost:3000")
#RequestMapping(value = "/verify", method = RequestMethod.POST, headers = "Content-Type=application/json", consumes = "application/json", produces = "application/json")
public ResponseEntity<AuthTokenVerification> verify(#RequestBody GoogleAuthToken glAuthToken) throws GeneralSecurityException, IOException {
// init return
AuthTokenVerification glAuthTokenVerification = new GoogleAuthTokenVerification();
// verify token
boolean isVerified = this.glAuthVerifier.verify(glAuthToken);
glAuthTokenVerification.setIsVerified(isVerified);
// return json response
ResponseEntity<AuthTokenVerification> response = new ResponseEntity<>(glAuthTokenVerification, HttpStatus.OK);
return response;
}
}
but I receive an exception
java.lang.IllegalStateException: Task is not yet complete
I'm trying to do something simple here, but I'm not sure how to have java wait for completion here.
Using custom jwt id token validation.
#Service
public class FirebaseAuthVerifier implements AuthVerifier {
private static final Logger logger = LoggerFactory.getLogger(FirebaseAuthVerifier.class);
private static final String pubKeyUrl = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com";
/**
*
* #param token
* #return
* #throws GeneralSecurityException
* #throws IOException
*/
public boolean verify(AuthToken token) throws GeneralSecurityException, IOException {
// get public keys
JsonObject publicKeys = getPublicKeysJson();
// verify count
int size = publicKeys.entrySet().size();
int count = 0;
// get json object as map
// loop map of keys finding one that verifies
for (Map.Entry<String, JsonElement> entry: publicKeys.entrySet()) {
// log
logger.info("attempting jwt id token validation with: ");
try {
// trying next key
count++;
// get public key
PublicKey publicKey = getPublicKey(entry);
// validate claim set
Jwts.parser().setSigningKey(publicKey).parse(token.getTokenId());
// success, we can return
return true;
} catch(Exception e) {
// log
logger.info("Firebase id token verification error: ");
logger.info(e.getMessage());
// claims may have been tampered with
// if this is the last key, return false
if (count == size) {
return false;
}
}
}
// no jwt exceptions
return true;
}
/**
*
* #param entry
* #return
* #throws GeneralSecurityException
*/
private PublicKey getPublicKey(Map.Entry<String, JsonElement> entry) throws GeneralSecurityException, IOException {
String publicKeyPem = entry.getValue().getAsString()
.replaceAll("-----BEGIN (.*)-----", "")
.replaceAll("-----END (.*)----", "")
.replaceAll("\r\n", "")
.replaceAll("\n", "")
.trim();
logger.info(publicKeyPem);
// generate x509 cert
InputStream inputStream = new ByteArrayInputStream(entry.getValue().getAsString().getBytes("UTF-8"));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(inputStream);
return cert.getPublicKey();
}
/**
*
* #return
* #throws IOException
*/
private JsonObject getPublicKeysJson() throws IOException {
// get public keys
URI uri = URI.create(pubKeyUrl);
GenericUrl url = new GenericUrl(uri);
HttpTransport http = new NetHttpTransport();
HttpResponse response = http.createRequestFactory().buildGetRequest(url).execute();
// store json from request
String json = response.parseAsString();
// disconnect
response.disconnect();
// parse json to object
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return jsonObject;
}
}
I'm working to make client rest service with jasperserver to generate reports. I'm using the following code to make that:
I have problem in setting server url and report path,
for server url I put http://localhost:8081/jasperserver/
and as shown in next image I put report path rest/report/mytest/my_report but I get 404 not found error in line
File remoteFile = resource.get(File.class);
So how can I get the proper report path from jasperserver?
public class App2 {
private final static String serverUrl = "http://localhost:8081
/jasperserver/";
private final static String serverUser = "jasperadmin";
private final static String serverPassword = "jasperadmin";
public static void main(String arg[]) throws Exception {
Report reporte = new Report();
reporte.setFormat("pdf");
reporte.setOutputFolder("/home/ali/images");
ClientConfig clientConfig;
Map<String, String> resourceCache=new HashMap<String, String>();
clientConfig = new DefaultApacheHttpClientConfig();
clientConfig.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
clientConfig.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
ApacheHttpClient client = ApacheHttpClient.create(clientConfig);
client.addFilter(new HTTPBasicAuthFilter(serverUser, serverPassword));
String describeResourcePath = "/rest/resource" + "/mytest/my_report/";
String generateReportPath = "/rest/report" + "/mytest/my_report/" + "?RUN_OUTPUT_FORMAT=" + reporte.getFormat();
WebResource resource = null;
String resourceResponse = null;
if (resourceCache.containsKey(describeResourcePath)) {
resourceResponse = resourceCache.get(describeResourcePath);
} else {
resource = client.resource(serverUrl);
resource.accept(MediaType.APPLICATION_XML);
resourceResponse = resource.path(describeResourcePath).get(String.class);
resourceCache.put(describeResourcePath, resourceResponse);
}
Document resourceXML = parseResource(resourceResponse);
resourceXML = addParametersToResource(resourceXML, reporte);
resource = client.resource(serverUrl + generateReportPath);
resource.accept(MediaType.TEXT_XML);
System.out.println(resource);
String reportResponse = resource.put(String.class, serializetoXML(resourceXML));
String urlReport = parseReport(reportResponse);
resource = client.resource(urlReport);
System.out.println(resource);
File destFile = null;
try {
File remoteFile = resource.get(File.class);
File parentDir = new File(reporte.getOutputFolder());
destFile = File.createTempFile("report_", "." + getExtension(reporte.getFormat()), parentDir);
FileUtils.copyFile(remoteFile, destFile);
} catch (IOException e) {
throw e;
}
}
/**
*
* #return
* #throws DocumentException
*/
private static Document parseResource(String resourceAsText) throws Exception {
// LOGGER.debug("parseResource:\n" + resourceAsText);
Document document;
try {
document = DocumentHelper.parseText(resourceAsText);
} catch (DocumentException e) {
throw e;
}
return document;
}
/**
*
*/
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}
/**
*
* #param resource
* #param reporte
* #return
*/
private static Document addParametersToResource(Document resource, Report reporte) {
// LOGGER.debug("addParametersToResource");
Element root = resource.getRootElement();
Map<String, String> params = reporte.getParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
root.addElement("parameter").addAttribute("name", key).addText(value);
}
}
// LOGGER.debug("resource:" + resource.asXML());
return resource;
}
/**
*
* #param aEncodingScheme
* #throws IOException
* #throws Exception
*/
private static String serializetoXML(Document resource) throws Exception {
OutputFormat outformat = OutputFormat.createCompactFormat();
ByteArrayOutputStream out = new ByteArrayOutputStream();
outformat.setEncoding("ISO-8859-1");
try {
XMLWriter writer = new XMLWriter(out, outformat);
writer.write(resource);
writer.flush();
} catch (IOException e) {
throw e;
}
return out.toString();
}
/**
*
* #param format
* #return
*/
private static String getExtension(String format) {
String ext = null;
if (format.equals(Report.FORMAT_PDF)) {
ext = "pdf";
} else if (format.equals(Report.FORMAT_EXCEL)) {
ext = "xls";
}
return ext;
}
}
I have fixed it,I need to change path
urlReport = serverUrl + "/report/" + uuid + "?file=report";
to
urlReport = serverUrl + "/rest/report/" + uuid + "?file=report";
in parseReport method
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}
I hava a java swing application and would like to use auto update using AppLoader.java class that i found online at
**https://reportmill.wordpress.com/2014/12/04/automatically-update-your-javapackager-applications/
**
has anybody had any experience with this class. i can not seem to implement this class with my application and am getting errors:
java.io.FileNotFoundException: C:\Users\home\Documents\NetBeansProjects\test_update\build\classes (Access is denied)
and
java.lang.RuntimeException: Main Jar not found!
yep, the code seems not working. I did some modification for the code to make it work. please do as follows:
download the file through http://reportmill.com/snap1/SnapCode1.jar.pack.gz
copy this file to C:\Users\home\Documents\NetBeansProjects\test_update\build\classes
copy and paste the code below and give it a run
import java.io.;
import java.lang.reflect.Method;
import java.net.;
import java.text.;
import java.util.jar.;
import javax.swing.*;
import java.util.zip .GZIPInputStream;
/**
* This app
*/
public class AppLoader {
// Constants
static final String AppDirName = "SnapCode";
static final String JarName = "SnapCode1.jar";
static final String JarURL = "http://reportmill.com/snap1/SnapCode1.jar.pack.gz";
static final String MainClass = "snap.app.App";
/**
* Main method - reinvokes main1() on Swing thread in exception handler.
*/
public static void main(final String args[]) {
// Invoke real main with exception handler
try {
main1(args);
} catch (Throwable e) {
JOptionPane.showMessageDialog(null, e.toString());
e.printStackTrace();
}
}
/**
* Main method: - Gets main Jar file from default, if missing - Updates main
* Jar file from local update file, if previously loaded - Load main Jar
* into URLClassLoader, load main class and invoke main method - Check for
* update from remove site in background
*/
public static void main1(final String args[]) throws Exception {
// Make sure default jar is in place
try {
copyDefaultMainJar();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.toString());
e.printStackTrace();
}
// If Update Jar exists, copy it into place
File jar = getAppFile(JarName);
File updateJar = getAppFile(JarName + ".update");
if (updateJar.exists()) {
copyFile(updateJar, jar);
jar.setLastModified(updateJar.lastModified());
updateJar.delete();
}
// If jar doesn't exist complain bitterly
if (!jar.exists() || !jar.canRead())
throw new RuntimeException("Main Jar not found!");
// Check for updates in background thread
if (args.length == 0 || !args[0].equals("-snap"))
new Thread(new Runnable() {
public void run() {
checkForUpdatesSilent();
}
}).start();
// Create URLClassLoader for main jar file, get App class and invoke
// main
// URLClassLoader ucl = new URLClassLoader(
// new URL[] { jar.toURI().toURL() });
// Class cls = ucl.loadClass(MainClass); // ucl.close();
// Method meth = cls.getMethod("main", new Class[] { String[].class });
// meth.invoke(null, new Object[] { args });
// if (cls == Object.class)
// ((Closeable) ucl).close(); // Getting rid of warning message for ucl
}
/**
* Copies the default main jar into place for initial run.
*/
private static void copyDefaultMainJar() throws IOException, ParseException {
// Get main jar from app package and get location of working jar file
URL url = AppLoader.class.getProtectionDomain().getCodeSource()
.getLocation();
String path0 = url.getPath();
path0 = URLDecoder.decode(path0, "UTF-8");
path0 = path0 + "SnapCode1.jar.pack.gz" ;
File jar0 = getAppFile(JarName);
File jar1 = new File(path0);
// If app package main jar is newer, copy it into place and set time
if (jar0.exists() && jar0.lastModified() >= jar1.lastModified())
return;
copyFile(jar1, jar0);
}
/**
* Check for updates.
*/
private static void checkForUpdatesSilent() {
try {
checkForUpdates();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Check for updates.
*/
private static void checkForUpdates() throws IOException,
MalformedURLException {
// Get URL connection and lastModified time
File jarFile = getAppFile(JarName);
URL url = new URL(JarURL);
URLConnection connection = url.openConnection();
long mod0 = jarFile.lastModified(), mod1 = connection.getLastModified();
if (mod0 >= mod1) {
System.out.println("No update available at " + JarURL + '(' + mod0
+ '>' + mod1 + ')');
return;
}
// Get update file and write to JarName.update
System.out.println("Loading update from " + JarURL);
byte bytes[] = getBytes(connection);
System.out.println("Update loaded");
File updatePacked = getAppFile(JarName + ".pack.gz"), updateFile = getAppFile(JarName
+ ".update");
writeBytes(updatePacked, bytes);
System.out.println("Update saved: " + updatePacked);
unpack(updatePacked, updateFile);
System.out.println("Update unpacked: " + updateFile);
updateFile.setLastModified(mod1);
updatePacked.delete();
// Let the user know
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane
.showMessageDialog(null,
"A new update is available. Restart application to apply");
}
});
}
/**
* Returns the Main jar file.
*/
private static File getAppFile(String aName) {
return new File(getAppDir(), aName);
}
/**
* Returns the Main jar file.
*/
private static File getAppDir() {
return getAppDataDir(AppDirName, true);
}
/**
*
* Utility Methods for AppLoader.
*
*/
/**
* Copies a file from one location to another.
*/
public static File copyFile(File aSource, File aDest) throws IOException {
// Get input stream, output file and output stream
FileInputStream fis = new FileInputStream(aSource);
File out = aDest.isDirectory() ? new File(aDest, aSource.getName())
: aDest;
FileOutputStream fos = new FileOutputStream(out);
// Iterate over read/write until all bytes written
byte[] buf = new byte[8192];
for (int i = fis.read(buf); i != -1; i = fis.read(buf))
fos.write(buf, 0, i);
// Close in/out streams and return out file
fis.close();
fos.close();
return out;
}
/**
* Writes the given bytes (within the specified range) to the given file.
*/
public static void writeBytes(File aFile, byte theBytes[])
throws IOException {
if (theBytes == null) {
aFile.delete();
return;
}
FileOutputStream fileStream = new FileOutputStream(aFile);
fileStream.write(theBytes);
fileStream.close();
}
/**
* Unpacks the given file into the destination file.
*/
public static File unpack(File aFile, File aDestFile) throws IOException {
// Get dest file - if already unpacked, return
File destFile = getUnpackDestination(aFile, aDestFile);
if (destFile.exists() && destFile.lastModified() > aFile.lastModified())
return destFile;
// Create streams: FileInputStream -> GZIPInputStream -> JarOutputStream
// -> FileOutputStream
FileInputStream fileInput = new FileInputStream(aFile);
GZIPInputStream gzipInput = new GZIPInputStream(fileInput);
FileOutputStream fileOut = new FileOutputStream(destFile);
JarOutputStream jarOut = new JarOutputStream(fileOut);
// Unpack file
Pack200.newUnpacker().unpack(gzipInput, jarOut);
// Close streams
fileInput.close();
gzipInput.close();
jarOut.close();
fileOut.close();
// Return destination file
return destFile;
}
/**
* Returns the file that given packed file would be saved to using the
* unpack method.
*/
public static File getUnpackDestination(File aFile, File aDestFile) {
// Get dest file - if null, create from packed file minus .pack.gz
File destFile = aDestFile;
if (destFile == null)
destFile = new File(aFile.getPath().replace(".pack.gz", ""));
// If dest file is directory, change to file inside with packed file
// minus .pack.gz
else if (destFile.isDirectory())
destFile = new File(destFile, aFile.getName().replace(".pack.gz",
""));
// Return destination file
return destFile;
}
/**
* Returns the AppData or Application Support directory file.
*/
public static File getAppDataDir(String aName, boolean doCreate) {
// Get user home + AppDataDir (platform specific) + name (if provided)
String dir = System.getProperty("user.home");
if (isWindows)
dir += File.separator + "AppData" + File.separator + "Local";
else if (isMac)
dir += File.separator + "Library" + File.separator
+ "Application Support";
if (aName != null)
dir += File.separator + aName;
// Create file, actual directory (if requested) and return
File dfile = new File(dir);
if (doCreate && aName != null)
dfile.mkdirs();
return dfile;
}
/**
* Returns bytes for connection.
*/
public static byte[] getBytes(URLConnection aConnection) throws IOException {
InputStream stream = aConnection.getInputStream(); // Get stream for
// connection
byte bytes[] = getBytes(stream); // Get bytes for stream
stream.close(); // Close stream
return bytes; // Return bytes
}
/**
* Returns bytes for an input stream.
*/
public static byte[] getBytes(InputStream aStream) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
byte chunk[] = new byte[8192];
for (int len = aStream.read(chunk, 0, 8192); len > 0; len = aStream
.read(chunk, 0, 8192))
bs.write(chunk, 0, len);
return bs.toByteArray();
}
// Whether Windows/Mac
static boolean isWindows = (System.getProperty("os.name")
.indexOf("Windows") >= 0);
static boolean isMac = (System.getProperty("os.name").indexOf("Mac OS X") >= 0);
}
Your problem is that in your copyFile method FileInputStream takes a wrong File object