Jersey REST consumer over https - rest

I was using this Jersey annotated Rest consumer POJO without any issue over http, but then we had to start deploying our app over HTTPS.
I am getting a big fat 404, and I concluded, that everything else worked in the code (which is running over MULE beautifully btw) and my POJO simply doesn't consume HTTPS requests.
I suspect that
I am out of luck and Jersey doesn't speak https and I have to redo something here or revert back the part to http
There is a pretty little annotation that i add and voiala! all good.
Obviously, hoping for 2. here.
Here is the code:
package org.acme.api;
import java.net.UnknownHostException;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import com.mongodb.util.JSON;
import com.mongodb.DB;
/**
REST Web service implementation.
#author menashe#acme.org
*/
#Path("/")
public class Product {
MongoClient client = null;
DB db = null;
DBCollection products = null;
public Product() throws UnknownHostException {
this.client = new MongoClient(new ServerAddress("localhost", 27027));
this.db = this.client.getDB("dailysale");
this.products = this.db.getCollection("products");
}
#GET
#Produces("application/json")
#Path("/product/{productId}")
public String retrieveProduct(#PathParam("productId") Integer productId) {
String product;
try{
DBObject query = new BasicDBObject("productId", String.valueOf(productId));
product = this.products.findOne(query).toString();
} catch(Exception e) {
product = "{ error: 'We were not able to find product with Id: '" + productId + ". " + e.getLocalizedMessage() + " }";
}
return product;
}
#GET
#Produces("application/json")
#Path("/product/grid/{query}")
#HeaderParam("range")
public Response listProducts(#HeaderParam("range") String range, #PathParam("query") String query) {
Integer pageNum = 1;
Integer pageSize = 10;
Integer resultCount = null;
BasicDBList result = new BasicDBList();
Integer firstItem = (pageNum - 1 ) * pageSize;
Long allProductsCount = null;
Integer lastItem = null;
DBObject searchQuery = new BasicDBObject("$regex", query);
try {
DBCursor productListCursor = products.find(searchQuery).skip(firstItem).limit( pageSize );
List<DBObject> productList = productListCursor.toArray();
for(DBObject product : productList) {
result.add(this.itemToGridConverter(product));
}
resultCount = productList.size();
allProductsCount = products.count();
lastItem = firstItem + resultCount - 1;
} catch(Exception e) {
result = new BasicDBList();
result.add(new BasicDBObject("error", "We were not able to retrieve all products with pageSize: " + pageSize + " and pageNumber " + pageNum + ". " + e.getLocalizedMessage() ));
}
return Response.ok(result).header("Content-Range", "items " + firstItem + "-" + lastItem + "/" + allProductsCount).build();
}
#GET
#Produces("application/json")
#Path("/product/grid/")
#HeaderParam("range")
public Response listProducts(#HeaderParam("range") String range) {
Integer pageNum = 1;
Integer pageSize = 10;
Integer resultCount = null;
BasicDBList result = new BasicDBList();
Integer firstItem = (pageNum - 1 ) * pageSize;
Long allProductsCount = null;
Integer lastItem = null;
try {
DBCursor productListCursor = products.find().skip(firstItem).limit( pageSize ).sort( new BasicDBObject( "sku", 1)) ;
List<DBObject> productList = productListCursor.toArray();
for(DBObject product : productList) {
result.add(this.itemToGridConverter(product));
}
resultCount = productList.size();
allProductsCount = products.count();
lastItem = firstItem + resultCount - 1;
} catch(Exception e) {
result = new BasicDBList();
result.add(new BasicDBObject("error", "We were not able to retrieve all products with pageSize: " + pageSize + " and pageNumber " + pageNum + ". " + e.getLocalizedMessage() ));
}
return Response.ok( result ).header("Content-Range", "items " + firstItem + "-" + lastItem + "/" + allProductsCount).build();
}
#GET
#Produces("application/json")
#Path("/product/grid/?{sort}")
#HeaderParam("range")
public Response listProductsWithSort(#HeaderParam("range") String range, #PathParam("sort") String sorting) {
Response response = null;
return response;
}
#PUT
#Produces("application/json")
#Path("/product")
public String createProduct(String productJson) {
DBObject product = null;
String result;
try{
product = (DBObject)JSON.parse(productJson);
WriteResult wResult =this.products.insert(product);
result = wResult.toString();
}
catch(Exception e){
result = "{ error: 'We were not able to insert the product.' " + e.getLocalizedMessage() + " }";
}
return result;
}
#POST
#Produces("application/json")
#Path("/product/{productId}")
public String updateProduct(#PathParam("productId") Integer productId, String productJson) {
DBObject product = null;
DBObject query = new BasicDBObject();
String result = null;
try{
product = (DBObject)JSON.parse(productJson);
query.put("productId", productId.toString());
WriteResult wResult = this.products.update(query, product);
result = wResult.toString();
}
catch(Exception e){
result = "{ error: 'We were not able to update the product.' " + e.getLocalizedMessage() + " }";
}
return result;
}
#DELETE
#Produces("application/json")
#Path("/product/{productId}")
public String deleteProduct(#PathParam("productId") Integer productId) {
return "{ error: 'This function is not implemented [delete].' }";
}
private DBObject itemToGridConverter(DBObject product) {
DBObject item = new BasicDBObject();
BasicDBList images = (BasicDBList)product.get("images");
BasicDBObject firstImage = (BasicDBObject)images.get(0);
item.put("productId", product.get("productId"));
item.put("sku", product.get("sku"));
item.put("image", firstImage.get("imageurl"));
BasicDBList spec = (BasicDBList)product.get("productSpecifics");
BasicDBObject firstSpec = (BasicDBObject)spec.get(0);
BasicDBObject attributes = (BasicDBObject)product.get("productAttributes");
item.put("name", firstSpec.get("title"));
item.put("cost", "no source");
item.put("list_price", attributes.get("defaultsalePrice"));
item.put("qty_available", product.get("qtyonHand"));
item.put("condition", "no source");
item.put("active", "true".equals(product.get("active")) ? "Yes" : "No");
item.put("manufacturer", attributes.get("manufacturer"));
item.put("part_number", attributes.get("manufacturerPartNumber"));
item.put("date_created", product.get("_id"));
return item;
}
}
Thanks much.
UPDATE:
I fixed the issue by fixing the path. The issue was how MULE resolves scope boundaries and here the original #Path / was actually in the previous scope. Now that we changed the flow the #Path became /controllers/.
Uyodiin Mevin.

