Spring Batch picking old values from csv file - csv

I have Spring Batch application that reads osm-billers.csv file. When I run the application , it is processing the records available in csv file. Then I changed the content of the file and saved it. But, it still reads the old contents. It was reading the file earlier without problem, now giving issue as if there is caching problem. My csv file contains only 3 or 4 records.
BillerOrderId
1001289463281044
1001289073251049
1000819614021112
000000002
public class BatchConfiguration {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
private CsvFileToDatabaseJobConfig csvFileToDatabaseJobConfig;
#Autowired
private DatabaseToCsvFileJobConfig databaseToCsvFileJobConfig;
#Bean
public FlatFileItemReader<Biller> reader(){
try {
FlatFileItemReader<Biller> itemReader = csvFileToDatabaseJobConfig.csvFileItemReader();
return itemReader ;
} catch (UnexpectedInputException e) {
throw new OrderBatchException("Invalid Input..." + e.getMessage());
} catch (ParseException e) {
throw new OrderBatchException("Parsing error..." + e.getMessage());
} catch (NonTransientResourceException e) {
throw new OrderBatchException("NonTransientReasource error..." + e.getMessage());
} catch (Exception e) {
throw new OrderBatchException("Unknown Read error..." + e.getMessage());
}
}
#Bean
public OrderProcessor processor() {
return new OrderProcessor();
}
#Bean
public ItemWriter<Biller> writer() {
try {
ItemWriter<Biller> itemWriter = databaseToCsvFileJobConfig.databaseCsvItemWriter();
return itemWriter;
} catch (Exception e) {
throw new OrderBatchException("Unknown Write error..." + e.getMessage());
}
}
#Bean
public Job importJobOrder(JobCompletionNotificationListner listener, Step step1) {
return jobBuilderFactory.get("importJobOrder")
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end()
.build();
}
#Bean
public Step step1(ItemWriter<Biller> writer) {
return stepBuilderFactory.get("step1")
.<Biller, Biller> chunk(10)
.reader((ItemReader<? extends Biller>) reader())
.processor(processor())
.writer(writer)
.build();
}
}
public class CsvFileToDatabaseJobConfig {
#Bean
FlatFileItemReader<Biller> csvFileItemReader() {
FlatFileItemReader<Biller> csvFileReader = new FlatFileItemReader<>();
csvFileReader.setResource(new ClassPathResource("osm-billers.csv"));
csvFileReader.setLinesToSkip(1);
LineMapper<Biller> billerLineMapper = createBillerLineMapper();
csvFileReader.setLineMapper(billerLineMapper);
return csvFileReader;
}
private LineMapper<Biller> createBillerLineMapper() {
DefaultLineMapper<Biller> billerLineMapper = new DefaultLineMapper<>();
LineTokenizer billerLineTokenizer = createBillerLineTokenizer();
billerLineMapper.setLineTokenizer(billerLineTokenizer);
FieldSetMapper<Biller> billerInformationMapper = createBillerInformationMapper();
billerLineMapper.setFieldSetMapper(billerInformationMapper);
return billerLineMapper;
}
private FieldSetMapper<Biller> createBillerInformationMapper() {
BeanWrapperFieldSetMapper<Biller> billerInformationMapper = new BeanWrapperFieldSetMapper<>();
billerInformationMapper.setTargetType(Biller.class);
return billerInformationMapper;
}
private LineTokenizer createBillerLineTokenizer() {
DelimitedLineTokenizer billerLineTokenizer = new DelimitedLineTokenizer();
billerLineTokenizer.setNames(new String[] {"billerOrderId"});
return billerLineTokenizer;
}
}
public class OrderReader implements ItemReader<OrderResponse>{
private static final Logger log = LoggerFactory.getLogger(OrderReader.class);
private final String apiUrl;
private final RestTemplate restTemplate;
private OrderResponse orderResponse;
#Autowired
private OrderRequest orderRequest;
private String userName;
private String password;
public OrderReader(String apiUrl, String userName, String password, RestTemplate restTemplate, OrderRequest orderRequest) {
this.apiUrl = apiUrl;
this.restTemplate = restTemplate;
this.orderRequest = orderRequest;
this.userName = userName;
this.password = password;
}
private boolean orderisNotInitialized() {
return this.orderResponse == null;
}
private OrderResponse fetchOrderDataFromApi(OrderRequest orderRequest) {
log.debug("OrderRequest = " + orderRequest.getOrder().getBillerOrderId());
log.debug("apiUrl = " + apiUrl);
log.debug("userName = " + userName);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setBasicAuth(userName, password);
HttpEntity<OrderRequest> requestEntity =
new HttpEntity<OrderRequest>(orderRequest, headers);
ResponseEntity<OrderResponse> response =
restTemplate.exchange(apiUrl,HttpMethod.POST, requestEntity,OrderResponse.class);
log.debug("response = " + response);
OrderResponse orderResponse = response.getBody();
return orderResponse;
}
#Override
public OrderResponse read()
throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
if (orderisNotInitialized()) {
orderResponse = fetchOrderDataFromApi(orderRequest);
}
return orderResponse;
}
}
public class OrderProcessor implements ItemProcessor<Biller, Biller>{
#Value("${osm.service.url}")
private String orderUrl;
#Value("${osm.service.username}")
private String userName;
#Value("${osm.service.password}")
private String password;
#Autowired
RestTemplate restTemplate;
#Override
public Biller process(Biller biller) throws Exception {
OrderRequest orderRequest = new OrderRequest();
Order order = new Order();
order.setBillerOrderId(biller.getBillerOrderId());
orderRequest.setOrder(order);
OrderReader osmReader = new OrderReader(orderUrl, userName, password, restTemplate, orderRequest);
OrderResponse orderResponse = osmReader.read();
if (orderResponse.getResult().equals("SUCCESS") ) {
return null;
} else {
//Failed transactions
return biller;
}
}
}
For testing purpose, I made BillerOrderId as 4 digits and picks up immediately but when I change to 16 digits , it takes time to execute updated 16 digit BillerOrderId. It works after 4 or 5 attempts. I tried to see the duration it picks up updated records. But, i didn't see any consistency.
Thanks,
Bandita Pradhan

