I was wondering, I have the following snippets of code that I would like to eliminate the use of sessions and make it RESTful. I have a controller servlet that uses several handlers, which are used to determine the page to return to. For example, here are two of my handlers:
public class ReporterLoginHandler implements ActionHandler {
public String handleIt(Map params, HttpSession session) {
String reporterId = null;
String passwd = null;
String errMsg = null;
ReporterBean reporterBean = null;
String returnPage = "home";
try {
reporterId = ((String[]) params.get("reporterid"))[0];
passwd = ((String[]) params.get("passwd"))[0];
} catch (Exception ex) {
System.out.println("Oops, couldn't parse the parameters for login!");
}
if (reporterId == null || reporterId.length() == 0 || passwd == null || passwd.length() == 0) {
errMsg = "The reporterID or password cannot be empty";
} else if ((reporterBean = ReporterBeanFactory.getReporter(reporterId, passwd)) == null) {
errMsg = "The reporterID or password is not valid";
}
if (errMsg != null) {
session.setAttribute("msg", errMsg); //should be removed and replaced by a RESTful API
} else }
returnPage = "reporter_home";
session.setAttribute("reporterBean", reporterBean);
}
return returnPage;
}
}
public class PostItemHandler implements ActionHandler {
#Override
public String handleIt(Map<String, String[]> params, HttpSession session) {
String title = params.get("title")[0];
String story = params.get("story")[0];
String itemId = null;
String returnPage = "home";
if (params.containsKey("item")) {
itemId = params.get("item")[0];
}
ReporterBean rBean = (ReporterBean) session.getAttribute("reporterBean"); // needs to be replaced by a RESTful API
String msg = "";
int id = 0;
String filename = session.getAttribute("newsfile").toString();
if (title != null && title.length() > 0 && story != null && story.length() > 0) {
if (itemId != null && itemId.length() > 0) {
try {
id = Integer.parseInt(itemId);
} catch (Exception exc) {
msg = "Invalid format for news item ID";
}
if (rBean != null) {
if (msg.equals("") && NewsItemBeanFactory.editNewsItem(id, title, story, rBean.getReporterId())) {
msg = "News item " + id + " successfully edited!";
returnPage = "reporter_home";
try {
NewsItemBeanFactory.saveNewsItems(filename);
} catch (IOException ex) {
Logger.getLogger(PostItemHandler.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
msg = "News item " + id + " could not be edited!";
}
} else }
msg = "Error: please log in before adding or editing an item.";
}
} else {
if (rBean != null) {
NewsItemBeanFactory.addNewsItem(title, story, rBean.getReporterId());
msg = "News item successfully added!";
returnPage = "reporter_home";
try {
NewsItemBeanFactory.saveNewsItems(filename);
} catch (IOException ex) {
Logger.getLogger(PostItemHandler.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
msg = "Error: please log in before adding a new item.";
}
}
}
if (params.get("returnpage") != null) {
if (params.get("returnpage")[0].toString().equals("mynews")) {
Collection<NewsItemBean> newsItems = NewsItemBeanFactory.getAllItems();
ArrayList<NewsItemBean> myNewsItems = new ArrayList<NewsItemBean>();
for (NewsItemBean item : newsItems) {
if (rBean != null && rBean.getReporterId().equals(item.getReporterId())) {
myNewsItems.add(item);
}
}
session.setAttribute("mynews", myNewsItems); //needs to be replaced by a RESTful API
returnPage = "mynews";
}
}
session.setAttribute("msg", msg); //needs to be replaced by a RESTful API
return returnPage;
}
}
Specifically, I would like to eliminate the use of all sessions from my handlers (as well as from my controller servlet) and would like to create a RESTful API where the java beans are represented with JSON.
I would prefer not to use an external REST API creator such as Spring or Jersey, however, I am open to using Google's Gson to convert my beans to and from JSON.
EDIT: Also, I would like the login to return an authorization token when successful.
Could anyone help me here?
Related
I was developing an app which had requirement to implement root detection logic, so by researching I found some detection logic in JAVA and had implemented following class.
class RootDetection {
public boolean isDeviceRooted() {
return checkForBinary("su") || checkForBinary("busybox") || checkForMaliciousPaths() || checkSUonPath()
|| detectRootManagementApps() || detectPotentiallyDangerousApps() || detectRootCloakingApps()
|| checkForDangerousProps() || checkForRWPaths()
|| detectTestKeys() || checkSuExists();
}
private boolean detectTestKeys() {
String buildTags = android.os.Build.TAGS;
String buildFinger = Build.FINGERPRINT;
String product = Build.PRODUCT;
String hardware = Build.HARDWARE;
String display = Build.DISPLAY;
System.out.println("Java: build: " + buildTags + "\nFingerprint: " + buildFinger + "\n Product: " + product + "\n Hardware: " + hardware + "\nDisplay: " + display);
return (buildTags != null) && (buildTags.contains("test-keys") || buildFinger.contains("genric.*test-keys") || product.contains("generic") || product.contains("sdk") || hardware.contains("goldfish") || display.contains(".*test-keys"));
}
private boolean detectRootManagementApps() {
return detectRootManagementApps(null);
}
private boolean detectRootManagementApps(String[] additionalRootManagementApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootAppsPackages));
if (additionalRootManagementApps != null && additionalRootManagementApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootManagementApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectPotentiallyDangerousApps() {
return detectPotentiallyDangerousApps(null);
}
private boolean detectPotentiallyDangerousApps(String[] additionalDangerousApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownDangerousAppsPackages));
if (additionalDangerousApps != null && additionalDangerousApps.length > 0) {
packages.addAll(Arrays.asList(additionalDangerousApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean detectRootCloakingApps() {
return detectRootCloakingApps(null);
}
private boolean detectRootCloakingApps(String[] additionalRootCloakingApps) {
ArrayList<String> packages = new ArrayList<>();
packages.addAll(Arrays.asList(knownRootCloakingPackages));
if (additionalRootCloakingApps != null && additionalRootCloakingApps.length > 0) {
packages.addAll(Arrays.asList(additionalRootCloakingApps));
}
return isAnyPackageFromListInstalled(packages);
}
private boolean checkForBinary(String filename) {
for (String path : suPaths) {
String completePath = path + filename;
File f = new File(completePath);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private boolean checkForMaliciousPaths() {
for (String path : maliciousPaths) {
File f = new File(path);
boolean fileExists = f.exists();
if (fileExists) {
return true;
}
}
return false;
}
private static boolean checkSUonPath() {
for (String pathDir : System.getenv("PATH").split(":")) {
if (new File(pathDir, "su").exists()) {
return true;
}
}
return false;
}
private String[] propsReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("getprop").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
}
return propval.split("\n");
}
private String[] mountReader() {
InputStream inputstream = null;
try {
inputstream = Runtime.getRuntime().exec("mount").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
if (inputstream == null) return null;
String propval = "";
try {
propval = new Scanner(inputstream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
e.printStackTrace();
}
return propval.split("\n");
}
private boolean isAnyPackageFromListInstalled(List<String> packages) {
PackageManager pm = activity.getPackageManager();
for (String packageName : packages) {
try {
pm.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
}
return false;
}
private boolean checkForDangerousProps() {
final Map<String, String> dangerousProps = new HashMap<>();
dangerousProps.put("ro.debuggable", "1");
dangerousProps.put("ro.secure", "0");
String[] lines = propsReader();
for (String line : lines) {
for (String key : dangerousProps.keySet()) {
if (line.contains(key)) {
String badValue = dangerousProps.get(key);
badValue = "[" + badValue + "]";
if (line.contains(badValue)) {
return true;
}
}
}
}
return false;
}
private boolean checkForRWPaths() {
String[] lines = mountReader();
for (String line : lines) {
String[] args = line.split(" ");
if (args.length < 4) {
continue;
}
String mountPoint = args[1];
String mountOptions = args[3];
for (String pathToCheck : pathsThatShouldNotBeWrtiable) {
if (mountPoint.equalsIgnoreCase(pathToCheck)) {
for (String option : mountOptions.split(",")) {
if (option.equalsIgnoreCase("rw")) {
return true;
}
}
}
}
}
return false;
}
private boolean checkSuExists() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[]{"which", "su"});
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
return in.readLine() != null;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
}
but now to increase security I want to do this root detection logic in native C++ JNI code. I managed to migrate package detection code to JNI C but am not able to find anything regarding these 3 functions
checkForDangerousProps(),checkForRWPaths(),checkSuExists()
these 3 use Runtime.getRuntime().exec which am not able to find. can someone help me in converting this 3 logics to JNI C one from above code? Help would be really appreciated.
Pls guys help.
I have written two methods one for attachments and one email body content. I need to extract the images from email body. These two methods are working fine but when images are coming in email body it is should be saved in database. So it can be used later.
For attachmnents:-
public static List getAttachments(MimeMultipart multipart, List existingAttachments) {
if (multipart != null) {
try {
if (existingAttachments == null) {
existingAttachments = new ArrayList<MimeBodyPart>();
}
for (int i = 0; i < multipart.getCount(); i++) {
if (multipart.getBodyPart(i) instanceof MimeBodyPart) {
MimeBodyPart currentPart = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(currentPart.getDisposition())) {
if (!existingAttachments.contains(currentPart)) {
existingAttachments.add(currentPart);
System.out.println(currentPart.getFileName());
}
} else if (currentPart.getContent() instanceof MimeMultipart) {
existingAttachments = getAttachments((MimeMultipart) currentPart.getContent(), existingAttachments);
}
}
}
} catch (MessagingException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
} catch (IOException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
}
}
return existingAttachments;
}
for email Body ContentThis method is extracting email body content
public static String getContent(MimeMultipart multipart) {
String emailContent = null;
if (multipart != null) {
try {
for (int i = 0; i < multipart.getCount(); i++) {
if (multipart.getBodyPart(i) instanceof MimeBodyPart) {
MimeBodyPart currentPart = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.INLINE.equalsIgnoreCase(currentPart.getDisposition())) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is inline");
emailContent = (String) currentPart.getContent();
} else if (currentPart.getDisposition() == null && currentPart.getContentType().toLowerCase().contains("text")) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is null and type is text/*");
try {
emailContent = (String) currentPart.getContent();
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
try {
InputStream is = currentPart.getInputStream();
emailContent = IOUtils.toString(is, currentPart.getEncoding());
Document doc=Jsoup.parse(emailContent);
Elements elements =doc.getElementsByTag("img");
System.out.println(elements);
int htmlCloseIndex = emailContent.indexOf("</html>");
emailContent = emailContent.substring(0, htmlCloseIndex);
emailContent+="</html>";
} catch (Exception e) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error("Exception rebound caught and managed, email content will not read");
//emailContent = "Unable to read email content";
e.printStackTrace();
}
}
}else if (currentPart.getDisposition() == null && currentPart.getContentType().contains("TEXT")) {
LoggerFactory.getLogger(EmailUtil.class.getName()).info("Content dispo is null and type is TEXT/*");
try {
emailContent = (String) currentPart.getContent();
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
try {
InputStream is = currentPart.getInputStream();
emailContent = IOUtils.toString(is, currentPart.getEncoding());
int htmlCloseIndex = emailContent.indexOf("</html>");
emailContent = emailContent.substring(0, htmlCloseIndex);
emailContent+="</html>";
} catch (Exception e) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error("Exception rebound caught and managed, email content will not read");
//emailContent = "Unable to read email content";
e.printStackTrace();
}
}
}
else if (currentPart.getContent() instanceof MimeMultipart) {
emailContent = getContent((MimeMultipart) currentPart.getContent());
}
}
}
} catch (MessagingException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("email content will not read");
//emailContent = "Unable to read email content";
} catch (IOException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).error(ex.getMessage());
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("email content will not read");
// emailContent = "Unable to read email content";
} catch (ClassCastException ex) {
LoggerFactory.getLogger(EmailUtil.class.getName()).warn("Classcast exception caught and managed");
// emailContent = "Unable to read email content";
}
}
return emailContent;
}
Okay one starts with the <img src="..."> tags, you already took:
Elements elements = doc.getElementsByTag("img");
An img tag for an embedded image looks like:
<img src="data:image/jpeg;base64,..." ...>
So having the src attribute do:
String src = ...
if (src.startsWith("data:")) { // Embedded image data.
int p = src.indexOf(';'); // Or better ";base64,"
if (p == -1) {
throw new IllegalArgumentException();
}
String mimeType = src.substring(5, p);
String base64Data = src.substring(p + 1 + 6 + 1); // ";base64,"
byte[] data = Base64.getDecoder().decode(base64Data);
String file = "test." + mimeType.replaceFirst("^.*/(.*)$", "$1");
Path path = Paths.get(file);
Files.write(path, data);
}
I created an Android application which uses the Google Books API. When I get the JSON response from the server, I parse the response and retrieve the title, authors, category, publisher, page count, thumbnail and some more information about the book. The problem is that some books in the JSON response don't have the thumbnail key or category key. When I try to get those JSON key values the program throws an error and consequently skips the code of adding other books after the error occurred.
I solved that with nested try catch blocks. For example, if there isn't a publisher key in the response, then I would return null.
String publisher;
try {
publisher = volumeInfo.getString("publisher");
} catch (JSONException e) {
publisher = null;
}
Here is how the whole method for parsing the JSON response looks like:
private List<BookData> parseJsonResponse(String jsonResponse) {
List<BookData> bookData = new ArrayList<>();
try {
JSONObject rootObject = new JSONObject(jsonResponse);
JSONArray itemsArray = rootObject.getJSONArray("items");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject itemObject = itemsArray.getJSONObject(i);
JSONObject volumeInfo =
itemObject.getJSONObject("volumeInfo");
String title;
try {
title = volumeInfo.getString("title");
} catch (JSONException e) {
title = null;
}
ArrayList<String> authors;
try {
JSONArray authorsArray =
volumeInfo.getJSONArray("authors");
authors = new ArrayList<>();
for (int j = 0; j < authorsArray.length(); j++) {
authors.add(authorsArray.getString(j));
}
} catch (JSONException e) {
authors = null;
}
ArrayList<String> categories;
try {
JSONArray categoriesArray =
volumeInfo.getJSONArray("categories");
categories = new ArrayList<>();
for (int k = 0; k < categoriesArray.length(); k++) {
categories.add(categoriesArray.getString(k));
}
} catch (JSONException e) {
categories = null;
}
String publisher;
try {
publisher = volumeInfo.getString("publisher");
} catch (JSONException e) {
publisher = null;
}
String publishedDate;
try {
publishedDate =
volumeInfo.getString("publishedDate");
} catch (JSONException e) {
publishedDate = null;
}
int pageCount;
try {
pageCount = volumeInfo.getInt("pageCount");
} catch (JSONException e) {
pageCount = 0;
}
String language;
try {
language = volumeInfo.getString("language");
} catch (JSONException e) {
language = null;
}
String description;
try {
description = volumeInfo.getString("description");
} catch (JSONException e) {
description = null;
}
String bookWebsite;
try {
bookWebsite = volumeInfo.getString("infoLink");
} catch (JSONException e) {
bookWebsite = null;
}
Bitmap thumbnail;
try {
JSONObject imageLink =
volumeInfo.getJSONObject("imageLinks");
String thumbnailUrl =
imageLink.getString("thumbnail");
thumbnail = getThumbnailBitmap(thumbnailUrl);
} catch (JSONException e) {
thumbnail = null;
}
// Add a new BookData object to the list
bookData.add(new BookData(title, thumbnail, authors,
categories, publisher, publishedDate,
pageCount, language, description,
bookWebsite));
}
} catch (JSONException e) {
Log.e(LOG_TAG, null, e);
}
return bookData;
}
After I complete my parsing, I have to update my views. I am using a list view, so the adapter needs to handle the views inflation.
I had to add an if statement to check if the variable is not null, then for example set the text of the text view. Else I set the text to "Publisher not available".
TextView publisher = listView.findViewById(R.id.book_publisher);
if (bookData.getPublisher() != null) {
publisher.setText(bookData.getPublisher());
} else {
publisher.setText("Publisher not available");
}
Here is how the whole adapter looks like:
public class BookDataAdapter extends ArrayAdapter<BookData> {
public BookDataAdapter(#NonNull Context context, #NonNull
List<BookData> bookDatas) {
super(context, 0, bookDatas);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView,
#NonNull ViewGroup parent) {
View listView = convertView;
if (listView == null) {
listView = LayoutInflater.from(getContext())
.inflate(R.layout.book_list_item, parent, false);
}
// Get current BookData object
BookData bookData = getItem(position);
ImageView thumbnail = listView.findViewById(R.id.book_thumbnail);
if (bookData.getThumbnail() != null) {
thumbnail.setImageBitmap(bookData.getThumbnail());
} else {
// Set default thumbnail
thumbnail.setImageResource(R.drawable.default_thumbnail);
}
TextView title = listView.findViewById(R.id.book_title);
if (bookData.getTitle() != null) {
title.setText(bookData.getTitle());
} else {
title.setText("Title not available");
}
TextView author = listView.findViewById(R.id.book_author);
if (bookData.getAuthors() != null) {
author.setText(listToString(bookData.getAuthors()));
} else {
author.setText("Authors not available");
}
TextView category = listView.findViewById(R.id.book_category);
if (bookData.getCategories() != null) {
category.setText("Category: " +
listToString(bookData.getCategories()));
} else {
category.setText("Category not available ");
}
TextView publisher = listView.findViewById(R.id.book_publisher);
if (bookData.getPublisher() != null) {
publisher.setText(bookData.getPublisher() + ", ");
} else {
publisher.setText("Publisher not available, ");
}
TextView publishedDate =
listView.findViewById(R.id.book_published_date);
if (bookData.getPublishedDate() != null) {
publishedDate.setText(bookData.getPublishedDate());
} else {
publishedDate.setText("Published date not available");
}
TextView pageCount = listView.findViewById(R.id.book_page_count);
if (bookData.getPageCount() != 0) {
pageCount.setText("Pages: " + bookData.getPageCount());
} else {
pageCount.setText("Page count not available");
}
TextView language = listView.findViewById(R.id.book_language);
if (bookData.getLanguage() != null) {
language.setText(bookData.getLanguage());
} else {
language.setText("Language not available");
}
TextView description =
listView.findViewById(R.id.book_description);
if (bookData.getDescription() != null) {
description.setText(bookData.getDescription());
} else {
description.setText("Description not available");
}
return listView;
}
private String listToString(List<String> list) {
if (list == null || list.size() == 0) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
builder.append(list.get(i));
if (i == (list.size() - 1)) {
break;
}
builder.append(", ");
}
return builder.toString();
}
}
And lastly I want to ask a question. Is there a better way or more efficient way of parsing the JSON response with different keys, because some people say that nested try catch statements are not a good practice?
Thank you very much!!
You have two options:
Using .has():
String publisher = null;
if(volumeInfo.has("publisher")){
publisher = volumeInfo.getString("publisher");
}
Using opt instead of get (better, IMO):
String publisher = volumeInfo.optString("publisher");
opt### methods default to null for objects and 0/false for primitives, so you don't have to write try/catch blocks or if conditions. You can also specify a second parameter as default value:
String publisher = volumeInfo.optString("publisher", "no publisher");
// if publisher is not a valid key, "no publisher" will be returned
Use can you .has() property of JSONObject
if(volumeInfo.has("publisher")){
volumeInfo.getString("publisher");
}
You don't need to wrap json operations in individual try/catch blocks.
There is a method in the json library to handle this problem:
jsonObject.isNull(key);
When you attempt to grab a value by key write it like this:
if (!volumeInfo.isNull("categories")) {
JSONArray categoryArray = volumeInfo.getJSONArray("categories");
}
Currently using open source project (https://github.com/mcollinge/07kit/tree/master/src/main)
And when i build the application, it looks like this: http://prntscr.com/f2zh5a
The thing is, the API is on their side (public static final String API_URL = "https://api.somesite.com/user";)
Their API is down. Therefore i cannot register on their site, to go through the logging in process.
Would there be any way to bypass login?
Providing LoginController class code below.
public class LoginController extends Controller<LoginView> {
public static final String API_URL = "";
private final Logger logger = Logger.getLogger(LoginController.class);
private LoginView view;
public LoginController() {
ControllerManager.add(LoginController.class, this);
}
public void show() {
try {
if (Session.get().getApiToken() != null) {
logger.info("Existing API token found - trying to retrieve account info...");
if (loadAccount(Session.get().getApiToken(), true, Session.get().getEmail().getValue())) {
logger.info("Logged in with pre-existing key.");
return;
}
}
} catch (Exception e) {
logger.error("Failed to authenticate.", e);
}
Toolkit toolkit = Toolkit.getDefaultToolkit();
int centerX = (toolkit.getScreenSize().width / 2) - (getComponent().getWidth() / 2);
int centerY = (toolkit.getScreenSize().height / 2) - (getComponent().getHeight() / 2);
getComponent().setLocation(centerX, centerY);
getComponent().setIconImage(Application.ICON_IMAGE);
getComponent().setVisible(true);
}
public void login(String email, String password, boolean rememberMe) {
try {
SwingWorker worker = new SwingWorker() {
#Override
protected Object doInBackground() throws Exception {
HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(Request.Post(API_URL + "/token")
.bodyString(JacksonUtil.serialize(new CreateTokenRequest(email, password)), ContentType.APPLICATION_JSON)).returnResponse();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
UserToken tokenResponse = JacksonUtil.deserialize(
EntityUtils.toString(response.getEntity()),
UserToken.class);
if (loadAccount(tokenResponse.getUuid(), rememberMe, email)) {
logger.info("Logged in.");
return null;
}
}
logger.error("Invalid login, response: [" + response.toString() + "]");
getComponent().getStatusLbl().setText("Status: Invalid login");
return null;
}
};
worker.execute();
} catch (Exception e) {
logger.error("Oops.", e);
getComponent().getStatusLbl().setText("Status: Error logging in");
}
}
private boolean loadAccount(String uuid, boolean rememberMe, String email) throws IOException {
HttpResponse getAccountResponse = Executor.newInstance(HttpUtil.getClient()).execute(Request.Get(API_URL)
.addHeader("Authorization", "Bearer " + uuid)).returnResponse();
if (getAccountResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
logger.info("Processed login [" + getAccountResponse.toString() + "]");
UserAccount account = JacksonUtil.deserialize(
EntityUtils.toString(getAccountResponse.getEntity()),
UserAccount.class);
if (account != null && account.getStatus() == UserAccount.Status.ACTIVE &&
account.getType() != null) {
getComponent().getStatusLbl().setText("Status: Logged in");
getComponent().dispose();
Session.get().setUserAccount(account);
Session.get().setApiToken(uuid);
Property emailProperty = Session.get().getEmail();
Property apiKeyProperty = Session.get().getApiKey();
if (rememberMe) {
if (emailProperty == null) {
emailProperty = new Property(Session.EMAIL_PROPERTY_KEY, email);
emailProperty.save();
} else {
emailProperty.setValue(email);
emailProperty.save();
}
if (apiKeyProperty == null) {
apiKeyProperty = new Property(Session.API_KEY_PROPERTY_KEY, uuid);
apiKeyProperty.save();
} else {
apiKeyProperty.setValue(uuid);
apiKeyProperty.save();
}
} else {
if (emailProperty != null) {
emailProperty.remove();
}
if (apiKeyProperty != null) {
apiKeyProperty.remove();
}
}
Session.get().onAuthenticated();
ControllerManager.get(MainController.class).show();
return true;
} else {
getComponent().getStatusLbl().setText("Status: Only BETA users can login");
return false;
}
}
return false;
}
#Override
public LoginView getComponent() {
if (view == null) {
view = new LoginView(this);
}
return view;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I was asked to work on this back-end scheduled job that export some customers data (from an e-commerce DB) to a custom-format text file. The code that follows is what I found.
I just would like to delete it all, but I can't. Would it be possible for me to improve this without changing it so much?
public class AConverter implements CustomerConverter {
protected final Logger LOG = LoggerFactory.getLogger(AConverter.class);
private final static String SEPARATOR = ";";
private final static String CR = "\n";
public String create(Customer customer) {
if (customer == null)
return null;
LOG.info("Exporting customer, uidpk: {}, userid: {}", customer.getUidPk(), customer.getUserId());
StringBuilder buf = new StringBuilder();
buf.append("<HEAD>");
buf.append(SEPARATOR);
buf.append(String.valueOf(customer.getUidPk()));
buf.append(SEPARATOR);
byte[] fullName = null;
try {
fullName = customer.getFullName().getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
fullName = customer.getFullName().getBytes();
}
String name = null;
try {
name = new String(fullName, "UTF-8");
} catch (UnsupportedEncodingException e) {
name = customer.getFullName();
}
buf.append(limitString(name, 40));
buf.append(SEPARATOR);
final CustomerAddress preferredShippingAddress = customer.getPreferredShippingAddress();
if (preferredShippingAddress != null) {
final String street1 = preferredShippingAddress.getStreet1();
if (street1 != null) {
buf.append(limitString(street1, 40));
}
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
final String addressStr = buildAddressString(customer);
buf.append(limitString(addressStr, 40));
buf.append(SEPARATOR);
buf.append(limitString(customer.getEmail(), 80));
buf.append(SEPARATOR);
if (preferredShippingAddress!=null && preferredShippingAddress.getStreet2() != null) {
buf.append(limitString(preferredShippingAddress.getStreet2(), 40));
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
buf.append(limitString(customer.getPhoneNumber(), 25));
buf.append(SEPARATOR);
if (preferredShippingAddress!=null) {
if(preferredShippingAddress.getCountry()!=null) {
buf.append(preferredShippingAddress.getCountry());
} else {
buf.append(" ");
}
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
if (preferredShippingAddress!=null) {
if(preferredShippingAddress.getCountry()!=null) {
buf.append(preferredShippingAddress.getCountry());
} else {
buf.append(" ");
}
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
String fodselsnummer = " ";
try {
Map<String, AttributeValue> profileValueMap = customer.getProfileValueMap();
AttributeValue attributeValue = profileValueMap.get("CODE");
fodselsnummer = attributeValue.getStringValue();
} catch (Exception e) {
}
buf.append(fodselsnummer);
buf.append(CR);
final String string = buf.toString();
return string;
}
private String buildAddressString(Customer customer) {
final CustomerAddress preferredShippingAddress = customer.getPreferredShippingAddress();
if (preferredShippingAddress != null) {
final String zipOrPostalCode = preferredShippingAddress.getZipOrPostalCode();
final String city = preferredShippingAddress.getCity();
if (zipOrPostalCode != null && city != null) {
return zipOrPostalCode + " " + city;
} else if(zipOrPostalCode == null && city != null) {
return city;
} else if(zipOrPostalCode != null && city == null) {
return zipOrPostalCode;
}
}
return " ";
}
private String limitString(String value, int numOfChars) {
if (value != null && value.length() > numOfChars)
return value.substring(0, numOfChars);
else
return value;
}
}
You say you want to improve it, you'd like to delete it, but you can't. I'm not sure why you can't. I also don't understand why you'd want to delete it. But it sounds to me like the kind of attitude I used to have before I read Refactoring by Martin Fowler. I would strongly suggest you read that book, if you haven't already.
It is certainly possible to improve this code (or any code) without rewriting it all. The most obvious improvements would be to eliminate some of the repetitive code in the create method by creating some utility methods, and then breaking up the create method into several smaller methods à la template methods.
Also, there is a questionable bit of code in the create method that turns the customer's name into a UTF-8 byte stream and then back into a string. I can't imagine what that's for. Finally, it returns null if the customer is null. That is unlikely to be necessary or wise.
For fun, I decided to do a little refactoring on this code. (Note that proper refactoring involves unit tests; I don't have any tests for this code and have not even compiled the code below, much less tested it.) Here is one possible way you could rewrite this code:
public class AConverter implements CustomerConverter {
protected final Logger LOG = LoggerFactory.getLogger(AConverter.class);
private final static String SEPARATOR = ";";
private final static String CR = "\n";
public String create(Customer customer) {
if (customer == null) throw new IllegalArgumentException("no cust");
LOG.info("Exporting customer, uidpk: {}, userid: {}",
customer.getUidPk(), customer.getUserId());
StringBuilder buf = new StringBuilder();
doHead(buf, customer);
doAddress(buf, customer);
doTail(buf, customer);
return buf.toString();
}
private void doHead(StringBuilder buf, Customer customer) {
append(buf, "<HEAD>");
append(buf, String.valueOf(customer.getUidPk()));
append(buf, limitTo(40, customer.getFullName()));
}
private void doAddress(StringBuilder buf, Customer customer) {
append(buf, limitTo(40, street1of(customer)));
append(buf, limitTo(40, addressOf(customer)));
append(buf, limitTo(80, customer.getEmail()));
append(buf, limitTo(40, street2of(customer)));
append(buf, limitTo(25, customer.getPhoneNumber()));
append(buf, countryOf(customer));
append(buf, countryOf(customer));
}
private void doTail(StringBuilder buf, Customer customer) {
buf.append(fodselsnummerOf(customer));
buf.append(CR);
}
private void append(StringBuilder buf, String s) {
buf.append(s).append(SEPARATOR);
}
private String street1of(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
if (shipto.getStreet1() != null) return shipto.getStreet1();
return " ";
}
private String street2of(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
if (shipto.getStreet2() != null) return shipto.getStreet2();
return " ";
}
private String addressOf(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
final String post = preferredShippingAddress.getZipOrPostalCode();
final String city = preferredShippingAddress.getCity();
if (post != null && city != null) return post + " " + city;
if (post == null && city != null) return city;
if (post != null && city == null) return post;
return " ";
}
private String countryOf(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
if (shipto.getCountry() != null) return shipto.getCountry();
return " ";
}
private String limitTo(int numOfChars, String value) {
if (value != null && value.length() > numOfChars)
return value.substring(0, numOfChars);
return value;
}
private String fodelsnummerOf(Customer customer) {
try {
Map<String, AttributeValue> profileValueMap =
customer.getProfileValueMap();
AttributeValue attributeValue = profileValueMap.get("CODE");
return attributeValue.getStringValue();
} catch (Exception e) {
return " ";
}
}
}
I also notice that there is a problem with your format for the custom-format text file if any of the fields of the customer data (email address, for example) happen to have a semicolon in them, because that is your separator character. I trust that is a known issue?