Related

Updating execution status by test case ID/schedule ID using REST API

I have Zephyr related Query, how I can update the execution status of a test case to PASS/FAIL/WIP by using test case ID with rest API.
I have referred to the article at below link
https://support.getzephyr.com/hc/en-us/articles/205042055-Sample-REST-API-Update-execution-status-of-a-testcase-JAVA-
In this example they have shown how to update execution status by using Schedule ID, but the implementation is in SOAP and we need to achieve the same using REST API. Is there any direct REST API to get schedule ID ?
Also, is there a direct REST API to update execution status of a test case using test case ID ? If yes, can you provide examples for both the above cases?
Thanks in advance.
There is no direct method in Jira REST API to update the execution status using test case ID. However,you can use the following custom method :
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.methods.HttpPost;
import org.apache.commons.io.IOUtils;
import org.codehaus.jettison.json.JSONObject;
import java.net.Proxy;
import java.net.HttpURLConnection;
import java.net.URL;
public class JiraAuthHeader {
public static void main(String args[])
{
try {
JiraAuthHeader jiraAuthHeaderObj= new JiraAuthHeader();
System.out.println(" Create Execution method*********");
int executionId= jiraAuthHeaderObj.createExecution(<project id>,<issue id>,<cycle id>);
System.out.println(" Update Execution method*********");
jiraAuthHeaderObj.updateExecution(executionId,"pass");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String updateExecution(int executionId, String status) throws Exception {
System.out.println("Executing execution with executionId " + executionId + " and status = " + status);
String url = "https://jira.company.com/jira/rest/zapi/latest/execution/" + executionId + "/execute";
//String url = "https://jira.company.com/jira/rest/zapi/latest/execution";
String statusInReq = "";
if (status.equalsIgnoreCase("pass")) {
statusInReq = "1";
} else if (status.equalsIgnoreCase("fail")) {
statusInReq = "2";
}
// Create request body
JSONObject obj = new JSONObject();
obj.put("status", statusInReq);
obj.put("comment", "through java");
String requestBody = obj.toString();
System.out.println("Request body: " + requestBody);
HttpURLConnection conn
= httpPut(url, null, null, obj.toString());
System.out.println("HTTP response code: " + conn.getResponseCode());
String response = getResponse(conn);
System.out.println("HTTP response content: " + response);
System.out.println("from HTTP response content fetch the execution id: " + response.substring(6, 12));
return response;
}
public HttpURLConnection httpGet(String url, Map<String, String> requestHeaders, String queryString) throws Exception {
System.out.println("Get request");
if (queryString != null) {
url += "?" + queryString;
}
if (requestHeaders == null) {
requestHeaders = new HashMap<String, String>();
}
requestHeaders.put("Content-Type", "application/json");
return openConnection(url, "GET", requestHeaders, null);
}
public HttpURLConnection httpPut(String url, Map<String, String> requestHeaders, String queryString, String requestContent) throws Exception {
System.out.println("Put request");
if (queryString != null) {
url += "?" + queryString;
}
System.out.println(url);
if (requestHeaders == null) {
requestHeaders = new HashMap<String, String>();
}
requestHeaders.put("Content-Type", "application/json");
return openConnection(url, "PUT", requestHeaders, requestContent);
}
public HttpURLConnection httpPost(String url, Map<String, String> requestHeaders, String queryString, String requestContent) throws Exception {
System.out.println("Post request");
if (queryString != null) {
url += "?" + queryString;
}
System.out.println(url);
if (requestHeaders == null) {
requestHeaders = new HashMap<String, String>();
}
requestHeaders.put("Content-Type", "application/json");
return openConnection(url, "POST", requestHeaders, requestContent);
}
private HttpURLConnection openConnection(String url, String requestMethod, Map<String, String> requestHeaders, String requestContent)
throws Exception {
boolean usingProxy = false;
HttpURLConnection conn = null;
if (usingProxy) {
/*String[] proxyInfo = jiraIntegrationConfig.getProxyServer().split(":");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyInfo[0], Integer.valueOf(proxyInfo[1])));
conn = (HttpURLConnection) new URL(url).openConnection(proxy);*/
} else {
conn = (HttpURLConnection) new URL(url).openConnection(Proxy.NO_PROXY);
String auth = "ssing621" + ":" + "amex^123";
auth = "Basic " + new String(new sun.misc.BASE64Encoder().encode(auth.getBytes()));
conn.setRequestProperty("Authorization", auth);
conn.setRequestMethod(requestMethod);
if (requestHeaders != null && requestHeaders.size() > 0) {
for (String key : requestHeaders.keySet()) {
conn.setRequestProperty(key, requestHeaders.get(key));
}
}
if (requestContent != null) {
conn.setDoOutput(true);
conn.getOutputStream().write(requestContent.getBytes("UTF-8"));
}
}
return conn;
}
private String getResponse(HttpURLConnection conn) throws Exception {
String response;
if (conn.getResponseCode() == 200 || conn.getResponseCode() == 201) {
response = IOUtils.toString(conn.getInputStream());
return response;
} else {
response = IOUtils.toString(conn.getErrorStream());
throw new Exception(response);
}
}
public int getIssueIdByKey(String issueKey) throws Exception {
System.out.println("Getting issue ID for test: [" + issueKey + "]");
String url = ("https://jira.company.com/jira/rest/api/2/issue/" + issueKey);
HttpURLConnection conn = httpGet(url, null, null);
String response = getResponse(conn);
JSONObject resObj = new JSONObject(response);
if (resObj.has("id")) {
int issueId = resObj.getInt("id");
System.out.println("Found issue ID: " + issueId);
return issueId;
}
System.out.println("Could not find IssueId for test: [" + issueKey + "]");
return 0;
}
public int createExecution(int projectId, int issueId, int cycleId) throws Exception {
System.out.print("Creating execution for project Id " + projectId + " and issueId " + issueId);
String url = ("https://jira.company.com/jira/rest/zapi/latest/execution");
// Create request body
JSONObject reqObj = new JSONObject();
reqObj.put("issueId", issueId);
reqObj.put("projectId", projectId);
reqObj.put("cycleId", cycleId);
String requestBody = reqObj.toString();
System.out.println("Request body: " + requestBody);
HttpURLConnection conn = httpPost(url, null, null, requestBody);
System.out.println("HTTP response code: " + conn.getResponseCode());
String response = getResponse(conn);
System.out.println("HTTP response content: " + response);
// Parse the Execution Id, and return it
JSONObject resObj = new JSONObject(response);
int executionId = Integer.valueOf(resObj.keys().next().toString());
System.out.println("Creation done, execution ID: " + executionId);
return executionId;
}
}

Print the shortest path to the java console using orientdb

I want to print in the Java console shortestpath between two vertices. I can not print anything or if you have any way to do that would appreciate it.
String subquery = "Select shortestpath(17:10, 17:14, BOTH) ";
Iterable<OrientVertex> result = orientDBGraph.command(new OSQLSynchQuery<OrientVertex>(subquery)).execute();
Assert.assertTrue(result.iterator().hasNext());
System.out.println(result);
for (OrientVertex d : result) {
System.out.println("Shortest path from " + ((OrientVertex) d.getProperty("$current")).getProperty("name") + " and "
+ ((Iterable<OrientVertex>) d.getProperty("$target")).iterator().next().getProperty("name") + " is: "
+ d.getProperty("path"));
}
Code:
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dbName = "ytrewa";
OrientGraphFactory dbfactory = new OrientGraphFactory("remote:127.0.0.1:2424/"+dbName, "root", "root").setupPool(1, 50);
OrientGraph g = dbfactory.getTx();
try {
String query = "select expand(shortestPath) from (select shortestPath(#9:0,#9:1,BOTH))";
Iterable<OrientVertex> res = g.command(new OCommandSQL(query)).execute();
while(res.iterator().hasNext()){
OrientVertex v = res.iterator().next();
System.out.println("rid: "+v.getId().toString());
}
} finally {
g.shutdown();
}
}
}
Output:
rid: #9:0
rid: #10:0
rid: #12:0
rid: #9:1

