Error while exporting test result to excel by using TestNG - testng.xml

I have get sample code from google and tried,
Test scenario: To export test result into excel by using TestNG
Installed TestNG and Jars
Apache jar poi-4.1.1
Selenium stand alone jar Selenium-server-standalone-2.7.0-patched resources
I am getting few errors, experts please help to resolve.
public UImap throwing error
Code:
package com.techbeamers.testng;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SaveTestNGResultToExcel {
public WebDriver driver;
public UIMap uimap;
public UIMap datafile;
public String workingDir;
// Declare An Excel Work Book
HSSFWorkbook workbook;
// Declare An Excel Work Sheet
HSSFSheet sheet;
// Declare A Map Object To Hold TestNG Results
Map<String, Object[]> TestNGResults;
public static String driverPath = "C:\workspace\tools\selenium\";
#Test(description = "Opens the TestNG Demo Website for Login Test", priority = 1)
public void LaunchWebsite() throws Exception {
try {
driver.get("http://phptravels.net/login");
driver.manage().window().maximize();
TestNGResults.put("2", new Object[] { 1d, "Navigate to demo website", "Site gets opened", "Pass" });
} catch (Exception e) {
TestNGResults.put("2", new Object[] { 1d, "Navigate to demo website", "Site gets opened", "Fail" });
Assert.assertTrue(false);
}
}
#Test(description = "Fill the Login Details", priority = 2)
public void FillLoginDetails() throws Exception {
try {
// Get the username element
WebElement username = driver.findElement(uimap.getLocator("Username_field"));
username.sendKeys(datafile.getData("username"));
// Get the password element
WebElement password = driver.findElement(uimap.getLocator("Password_field"));
password.sendKeys(datafile.getData("password"));
Thread.sleep(1000);
TestNGResults.put("3", new Object[] { 2d, "Fill Login form data (Username/Password)",
"Login details gets filled", "Pass" });
} catch (Exception e) {
TestNGResults.put("3",
new Object[] { 2d, "Fill Login form data (Username/Password)", "Login form gets filled", "Fail" });
Assert.assertTrue(false);
}
}
#Test(description = "Perform Login", priority = 3)
public void DoLogin() throws Exception {
try {
// Click on the Login button
WebElement login = driver.findElement(uimap.getLocator("Login_button"));
login.click();
Thread.sleep(1000);
// Assert the user login by checking the Online user
WebElement onlineuser = driver.findElement(uimap.getLocator("online_user"));
AssertJUnit.assertEquals("Hi, John Smith", onlineuser.getText());
TestNGResults.put("4",
new Object[] { 3d, "Click Login and verify welcome message", "Login success", "Pass" });
} catch (Exception e) {
TestNGResults.put("4",
new Object[] { 3d, "Click Login and verify welcome message", "Login success", "Fail" });
Assert.assertTrue(false);
}
}
#BeforeClass(alwaysRun = true)
public void suiteSetUp() {
// create a new work book
workbook = new HSSFWorkbook();
// create a new work sheet
sheet = workbook.createSheet("TestNG Result Summary");
TestNGResults = new LinkedHashMap<String, Object[]>();
// add test result excel file column header
// write the header in the first row
TestNGResults.put("1", new Object[] { "Test Step No.", "Action", "Expected Output", "Actual Output" });
try {
// Get current working directory and load the data file
workingDir = System.getProperty("user.dir");
datafile = new UIMap(workingDir + "\Resources\datafile.properties");
// Get the object map file
uimap = new UIMap(workingDir + "\Resources\locator.properties");
// Setting up Chrome driver path.
System.setProperty("webdriver.chrome.driver", driverPath + "chromedriver.exe");
// Launching Chrome browser.
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
} catch (Exception e) {
throw new IllegalStateException("Can't start the Firefox Web Driver", e);
}
}
#AfterClass
public void suiteTearDown() {
// write excel file and file name is SaveTestNGResultToExcel.xls
Set<String> keyset = TestNGResults.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = TestNGResults.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File("SaveTestNGResultToExcel.xls"));
workbook.write(out);
out.close();
System.out.println("Successfully saved Selenium WebDriver TestNG result to Excel File!!!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// close the browser
driver.close();
driver.quit();
}
}
Below are the errors
Error:
org.testng.TestNGException:
Cannot instantiate class com.techbeamers.testng.SaveTestNGResultToExcel
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:40)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:363)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:275)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:126)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:191)
at org.testng.TestClass.getInstances(TestClass.java:100)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:86)
at org.testng.TestClass.init(TestClass.java:78)
at org.testng.TestClass.<init>(TestClass.java:41)
at org.testng.TestRunner.initMethods(TestRunner.java:425)
at org.testng.TestRunner.init(TestRunner.java:252)
at org.testng.TestRunner.init(TestRunner.java:222)
at org.testng.TestRunner.<init>(TestRunner.java:171)
at org.testng.remote.support.RemoteTestNG6_10$1.newTestRunner(RemoteTestNG6_10.java:28)
at org.testng.remote.support.RemoteTestNG6_10$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_10.java:61)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:623)
at org.testng.SuiteRunner.init(SuiteRunner.java:189)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:136)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1375)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1355)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
at org.testng.TestNG.runSuites(TestNG.java:1133)
at org.testng.TestNG.run(TestNG.java:1104)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:29)
... 25 more
Caused by: java.lang.Error: Unresolved compilation problems:
UIMap cannot be resolved to a type
UIMap cannot be resolved to a type
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
UIMap cannot be resolved to a type
UIMap cannot be resolved to a type
UIMap cannot be resolved to a type
UIMap cannot be resolved to a type
UIMap cannot be resolved to a type
UIMap cannot be resolved to a type
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
at com.techbeamers.testng.SaveTestNGResultToExcel.<init>(SaveTestNGResultToExcel.java:29)
... 30 more

