How to find and update properties embedded in a String in Java - java

I am trying to find and update the values of a string. The string is a recurrence rule sent by a client which I need to get the until property and add time to it. (Ps the setTime/setHour... is depricated)
What i have is:
import java.util.Calendar;
public class TestReplaceString {
/**
* #param args
*/
public static void main(final String[] args) {
String originalRecurrenceRule = "FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;WKST=MO;UNTIL=20160731T223030Z;";
System.out.println("Unformated: " + originalRecurrenceRule);
System.out.println("Formated: " + originalRecurrenceRule.replaceAll("UNTIL.*?Z", "UNTIL=" + "sameDateAsPassedByTheCLient" + "T235959Z;"));
}
The problem with this is that I need to keep the date supplied by the client and only add time eg
The date 20170101T220000Z would become 20170101T235959Z
What i was trying to accomplish is something like a validator to get the property UNTIL from the string and change it.
Any suggestions are welcome.
Kind Regards

Something like this might be a bit more suitable:
String originalRecurrenceRule = "FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;WKST=MO;UNTIL=20160731T223030Z;";
String until = originalRecurrenceRule.substring(originalRecurrenceRule.indexOf("UNTIL"), originalRecurrenceRule.indexOf(";", originalRecurrenceRule.indexOf("UNTIL")));
SimpleDateFormat sdf = new SimpleDateFormat();
Date date = sdf.parse(until.substring(until.indexOf("=") + 1),until.length() - 1);
date.setTime(timeInMilliseconds);
originalRecurrenceRule.replace(until, "UNTIL="+ date.toString() + ";");

Related

How to solve this error "String Cannot be converted to Date"?

Hello I am trying to store the birthdate of the user in database with the code below:
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
String username = txtUserName.getText();
String password = txtPassword.getText();
String email = txtEmail.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthdate = sdf.format(JDateChooser.getDate());
Users user = new Users();
user.setUserName(cin);
user.setPassWord(firstName);
user.setEmail(email);
user.setBirthDate(birthdate);
try {
int count = Users.getInstance().insert(user);
if(count == 1){
JOptionPane.showMessageDialog(null,"success");
reset();
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
I got an error which says String connot be converted to Date in the line "user.setBirthDate(birthdate);"
Because the parameter birthdate is assigned as Date type in the encapsulation(setBirthDate)
is there any way to solve this issue, I am new in java programming and I am trying to improve my skills in java.
If this returns a Date:
JDateChooser.getDate()
And what you need is a Date, then don't convert it to a String. Just keep it as a Date:
Date birthdate = JDateChooser.getDate();
// later...
user.setBirthDate(birthdate);
Note that you can then also remove this line, since you're not using the variable it declares:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
In general you want to keep data types in their raw form pretty much as often as possible. Unless there's a specific need for something to be represented as a string (displaying it to the user, sending it over a serialized API of some kind, etc.) then just use the data as-is instead of converting it to something else.
After you get the date with JDateChooser.getDate(), you are immediately converting it to a string: sdf.format(JDateChooser.getDate());
You should store the returned Date from JDateChooser.getDate() as an actual Date object.
Date birthdate = JDateChooser.getDate();
Then you can use it in your other function directly:
user.setBirthDate(birthdate);
If you do need the date as a string for some other purpose (perhaps display to the user), you can store a formatted string version in a different variable:
String birthdateString = sdf.format(birthdate);
Otherwise, if you don't need a string version, you can delete the line where you create sdf.

Most efficient way to parse URL's with handling errors and extracting required values

I have the Problem framed in the below Program i am trying to extract values from URL strings like the values that come after a=, symbol=, uid=, cid=, o=.
What is the best way to extract these values for the sample URLS shown in the array declared in the program.
I want to keep the time taken to parse shown in the output statement of program to have a minimal possible value.
package com.xyz.urlagent;
import java.util.Date;
import java.util.Random;
public class UrlExtract {
public static String[] urlArray = {"https://example.com/grid/p/login?cid=testcidcombo4&uid=testuidcombo4&a=testadcodecombo4&o=testoffercodecombo4",
"https://example.com/grid/p/site#r=jPage/https://research-example.com/grid/wwws/research/stocks/earnings?c_name=hvfkhfk_VENDOR&symbol=IBM",
"https://example.com/grid/p/login?a=testadcode3",
"https://example.com/grid/p/site#r=jPage/https://research-example.com/grid/wwws/fixedIncome/bondTicker.asp?c_name=_jhcjhfhyjkh_VENDOR&Extra=",
"https://example.com/grid/p/site#r=jPage/https://example.com/grid/wwws/ideas/overview/overview.asp?YYY600_4TasO+9+jFhYnkq2U5YXohiZ9qsMKu/jUh6HR8N5EWKAOlRWVhC18/dapBTvnqGaqgNGUMvWP3EfysyWRfCNYsqUFBc1pxuB8/ho+4G2BBo=&c_name=khhfjkuk_VENDOR",
"https://example.com/grid/p/site#r=jPage/https://research-example.com/grid/wwws/research/stocks/earnings?symbol=AAPL&c_name=jkvkjgljlj_VENDOR",
"https://example.com/grid/p/login?CID=testcid1"};
public static int numurl = 2000;
public static Random rand = new Random(System.currentTimeMillis());
public static void main(String[] args) {
Date StartDate= new Date();
for(int i=0; i<numurl;i++){
String SampleURL = urlArray[rand.nextInt(urlArray.length)];
////////////############ CODE To Extract symbol Values from URL(value after symbol=)
////////////############ CODE To Extract UID Values from URL(value after uid=)
////////////############ CODE To Extract CID Values from URL(value after cid=)
////////////############ CODE To Extract O Values from URL(value after o=)
////////////############ CODE To Extract A Values from URL(value after a=)
System.out.println("Values extracted from Sample URL: "+ "(Extracted Values are printed HERE)");
}
Date EndDate= new Date();
long diff = (EndDate.getTime()-StartDate.getTime())/(1000%60);
System.out.println("Time taken to parse "+numurl+ " url's is: "+diff+ " seconds.");
}
}
The URI class and URLDecoder class are designed to do what you want:
URI uri = URI.create(sampleURL);
String query = uri.getRawQuery();
String[] nameValuePairs = query.split("&");
for (String nameValuePair : nameValuePairs) {
String nameAndValue = nameValuePair.split("=", 2);
String name = URLDecoder.decode(nameAndValue[0], "UTF-8");
String value = URLDecoder.decode(nameAndValue[1], "UTF-8");
System.out.printf("Found query parameter \"%s\" with value \"%s\"%n",
name, value);
}
Be aware that some of your example Strings are not valid URLs at all, because the #r comes before the query separator, ?. The structure of a URI is documented in the URI class documentation and in the RFC that defines the structure of a URI, RFC 3986.

Java stored procedure returns nothing in Oracle Database

I have a fairly simple stored java procedure in an oracle database. The intended purpose is to read the contents of a folder which resides on the Oracle server. If it encounters a folder it will step into the folder and write the name of the contents into a global temp table, and move on to the next folder. The Java procedure compiles fine and submits into the database with no issues. When it's called by a stored Oracle procedure it runs successfully as well. But produces no results into the global temp table. I am using TOAD and i'm not sure how to put a break or view the variables during run time so i'm kind of flying blind. And i'm admittedly not great a java.
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED BALT_CHECK."WebDirList" AS
import java.io.*;
import java.sql.*;
import java.util.Date;
import java.text.SimpleDateFormat;
public class WebDirList
{
public static void getList(String rootdirectory) throws SQLException
{
File path = new File( rootdirectory );
String[] rootDirList = path.list();
String element;
for( int x = 0; x < rootDirList.length; x++)
{
element = rootDirList[x];
String newPath = rootdirectory + "/" + rootDirList[x] ;
File f = new File(newPath);
if (f.isFile()){
/* Do Nothing */
} else {
/*if it is a folder than load the subDirPath variable with the newPath variable */
File subDirPath = new File( newPath+"/");
String[] subDirList = subDirPath.list();
String efileName;
for(int i = 0; i < subDirList.length; i++)
{
efileName = subDirList[i];
String fpath = subDirPath + "/" + subDirList[i];
File nf = new File(fpath);
long len;
Date date;
String ftype;
String sqlDate;
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss");
if (f.isFile()) {
len = f.length();
date = new Date(f.lastModified());
sqlDate = df.format(date);
#sql { INSERT INTO WEB_DIRLIST (FILENAME, LENGTH, CREATEDATE)
VALUES (:efileName, :len, to_date(:sqlDate, 'YYYY-MM-DD HH24:MI:SS')) };
}else{
/* Do nothing */
}
}
}
}
}
}
/
Procedure is created as
CREATE OR REPLACE procedure BALT_CHECK.get_webdir_list( p_directory in varchar2)
as language java
name 'WebDirList.getList( java.lang.String )';
/
Procedure is called as
exec get_webdir_list( '/transfer_edi/hs122/');
in the folder /transfer/edi/hs122/ are 10 sub directories each have between 1 and 100 items in them at any given time.
I'm not sure how you check the results (same session or not). Do you perform commit somewhere? There are some specifics with global temp tables (there is option whether data is purged after commit or not). You may wish to initially try with permanent one until you sort out the problem.
It may be useful if you add some logging (e.g. to another table). E.g. rootDirList.length may be a good indicator to check.
Some other remarks:
The /* Do nothing */ branches in your if statements are adding additional noise. Good to remove them.
Perhaps would be better to use .isDirectory() if you want to check if the paths is a directory (instead of isFile).
There were a few errors in this code that prevented it from writing to the database. Based on Yavor's suggestion of writing String variables to a temp table I was able to find that I had duplicated "/" on the file path e.g. (/transfer_edi/hs122//Acctg). I also found I had an incorrect data type on one of my columns in my data table that I was writing too. I also switched to a regular table instead of a global temp table which was deleting after commit. Again thanks Yavor. Regardless of all that I ended up re-writing the entire thing. I realized that I needed to traverse down the directory structure to get all the files so here is the final code that worked for me. Again i'm not a java guy so i'm sure this could be done better.
This link helped me quite a bit
http://rosettacode.org/wiki/Walk_a_directory/Recursively#Java
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED BALT_CHECK."WebDocs" AS
import java.io.*;
import java.sql.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.lang.String;
public class WebDocs
{
public static long fileID;
public static void GetDocs(String rootdirectory) throws SQLException
{
stepinto(rootdirectory);
}
public static void stepinto(String rootdirectory) throws SQLException
{
File path = new File( rootdirectory );
String[] DirList = path.list();
for( int x = 0; x < DirList.length; x++)
{
String newPath = rootdirectory + DirList[x];
if (newPath != null) {
File f = new File(newPath);
if (f.isDirectory()) {
GetDocs(newPath +"/");
}
if (f.isFile()){
WriteFile(f);
}else{
}
}
}
}
public static void WriteFile(File file) throws SQLException
{
String fileName;
String filePath;
String elementID;
long len;
Date date;
String sqlDate;
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss");
fileID = fileID + 1;
elementID = String.valueOf(fileID);
fileName = file.getName();
filePath = file.getPath();
len = file.length();
date = new Date(file.lastModified());
sqlDate = df.format(date);
#sql { INSERT INTO WEB_STATICDOCS (ID, FILE_NAME, FILE_SIZE, CREATE_DATE, FILE_PATH)
VALUES (:elementID, :fileName, :len, to_date(:sqlDate, 'YYYY-MM-DD HH24:MI:SS'), :filePath) };
}
}
/
Oracle Stored Procedure
CREATE OR REPLACE procedure BALT_CHECK.getWebDocs( p_directory in varchar2)
as language java
name 'WebDocs.GetDocs( java.lang.String )';
/
Calling the stored Procedure
exec getWebDocs( '/transfer_edi/hs122/');

Storing objects in a database java

So I'm working on a program to interface with a file based database. Mostly I'm trying to figure out how to work with it so that I can make objects and store their information in the database so that I can pull the data later.
IE Object Taylor
Name = Taylor
Age = 20
School = Whatever
So that I can get back on and call that information up when queried.
This is an example of an object I want to store. I may be doing this part wrong.
package com.catalyse.db;
public class Taylor implements java.io.Serializable
{
public String name = "Taylor M May";
public int age = 20;
public String school = "UC Boulder";
}
The DB structure I'm using is based on RandomAccessFile and I didn't make it, I'm just trying to figure out how to implement it.
package com.catalyse.db;
import java.util.*;
import java.util.Scanner;
/**
* Simple test class for the RecordsFile example. To run the test,
* set you CLASSPATH and then type "java hamner.dbtest.TestRecords"
*/
public class Run {
static void log(String s) {
System.out.println(s);
}
private static String name()
{
Scanner name = new Scanner(System.in);
String name1 = name.next();
return name1;
}
public static void main (String[] args) throws Exception {
System.out.println(new Date());
Scanner SC = new Scanner(System.in);
log("What would you like to name the database?");
String filename = SC.next();
log("creating records file...");
RecordsFile recordsFile = new RecordsFile(filename+".records", 64);
log("adding a record...");
RecordWriter rw = new RecordWriter("foo.username");
rw.writeObject(new Taylor());
recordsFile.insertRecord(rw);
log("reading record...");
RecordReader rr = recordsFile.readRecord("foo.username");
Taylor name = (Taylor)rr.readObject();
System.out.println("\tlast access was at: " + name.toString());
log("test completed.");
}
}
And here is what I get back from it,
Wed Nov 20 11:56:04 MST 2013
What would you like to name the database?
save3
creating records file...
adding a record...
reading record...
last access was at: com.catalyse.db.Taylor#50aed564
test completed.
My problem is that I want it to return information about the class, not just its name and location in the DB.
You need to override the toString method.
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Name: ");
sb.append(this.name);
//rest of fields
return sb.toString();
}
As a matter of clarity, you are not returning its location in the database. You are getting back the object hashValue + the class name.
At this point
Taylor name = (Taylor)rr.readObject();
You can access whatever information you like in the object, e.g.
Taylor name = (Taylor)rr.readObject();
System.out.println(name.age + ", " + name.name + ", " + name.school);
Alternatively, just add a
public String toString()
{
return name + ", " + age + ", " + school;
}
method in Taylor and then output it like so
Taylor name = (Taylor)rr.readObject();
System.out.println(name);
Now, concerning...
System.out.println("\tlast access was at: " + name.toString());
name.toString() isn't really required. If you append an object to a String then it automatically calls that objects toString() method to get a value.
Lastly, I'd like to note that generally we don't access object members like name, school and age by just accessing them. We generally make them private members then add methods to get and set them, so that we control and can track how they are manipulated.