How to fetch unread email using javax.mail pop3 from outlook

I am trying to fetch unread email from Inbox(Outlook.office365.com) and also copy the read message to another folder. But I am getting some of the following issues.
Email is being re-read again, even if we mark the email as being
read programmatically.
Unable to copy an email to another folder even when we open the Inbox is RW(Read&Write) mode.
Attached my code as well.
package com.xyz.mail;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
public class ReadEmail {
private static final String TRUE = "true";
private static final String MAIL_POP3_HOST = "mail.pop3.host";
private static final String MAIL_POP3_PORT = "mail.pop3.port";
private static final String MAIL_POP3_STARTTLS_ENABLE = "mail.pop3.starttls.enable";
private static final String MAIL_FOLDER_INBOX = "INBOX";
public static void check(String host, String storeType, String user, String password) throws Exception {
Store store = null;
Folder emailFolder = null;
try {
Properties properties = new Properties();
properties.put(MAIL_POP3_HOST, host);
properties.put(MAIL_POP3_PORT, "995");
properties.put(MAIL_POP3_STARTTLS_ENABLE, TRUE);
Session emailSession = Session.getDefaultInstance(properties);
// create the POP3 store object and connect with the pop server
store = emailSession.getStore(storeType);
store.connect(host, user, password);
emailFolder = store.getFolder(MAIL_FOLDER_INBOX);
emailFolder.open(Folder.READ_WRITE);
Message[] messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println("messages.length---" + messages.length);
if (messages.length == 0) {
System.out.println("No new messages found.");
} else {
for (int i = 0, len = messages.length; i < len; i++) {
Message message = messages[i];
boolean hasAttachments = hasAttachments(message);
if (hasAttachments) {
System.out.println(
"Email #" + (i + 1) + " with subject " + message.getSubject() + " has attachments.");
readAttachment(message);
} else {
System.out.println("Email #" + (i + 1) + " with subject " + message.getSubject()
+ " does not have any attachments.");
continue;
}
Folder copyFolder = store.getFolder("copyData");
if (copyFolder.exists()) {
System.out.println("copy messages...");
copyFolder.copyMessages(messages, emailFolder);
message.setFlag(Flags.Flag.DELETED, true);
}
}
}
} catch (Exception e) {
throw new Exception(e);
} finally {
emailFolder.close(false);
store.close();
}
}
public static void main(String[] args) throws Exception {
String host = "outlook.office365.com";
String username = "emailtest#xyz.com";
String password = "passw0rd{}";
String mailStoreType = "pop3s";
check(host, mailStoreType, username, password);
}
private static boolean hasAttachments(Message msg) throws Exception {
if (msg.isMimeType("multipart/mixed")) {
Multipart mp = (Multipart) msg.getContent();
if (mp.getCount() > 1) {
return true;
}
}
return false;
}
public static void readAttachment(Message message) throws Exception {
Multipart multiPart = (Multipart) message.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String destFilePath = "/home/user/Documents/" + part.getFileName();
System.out.println("Email attachement ---- " + destFilePath);
FileOutputStream output = new FileOutputStream(destFilePath);
InputStream input = part.getInputStream();
byte[] buffer = new byte[4096];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
output.close();
}
}
}
}
How to I fetch only unread email and copy the email to another folder.
change the protocal to imap and change the prot respecitvely ..using pop3 we can access only inbox that is the reason why you are unable to copy the mail to another folder