Related

package org.apache.http.util does not exist

I am trying on my own to implement a useful trip planner application using android studio with the help of goolge and some open sources
I have android application with no gradle.build. when it try to run it i get the error.
Error:(20, 28) java: package org.apache.http.util does not exist
Here is the part of the code that has the error.
How to solve the error ?
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public static String queryUrl(String url) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
Log.i(TAG, "Url:" + url + "");
Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]");
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(instream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
instream.close();
String result = total.toString();
return result;
}
} catch (ClientProtocolException e) {
Log.e(TAG, "There was a protocol based error", e);
} catch (Exception e) {
Log.e(TAG, "There was some error", e);
}
return null;
}
See following answer, HttpClient won't import in Android Studio
I don't know how your module's build.gradle looks like, but I assume you are including apache libraries some wrong way.
Also, I would not reccomend using apache HTTP libraries in new android applications. Have look at OkHttp or Volley
I would post this in comments, but I don't have enough reputation yet.

Fastest way to return view in customRestService using a bean

I have written a custom rest Service on an Xpage, which is tied to a bean. The Xpage is:
<xe:restService
id="restServiceCustom"
pathInfo="custom"
ignoreRequestParams="false"
state="false"
preventDojoStore="true">
<xe:this.service>
<xe:customRestService
contentType="application/json"
serviceBean="XXXX.PCServiceBean">
</xe:customRestService>
</xe:this.service>
</xe:restService>
I cobbled together my java agent from some excellent posts around the net. I have just started on the GET. My code runs but I it seems pretty slow (on my dev server). I want to make it as fast as possible. I am using a ViewEntryCollection and I am "flushing" at each record which I assume is streaming.
I am putting my own "[" in the code, so I assume that I am not doing something right, as I never saw any examples of anyone else doing this.
Any suggestions would be greatly appreciated.
package com.XXXXX.bean;
import java.io.IOException;
import java.io.Writer;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewEntryCollection;
import org.openntf.domino.utils.Factory;
import com.ibm.commons.util.io.json.JsonException;
import com.ibm.commons.util.io.json.util.JsonWriter;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
public class PCServiceBean extends CustomServiceBean {
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
try {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
String method = request.getMethod();
if (method.equals("GET")) {
this.doGet(request, response);
} else if (method.equals("POST")) {
this.doPost(request, response);
} else if (method.equals("PUT")) {
this.doPut(request, response);
} else if (method.equals("DELETE")) {
this.doDelete(request, response);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doDelete(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
}
private void doPut(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
}
private void doPost(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
}
private void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, JsonException {
Session session = Factory.getSession();
Database DB = session.getDatabase(session.getCurrentDatabase().getServer(), "scoApps\\PC\\PCData.nsf");
View pcView = DB.getView("viewAllByStatus");
int i = 1;
Writer out = response.getWriter();
JsonWriter writer = new JsonWriter(out, false);
writer.out("[");
ViewEntryCollection vec = pcView.getAllEntries();
int count = vec.getCount();
for (ViewEntry entry : vec) {
Vector<?> columnValues = entry.getColumnValues();
writer.startObject();
writer.startProperty("unid");
writer.outStringLiteral(String.valueOf(columnValues.get(1)));
writer.endProperty();
writer.startProperty("status");
writer.outStringLiteral(String.valueOf(columnValues.get(0)));
writer.endProperty();
writer.startProperty("assetTag");
writer.outStringLiteral(String.valueOf(columnValues.get(2)));
writer.endProperty();
writer.startProperty("serialNumber");
writer.outStringLiteral(String.valueOf(columnValues.get(3)));
writer.endProperty();
writer.startProperty("model");
writer.outStringLiteral(String.valueOf(columnValues.get(4)));
writer.endProperty();
writer.startProperty("currentLocation");
writer.outStringLiteral(String.valueOf(columnValues.get(5)));
writer.endProperty();
writer.endObject();
if (i != count) {
i = i + 1;
writer.out(",");
writer.flush();
}
}
writer.out("]");
writer.flush();
}
}
Change your code to
JsonWriter writer = new JsonWriter(out, false);
writer.startArray();
ViewEntryCollection vec = pcView.getAllEntries();
int count = vec.getCount();
for (ViewEntry entry : vec) {
Vector<?> columnValues = entry.getColumnValues();
writer.startArrayItem();
writer.startObject();
writer.startProperty("unid");
writer.outStringLiteral(String.valueOf(columnValues.get(1)));
writer.endProperty();
...
writer.endObject();
writer.endArrayItem();
}
writer.endArray();
writer.flush();
It uses JsonWriter's
startArray() and endArray() instead of out("[") and out("]")
startArrayItem() and endArrayItem() instead of out(",") and flush()
The JSON response string gets shorter if you set JsonWriter's compact option to true:
JsonWriter writer = new JsonWriter(out, true);
I see two problems.
First - use ViewNavigator. Here's good explanation of its performance gain.
https://www.mindoo.com/web/blog.nsf/dx/17.01.2013085308KLEB9S.htm
Second - prepare your JSON in advance. This is very good technique to avoid unnecessary code (and time to process it) to get JSON data from Domino documents.
https://quintessens.wordpress.com/2015/09/05/working-with-json-in-your-xpages-application/

TestNG Close Browsers after Parallel Test Execution

I want to close browsers after completion of all test. Problem is I am not able to close the browser since the object created ThreadLocal driver does not recognize the driver after completion of test value returning is null.
Below is my working code
package demo;
import java.lang.reflect.Method;
import org.openqa.selenium.By;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ParallelMethodTest {
private static ThreadLocal<dummy> driver;
private int input;
private int length;
#BeforeMethod
public void beforeMethod() {
System.err.println("Before ID" + Thread.currentThread().getId());
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
if (driver == null) {
driver = new ThreadLocal<dummy>();
}
if (driver.get()== null) {
driver.set(new dummy());
}
}
#DataProvider(name = "sessionDataProvider", parallel = true)
public static Object[][] sessionDataProvider(Method method) {
int len = 12;
Object[][] parameters = new Object[len][2];
for (int i = 0; i < len; i++) {
parameters[i][0] = i;
parameters[i][1]=len;
}
return parameters;
}
#Test(dataProvider = "sessionDataProvider")
public void executSessionOne(int input,int length) {
System.err.println("Test ID---" + Thread.currentThread().getId());
this.input=input;
this.length=length;
// First session of WebDriver
// find user name text box and fill it
System.out.println("Parameter size is:"+length);
driver.get().getDriver().findElement(By.name("q")).sendKeys(input + "");
System.out.println("Input is:"+input);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#AfterMethod
public void afterMethod() {
System.err.println("After ID" + Thread.currentThread().getId());
driver.get().close();
}
}
package demo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
public class dummy {
public WebDriver getDriver() {
return newDriver;
}
public void setNewDriver(WebDriver newDriver) {
this.newDriver = newDriver;
}
private WebDriver newDriver;
public dummy() {
newDriver = new ChromeDriver();
newDriver.get("https://www.google.co.in/");
}
#AfterClass
public void close(){
if(newDriver!=null){
System.out.println("In After Class");
newDriver.quit();
}
}
}
Thanks in Advance.
private static ThreadLocal<dummy> driver is added at the class level. What is happening is that you have already declared the variable at class level. i.e. memory is already allocated to it. Multiple threads are just setting and resetting the values of the same variable.
What you need to do is create a factory that will return an instance of Driver based on a parameter you pass to it.Logic can be anything but taking a general use case example the factory will create a new object and return only if an existing object doesn't exist. Declare and initialise the driver (from factory) in your #Test Methods
Sample code for the factory would be something like
static RemoteWebDriver firefoxDriver;
static RemoteWebDriver someOtherDriver;
static synchronized RemoteWebDriver getDriver(String browser, String browserVersion, String platform, String platformVersion)
{
if (browser == 'firefox')
{
if (firefoxDriver == null)
{
DesiredCapabilities cloudCaps = new DesiredCapabilities();
cloudCaps.setCapability("browser", browser);
cloudCaps.setCapability("browser_version", browserVersion);
cloudCaps.setCapability("os", platform);
cloudCaps.setCapability("os_version", platformVersion);
cloudCaps.setCapability("browserstack.debug", "true");
cloudCaps.setCapability("browserstack.local", "true");
firefoxDriver = new RemoteWebDriver(new URL(URL),cloudCaps);
}
}
else
{
if (someOtherDriver == null)
{
DesiredCapabilities cloudCaps = new DesiredCapabilities();
cloudCaps.setCapability("browser", browser);
cloudCaps.setCapability("browser_version", browserVersion);
cloudCaps.setCapability("os", platform);
cloudCaps.setCapability("os_version", platformVersion);
cloudCaps.setCapability("browserstack.debug", "true");
cloudCaps.setCapability("browserstack.local", "true");
someOtherDriver = new RemoteWebDriver(new URL(URL),cloudCaps);
}
return someOtherDriver;
}
You have a concurrency issue: multiple threads can create a ThreadLocal instance because dummy == null can evaluate to true on more than one thread when run in parallel. As such, some threads can execute driver.set(new dummy()); but then another thread replaces driver with a new ThreadLocal instance.
In my experience it is simpler and less error prone to always use ThreadLocal as a static final to ensure that multiple objects can access it (static) and that it is only defined once (final).
You can see my answers to the following Stack Overflow questions for related details and code samples:
How to avoid empty extra browser opens when running parallel tests with TestNG
Session not found exception with Selenium Web driver parallel execution of Data Provider test case
This is happening because you are creating the driver instance in beforeMethod function so it's scope ends after the function ends.
So when your afterMethod start it's getting null because webdriver instance already destroy as beforeMethod function is already completed.
Refer below links:-
http://www.java-made-easy.com/variable-scope.html
What is the default scope of a method in Java?

groovy.lang.MissingPropertyException while Downloading Files from FTP Server

I want to create job in grails which download the files from ftp
server after certain interval of time say 2-3 days and store it on
specified local path. the same code with minor changes is written in
java which was working fine but when write the similar code in Grails
I'm facing the Error and not able to resolve it. Can any body Tell me
where I'm making mistake?
Following is the Error that I'm facing when job start.
JOB STARTED::************************************************************************************
2015-08-24 18:20:35,285 INFO org.quartz.core.JobRunShell:207 Job GRAILS_JOBS.com.hoteligence.connector.job.DownloadIpgGzipFilesJob threw a JobExecutionException:
org.quartz.JobExecutionException: groovy.lang.MissingPropertyException: No such property: ftpClient for class: com.hoteligence.connector.job.DownloadIpgGzipFilesJob [See nested exception: groovy.lang.MissingPropertyException: No such property: ftpClient for class: com.hoteligence.connector.job.DownloadIpgGzipFilesJob]
at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:111)
at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: groovy.lang.MissingPropertyException: No such property: ftpClient for class: com.hoteligence.connector.job.DownloadIpgGzipFilesJob
at com.hoteligence.connector.job.DownloadIpgGzipFilesJob.execute(DownloadIpgGzipFilesJob.groovy:93)
at grails.plugins.quartz.GrailsJobFactory$GrailsJob.execute(GrailsJobFactory.java:104)
... 2 more
/* I've added all the related dependencies in grails Build Config.
*/
package com.hoteligence.connector.job
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.codehaus.groovy.grails.commons.ConfigurationHolder as ConfigHolder;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* #author Gajanan
* this is back-end job which download Files from ftp server and store it on locally
*/
class DownloadIpgGzipFilesJob {
static triggers = {
simple repeatInterval: Long.parseLong(ConfigHolder.config.DEVICE_PING_ALERT_JOB_REPEAT_INTERVAL),
startDelay : 60000
}
def execute() {
try{
println "JOB STARTED::************************************************************************************";
/* following is the details which are required for server connectivity
*/
String server = ConfigHolder.config.IPG_SERVER_NAME;
int port = ConfigHolder.config.IPG_SERVER_PORT_NO;
String user = ConfigHolder.config.IPG_SERVER_USER_NAME;
String pass = ConfigHolder.config.IPG_SERVER_USER_PASSWORD;
String [] fileNames = ConfigHolder.config.IPG_DOWNLOADABLE_GZIP_FILE_LIST.split(",");
String downloadFilePath = ConfigHolder.config.IPG_GZIP_DOWNLOAD_LOCATION;
String fileDate = (todaysDate.getYear()+1900)+""+((todaysDate.getMonth()+1)<=9?("0"+(todaysDate.getMonth()+1)):(todaysDate.getMonth()+1))+""+todaysDate.getDate();
FTPClient ftpClient = new FTPClient();
/* Here we are making connection to the server and the reply
from server is printed on console
*/
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Connect failed");
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
}
/* Here we are iterate the FileList and download them to specified directory
*/
for(int i =0; i<fileNames.length;i++) {
String fileName = "on_"+ConfigHolder.config.IPG_DATA_COUNTRY_CODE+fileNames[i]+fileDate+".xml.gz";
System.out.println(fileName);
downloadFtpFileByName(ftpClient,fileName,downloadFilePath+fileName);
}
}
catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// logs out and disconnects from server
/* In finally block we forcefully close the connection and close the file node also
*/
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/* this function is nothing but to print the ftp server reply after connection to ftp server
*/
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
/* This is the actual logic where we copy the file from ftp
and store on local directory
this method accept three parameter FtpClient object, Name of the file which has to be downloaded from server and the path where downloaded file has to be stored
*/
private static void downloadFtpFileByName(FTPClient ftpClient,String fileName,String downloadfileName){
System.out.println("Strat Time::"+System.currentTimeMillis());
try {
String remoteFile1 = "/"+fileName; // file on server
File downloadFile1 = new File(downloadfileName); // new file which is going to be copied on local directory
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
Boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
if (success) {
System.out.println("File"+fileName+" has been downloaded successfully.");
}
else
{
System.out.println("File"+fileName+" has been DOWNLOAD FAILURE....");
}
outputStream1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("END Time::"+System.currentTimeMillis());
}
}
Move this line:
FTPClient ftpClient = new FTPClient();
Outside of the try { ... } catch() block (ie, move it up to before the try)
You are declaring the local variable inside the try, then trying to use it in the finally block

twitter4j: getting credential errors even though i had set them?

package twitter4j.examples.tweets;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.*;
import java.io.IOException;
public final class UpdateStatus {
public static void main(String[] args) throws IOException {
String testPost = "hello from otc";
String consumerKey = "key";
String consumerSecret = "secret";
String accessToken = "access";
String accessSecret = "access_secret";
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumerKey)
.setOAuthConsumerSecret(consumerSecret)
.setOAuthAccessToken(accessToken)
.setOAuthAccessTokenSecret(accessSecret);
try {
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
AccessToken accestoken = new AccessToken(accessToken, accessSecret);
twitter.setOAuthAccessToken(accestoken);
Status status = twitter.updateStatus(testPost);
System.out.println("it worked!");
if (status.getId() == 0) {
System.out
.println("Error occured while posting tweets to twitter");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
why do i keep getting this error:
401:Authentication credentials (http://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid conumer key/secret, access token/secret, and the system clock in in sync.
error - Could not authenticate with OAuth.
request - /1/statuses/update.json
Relevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=e06d87a8 or
http://www.google.co.jp/search?q=5851cbdb
TwitterException{exceptionCode=[e06d87a8-5851cbdb], statusCode=401, retryAfter=-1, rateLimitStatus=null, featureSpecificRateLimitStatus=null, version=2.2.3}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
at twitter4j.TwitterImpl.post(TwitterImpl.java:1871)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:459)
at twitter4j.examples.tweets.UpdateStatus.main(UpdateStatus.java:35)
i have set the credentials in the file already, have i not?
i figured it out heres a working code:
package twitter4j.examples.tweets;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import java.io.IOException;
public final class UpdateStatus {
public static void main(String[] args) throws IOException {
String tweet = "your first tweet via java";
String accessToken = "your access token";
String accessSecret = "your access token secret";
try {
TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
AccessToken accestoken = new AccessToken(accessToken, accessSecret);
twitter.setOAuthAccessToken(accestoken);
Status status = twitter.updateStatus(tweet);
System.out.println("it worked!");
if (status.getId() == 0) {
System.out
.println("Error occured while posting tweets to twitter");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
note: for this to work you MUST create an application on twitter
you must have a twitter4j.properties file which contain the following
debug set to true
oauth.consumerKey
oauth.consumerSecret
oauth.accessToken
oauth.accessTokenSecret
all the keys and tokens are from the twitter application
make sure your application access level all say "read and write"

Resources