Why does non-lenient SimpleDateFormat parse dates with letters in?

When I run the following code I would expect a stacktrace, but instead it looks like it ignores the faulty part of my value, why does this happen?
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(final String[] args) {
final String format = "dd-MM-yyyy";
final String value = "07-02-201f";
Date date = null;
final SimpleDateFormat df = new SimpleDateFormat(format);
try {
df.setLenient(false);
date = df.parse(value.toString());
} catch (final ParseException e) {
e.printStackTrace();
}
System.out.println(df.format(date));
}
}
The output is:
07-02-0201
The documentation of DateFormat.parse (which is inherited by SimpleDateFormat) says:
The method may not use the entire text of the given string.
final String value = "07-02-201f";
In your case (201f) it was able to parse the valid string till 201, that's why its not giving you any errors.
The "Throws" section of the same method has defined as below:
ParseException - if the beginning of the specified string cannot be parsed
So if you try changing your string to
final String value = "07-02-f201";
you will get the parse exception, since the beginning of the specified string cannot be parsed.
You can look whether the entire string was parsed as follows.
ParsePosition position = new ParsePosition(0);
date = df.parse(value, position);
if (position.getIndex() != value.length()) {
throw new ParseException("Remainder not parsed: "
+ value.substring(position.getIndex()));
}
Furthermore when an exception was thrown by parse the position will also yield getErrorIndex().
Confirmed... I also found that "07-02-201", "07-02-2012 is the date" compiles. However, "bar07-02-2011" does not.
From the code in SimpleDateFormat, it seems like the parsing terminates the moment an illegal character is found that breaks the matching. However, if the String that has already been parsed up to that point is valid, it is accepted.

Categories

Resources