SQLite database is not updating within an application

I am developing an application. When I modify my data, the previous data is displayed and not the updated data. This is the ModifyActivity.java file:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ModifyCountryActivity extends Activity implements OnClickListener {
private EditText titleText, dateText, timeText;
private Button updateBtn, deleteBtn;
public Calendars calendars;
private DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Record");
setContentView(R.layout.activity_modify_record);
dbHelper = new DatabaseHelper(this);
calendars = new Calendars();
titleText = (EditText) findViewById(R.id.title_edittext_modify);
timeText = (EditText) findViewById(R.id.time_edittext_modify);
dateText = (EditText) findViewById(R.id.date_edittext_modify);
updateBtn = (Button) findViewById(R.id.btn_update);
deleteBtn = (Button) findViewById(R.id.btn_delete);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
String time = intent.getStringExtra("time");
String date = intent.getStringExtra("date");
titleText.setText(title);
timeText.setText(time);
dateText.setText(date);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_update:
titleText.setText(titleText.getText().toString() + " ");
timeText.setText(dateText.getText().toString() + " ");
dateText.setText(timeText.getText().toString() + " ");
calendars.set_remindertitle(titleText.getText().toString() + " ");
calendars.set_reminderdate(dateText.getText().toString() + " ");
calendars.set_remindertime(timeText.getText().toString() + " ");
dbHelper.update(calendars);
this.returnHome();
break;
case R.id.btn_delete:
dbHelper.delete(calendars);
this.returnHome();
break;
}
}
public void returnHome() {
Intent home_intent = new Intent(getApplicationContext(), CountryListActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
The database doesn't update. It shows the previous data again. This is the database class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "calendar.db";
public static final String TABLE_REMINDER = "reminder";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_REMINDER_TITLE = "_remindertitle";
public static final String COLUMN_REMINDER_DESCRIPTION = "_reminderdescription";
public static final String COLUMN_REMINDER_DATE = "_reminderdate";
public static final String COLUMN_REMINDER_TIME = "_remindertime";
public static final String COLUMN_REMINDER_REPEAT = "_reminderrepeat";
public static final String COLUMN_REMINDER_SNOOZE = "_remindersnooze";
SQLiteDatabase database;
// Database Information
Class<? extends DatabaseHelper> context = getClass();
DatabaseHelper dbHelper;
// Creating table query
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_REMINDER + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_REMINDER_DATE + " TEXT, " + COLUMN_REMINDER_TIME + " TEXT, " + COLUMN_REMINDER_TITLE + " TEXT, "
+ COLUMN_REMINDER_DESCRIPTION + " TEXT, " + COLUMN_REMINDER_REPEAT + " TEXT, " + COLUMN_REMINDER_SNOOZE + " TEXT " + ");";
Log.i("Query", query);
db.execSQL(query);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDER);
onCreate(db);
}
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
public void remove(String id) {
String string = String.valueOf(id);
SQLiteDatabase database = getReadableDatabase();
database.execSQL("DELETE FROM " + TABLE_REMINDER + " WHERE _id = '" + string + "'");
}
public void addReminder(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());
SQLiteDatabase database = getReadableDatabase();
database.insert(TABLE_REMINDER, null, contentValues);
Log.i("insData", "the data has been inseted");
database.close();
}
public Cursor fetch() {
String[] columns = new String[]{COLUMN_ID, /*COLUMN_REMINDER_DATE, COLUMN_REMINDER_TIME, COLUMN_REMINDER_TITLE,*/
COLUMN_REMINDER_DESCRIPTION, COLUMN_REMINDER_REPEAT, COLUMN_REMINDER_SNOOZE};
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = database.query(TABLE_REMINDER, columns, null, null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
}
return cursor;
}
public int update(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());/*
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());*/
SQLiteDatabase database = getReadableDatabase();
int i = database.update(TABLE_REMINDER, contentValues, COLUMN_ID + " = " + calendars.get_id(), null);
database.close();
return i;
}
public void delete(Calendars calendars) {
database = getReadableDatabase();
database.delete(TABLE_REMINDER, COLUMN_ID + "=" + calendars.get_id(), null);
}
}
I believe that the update button should be working fine. I am new to Android and don't know how to solve this problem. Any suggestions on how to solve it?
If you're update function returns an int, then in your onClick function, rather than typing:
dbHelper.update(calendars);
You need to type:
int update = dbHelper.update(calendars);
Or:
if (dbHelper.update(calendars) > 0) {
// do something here
}
I would recommend the latter of the options. See how you go.