Related

How to parse below json response using jackson 2.X? The bracket [ after the result is causing issue

I am struggling to parse the below json using jackson libraries
{"result":[{"userID":"xyz","firstName":"abc","lastName":"def","vFlag":"false","URL":"xyz://abc.com/cti.do?sysparm_caller=abc%20def&sysparm_caller_phone=+1 800 123 456"}]}
the square bracket after the "result" seems to be causing the issue.
I already have UNWRAP_ROOT_VALUE set in my code.
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
If i remove the [] then the json to pojo works fine. Is their any annotation i can use without fiddling around with string manipulations ?
POJO class
package com.parse.input;
import com.fasterxml.jackson.annotation.JsonRootName;
#JsonRootName(value = "result")
public class Employee {
private String userID = null;
private String firstName = null;
private String lastName = null;
private String vFlag = null;
private String uRl = null;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getVFlag() {
return vFlag;
}
public void setVFlag(String vipFlag) {
this.vFlag = vipFlag;
}
public String getURL() {
return uRl;
}
public void setURL(String ctiURL) {
this.uRl = ctiURL;
}
}
======And the Code to invoke REST API and parse the response======
Client restClient = Client.create();
WebResource webResource = restClient.resource(wURL);
ClientResponse resp = webResource.accept(MediaType.APPLICATION_JSON)
.header("Authorization", "Basic " + authStringEnc)
.header("EXT_URL", sURL + inputParameter)
.get(ClientResponse.class);
String output = resp.getEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
try {
System.out.println("Starting to parse the employee response");
Employee employee = mapper.readValue(ouput.toString(), Employee.class);
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I was able to get around it like this.
try{
JSONObject j=new JSONObject(output.toString());
extractedJsonEmployee = j.getJSONArray("result").get(0).toString();
} catch (JSONException e) {
e.printStackTrace();
}
//Commented out the UNWRAP_ROOT_VALUE, since i am already taking out the root
Employee employee = mapper.readValue(extractedJsonEmployee, Employee.class);

How to handle timeout exception using in spring integration using annotation?

I am using AbstractClientConnectionFactory for client server connection and TcpReceivingChannelAdapter, TcpSendingMessageHandler for sending and receiving respectively, CorrelationStrategy for context.In this case how can i handle timeoutException ?
public class ClientCall {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext ctx = new AnnotationConfigApplicationContext(GatewayConfig.class);
GatewayService gatewayService = ctx.getBean(GatewayService.class);
//int i=0;
Message message = new Message();
/*while(i<4)
{*/
message.setPayload("It's working");
gatewayService.sendMessage(message);
/* i++;
}*/
}
}
public class Message {
private String payload;
// getter setter
}
#EnableIntegration
#IntegrationComponentScan
#Configuration
#ComponentScan(basePackages = "com.gateway.service")
public class GatewayConfig {
// #Value("${listen.port:6788}")
private int port = 6785;
#Autowired
private GatewayService<Message> gatewayService;
#MessagingGateway(defaultRequestChannel = "sendMessageChannel")
public interface Gateway {
void viaTcp(String payload);
}
#Bean
public AbstractClientConnectionFactory clientCF() {
TcpNetClientConnectionFactory clientConnectionFactory = new TcpNetClientConnectionFactory("localhost",
this.port);
clientConnectionFactory.setSingleUse(false);
return clientConnectionFactory;
}
#Bean
#ServiceActivator(inputChannel = "sendMessageChannel")
public MessageHandler tcpOutGateway(AbstractClientConnectionFactory connectionFactory) {
TcpOutboundGateway outGateway = new TcpOutboundGateway();
outGateway.setConnectionFactory(connectionFactory);
// outGateway.setAsync(true);
outGateway.setOutputChannel(receiveMessageChannel());
outGateway.setRequiresReply(true);
outGateway.setReplyChannel(receiveMessageChannel());
return outGateway;
}
#Bean
public MessageChannel sendMessageChannel() {
DirectChannel channel = new DirectChannel();
return channel;
}
#Bean
public MessageChannel receiveMessageChannel() {
DirectChannel channel = new DirectChannel();
return channel;
}
#Transformer(inputChannel = "receiveMessageChannel", outputChannel = "processMessageChannel")
public String convert(byte[] bytes) {
return new String(bytes);
}
#ServiceActivator(inputChannel = "processMessageChannel")
public void upCase(String response) {
gatewayService.receiveMessage(response);
}
#Transformer(inputChannel = "errorChannel", outputChannel = "processMessageChannel")
public void convertError(byte[] bytes) {
String str = new String(bytes);
System.out.println("Error: " + str);
}
}
public interface GatewayService<T> {
public void sendMessage(final T payload);
public void receiveMessage(String response);
}
#Service
public class GatewayServiceImpl implements GatewayService<Message> {
#Autowired
private Gateway gateway;
#Autowired
private GatewayContextManger<String, Object> gatewayContextManger;
#Override
public void sendMessage(final Message message) {
new Thread(new Runnable() {
#Override
public void run() {
gateway.viaTcp(message.getPayload());
}
}).start();
}
#Override
public void receiveMessage(final String response) {
new Thread(new Runnable() {
#Override
public void run() {
Message message = new Message();
message.setPayload(response);
Object obj = gatewayContextManger.get(message.getPayload());
synchronized (obj) {
obj.notify();
}
}
}).start();
}
}
this is my client side code if i sent a request to server and the response doesn't came within time then how should I catch Time out exception or the socket exceptions if server is not available ?
Add an error channel to your messaging gateway; it will receive an ErrorMessage; the payload is a MessagingException with two properties cause and failedMessage.

Return JSON string from spring controller

I have written a service which query through an AJAX call from solr and return search results as json. I want to return this json from my controller to AJAX.
public class SearchServiceImpl implements SearchService {
private String getSearchResults(String url) throws ClientProtocolException,
IOException {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
//logger.info("Response: " + response.getEntity().getContent());
BufferedReader rd = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
public String performSearch(String term) {
String result = "";
try {
result = getSearchResults(getSolrURL(term)); // getSolrURL() prepares the solr url
} catch (ClientProtocolException e) {
logger.error(e);
} catch (IOException e) {
logger.error(e);
}
return result;
}
}
This is handleRequest() method in my controller -
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
logger.info("Perform search view");
String term = request.getParameter("term");
String result = searchService.performSearch(term);
// Here I need to return result which is a json
ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
// mav.addObject("key1", "value1");
// mav.addObject("key2", "value2");
return mav;
}
The best thing to do is to let Jackson automatically do all the serialization. So your controller would look like this
#RequestMapping(value = "/payment/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody Payment get(#PathVariable Long id) {
return paymentService.getById(id);
}
The Payment class has all it's getters and setters for Jackson
package net.isban.example.vo;
public class Payment {
private Long id;
private String sort;
private String account;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
#Override
public String toString() {
return "Payment [id=" + id + ", sort=" + sort + ", account="
+ account + "]";
}
}
And make sure you include Jackson in the classpath
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.0</version>
</dependency>
This assumes you are using Spring, if not you can still use Jackson to generate json:
String json = new ObjectMapper().writeValueAsString(payment);

