I am new to Google Contact Api. i am trying to retrieve all my contacts using Google Contact API. For this I used Oauth authentication and Google Contact API.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gdata.client.Query;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters.OAuthType;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.GroupMembershipInfo;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.Im;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.ServiceException;
public class GoogleContactsAccess{
/* This method will authenticate the user credentials passed to it and returns an instance of ContactService class.*/
public ContactsService authenticateId(){
GoogleOAuthParameters oAuthParameters = null;
ContactsService contactService = null;
try{
contactService = new ContactsService("API Project");
oAuthParameters = new GoogleOAuthParameters();
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
oAuthParameters.setScope("https://www.google.com/m8/feeds");
oAuthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
oAuthParameters.addCustomBaseParameter("xoauth_requestor_id", "my ID#gmail.com");
contactService.setOAuthCredentials(oAuthParameters,new OAuthHmacSha1Signer());
contactService.getRequestFactory().setHeader("GData-Version", "3.0");
}catch(Exception e){
e.printStackTrace();
}
return contactService;
}
/* This method will print details of all the contacts available in that particular Google account. */
public void printAllContacts(ContactsService myService)throws ServiceException, IOException {
// Request the feed
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json'");
// The query that will retrieve all contacts
Query myQuery = new Query(feedUrl);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
// Print the results
System.out.println(resultFeed.getTitle().getPlainText());
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName()) {
Name name = entry.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi()) {
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
System.out.println("\t\t" + fullNameToDisplay);
} else {
System.out.println("\t\t (no full name found)");
}
if (name.hasNamePrefix()) {
System.out.println("\t\t" + name.getNamePrefix().getValue());
} else {
System.out.println("\t\t (no name prefix found)");
}
if (name.hasGivenName()) {
String givenNameToDisplay = name.getGivenName().getValue();
if (name.getGivenName().hasYomi()) {
givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
}
System.out.println("\t\t" + givenNameToDisplay);
} else {
System.out.println("\t\t (no given name found)");
}
if (name.hasAdditionalName()) {
String additionalNameToDisplay = name.getAdditionalName().getValue();
if (name.getAdditionalName().hasYomi()) {
additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
}
System.out.println("\t\t" + additionalNameToDisplay);
} else {
System.out.println("\t\t (no additional name found)");
}
if (name.hasFamilyName()) {
String familyNameToDisplay = name.getFamilyName().getValue();
if (name.getFamilyName().hasYomi()) {
familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
}
System.out.println("\t\t" + familyNameToDisplay);
} else {
System.out.println("\t\t (no family name found)");
}
if (name.hasNameSuffix()) {
System.out.println("\t\t" + name.getNameSuffix().getValue());
} else {
System.out.println("\t\t (no name suffix found)");
}
} else {
System.out.println("\t (no name found)");
}
System.out.println("Email addresses:");
for (Email email : entry.getEmailAddresses()) {
System.out.print(" " + email.getAddress());
if (email.getRel() != null) {
System.out.print(" rel:" + email.getRel());
}
if (email.getLabel() != null) {
System.out.print(" label:" + email.getLabel());
}
if (email.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("IM addresses:");
for (Im im : entry.getImAddresses()) {
System.out.print(" " + im.getAddress());
if (im.getLabel() != null) {
System.out.print(" label:" + im.getLabel());
}
if (im.getRel() != null) {
System.out.print(" rel:" + im.getRel());
}
if (im.getProtocol() != null) {
System.out.print(" protocol:" + im.getProtocol());
}
if (im.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("Groups:");
for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
String groupHref = group.getHref();
System.out.println(" Id: " + groupHref);
}
System.out.println("Extended Properties:");
for (ExtendedProperty property : entry.getExtendedProperties()) {
if (property.getValue() != null) {
System.out.println(" " + property.getName() + "(value) = " +
property.getValue());
} else if (property.getXmlBlob() != null) {
System.out.println(" " + property.getName() + "(xmlBlob)= " +
property.getXmlBlob().getBlob());
}
}
Link photoLink = entry.getContactPhotoLink();
String photoLinkHref = photoLink.getHref();
System.out.println("Photo Link: " + photoLinkHref);
if (photoLink.getEtag() != null) {
System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
}
System.out.println("Contact's ETag: " + entry.getEtag());
}
}
public static void main(String args[]){
try {
GoogleContactsAccess googleContactsAccess = new GoogleContactsAccess();
ContactsService contactSrv = googleContactsAccess.authenticateId();
googleContactsAccess.printAllContacts(contactSrv);
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
i tried the above code. i am getting the below exception
java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
at com.google.gdata.util.AuthenticationException.(AuthenticationException.java:67)
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:1077)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:676)
at com.google.gdata.client.Service.getFeed(Service.java:1034)
at com.cohere.getcontacts.GoogleContactsAccess.printAllContacts(GoogleContactsAccess.java:59)
at com.cohere.getcontacts.GoogleContactsAccess.main(GoogleContactsAccess.java:197)
so any one help me to resolve the problem thanks in advance
It looks like you are using ConsumerKey as both key and secret in your code :
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
You need to use the correct ConsumerSecret of your app
Related
Please note that i am writing a java program using tes4j and i am able to extract the tiff file and save it as pdf but many times i am getting this error. I am running the files as a batch using callable i am taking 5 files and process them during which i get this error. test4j i am using as a maeven dependency.
Error Description
java.util.concurrent.ExecutionException: java.lang.Error: Invalid memory access
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.mkyong.listener.SerachablePDFConversionService.processAllFiles(SerachablePDFConversionService.java:197)
at com.mkyong.listener.SerachablePDFConversionService.run(SerachablePDFConversionService.java:107)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeInt(Native Method)
at com.sun.jna.Function.invoke(Function.java:419)
at com.sun.jna.Function.invoke(Function.java:354)
at com.sun.jna.Library$Handler.invoke(Library.java:244)
at com.sun.proxy.$Proxy0.gsapi_init_with_args(Unknown Source)
at org.ghost4j.Ghostscript.initialize(Ghostscript.java:350)
at com.mkyong.listener.SerachablePDFConversionService.convertPDFToTiff(SerachablePDFConversionService.java:137)
at com.mkyong.listener.SerachablePDFConversionService$1.call(SerachablePDFConversionService.java:213)
at com.mkyong.listener.SerachablePDFConversionService$1.call(SerachablePDFConversionService.java:1)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
Code
package com.apache.pdfbox.ocr.tesseract;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.ghost4j.Ghostscript;
import org.ghost4j.GhostscriptException;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.ITesseract.RenderedFormat;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class SerachablePDFConversionService {
private static final String OCR_INPUT_FOLDER = System.getenv("OCR_INPUT");
private static final String OCR_OUTPUT_FOLDER = System.getenv("OCR_OUTPUT");
private static final String OCR_SUCCESS_FOLDER = System.getenv("OCR_SUCCESS");
private static final String TESSDATA_PREFIX = System.getenv("TESSDATA_PREFIX");
public static void main(String[] args) {
File inputFiles[] = new File(OCR_INPUT_FOLDER).listFiles();
String tiffFileName = "";
String inputFileName = "";
try {
for (File inputFile : inputFiles) {
inputFileName = inputFile.getName();
System.out.println("Input File Name is [" + inputFileName + "]");
if (inputFileName != null && inputFileName.length() > 0
&& inputFileName.toLowerCase().indexOf(".pdf") > 0) {
tiffFileName = inputFile.getName().replaceAll(".pdf", ".tif").replaceAll(".PDF", ".tif");
System.out.println("Tiff File Name is [" + tiffFileName + "]");
System.out.println("Start Time" + new Date());
if (SerachablePDFConversionService.convertPDFToTiff(inputFileName, tiffFileName).equals("true")) {
System.out.println("PDF to tiff conversion is successful");
if (SerachablePDFConversionService.doOCR(inputFileName, tiffFileName).equals("true")) {
System.out.println("Searchable PDF creation is successful");
Files.move(
FileSystems.getDefault()
.getPath(OCR_OUTPUT_FOLDER + File.separator + inputFileName),
FileSystems.getDefault()
.getPath(OCR_SUCCESS_FOLDER + File.separator + inputFileName),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("End Time" + new Date());
} else {
System.out.println("Searchable PDF creation is failed");
}
} else {
System.out.println("PDF to tiff conversion is failed");
}
} else {
}
}
} catch (Exception e) {
System.out.println("ERROR in Main Method: " + e.getMessage());
System.err.println(e.getMessage());
}
}
public static String covertToTiffAndOCR(ArrayList<String> inputFiles) throws Exception {
String success = "false";
for (String inputFileName : inputFiles) {
System.out.println("File Name " + inputFileName);
String tiffFileName = "";
if (inputFileName != null && inputFileName.length() > 0
&& inputFileName.toLowerCase().indexOf(".pdf") > 0) {
tiffFileName = inputFileName.replaceAll(".pdf", ".tif").replaceAll(".PDF", ".tif");
System.out.println("Tiff File Name is [" + tiffFileName + "]");
if (SerachablePDFConversionService.convertPDFToTiff(inputFileName, tiffFileName).equals("true")) {
System.out.println("PDF to tiff conversion is successful");
if (SerachablePDFConversionService.doOCR(inputFileName, tiffFileName).equals("true")) {
System.out.println("Searchable PDF creation is successful");
Files.move(FileSystems.getDefault().getPath(OCR_OUTPUT_FOLDER + File.separator + inputFileName),
FileSystems.getDefault().getPath(OCR_SUCCESS_FOLDER + File.separator + inputFileName),
StandardCopyOption.REPLACE_EXISTING);
} else {
System.out.println("Searchable PDF creation is failed");
}
} else {
System.out.println("PDF to tiff conversion is failed");
}
} else {
}
}
success = "true";
return success;
}
public static String convertPDFToTiff(String pdfFile, String tiffFile) {
System.out.println("Called=========convertPDFToTiff " + pdfFile + "tiffFile " + tiffFile);
String opSuccess = "false";
Ghostscript gs = Ghostscript.getInstance();
try {
synchronized (gs) {
String[] gsArgs = new String[9];
gsArgs[0] = "-gswin64";
gsArgs[1] = "-q";
gsArgs[2] = "-r300x300";
gsArgs[3] = "-dNOPAUSE";
gsArgs[4] = "-dBATCH";
// gsArgs[5] = "-sDEVICE=tiffg4";
// gsArgs[5] = "-sDEVICE=tiffgray";
gsArgs[5] = "-sDEVICE=tiff24nc";
gsArgs[6] = "-sCompression=lzw";
gsArgs[7] = "-sOutputFile=" + OCR_OUTPUT_FOLDER + File.separator + tiffFile;
gsArgs[8] = OCR_INPUT_FOLDER + File.separator + pdfFile;
// execute and exit interpreter
gs.initialize(gsArgs);
gs.exit();
opSuccess = "true";
}
} catch (GhostscriptException e) {
opSuccess = "false";
System.out.println("ERROR: " + e.getMessage());
} catch (Exception e) {
opSuccess = "false";
System.out.println("ERROR: " + e.getMessage());
} finally {
try {
Ghostscript.deleteInstance();
} catch (GhostscriptException e) {
opSuccess = "false";
System.out.println("ERROR: " + e.getMessage());
}
}
return opSuccess;
}
public synchronized static String doOCR(String pdfFile, String tiffFile) {
System.out.println("Called======doOCR " + pdfFile + " tiffFile " + tiffFile);
String opSuccess = "false";
ITesseract instance = new Tesseract();
List<RenderedFormat> formats = new ArrayList<RenderedFormat>();
formats.add(RenderedFormat.PDF);
try {
instance.setDatapath(TESSDATA_PREFIX);
instance.setLanguage("eng+ara");
instance.setOcrEngineMode(1);
instance.setPageSegMode(3);
instance.createDocuments(OCR_OUTPUT_FOLDER + File.separator + tiffFile,
OCR_OUTPUT_FOLDER + File.separator + pdfFile.replaceAll(".pdf", "").replaceAll(".PDF", ""),
formats);
opSuccess = "true";
} catch (TesseractException e) {
opSuccess = "false";
System.out.println("OCR ERROR: " + e.getMessage());
System.err.println(e.getMessage());
} catch (Exception e) {
opSuccess = "false";
System.out.println("OCR ERROR: " + e.getMessage());
System.err.println(e.getMessage());
}
return opSuccess;
}
public void processAllFiles(ArrayList<String> ipFiles) throws Exception {
java.util.List<Callable<String>> tasks = new ArrayList<Callable<String>>(ipFiles.size());
for (String ipFileName : ipFiles) {
System.out.println("11111111" + ipFileName);
tasks.add(processPartTask1(ipFileName));
}
ExecutorService es = Executors.newFixedThreadPool(ipFiles.size());
java.util.List<Future<String>> results = es.invokeAll(tasks);
for (Future<String> result : results)
System.out.println(result.get());
es.shutdown();
}
public Callable<String> processPartTask1(String ipFileName) {
return new Callable<String>() {
public String call() throws Exception {
System.out.println("22222222" + ipFileName);
String tiffFileName = "";
String inputFileName = ipFileName;
String returnvalue = "false";
if (inputFileName != null && inputFileName.length() > 0
&& inputFileName.toLowerCase().indexOf(".pdf") > 0) {
tiffFileName = ipFileName.replaceAll(".pdf", ".tif").replaceAll(".PDF", ".tif");
}
if (SerachablePDFConversionService.convertPDFToTiff(inputFileName, tiffFileName).equals("true")) {
System.out.println("PDF to tiff conversion is successful");
if (SerachablePDFConversionService.doOCR(inputFileName, tiffFileName).equals("true")) {
System.out.println("Searchable PDF creation is successful");
Files.move(FileSystems.getDefault().getPath(OCR_OUTPUT_FOLDER + File.separator + inputFileName),
FileSystems.getDefault().getPath(OCR_SUCCESS_FOLDER + File.separator + inputFileName),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("End Time" + new Date());
returnvalue = "true " + inputFileName;
} else {
System.out.println("Searchable PDF creation is failed");
}
}
return returnvalue;// this needs to be changed
}
};
}
public void processPDFFiles() throws Exception {
File inputFiles[] = new File(OCR_INPUT_FOLDER).listFiles();
String inputFileName = "";
ArrayList<String> files = new ArrayList<String>();
try {
for (File inputFile : inputFiles) {
inputFileName = inputFile.getName();
files.add(inputFileName);
}
} catch (Exception e) {
}
SerachablePDFConversionService serachablePDFConversionService = new SerachablePDFConversionService();
serachablePDFConversionService.processAllFiles(files);
}
}
The file which i am trying to store in the back end is not a valid directory.. I think the code has a Unix directory config which i need to change to make this work in your windows.
how i can identify the directory where the file is trying to be stored.
i am getting the following error.
[com.keenan.oacommon.forms.services.FormServiceImpl] [checkFileDtlPathCreateIfNotExists] - strFileMstPath is not valid
[INFO ] [java.lang.Class] [processListFiles] - strFinalUploadPath []
[INFO ] [com.keenan.oacommon.forms.services.FormServiceImpl] [verifyFilePath] - Validating path []
[ERROR] [com.keenan.oacommon.forms.services.FormServiceImpl] [verifyFilePath] - strFilePath is NULL
[ERROR] [java.lang.Class] [processListFiles] - File upload path is not valid
here is my java code..
#Override
public boolean verifyFilePath(String inFilePath) {
boolean isFilePathValid = false;
String strFilePath = inFilePath;
logger.info("Validating path [" + strFilePath + "]");
if (strFilePath == null || strFilePath.equalsIgnoreCase("")) {
logger.error("strFilePath is NULL");
isFilePathValid = false;
} else {
try {
File fileUploadDir = new File(strFilePath);
if (fileUploadDir.exists() && fileUploadDir.isDirectory()) {
logger.error("File Path [" + strFilePath + "] is good");
isFilePathValid = true;
} else {
logger.warn("File Path [" + strFilePath + "] is not valid");
isFilePathValid = false;
}
} catch (Exception e) {
isFilePathValid = false;
logger.error("Exception while validating File Path [" + strFilePath + "] - " + e.getMessage(), e);
}
}
return isFilePathValid;
}
#Override
public String checkFileDtlPathCreateIfNotExists(String inFilePath, String inAppSeqNo, String inUploadSeqNo) {
boolean isFilePathValid = false;
/* Main directory (all file uploads) */
String strFileMstPath = null;
File fileUploadMstDir = null;
/* Sub directory (file uploads per application) */
String strFileDtlAppPath = null;
File fileUploadDtlAppDir = null;
/* Sub-sub directory (file uploads per upload request) */
String strFileDtlAppUploadPath = null;
File fileUploadDtlAppUploadDir = null;
boolean fileDirExists = false;
String strFinalReturnPath = null;
if (inFilePath == null || inFilePath.equalsIgnoreCase("")) {
logger.error("inFilePath is NULL");
isFilePathValid = false;
} else {
try {
if (!inFilePath.endsWith("/"))
strFileMstPath = inFilePath + "/";
else
strFileMstPath = inFilePath;
fileUploadMstDir = new File(strFileMstPath);
if (fileUploadMstDir.exists() && fileUploadMstDir.isDirectory()) {
logger.error("strFileMstPath is good");
strFileDtlAppPath = strFileMstPath + inAppSeqNo + "/";
fileUploadDtlAppDir = new File(strFileDtlAppPath);
if (fileUploadDtlAppDir.exists() && fileUploadDtlAppDir.isDirectory()) {
fileDirExists = true;
logger.debug("fileUploadDtlAppDir [" + fileUploadDtlAppDir.toString() + "] exists and is a dir");
} else {
fileDirExists = fileUploadDtlAppDir.mkdir();
}
if (fileDirExists) {
/* Set fileDirExists to false for the next check */
fileDirExists = false;
strFileDtlAppUploadPath = strFileDtlAppPath + inUploadSeqNo + "/";
fileUploadDtlAppUploadDir = new File(strFileDtlAppUploadPath);
if (fileUploadDtlAppUploadDir.exists() && fileUploadDtlAppUploadDir.isDirectory()) {
fileDirExists = true;
logger.debug("fileUploadDtlAppUploadDir [" + fileUploadDtlAppUploadDir.toString()
+ "] exists and is a dir");
} else {
fileDirExists = fileUploadDtlAppUploadDir.mkdir();
}
strFinalReturnPath = strFileDtlAppUploadPath;
} else
logger.error("Could not create strFileDtlAppPath [" + strFileDtlAppPath
+ "] - not attempting to create strFileDtlAppUploadPath [" + strFileDtlAppUploadPath + "]");
if (fileDirExists)
isFilePathValid = true;
else
isFilePathValid = false;
} else {
logger.info("strFileMstPath is not valid");
isFilePathValid = false;
}
} catch (Exception e) {
isFilePathValid = false;
logger.error("Exception while validating filePath - " + e.getMessage(), e);
}
}
if (isFilePathValid)
return strFinalReturnPath;
else
return "";
}
#Override
#Transactional(readOnly = true)
public FileUpload getUploadedFileBySeqNo(int inFileSeqNo) {
FileUpload fileUploadInstance = null;
try {
logger.debug("Fetching FileUpload for inFileUploadSeqNo [" + inFileSeqNo + "]");
fileUploadInstance = FormsHelper.getFormDAO().getUploadedFileDetailsBySeqNo(inFileSeqNo);
logger.debug("FileUpload for inFileUploadSeqNo[" + inFileSeqNo + "] is [" + fileUploadInstance.toString() + "]");
} catch (Exception e) {
logger.error("Exceoption while fetching FileUpload for inFileUploadSeqNo [" + inFileSeqNo + "] - " + e.getMessage(), e);
fileUploadInstance = null;
}
return fileUploadInstance;
}
#Override
#Transactional(readOnly = true)
public FileUpload getUploadedFileByName(String inFileName, String inUploadSeqNo, String inAppSeqNo) {
FileUpload fileUploadInstance = null;
int uploadSeqNo = 0;
int appSeqNo = 0;
try {
uploadSeqNo = Integer.parseInt(inUploadSeqNo);
appSeqNo = Integer.parseInt(inAppSeqNo);
logger.debug("Fetching FileUpload for inFileName [" + inFileName + "]");
fileUploadInstance = FormsHelper.getFormDAO().getUploadedFileDetailsByName(inFileName, uploadSeqNo, appSeqNo);
logger.debug("FileUpload for inFileName [" + inFileName + "] is [" + fileUploadInstance.toString() + "]");
} catch (Exception e) {
logger.error("Exception while fetching FileUpload for inFileName [" + inFileName + "] - " + e.getMessage(), e);
fileUploadInstance = null;
}
return fileUploadInstance;
}
#Override
#Transactional(readOnly = false)
public boolean saveUploadedFileInfo(FileUpload inFileUpload) {
boolean fileUploadInfoSavedSuccessfully = false;
try {
if (inFileUpload == null) {
logger.error("inFileUpload is NULL / Blank");
fileUploadInfoSavedSuccessfully = false;
} else {
FormsHelper.getFormDAO().saveUploadedFileInfo(inFileUpload);
fileUploadInfoSavedSuccessfully = true;
}
} catch (Exception e) {
logger.error("Exception while saving FileUpload - " + e.getMessage(), e);
fileUploadInfoSavedSuccessfully = false;
}
return fileUploadInfoSavedSuccessfully;
}
#Override
#Transactional(readOnly = true)
public List<FileUpload> getUploadedFilesList(int inUploadSeqNo) {
List<FileUpload> uploadedFilesList = null;
try {
logger.debug("Fetching FileUpload for inFileUploadSeqNo [" + inUploadSeqNo + "]");
uploadedFilesList = FormsHelper.getFormDAO().getUploadedFilesList(inUploadSeqNo);
logger.debug("FileUpload for inUploadSeqNo [" + inUploadSeqNo + "]");
} catch (Exception e) {
logger.error("Exceoption while fetching FileUpload for inUploadSeqNo [" + inUploadSeqNo + "] - " + e.getMessage(), e);
uploadedFilesList = null;
}
return uploadedFilesList;
}
#Override
public Map<String, String> getUserNUploadDetailsForMail(int appSeqNo, String emailAddress) {
Map<String, String> details = new HashMap<String, String>();
try {
logger.debug("Fetching getUserNUploadDetailsForMail appSeqNo =[" + appSeqNo + "]" + "and emailAddress = [" + emailAddress
+ "]");
details = FormsHelper.getFormDAO().getUserNUploadDetailsForMail(appSeqNo, emailAddress);
logger.debug("Fetched details [" + details + "]");
} catch (Exception e) {
logger.error("Exceoption while fetching getUserNUploadDetailsForMail " + e.getMessage(), e);
}
return details;
}
Thanks..
I'm trying to make some functional tests for my webapplication that is using Play 2.1.4 and Socialsecure. Before using securesocial the tests where pretty straight forward but now im having troubles figuering out how i can make tests on the secured actions.
#Test
public void createNewNote() {
Result result;
// Should return bad request if no data is given
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "", "text",
"")));
assertThat(status(result)).isEqualTo(BAD_REQUEST);
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "My note title", "text",
"My note content")));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/notes");
Note newNote = Note.find.where().eq("title", "My note title")
.findUnique();
// Should be saved to DB
assertNotNull(newNote);
assertEquals("My note title", newNote.title);
assertEquals("My note content", newNote.text);
}
As of right now i got a user in the test yml file:
- !!models.User
id: 1234567890
username: Pingu
provider: Twitter
firstName: Pingu
lastName: Pingusson
email: pingu#note.com
password: password
My user is pretty straight forward...:
#Table(
uniqueConstraints=
#UniqueConstraint(columnNames={"username"}))
#Entity
public class User extends Model {
private static final long serialVersionUID = 1L;
#Id
public String id;
public String provider;
public String firstName;
public String lastName;
public String email;
public String password;
#MinLength(5)
#MaxLength(20)
public String username;
public static Finder<String, User> find = new Finder<String, User>(
String.class, User.class);
public static User findById(String id) {
return find.where().eq("id", id).findUnique();
}
public static User findByEmail(String email) {
return find.where().eq("email", email).findUnique();
}
#Override
public String toString() {
return this.id + " - " + this.firstName;
}
}
and the UserService:
public class UserService extends BaseUserService {
public UserService(Application application) {
super(application);
}
#Override
public void doDeleteExpiredTokens() {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteExpiredTokens...");
}
List<LocalToken> list = LocalToken.find.where().lt("expireAt", new DateTime().toString()).findList();
for(LocalToken localToken : list) {
localToken.delete();
}
}
#Override
public void doDeleteToken(String uuid) {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteToken...");
Logger.debug(String.format("uuid = %s", uuid));
}
LocalToken localToken = LocalToken.find.byId(uuid);
if(localToken != null) {
localToken.delete();
}
}
#Override
//public Identity doFind(UserId userId) {
public Identity doFind(IdentityId identityId){
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("finding by Id = %s", identityId.userId()));
}
User localUser = User.find.byId(identityId.userId());
Logger.debug(String.format("localUser = " + localUser));
if(localUser == null) return null;
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("socialUser = %s", socialUser));
}
return socialUser;
}
#Override
public Identity doFindByEmailAndProvider(String email, String providerId) {
List<User> list = User.find.where().eq("email", email).eq("provider", providerId).findList();
if(list.size() != 1){
Logger.debug("found a null in findByEmailAndProvider...");
return null;
}
User localUser = list.get(0);
SocialUser socialUser =
new SocialUser(new IdentityId(localUser.email, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
return socialUser;
}
#Override
public Token doFindToken(String token) {
if (Logger.isDebugEnabled()) {
Logger.debug("findToken...");
Logger.debug(String.format("token = %s", token));
}
LocalToken localToken = LocalToken.find.byId(token);
if(localToken == null) return null;
Token result = new Token();
result.uuid = localToken.uuid;
result.creationTime = new DateTime(localToken.createdAt);
result.email = localToken.email;
result.expirationTime = new DateTime(localToken.expireAt);
result.isSignUp = localToken.isSignUp;
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("foundToken = %s", result));
}
return result;
}
#Override
public Identity doSave(Identity user) {
if (Logger.isDebugEnabled()) {
Logger.debug("save...!_!");
Logger.debug(String.format("user = %s", user));
}
User localUser = null;
localUser = User.find.byId(user.identityId().userId());
Logger.debug("id = " + user.identityId().userId());
Logger.debug("provider = " + user.identityId().providerId());
Logger.debug("firstName = " + user.firstName());
Logger.debug("lastName = " + user.lastName());
Logger.debug(user.fullName() + "");
Logger.debug("email = " + user.email());
Logger.debug(user.email().getClass() + "");
if (localUser == null) {
Logger.debug("adding new...");
localUser = new User();
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.save();
} else {
Logger.debug("existing one...");
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.update();
}
return user;
}
#Override
public void doSave(Token token) {
LocalToken localToken = new LocalToken();
localToken.uuid = token.uuid;
localToken.email = token.email;
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
localToken.createdAt = df.parse(token.creationTime.toString("yyyy-MM-dd HH:mm:ss"));
localToken.expireAt = df.parse(token.expirationTime.toString("yyyy-MM-dd HH:mm:ss"));
} catch (ParseException e) {
Logger.error("UserService.doSave(): ", e);
}
localToken.isSignUp = token.isSignUp;
localToken.save();
}
}
As of my understanding i should in someway set the session so the user is logged in by using the .withsession method on the fakerequest and maybe also set some value on the serverside.
Tried searching the web for examples using securesocial and play but found no tests at all.
How can i login in my user so i can preform the tests?
Best regards
Rawa
Thanks to David Weinbergs comment i was able to solve this after some trail and error. (:
I started out my LocalUser implementation from this reply:
https://stackoverflow.com/a/18589402/1724097
This is how i solved it:
To make unit tests i created a local user in the database, using the test-data.yml file:
- !!models.LocalUser
id: 1234567890
username: Username
provider: userpass
firstName: firstName
lastName: lastName
email: user#example.com
#hash for "password"
password: $2a$10$.VE.rwJFMblRv2HIqhZM5.CiqzYOhhJyLYrKpMmwXar6Vp58U7flW
Then i made a test utils class that create my fakeCookie.
import models.LocalUser;
import play.Logger;
import securesocial.core.Authenticator;
import securesocial.core.IdentityId;
import securesocial.core.SocialUser;
import securesocial.core.PasswordInfo;
import scala.Some;
import securesocial.core.AuthenticationMethod;
import scala.Option;
import scala.util.Right;
import scala.util.Either;
import play.mvc.Http.Cookie;
public class Utils {
public static Cookie fakeCookie(String user){
LocalUser localUser = LocalUser.findByEmail(user);
Logger.debug("Username: " + localUser.username +" - ID: " + localUser.id);
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
Either either = Authenticator.create(socialUser);
Authenticator auth = (Authenticator) either.right().get();
play.api.mvc.Cookie scalaCookie = auth.toCookie();
//debug loggig
Logger.debug("Cookie data:");
Logger.debug("Name: " + "Value: " + auth.cookieName() + " | Class: " + auth.cookieName().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Value: " + "Value: " + scalaCookie.value() + " | Class: " + scalaCookie.value().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("MaxAge: " + "Value: " + scalaCookie.maxAge() + " | Class: " + scalaCookie.maxAge().getClass() + " | Should be type: " + "int");
Logger.debug("Path: " + "Value: " + scalaCookie.path() + " | Class: " + scalaCookie.path().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Domain: " + "Value: " + scalaCookie.domain() + " | Class: " + auth.cookieDomain().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Secure: " + "Value: " + auth.cookieSecure() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
Logger.debug("HttpOnly: " + "Value: " + auth.cookieHttpOnly() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
// secureSocial doesnt seem to set a maxAge or Domain so i set them myself.
Cookie fakeCookie = new Cookie(auth.cookieName(), scalaCookie.value(), 120, scalaCookie.path(), "None", auth.cookieSecure(), auth.cookieHttpOnly());
return fakeCookie;
}
}
And then i simply use my cookie to in the fakeRequest so im logged in:
Cookie cookie = Utils.fakeCookie("user#example.com");
Result result = callAction(
controllers.routes.ref.yourSampleClass.yourSecuredFucntion(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("Value", "Some input value")).withCookies(cookie));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/yourWantedResult");
Hope this helps others!
I want to get the mac address of another computer in lan how can I do it? I am using JPCAP
private void getPackage(JpcapCaptor captor)
{
try{
IPPacket ip = (IPPacket)captor.getPacket();
for(int a =0 ; a <found.size(); a++ )
{
if(ip.dst_ip.equals(found.get(a)))
check = true;
}
if(!check)
{
if(ip.dst_ip.isSiteLocalAddress())
{
host = ip.dst_ip.getHostName();
System.out.println("destination ip : " + ip.dst_ip + " " + ip.dst_ip.getHostName());
System.out.println("Source ip : " + ip.src_ip + " " + ip.src_ip.getHostName());
found.addElement(ip.dst_ip);
}
}
check = false;
}catch(Exception ex)
{
//Sys.alert("Error" ,"lobby exeption :" + ex);
//wegens null reverence exeption
}
}
this code just get the IP address but I want mac address too
http://netresearch.ics.uci.edu/kfujii/Jpcap/doc/javadoc/jpcap/packet/ARPPacket.html
You need the method:
public java.lang.Object getSenderHardwareAddress()
package jpcapExample;
import jpcap.*;
import jpcap.packet.*;
class PacketPrinter implements PacketReceiver {
public void receivePacket(Packet packet) {
if (packet instanceof ARPPacket){
ARPPacket arpp = (ARPPacket) packet;
Object str = arpp.getSenderHardwareAddress();
System.out.println("got arp from: " + str.toString());
}
System.out.println(packet);
}
}
---------------------[ different file ]-------------
try {
JpcapCaptor eth0=
JpcapCaptor.
openDevice(devices[eth0idx], 65535, false, 20000);
while (true){
eth0.processPacket(1233,new PacketPrinter());
}
} catch (IOException io){
io.printStackTrace();
}
I try to connect to a custom Bluetooth device using BlueCove. I can pair the device, but when I try to search for services I always get SERVICE_SEARCH_DEVICE_NOT_REACHABLE in serviceSearchCompleted() and no services are discovered. If I try the same thing outside Java (in Windows), the PC bluetooth device discovers and can connect (using COM21, COM22, ...) to the SPP service on my device.
What am I doing wrong?
I also tried to do the service search after the device discovery is ended. Same issue.
Please find below my code.
Many thanks in advance for any idea on how to solve this,
Adrian.
public class Test {
private static Logger LOG = Logger.getLogger(Test.class.getName());
private static final String NAME = "XXXX";
private static final String PIN = "1234";
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003), new UUID(0x1101)};
private LocalDevice localDevice;
private DiscoveryAgent discoveryAgent;
private DiscoveryListener discoveryListener = new GDiscoveryListener();
private Map<Integer, RemoteDevice> searchForServices = new HashMap<Integer, RemoteDevice>();
private Collection<ServiceRecord> servicesDiscovered = new HashSet<ServiceRecord>();
private Object lock = new Object();
private CountDownLatch waitForDevices;
protected void connect() {
try {
localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
LOG.info("Local Device: " + localDevice.getFriendlyName()
+ "(" + localDevice.getBluetoothAddress() + ")");
discoveryAgent = localDevice.getDiscoveryAgent();
LOG.finest("Start discovering devices");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, discoveryListener);
try {
synchronized(lock) {
lock.wait();
}
if (searchForServices.size() > 0) {
waitForDevices = new CountDownLatch(searchForServices.size());
waitForDevices.await();
}
}
catch (InterruptedException e) {
LOG.log(Level.WARNING, "Error waiting to terminate discovery", e);
}
LOG.finest(servicesDiscovered.size() + " services discovered");
LOG.finest("Device discovery completed");
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Error initializing Bluetooth", e);
}
}
private class GDiscoveryListener implements DiscoveryListener {
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
try {
String name = rd.getFriendlyName(false);
boolean isMine = NAME.equals(name);
LOG.info("Discovered: " + name + "(" + rd.getBluetoothAddress() + ")"
+ (isMine ? "" : " - ignoring"));
if (!isMine)
return;
if (!rd.isAuthenticated()) {
LOG.finest("Try to pair with " + name
+ " PIN: " + PIN);
boolean paired = RemoteDeviceHelper.authenticate(rd, PIN);
LOG.info("Pair with " + name + (paired ? " succesfull" : " failed"));
}
int transID = discoveryAgent.searchServices(null, UUIDS, rd, discoveryListener);
searchForServices.put(transID, rd);
LOG.finest("Searching for services for " + name + " with transaction " + transID);
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), e);
} catch (IOException e) {
LOG.log(Level.WARNING, "Error connecting ", e);
} catch (Throwable t) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), t);
}
}
public void inquiryCompleted(int respCode) {
synchronized(lock) {
lock.notify();
}
switch (respCode) {
case DiscoveryListener.INQUIRY_COMPLETED :
LOG.fine("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
LOG.fine("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
LOG.fine("INQUIRY_ERROR");
break;
default :
LOG.fine("Unknown Response Code - " + respCode);
break;
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String rd = searchForServices.get(transID).getBluetoothAddress();
//searchForServices.remove(transID);
switch (respCode) {
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
LOG.fine(rd + ": The service search completed normally");
break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
LOG.fine(rd + ": The service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch(int)");
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
LOG.warning(rd + ": An error occurred while processing the request");
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
LOG.info(rd + ": No records were found during the service search");
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
LOG.warning(rd + ": The device specified in the search request could not be reached or the local device could not establish a connection to the remote device");
break;
default:
LOG.warning(rd + ": Unknown Response Code - " + respCode);
break;
}
if (waitForDevices != null)
waitForDevices.countDown();
}
public void servicesDiscovered(int transID, ServiceRecord[] srs) {
LOG.info("Services discovered in transaction " + transID + " : " + srs.length);
for (ServiceRecord sr : srs) {
LOG.info(sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
servicesDiscovered.add(sr);
}
}
}
public static void main(String[] args) {
new Test().connect();
}
}
I had the same problem while connecting to a Bluetooth earpiece. Like you I was also searching for more than one service at a time and It always returned SERVICE_SEARCH_DEVICE_NOT_REACHABLE. So, I tried searching for only one service and it worked. So, try modifying your code as:
...
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003)}