I've looked at several questions and answers about this but I'm still unable to upload to an S3 bucket. I have alreadydeclared the service in the manifest within the application tags.
Every log statement returns the correct information, but the status is always WAITING and none of the transfer listeners are triggered. I do not receive any errors whatsoever and the S3 bucket continues to be empty.
What am I doing wrong?
public void uploadStoredItems() {
TransferUtility transferUtility = TransferUtility.builder()
.context(AWSProvider.getInstance().getContext())
.awsConfiguration(AWSProvider.getInstance().getConfiguration())
.s3Client(new AmazonS3Client(AWSProvider.getInstance().getIdentityManager().getCredentialsProvider()))
.build();
try {
for (File csvFile : csvFiles) {
String filename = csvFile.getName(); //.substring(csvFile.getName().lastIndexOf('/') + 1);
Log.d(TAG, "This is the filename for upload: " + filename);
// FileReader reads text files in the default encoding.
String line = null;
FileReader fileReader = new FileReader(csvFile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
Log.d(TAG, "Here are the lines: " + line);
}
// Always close files.
bufferedReader.close();
TransferObserver uploadObserver = transferUtility.upload(filename, csvFile);
// Gets id of the transfer.
Log.d(TAG, "This is the bucket: " + uploadObserver.getBucket());
Log.d(TAG, "This is the state: " + uploadObserver.getState());
Log.d(TAG, "This is the id: " + uploadObserver.getId());
observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
TransferListener listener = new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
Log.d(TAG, "onStateChanged: " + state.toString());
if (TransferState.COMPLETED == state) {
Log.d(TAG, "COMPLETE: " + state.toString());
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100;
int percentDone = (int) percentDonef;
Log.d(TAG, "ID:" + id + " bytesCurrent: " + bytesCurrent
+ " bytesTotal: " + bytesTotal + " " + percentDone + "%");
}
#Override
public void onError(int id, Exception ex) {
// Handle errors
Log.d(TAG, "ERROR ID:" + id + " " + ex.getMessage());
}
};
for (TransferObserver observer : observers) {
if (TransferState.WAITING.equals(observer.getState())
|| TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
|| TransferState.IN_PROGRESS.equals(observer.getState())) {
observer.setTransferListener(listener);
}
Log.d(TAG, "\n observers - id: " + observer.getId() + " state: " + observer.getState() + " key: " + observer.getKey() + " bytes total: " + observer.getBytesTotal());
}
Log.d(TAG, "Bytes Total: " + uploadObserver.getBytesTotal());
}
csvFiles.clear();
} catch(java.io.FileNotFoundException ex) {
System.out.println("Unable to open file");
} catch(java.io.IOException ex) {
System.out.println("Error reading file");
}
}
Turns out I have to declare the TransferUtility service to run in the same process that the service I am calling it from is running:
<application
...
<service
android:name=".MainService"
android:enabled="true"
android:process=":main_service"
android:stopWithTask="false" />
<service
android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
android:process=":main_service"
android:enabled="true" />
...
</application>
Related
I am making a multicast messenger for part of my masters degree. I have previously successfully made this exact same implementation on desktop Java and had no issues what so ever. HOWEVER, when I run the code from Android problems occur. I can send to the multicast group just fine, but receiving does not work.
The output simply stops in the console after "2".
The application just stops giving me feedback on the line that is socket.receive()I am getting no exceptions either.
Below I have attached the class that I am using to receive the messages.
For the full android implementation I have the dropbox link available at: https://www.dropbox.com/s/vuoifbxqk01c079/MyApplication.zip?dl=0
It is pretty rough, but it does successfully send, just not receive.
public class EMMS extends Thread{
MulticastSocket socket;
InetAddress ip;
byte [ ] buffer;
int usedPort;
public boolean isSending;
private MainActivity view;
public EMMS(MainActivity view, int port, String ipAddress){
try {
// Create Multicast socket
socket = new MulticastSocket(port);
usedPort = port;
// Set address to join
ip = InetAddress.getByName(ipAddress);
// join group
socket.joinGroup(ip);
System.out.println("Group Joined! ");
// create buffer
buffer = new byte[512];
isSending = false;
this.view = view;
}//end of try
catch (SocketException se){
System.out.println("Socket Exception : " + se); }
catch (IOException e) { System.out.println("Exception : " + e); }
}
public void run(){
try {
System.out.println("Incoming Message! ");
while (isSending == false) {
// Create and receive packet
System.out.println("1");
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,ip, usedPort);
System.out.println("2");
socket.receive(dp);
System.out.println("3");
String str = new String(dp.getData());
System.out.println("4");
String ipAddress = dp.getAddress().getHostAddress();
System.out.println("5");
// Create string array of components
String[] data = str.split("##");
String senderName= data[2];
String sourceIP= ipAddress;
String typeOfEmergency=data[3];
String condition=data[0];
String instruction=data[1];
System.out.println("Incoming Message! ");
System.out.println(
"Sender: " + senderName + "\n" +
"Source IP: " + sourceIP + "\n" +
"Emergency Type: " + typeOfEmergency + "\n" +
"Condition: " + condition + "\n" +
"Instruction: " + instruction
);
// Create popup window
AlertDialog alertDialog = new AlertDialog.Builder(view).create(); //Read Update
alertDialog.setTitle("ALERT");
alertDialog.setMessage(
"Sender: " + senderName + "\n" +
"Source IP: " + sourceIP + "\n" +
"Emergency Type: " + typeOfEmergency + "\n" +
"Condition: " + condition + "\n" +
"Instruction: " + instruction
);
alertDialog.show(); //<-- See This!
}
}//end of try
catch (SocketException se){
System.out.println("Socket Exception : " + se); }
catch (IOException e) { System.out.println("Exception : " + e); }
}
public void disconnect() throws IOException{
socket.leaveGroup(ip);
}
It works upto sock.receive(incoming); On my browser under applet.
After sock.receive(incoming); This line it is stuck. Nothing is display.
Or No Error or exception is throw even it goes away from this line.
Please Help me. Thank you in advance :)
sorry for my bad an English
This is my code.
while(true)
{
System.out.println("Under While loop...");
if(incoming != null)
{
System.out.println("Data is not blank..." + incoming );
}
else
{
System.out.println("Data is blank..." + incoming );
}
sock.receive(incoming);
System.out.println("Hello..");
byte[] data = incoming.getData();
if(data != null)
{
System.out.println("Data is not blank...");
}
else
{
System.out.println("Data is blank...");
}
String s = new String(data, 0, incoming.getLength());
//echo the details of incoming data - client ip : client port - client message
System.out.println(incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " : " + s);
if(s != "" )
{
String R = incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " : " + s;
//lblResultTest.setText(R);
String[] words = s.split("&");
txtResult.setText(words[2]);
this.getAppletContext().showDocument( this.getDocumentBase() );
}
//s = "OK : " + s;
//DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , incoming.getPort());
//sock.send(dp);
}
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
I'm pretty new here, and have been following all I could find on getting my program to append a series of numbers (determined from how often a button was pressed) to a .txt file whenever a timer runs out, but to no avail-I'm not sure what I'm missing...the app starts out by creating a .txt file in the downloads folder with a template in it:
String initialTemplate ="\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\"";
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, filename+".txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(initialTemplate.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And then when a countdowntimer object finishes and restarts/ends, it triggers the class writeresults() to append the values:
if (CountsRemaining < 1){
textViewTime.setText("00:00:00");
cancel();
writeResults();
finishcount();
} else {
//append data
writeResults();
//Clear all variables
clearCounts();
start();
}
And the important part, to actually write the data, which is what isn't working:
public void writeResults(){
String Message = Count1 + ", " + Count2 + ", " + Count3 + ", " + Count4 + ", " + Count5 + ", " +
Count6 + ", " + Count7 + ", " + Count8 + ", " + Count9 + ", " + Count10 + ", " + Count11 + Count12;
FileWriter writer;
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File (path + filename+".txt");
writer = new FileWriter(file, true);
writer.append(Message);
writer.append("this is a writing test message");
writer.close();
Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Any idea what I might be missing? Parameters?
The problem is in this line:
File file = new File (path + filename+".txt");
It should be like this, if you look at your first code, when creating file:
File file = new File (path, filename+".txt");
I have a linux java program that is reading and writing to a CIFS mounted Windows file share. See code snippet at bottom.
After execution, there are files named "cifs*" left in the directory. If the target directory is on the local file system, the code works like a champ. However, if the target directory is a CIFS mounted Windows file share, I get the left-over files. I'm not sure what configuration changes I need to make to fix. Any help is greatly appreciated.
FileRenameMutex myFileRenameMutex = new FileRenameMutex("/WindowsMount/MoveLock");
class FileRenameMutex
{
// global variables
String lockFileBasename;
String unusedExtension = "_Unused";
String unusedFilename;
String inUseFilename;
String localMachineAddress;
String formattedTime;
// log4j logger for this class
public static Logger logMutex = Logger.getLogger(FileRenameMutex.class.getName());
public FileRenameMutex(String _lockFileBase) {
this.lockFileBasename = _lockFileBase;
logMutex.debug("FileRenameMutex: Constructor, with file " + lockFileBasename + " user = " + System.getProperty("user.name"));
try {
localMachineAddress = InetAddress.getLocalHost().getHostAddress();
//localMachineAddress = InetAddress.getLocalHost().getHostName();
} catch ( Exception e ) {
localMachineAddress = "UNKNOWN_HOST";
logMutex.error(" Could not determine host address. " + e.getMessage());
}
// set the file names
unusedFilename = lockFileBasename + unusedExtension;
inUseFilename = lockFileBasename + "_" + localMachineAddress;
logMutex.debug(" Local machine = " + localMachineAddress);
logMutex.debug(" Unused file name = " + this.unusedFilename);
logMutex.debug(" In Use file name = " + this.inUseFilename);
}
public boolean tryAcquire() throws InterruptedException {
boolean returnVal = false;
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
formattedTime = new Date().toString();
String inUseText = "This file created by the Alfresco cron job to MoveFileAndCreateDir "
+ "(move files from Unfiled to Filed folders).\n"
+ "Running on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
// attempt to rename file
logMutex.debug(" Attempting to rename mutex file " + unusedFilename + " to " + inUseFilename);
if ( unusedFile.renameTo(inUseFile) ) {
logMutex.debug(" Rename to inUse successful");
out.write(inUseText);
out.flush();
out.close();
returnVal = true; // lock was acquired
} else {
// System.out.println("Rename to inUse failed");
logMutex.error(" Rename of " + unusedFilename + " to " + inUseFilename + " failed in tryAcquire().");
}
} catch ( Exception e ) {
throw new InterruptedException("Error acquiring lock in tryAcquire(): " + e.getMessage());
}
return returnVal;
}
public void release() {
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
String unusedText = "This file was last by the Alfresco cron job to MoveFileAndCreateDir "
+ "Ran on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
out.write(unusedText);
out.flush();
out.close();
// attempt to rename file
logMutex.debug(" Attempting to rename active mutex file " + inUseFilename + " back to " + unusedFilename);
if ( inUseFile.renameTo(unusedFile) ) {
logMutex.debug(" Rename back to unused successful");
} else {
logMutex.error(" Rename of " + inUseFilename + " to " + unusedFilename + " failed in release().");
}
} catch ( Exception e ) {
logMutex.error("Error resetting lock file in release(): " + e.getMessage());
}
} // release()
} // end of class FileRenameMutex
I am using twitter4j twitter Streaming API to get the tweets for the specific tag.
I am having number of keywords. I want to search the 100 tweets thats containing that tag
currently what i am doing is i wrote code for getting the tweets for single word
public class StreamAPI {
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("xxxx");
cb.setOAuthConsumerSecret("xxxxx");
cb.setOAuthAccessToken("xxxx");
cb.setOAuthAccessTokenSecret("xxxx");
cb.setUseSSL(true);
cb.setUserStreamRepliesAllEnabled(true);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
twitterStream.setOAuthAccessToken(accestoken);
StatusListener listener = new StatusListener() {
int countTweets = 0;
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
countTweets++;
System.out.println(countTweets);
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
#Override
public void onStallWarning(StallWarning stallWarning) {
//To change body of implemented methods use File | Settings | File Templates.
}
public void onException(Exception ex) {
ex.printStackTrace();
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"ipl"};
fq.track(keywords);
twitterStream.addListener(listener);
twitterStream.filter(fq);
}
}
how would i stop the process after it reaches the count 100 and should return that 100 tweet as list.
Please help me.
see the below code maybe helpfull for you
String token= "Key Word";
Query query = new Query(token);
FileWriter outFile = new FileWriter(token.replaceAll("^#","").concat(".txt"), true);
int numberOfTweets = 1500;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
if (numberOfTweets - tweets.size() > 100)
query.setCount(100);
else
query.setCount(numberOfTweets - tweets.size());
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
System.out.println("Gathered " + tweets.size() + " tweets");
for (Status t: tweets)
if(t.getId() < lastID) lastID = t.getId(); }
catch (TwitterException te) {
System.out.println("Couldn't connect: " + te); };
query.setMaxId(lastID-1);
}
PrintWriter out1 = new PrintWriter(outFile);
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
String user = t.getUser().getScreenName();
String msg = t.getText();
String time = "";
if (loc!=null) {
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
System.out.println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);}
else
// System.out.println(i + " USER: " + user + " wrote: " + msg.replaceAll("\n",""));
out1.append(i + " USER: " + user + " wrote: " +msg.replaceAll("\n"," ") );
out1.print("\n");
}
System.out.println("file write succefully");