org.codehaus.jackson.JsonGenerationException: Can not write number, expecting field name

Hi i am working on a spring mvc application well i need to Serialize an object in order to pass it with an ajax Post.
my bean class :
#JsonSerialize(using = AgentSer.class)
public class AgentCust implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long personneID;
private String nom;
private String prenom;
private String matriculation;
private String marche;
private String compte;
private String phone, mail, chat;
public String getMarche() {
return marche;
}
public void setMarche(String marche) {
this.marche = marche;
}
public String getCompte() {
return compte;
}
public void setCompte(String compte) {
this.compte = compte;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getChat() {
return chat;
}
public void setChat(String chat) {
this.chat = chat;
}
public Long getPersonneID() {
return personneID;
}
public void setPersonneID(Long personneID) {
this.personneID = personneID;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getMatriculation() {
return matriculation;
}
public void setMatriculation(String matriculation) {
this.matriculation = matriculation;
}
}
and the class that will serialize my bean :
public class AgentSer extends JsonSerializer<AgentCust> {
#Override
public void serialize(AgentCust value, JsonGenerator jgen, SerializerProvider arg2) throws IOException, JsonProcessingException {
// TODO Auto-generated method stub
jgen.writeStartObject();
jgen.writeNumber(value.getPersonneID());
jgen.writeString(value.getMatriculation());
jgen.writeString(value.getNom());
jgen.writeString(value.getPrenom());
jgen.writeString(value.getCompte());
jgen.writeString(value.getMarche());
jgen.writeString(value.getChat());
jgen.writeString(value.getMail());
jgen.writeString(value.getPhone());
jgen.writeEndObject();
}
}
in my controller i use my class like that:
AgentCust ags ;
// i set values here .
ObjectMapper mapper = new ObjectMapper();
String json = "";
try {
json = mapper.writeValueAsString(ags);
} catch (Exception e) {
System.out.println(e);
}
but at the end i get that :
org.codehaus.jackson.JsonGenerationException: Can not write number, expecting field name
any help please.
Why are you using a custom serializer(which is wrong as it doesn't include the field names). You are really complicating your life.
You can set the serialization options like this (you can also set them in a static block):
final ObjectMapper mapper = new ObjectMapper();
/*
you can set them globally in a static block and reuse the mapper...
performance gain
*/
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
mapper.setSerializationInclusion(Include.NON_NULL);
The rest of the code is the same(just add a constructor in your AgentCust.class to avoid some mapping errors):
AgentCust ags = new AgentCust();
ags.setChat("chat1");
ags.setCompte("compte1");
ags.setMail("mail1");
ags.setMarche("marche1");
ags.setMatriculation("matriculation1");
ags.setNom("nom1");
ags.setPersonneID(123456L);
ags.setPhone("phone1");
ags.setPrenom("prenom1");
String json = "";
try {
json = mapper.writeValueAsString(ags);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(json);
Another strange thing is that you're serializing the pojo as String. Why not JsonNode or ObjectNode?
public static ObjectNode convObjToONode(Object o) {
StringWriter stringify = new StringWriter();
ObjectNode objToONode = null;
try {
mapper.writeValue(stringify, o);
objToONode = (ObjectNode) mapper.readTree(stringify.toString());
} catch (JsonMappingException e) {
Logger.error("ERROR MAPPING JSON from object!", e);
} catch (JsonGenerationException e) {
Logger.error("ERROR GENERATING JSON from object!", e);
} catch (IOException e) {
Logger.error("ERROR IO when writing JSON from object!", e);
}
Logger.debug("Object as ObjectNode : " + objToONode);
return objToONode;
}

Error in deleting file using Drive Rest API + Drive Android Api. drive.files().delete(driveid.getResourceId())

Drive REST API + GDAA not able to delete the file.
Gone through this question and comments How to delete a file on google drive using Google Drive Android API but when I use driveid.getResourceId(); to pass as a fileId parameter to old Drive API service.files().delete() method its giving error:
Error Required parameteres must be passed it may lead to Dead Lock
My code:
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
private GoogleAccountCredential credential;
private static final int REQUEST_CODE_CREATOR = 2;
private static final int REQUEST_CODE_RESOLUTION = 3;
private static final int PICKFILE_RESULT_CODE = 1;
private static Uri fileUri;
private ContentsResult contentsresult;
private GoogleApiClient mGoogleApiClient;
byte[] buffer;
String EXISTING_FILE_ID = "";
int folderCreated = 0;
SharedPreferences prefs;
ArrayList<String> dbfileid = new ArrayList<String>();
ArrayList<String> dbfilename = new ArrayList<String>();
String fdd="";
DriveFolderResult sky;
private DriveId mFolderDriveId;
String isfolder;
SharedPreferences sp;
String Shared="Shared";
String folderid="";
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
int j=0;
String songfileid="";
private static com.google.api.services.drive.Drive service;
private static final String LOGTAG="EXPLORECA";
private static final String DATABASE_NAME="file.db";
private static final int DATABASE_VERSION=1;
private static final String TABLE="fileids";
private static final String filename="fname";
private static final String fileid="fid";
String realid ="";
#Override
protected void onResume() {
super.onResume();
initDrive();
}
private void initDrive() {
credential = GoogleAccountCredential.usingOAuth2(this,Arrays.asList(DriveScopes.DRIVE.split(",")));
credential.setSelectedAccountName("shivrajp130#gmail.com");
service = getDriveService(credential);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName("shivrajp130#gmail.com")
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
if (!result.hasResolution()) {
// show the localized error dialog.
showToast("Error in on connection failed");
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
showToast("error" + e.toString());
}
}
#Override
public void onConnected(Bundle connectionHint) {
showToast("Inside Connected");
sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
showToast("Inside Connected");
createSkyFolder();
}
private void createSkyFolder()
{
// TODO Auto-generated method stub
try
{
showToast("creating Folder");
if(!sp.getString(isfolder, "false").contains("created"))
{
MetadataChangeSet changeSet = new MetadataChangeSet.Builder().
setTitle("Sky folder").build();
sky = Drive.DriveApi.getRootFolder(getGoogleApiClient())
.createFolder(getGoogleApiClient(), changeSet).await();
showToast("folder created");
sp.edit().putString(isfolder, "created").commit();
// To store secret ID string of file or folder so that we can later get a DriveId object.
realid = sky.getDriveFolder().getDriveId().encodeToString();
sp.edit().putString(folderid, realid).commit();
showToast("Real== "+realid);
}
DriveId retid = DriveId.decodeFromString(sp.getString(folderid, ""));
DriveFolder folder = Drive.DriveApi.getFolder(getGoogleApiClient(), retid);
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setTitle("New folder")
.build();
MetadataResult res = folder.updateMetadata(getGoogleApiClient(), changeSet2).await();
showToast("Folder== "+folder.getDriveId().encodeToString());
showToast("folder created");
upladfile();
}
catch(Exception e)
{
showToast(""+e);
}
}
private void upladfile() {
// TODO Auto-generated method stub
String storedId=sp.getString(folderid, "");
DriveId retid = DriveId.decodeFromString(storedId);
DriveFolder skyfolder = Drive.DriveApi.getFolder(getGoogleApiClient(), retid);
contentsresult = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = contentsresult.getContents().getOutputStream();
String s = Environment.getExternalStoragePublicDirectory("Download")
.getPath().toString();
showToast(s);
File file = new File(s + "/k.mp3");
showToast("Path=" + Environment.DIRECTORY_DOWNLOADS + "/k"
+ file.length());
buffer = new byte[(int) file.length()];
try {
showToast("started reading n writing");
outputStream.write(buffer);
showToast("Buffer is written");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast("" + e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showToast("" + e.toString());
}
showToast("" + contentsresult.getContents().toString());
//DriveFolder fldr = Drive.DriveApi.getFolder(getGoogleApiClient(),sky.getDriveFolder().getDriveId());
MetadataChangeSet changeSet2 = new MetadataChangeSet.Builder()
.setTitle("New file").setMimeType("audio/MP3").setStarred(true)
.build();
showToast("meta data created");
DriveFileResult fileresult = skyfolder.createFile(getGoogleApiClient(),
changeSet2, contentsresult.getContents()).await();
songfileid = fileresult.getDriveFile().getDriveId().encodeToString();
showToast("file has been created "+fileresult.toString());
// Status stat = Drive.DriveApi.requestSync(mGoogleApiClient).await();
showToast("await() complete");
if (!contentsresult.getStatus().isSuccess()) {
showToast("Error while trying to create the file");
return;
}
add_to_db();
getvalues();
//String storedId=sp.getString(folderid, "");
DriveId fffid = DriveId.decodeFromString(dbfileid.get(0));
DriveFile fff = Drive.DriveApi.getFile(getGoogleApiClient(), fffid);
MetadataChangeSet changeSet3 = new MetadataChangeSet.Builder()
.setTitle("renamed")
.build();
MetadataResult res = fff.updateMetadata(getGoogleApiClient(), changeSet3).await();
if(res!=null)
{
showToast("renamed"+res.getMetadata().getTitle());
}
try {
//String iid=fffid.getResourceId();
service.files().delete(fffid.getResourceId()).execute();
showToast("Delete");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
showToast("Connected");
}
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast,
Toast.LENGTH_SHORT).show();
}
});
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
public void add_to_db()
{
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
ContentValues values = new ContentValues();
String id =songfileid;
String name="k";
showToast("database id ="+id);
values.put(fileid,id);
values.put(filename,name);
database.insert(TABLE, null, values);
database.close();
Toast.makeText(this,"Added Successfully" ,Toast.LENGTH_LONG).show();
}
public void getvalues()
{
showToast("getting Values");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
dbhelper=new fileiddb(this);
database=dbhelper.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
dbfileid.add(cursor.getString(0));
dbfilename.add(cursor.getString(1));
showToast("id=="+dbfileid.get(j).toString());
j++;
} while (cursor.moveToNext());
}
}
private com.google.api.services.drive.Drive getDriveService(GoogleAccountCredential credential) {
return new com.google.api.services.drive.Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
#Override
public void onConnectionSuspended(int cause) {
showToast("GoogleApiClient connection suspended");
}
}
Except delete everything is working fine.
service.files().delete(fffid.getResourceId()).execute();
Any REST Api's .execute() (as well as GDAA's .await() flavored calls) must be run off UI thread. You should wrap it in:
new AsyncTask<Void, Void, Void>() {
#Override protected Integer doInBackground(String... params) {
//...
return null;
}
}.execute(); // .cancel(true);
or
new Thread(new Runnable() { #Override public void run() {
//....
}}).start();
Good Luck