Error enlarging buttons on eclipse

Hello im trying to enlarge my buttons on eclipse. I found this code on the web that suppose to fix it
but it keeps giving me the error
Error: Could not find or load main class testEclipse.FixIcons
Any idea what can i do?
Im pretty new at this .. thanks
package testEclipse;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.imgscalr.Scalr;
import com.mortennobel.imagescaling.AdvancedResizeOp;
import com.mortennobel.imagescaling.ResampleOp;
/**
* Small utility to double the size of eclipse icons for QHD monitors.
*
* #author David Levy
* #since 2014/04/10
*
*/
public class FixIcons {
private static final Logger logger = Logger.getLogger(FixIcons.class);
public static final void main(String[] args) {
try {
Options options = new Options();
options.addOption(new Option("b", "baseDir", true,
"This is the base directory where we'll parse jars/zips"));
options.addOption(new Option("o", "outputDir", true,
"This is the base directory where we'll place output"));
for (Option o : new ArrayList<Option>(options.getOptions())) {
o.setRequired(true);
}
GnuParser parser = new GnuParser();
CommandLine commandLine = parser.parse(options, args);
String baseDirArg = "D:\\things\\tools\\eclipse";
logger.info("Base directory: " + baseDirArg);
String outputDirArg = "D:\\things\\tools\\eclipsetmp";
logger.info("Output directory: " + outputDirArg);
File base = new File(baseDirArg);
if (!base.exists() || !base.canRead() || !base.isDirectory()) {
logger.error("Unable to read from base directory");
return;
}
File output = new File(outputDirArg);
if (!output.exists() || !output.canRead() || !output.canWrite()
|| !output.isDirectory()) {
logger.error("Unable to write to output director");
return;
}
if (base.list() == null || base.list().length == 0) {
logger.error("The base directory is empty");
return;
}
if (output.list() != null && output.list().length != 0) {
logger.error("The output directory is not empty");
return;
}
processDirectory(base, output);
} catch (ParseException e) {
logger.error("Unable to parse arguments: " + e.getMessage());
} catch (Exception e) {
logger.error("Unexpected error: " + e.getMessage(), e);
}
}
public static void processDirectory(File directory, File outputDirectory)
throws Exception {
logger.info("Processing directory [" + directory.getAbsolutePath()
+ "]");
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
File targetDir = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
logger.info("Creating directory: "
+ targetDir.getAbsolutePath());
targetDir.mkdir();
processDirectory(file, targetDir);
} else {
File targetFile = new File(outputDirectory.getAbsolutePath()
+ File.separator + file.getName());
if (file.getName().toLowerCase().endsWith(".zip")
|| file.getName().toLowerCase().endsWith(".jar")) {
logger.info("Processing archive file: "
+ file.getAbsolutePath());
ZipFile zipSrc = new ZipFile(file);
Enumeration<? extends ZipEntry> srcEntries = zipSrc.entries();
ZipOutputStream outStream = new ZipOutputStream(
new FileOutputStream(targetFile));
while (srcEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) srcEntries.nextElement();
logger.info("Processing zip entry [" + entry.getName()
+ "]");
ZipEntry newEntry = new ZipEntry(entry.getName());
try {
outStream.putNextEntry(newEntry);
} catch (Exception e) {
if (!e.getMessage().startsWith("duplicate entry: ")) {
logger.error("error: ", e);
} else {
logger.info(e.getMessage(), e);
}
outStream.closeEntry();
continue;
}
BufferedInputStream bis = new BufferedInputStream(
zipSrc.getInputStream(entry));
if (ImageType.findType(entry.getName()) != null) {
processImage(zipSrc.getName() + "!/" + entry.getName(), bis, outStream);
} else {
IOUtils.copy(bis, outStream);
}
outStream.closeEntry();
bis.close();
}
zipSrc.close();
outStream.close();
} else if (ImageType.findType(file.getName()) != null) {
logger.info("Processing image: " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
processImage(file.getName(), inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
} else {
logger.info("Processing : " + file.getAbsolutePath());
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(targetFile);
IOUtils.copy(inStream, outStream);
} finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(outStream);
}
}
}
}
}
public static void processImage(String fileName, InputStream input,
OutputStream output) throws IOException {
logger.info("Scaling image: " + fileName);
boolean imageWriteStarted = false;
try {
BufferedImage out = ImageIO.read(input);
int outWidth = out.getWidth() * 2;
int outHeight = out.getHeight() * 2;
BufferedImage rescaledOut = createResizedCopy(out, outWidth, outHeight);
ImageIO.write(rescaledOut, ImageType.findType(fileName).name(),
output);
} catch (Exception e) {
if (imageWriteStarted) {
throw new RuntimeException("Failed to scale image [" + fileName
+ "]: " + e.getMessage(), e);
} else {
logger.error(
"Unable to scale [" + fileName + "]: " + e.getMessage(),
e);
IOUtils.copy(input, output);
}
}
}
private static BufferedImage createResizedCopy(BufferedImage originalImage, int scaledWidth, int scaledHeight) {
try {
// Resample failed - maybe the image was too small, try another way (Scalr)
BufferedImage scaledBI = Scalr.resize(originalImage, Scalr.Method.ULTRA_QUALITY, scaledWidth, scaledHeight);
return scaledBI;
} catch (RuntimeException e) {
return scale(originalImage, 2.0);
}
}
private static BufferedImage scale(BufferedImage source,double ratio) {
int w = (int) (source.getWidth() * ratio);
int h = (int) (source.getHeight() * ratio);
BufferedImage bi = getCompatibleImage(w, h);
Graphics2D g2d = bi.createGraphics();
double xScale = (double) w / source.getWidth();
double yScale = (double) h / source.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return bi;
}
private static BufferedImage getCompatibleImage(int w, int h) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
return image;
}
}