I use apache mina sshd to set up a mocked ssh server for Junit testing purpose. Since the documentation for apache mina is quite unclear, I cannot figure out how to deal with authentication problem in testing.
Code I would like to test, basically using Jsch to transfer file from local to remote.
public static void scpTo(String rfilePath, String lfilePath, String user, String host, String keyPath, int port) {
FileInputStream fis=null;
try {
while(true) {
String rfile = rfilePath;
String lfile = lfilePath;
JSch jsch = new JSch();
jsch.addIdentity(keyPath);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
Session session = jsch.getSession(user, host, port);
session.setConfig(config);
session.connect();
// exec 'scp -t rfile' remotely
String command = "scp " + " -t " + rfile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
if (checkAck(in) != 0) {
System.exit(0);
}
File _lfile = new File(lfile);
if(!_lfile.exists()) {
System.err.println("Local file not existing");
}
//check file existing
File _rfile = new File(rfile);
if (_rfile.exists()) {
System.out.println("Remote file already existed");
break;
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (lfile.lastIndexOf('/') > 0) {
command += lfile.substring(lfile.lastIndexOf('/') + 1);
} else {
command += lfile;
}
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
System.exit(0);
}
// send a content of lfile
fis = new FileInputStream(lfile);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
System.exit(0);
}
out.close();
channel.disconnect();
session.disconnect();
//System.exit(0);
Thread.sleep(2000);
}
} catch (Exception e) {
System.out.println(e);
try {
if (fis != null) fis.close();
} catch (Exception ee) {
}
}
}
And the setUp used for testing. If I would like to authenticate all the user & host pairs by using a given key file in my resource folder, what should I do for setUp? For the current setUp, it will have Auth fail error.
#Before
public void setup() {
user = "siyangli";
host = "localhost";
//pick a port not occupied for tesing
port = 22998;
sshd = SshServer.setUpDefaultServer();
sshd.setPort(port);
keyPath = "/Users/siyangli/.ssh/id_rsa";
//it will change the key file??? do not know why, how to work around the authentication key??
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[]{"/Users/siyangli/.ssh/id_rsa"}));
//sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(keyPath));
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
public boolean authenticate(String username, String password, ServerSession session) {
return true;
}
});
sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
#Override
public boolean authenticate(String username, PublicKey key, ServerSession session) {
return true;
}
});
CommandFactory myCommandFactory = new CommandFactory() {
public Command createCommand(String command) {
System.out.println("Command: " + command);
return null;
}
};
sshd.setCommandFactory(new ScpCommandFactory(myCommandFactory));
List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>();
userAuthFactories.add(new UserAuthPassword.Factory());
sshd.setUserAuthFactories(userAuthFactories);
List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>();
namedFactoryList.add(new SftpSubsystem.Factory()); sshd.setSubsystemFactories(namedFactoryList);
try {
sshd.start();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("Finished setup !!! ");
}
You need to change this line:
userAuthFactories.add(new UserAuthPassword.Factory());
to
userAuthFactories.add(new UserAuthPublicKey.Factory());
Related
I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.
I am writing a Java application which reads the data from MySQL and stores it in Cassandra as Sqoop does not support a direct import to Cassandra. I am using Producer-Consumer framework to achieve the same due to high number of records (in millions) in MySQL. But I am getting ReadTimeOut Exception (com.datastax.driver.core.exceptions.DriverException: Timeout during read). I have one Producer class which reads the data from MySQL and puts it into one queue. There is one consumer class which reads the data from that queue and pushes it to Cassndra. There is one manager class which acts as a coordination bridge between these two classes.
Producer class :-
public class MySQLPrintJobProducer implements Runnable {
private BlockingQueue<PrintJobDAO> printerJobQueue = null;
private Connection conn = null;
public MySQLPrintJobProducer(BlockingQueue<PrintJobDAO> printerJobQueue) throws MySQLClientException {
this.printerJobQueue = printerJobQueue;
connect();
}
private void connect() throws MySQLClientException {
try {
Class.forName(MySQLClientConstants.MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection("jdbc:mysql://mysqlserverhose/mysqldb?user=mysqluser&password=mysqlpasswd");
} catch (ClassNotFoundException e) {
throw new MySQLClientException(ExceptionUtils.getStackTrace(e));
} catch (SQLException e) {
throw new MySQLClientException(ExceptionUtils.getStackTrace(e));
}
}
public void run() {
ResultSet rs = null;
Statement stmt = null;
PreparedStatement pStmt = null;
try {
stmt = conn.createStatement();
// Get total number of print jobs stored.
rs = stmt.executeQuery(MySQLClientConstants.PRINT_JOB_COUNT_QUERY);
int totalPrintJobs = 0;
if(rs != null) {
while(rs.next()) {
totalPrintJobs = rs.getInt(1);
}
}
// Determine the number of iterations.
int rowOffset = 1;
int totalIteration = ((totalPrintJobs / ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE) + 1);
pStmt = conn.prepareStatement(MySQLClientConstants.PRINT_JOB_FETCH_QUERY);
int totalRecordsFetched = 0;
// Iterate over to fetch Print Job Records in bathces and put it into the queue.
for(int i = 1; i <= totalIteration; i++) {
pStmt.setInt(1, rowOffset);
pStmt.setInt(2, ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE);
System.out.println("In iteration : " + i + ", Row Offset : " + rowOffset);
rs = pStmt.executeQuery();
synchronized (this.printerJobQueue) {
if(this.printerJobQueue.remainingCapacity() > 0) {
while(rs.next()) {
totalRecordsFetched = rs.getRow();
printerJobQueue.offer(new PrintJobDAO(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDate(4),
rs.getTimestamp(5), rs.getInt(6), rs.getInt(7), rs.getInt(8), rs.getInt(9),
rs.getInt(10), rs.getFloat(11), rs.getFloat(12), rs.getInt(13), rs.getFloat(14), rs.getInt(15),
rs.getDouble(16), rs.getDouble(17), rs.getDouble(18), rs.getDouble(19), rs.getDouble(20),
rs.getFloat(21)));
this.printerJobQueue.notifyAll();
}
System.out.println("In iteration : " + i + ", Records Fetched : " + totalRecordsFetched +
", Queue Size : " + printerJobQueue.size());
rowOffset += ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE;
} else {
System.out.println("Print Job Queue is full, waiting for Consumer thread to clear.");
this.printerJobQueue.wait();
}
}
}
} catch (SQLException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
} catch (InterruptedException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
} finally {
try {
if(null != rs) {
rs.close();
}
if(null != stmt) {
stmt.close();
}
if(null != pStmt) {
pStmt.close();
}
} catch (SQLException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
}
}
ExportManager.setProducerCompleted(true);
}
}
Consumer Class :-
public class CassandraPrintJobConsumer implements Runnable {
private Cluster cluster = null;
private Session session = null;
private BlockingQueue<PrintJobDAO> printerJobQueue = null;
public CassandraPrintJobConsumer(BlockingQueue<PrintJobDAO> printerJobQueue) throws CassandraClientException {
this.printerJobQueue = printerJobQueue;
cluster = Cluster.builder().withPort(9042).addContactPoint("http://cassandrahost").build();
}
public void run() {
int printJobConsumed = 0;
int batchInsertCount = 1;
if(cluster.isClosed()) {
connect();
}
session = cluster.connect();
PreparedStatement ps = session.prepare(CassandraClientConstants.INSERT_PRINT_JOB_DATA);
BatchStatement batch = new BatchStatement();
synchronized (this.printerJobQueue) {
while(true) {
if(!this.printerJobQueue.isEmpty()) {
for(int i = 1; i <= ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE; i++) {
PrintJobDAO printJob = printerJobQueue.poll();
batch.add(ps.bind(printJob.getJobID(), printJob.getUserID(), printJob.getType(), printJob.getGpDate(), printJob.getDateTimes(),
printJob.getAppName(), printJob.getPrintedPages(), printJob.getSavedPages(), printJob.getPrinterID(), printJob.getWorkstationID(),
printJob.getPrintedCost(), printJob.getSavedCost(), printJob.getSourcePrinterID(), printJob.getSourcePrinterPrintedCost(),
printJob.getJcID(), printJob.getCoverageC(), printJob.getCoverageM(), printJob.getCoverageY(), printJob.getCoverageK(),
printJob.getCoverageTotal(), printJob.getPagesAnalyzed()));
printJobConsumed++;
}
session.execute(batch);
System.out.println("After Batch - " + batchInsertCount + ", record insert count : " + printJobConsumed);
batchInsertCount++;
this.printerJobQueue.notifyAll();
} else {
System.out.println("Print Job Queue is empty, nothing to export.");
try {
this.printerJobQueue.wait();
} catch (InterruptedException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
}
}
if(ExportManager.isProducerCompleted() && this.printerJobQueue.isEmpty()) {
break;
}
}
}
}
}
Manager Class :-
public class ExportManager {
private static boolean isInitalized = false;
private static boolean producerCompleted = false;
private static MySQLPrintJobProducer printJobProducer = null;
private static CassandraPrintJobConsumer printJobConsumer = null;
private static BlockingQueue<PrintJobDAO> printJobQueue = null;
public static boolean isProducerCompleted() {
return producerCompleted;
}
public static void setProducerCompleted(boolean producerCompleted) {
ExportManager.producerCompleted = producerCompleted;
}
private static void init() throws MySQLClientException, CassandraClientException {
if(!isInitalized) {
printJobQueue = new LinkedBlockingQueue<PrintJobDAO>(ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE * 2);
printJobProducer = new MySQLPrintJobProducer(printJobQueue);
printJobConsumer = new CassandraPrintJobConsumer(printJobQueue);
isInitalized = true;
}
}
public static void exportPrintJobs() throws ExportException {
try {
init();
} catch (MySQLClientException e) {
throw new ExportException("Print Job Export failed.", e);
} catch (CassandraClientException e) {
throw new ExportException("Print Job Export failed.", e);
}
Thread producerThread = new Thread(printJobProducer);
Thread consumerThread = new Thread(printJobConsumer);
consumerThread.start();
producerThread.start();
}
}
TestNG class :-
public class TestExportManager {
#Test
public void testExportPrintJobs() {
try {
ExportManager.exportPrintJobs();
Thread.currentThread().join();
} catch (ExportException e) {
Assert.fail("ExportManager.exportPrintJobs() failed.", e);
} catch (InterruptedException e) {
Assert.fail("ExportManager.exportPrintJobs() failed.", e);
}
}
}
I have also made some configuration changes by following this link. Still I am getting following exception after inserting 18000 - 20000 records.
Exception in thread "Thread-2" com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /192.168.10.80
(com.datastax.driver.core.exceptions.DriverException: Timeout during read))
at com.datastax.driver.core.exceptions.NoHostAvailableException.copy(NoHostAvailableException.java:64)
at com.datastax.driver.core.DefaultResultSetFuture.extractCauseFromExecutionException(DefaultResultSetFuture.java:256)
at com.datastax.driver.core.DefaultResultSetFuture.getUninterruptibly(DefaultResultSetFuture.java:172)
at com.datastax.driver.core.SessionManager.execute(SessionManager.java:91)
at com.incendiary.ga.client.cassandra.CassandraPrintJobConsumer.run(CassandraPrintJobConsumer.java:108)
at java.lang.Thread.run(Unknown Source)
Caused by: com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /192.168.10.80 (com.datastax.drive
r.core.exceptions.DriverException: Timeout during read))
at com.datastax.driver.core.RequestHandler.sendRequest(RequestHandler.java:100)
at com.datastax.driver.core.RequestHandler$1.run(RequestHandler.java:171)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
... 1 more
I am not able to figure out the actual reason for the issue. I could not find any exception in Cassandra system log. I am using Apache Cassandra 2.0.7 and cassandra-driver-core 2.0.1.
You can increase read time out in you driver side . By using withSocket method in this you have SocketOption class using that you can read time out .By default is read time out is 10 millisecond .
I am making a profile encryption program with 2 ciphers. I want to have a GUI with buttons for enciphering, deciphering and exiting.
My problem is with the actionPerformed method. It needs to throw the exception that the outputStream throws. This is the error I get when I try to complie it:
:53: error: actionPerformed(ActionEvent) in ProfileEncryption_2 cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws FileNotFoundException//When a button is clicked
I have though of multiple solutions, but am not sure how to implement them properly. I could catch the exception and do something with it, but I am not sure how and what. I could also check if the file exists, and if so, then output, but what I tried for that didn't work either.
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
{
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
//End of menu
//Start of create/view section
public static void createProfile() throws Exception //Create profile
{
String username = JOptionPane.showInputDialog("Enter your username.");
String password, confirmPass, strEncrType;
int intEncrType = 0, unlock = 0;
do
{
password = JOptionPane.showInputDialog("Enter your password.\nIt must be more than 7 characters long.");
confirmPass = JOptionPane.showInputDialog("Confirm password");
if (password.equals(confirmPass) && (password.length() >= 7))
{
JOptionPane.showMessageDialog(null, "Passwords match!");
unlock = 1;
}
else
{
if (!password.equals(confirmPass))
JOptionPane.showMessageDialog(null, "Passwords do not match!");
if (password.length() < 7)
JOptionPane.showMessageDialog(null, "Password is not long enough!");
}
}
while (unlock==0);
do
{
strEncrType = JOptionPane.showInputDialog("Choose which encryption type you would prefer:\n1. Vigenère\n2. Erénegiv mod 4");
if(!strEncrType.equals("1")&&!strEncrType.equals("2"))
JOptionPane.showMessageDialog(null, "Invalid response, try again.");
}
while (!strEncrType.equals("1")&&!strEncrType.equals("2"));
intEncrType = Integer.parseInt(strEncrType);
String name = JOptionPane.showInputDialog("Enter your real name.");
String phone = JOptionPane.showInputDialog("Enter your phone number.");
String email = JOptionPane.showInputDialog("Enter your email.");
String other = JOptionPane.showInputDialog("Enter notes/extra data you want stored.");
String data = password + "-" + username + "-tester-" + name + "-" + phone + "-" + email + "-" + other + "-" + strEncrType;
if (intEncrType ==1)
data = encrypt1(data);
else
data = encrypt2(data);
data = data + strEncrType;
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();
}
I am working on reading email attachment using java mail. This is the code I've used :
public static void main(String args[]) throws Exception {
String host = "172.16.0.186";
String user = "admin";
String password = "1234";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Get a Store object that implements the specified protocol.
Store store = null;
try {
store = session.getStore("pop3");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
} catch (Exception e) {
logger.warn("An exception occured," + e);
}
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("Inbox");
// Open the Folder.
folder.open(Folder.READ_WRITE);
Message[] message = folder.getMessages();
for (int a = 0; a < message.length; a++) {
System.out.println("-------------" + (a + 1) + "-----------");
System.out.println(message[a].getSentDate());
Multipart multipart = (Multipart) message[a].getContent();
for (int i = 0; i < multipart.getCount(); i++) {
//System.out.println(i);
//System.out.println(multipart.getContentType());
BodyPart bodyPart = multipart.getBodyPart(i);
InputStream stream = bodyPart.getInputStream();
File file = new File("C:\\Attachments\\" + bodyPart.getFileName());
BufferedReader br = new BufferedReader(
new InputStreamReader(stream));
while (br.ready()) {
System.out.println(br.readLine());
}
saveFile(bodyPart.getFileName(), stream);
attachments.add(file);
System.out.println();
}
System.out.println();
}
folder.close(true);
store.close();
}
/**
* Save file.
*
* #param filename
* the filename
* #param input
* the input
*/
public static void saveFile(String filename, InputStream input) {
System.out.println(filename);
try {
if (filename == null) {
//filename = File.createTempFile("VSX", ".out").getName();
return;
}
// Do no overwrite existing file
filename = "C:\\Attachments\\" + filename;
File file = new File(filename);
for (int i = 0; file.exists(); i++) {
file = new File(filename + i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) >= 0) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
} // end of try()
catch (IOException exp) {
System.out.println("IOException:" + exp);
}
} //end of saveFile()
}
The following exception occured : javax.mail.NoSuchProviderException: pop3
the last question : if it is possible to read all file types using java mail API then how can we read an excel file ,HTML file, or a word file.
The following WithDefaultCredentials() works but WithCredentialsMe() fails with a http 401 returned ?
The difference is that
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
works OK against the report server 2008 url , but
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
comes back with a HTTP 401.
The console app is being developed by me so, there should not be a difference between DefaultCredentials and NetworkCredential. There is no problem with my Username and password.
Any ideas ?
static void Main(string[] args)
{
WithDefaultCredentials();
WithCredentialsMe();
}
public static void WithDefaultCredentials()
{
try
{
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_WithDefaultCredentitials.pdf", bytes.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static void WithCredentialsMe()
{
try
{
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_Credentials_me_1.pdf", bytes.ToArray());
}
catch( Exception ex )
{
Console.WriteLine( ex.Message);
}
}
public static List<Byte> GetByteListFromUrl(string url, System.Net.ICredentials credentials)
{
List<Byte> lstByte = new List<byte>();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (credentials != null)
{
request.Credentials = credentials;
}
var response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
int totalBytesRead = 0;
int bufferbytesRead = 0;
try
{
byte[] buffer = new byte[1024];
while ((bufferbytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bufferbytesRead;
if (bufferbytesRead < buffer.Length)
{
bufferbytesRead = bufferbytesRead - 1 + 1;
}
for (int i = 0; i < bufferbytesRead; i++)
{
var bToAdd = buffer[i];
lstByte.Add(bToAdd);
}
}
}
catch (Exception ex)
{
}
finally{}
//-Return
return lstByte;
}
With the help of http://forums.asp.net/t/1217642.aspx this code got me what I wanted ...
Next step is clean it all up and unit test in dev ...
public static void ReportServerWebService()
{
// wsdl /out:rs.cs /namespace:ReportService2005 http://mybox/ReportServer_SQLSERVER2008/ReportService2005.asmx?wsdl
/// wsdl /out:rsExec.cs /namespace:ReportExecution2005 http://mybox/ReportServer_SQLSERVER2008/ReportExecution2005.asmx?wsdl
ICredentials credentials = new NetworkCredential("myUserName", "myPassword", "hcml");
Guid invoiceID = new Guid("115ABBA9-61BB-4070-BD28-F572115A2860");
var rs = new ReportService2005.ReportingService2005();
var rsExec = new ReportExecution2005.ReportExecutionService();
rs.Credentials = credentials;
rsExec.Credentials = credentials;
string historyID = null;
string deviceInfo = null;
string format = "PDF";
Byte[] bytPDF;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
ReportExecution2005.Warning[] warnings = null;
string[] streamIDs = null;
string _reportName = "/ElfInvoice/ElfInvoice" ;
string _historyID = null;
bool _forRendering = false;
ReportService2005.ParameterValue[] _values = null;
ReportService2005.DataSourceCredentials[] _credentials = null;
ReportService2005.ReportParameter[] _parameters = null;
try
{
// Get if any parameters needed.
_parameters = rs.GetReportParameters( _reportName, _historyID, _forRendering, _values, _credentials);
// Load the selected report.
var ei = rsExec.LoadReport(_reportName, historyID);
// Prepare report parameter.
// Set the parameters for the report needed.
var parameters = new ReportExecution2005.ParameterValue[1];
// // Place to include the parameter.
if (_parameters.Length > 0)
{
parameters[0] = new ReportExecution2005.ParameterValue();
parameters[0].Label = "InvoiceID";
parameters[0].Name = "InvoiceID";
parameters[0].Value = invoiceID.ToString();
}
rsExec.SetExecutionParameters(parameters, "en-us");
bytPDF = rsExec.Render( format , deviceInfo , out extension , out encoding , out mimeType , out warnings , out streamIDs ) ;
try
{
File.WriteAllBytes(#"c:\temp\A_WithMyCredentitials_ReportServerWebService.pdf", bytPDF.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}