after a little bit of trying I managed to get results from the ldap-server at my company. Now I have a little problem and I seem to be too dump to find any documentation about it.
Command objCmd = new Command();
Recordset RS = new Recordset();
objCmd.setActiveConnection(conn);
objCmd.setCommandText("<LDAP://scdldap.siemens.net:389>;(&(objectClass=scdInternetPerson)(mail=" + email + "));" +searchKeyword+";subTree");
RS = objCmd.Execute();
if (RS.getBOF())
System.out.printf(email + ";" + "null" + "\n");
else {
RS.MoveFirst();
System.out.printf(email + ";" + RS.getFields().getItem(0).getValue() + "\n");
}
This works fine as long as I print the result out to the console. But I would need to get the value as a String (it is always a String), but I can't make it. Can somebody tell me what I am missing? I know this is some VariableType Error, because the result is of type Variant, but
Variant.toString() or anything else is not possible.
Try to convert Variant to Object and then to String, for example:
Variant From = new Variant(1);
Variant To = new Variant(6);
Object[] args = new Object[]{From, To};
String From1 = args[0].toString();
String To1 = args[1].toString();
Related
I am getting a URL from a message that is in the form https://example.com/eUjKSv, however I need to insert a "tag" /raw/ in between .com/ and eUjKSv.
I was wondering what would be the easiest way to do it, currently I have a very "hacky" way to achieve it, new URL("https://example.com/raw" + new URL(link).getPath()), I know it's pretty awful and only works if I know exactly the URL. Any suggestions on how to make this better? I thought about regex but couldn't think of a good one to capture it.
You can use either the URL class or the URI class. They both work for this.
URL baseUrl = new URL("https://example.com/eUjKSv");
URL rawUrl = new URL(baseUrl, "/raw" + baseUrl.getPath());
System.out.println("baseUrl = " + baseUrl);
System.out.println("rawUrl = " + rawUrl);
URI baseUri = new URI("https://example.com/eUjKSv");
URI rawUri = baseUri.resolve("/raw" + baseUri.getPath());
System.out.println("baseUri = " + baseUri);
System.out.println("rawUri = " + rawUri);
Output
baseUrl = https://example.com/eUjKSv
rawUrl = https://example.com/raw/eUjKSv
baseUri = https://example.com/eUjKSv
rawUri = https://example.com/raw/eUjKSv
I have a logging function in CSharp and Java that I use in walking the stack. How do I make each log print to a new line only. Below are my Java and CSharp Functions.
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters );
}
the java version is this
public static void LogFunctionCall(string parameters,
[System.Runtime.CompilerServices.CallerMemberName] string methodName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
var stackFrame = new StackFrame(1);
var callerMethod = stackFrame.GetMethod();
var className = callerMethod.DeclaringType;
System.Diagnostics.Trace.WriteLine("CCCCCCCCCCCCCCCC" + " " + className + " " + methodName + " " + sourceLineNumber + " " + parameters + "\n");
}
I code on a windows machine.
Please where exactly do I need to place the new line character. I tried this
public static void LogFunctionCall(String parameters){
Object trace = Thread.currentThread().getStackTrace()[3];
android.util.Log.i("##################" + trace.toString()+ "", parameters + "\n" );
}
but I still saw some of the logs being clumped up on a single line.
Instead of \n, try \r\n (carriage return and newline). Some text editors will display differently, so the newline may be in there, but whatever app you're using to read the logs might not be displaying it correctly.
You could also try
System.lineSeparator();
I've seen instances where the /n won't work but the lineSep does.
Also, because it hasn't been mentioned, Environment.NewLine will give you the new line character that is configured for the current environment.
I am using Java and MySQL. This code works and returns the expected results:-
queryStr = "SELECT PROGRAM, EQUIPMENT, t.PART_NUMBER, SN, GFE_CAP, t.STATUS, ii.Part_Number, ii.Serial_Number, [Inventory_Type – Level 1], ii.Status, ii.Destination, ii.Location" +
" FROM tblGFE_CAP as t, NGC_BJ_DEV.dbo.ISSUE_ITEMS as ii" +
" WHERE (t.PART_NUMBER = ii.Part_Number)" +
" AND (SN = ii.SERIAL_NUMBER)" +
" AND (GFE_CAP != [Inventory_Type – Level 1])" +
" AND NOT (([Inventory_Type – Level 1] = 'GFP') and (GFE_CAP = 'GFE'))" +
" AND NOT ((ii.Status = 'Retired') AND (t.Status = 'INACTIVE-REPLACED/RETIRED/DISPOSITION'))" +
" AND NOT ((ii.Status = 'Consumed') and (t.Status = 'INACTIVE-REPLACED/RETIRED/DISPOSITION'))" +
" GROUP BY PROGRAM, EQUIPMENT, t.PART_NUMBER, SN, GFE_CAP, t.Status, ii.Part_Number, ii.Serial_Number, [Inventory_Type – Level 1], ii.Destination, ii.Location, ii.Status" +
" ORDER BY GFE_CAP, t.PART_NUMBER, SN";
stmt = con.prepareStatement(queryStr);
rs = stmt.executeQuery();
However, if I read the exact same text from a file (as below) and copy the results into queryStr, the code chokes on the Inventory_Type - Level 1 column name. I confirmed that the resultant strings are identical when passed to preparedStatement. I understand that special characters are not a good idea for the column name, but that is beyond my control.
I cannot change the column name. My real question is why the hard coded query works but the file read does not. Alternatively if there is a syntax that can be used to capture the column name within the java built query string.
String bStr = "";
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(in.getAbsolutePath()));
while (true)
{
bStr = br.readLine();
if (bStr == null)
break;
sb.append(bStr);
}
br.close();
queryStr = sb.toString();
stmt = con.prepareStatement(queryStr);
rs = stmt.executeQuery();
Use sb.append(bStr).append("\n") instead of sb.append(bStr).
Your current code lose line breaks and probably two different words from adjusting lines become one.
This issue has to do with the fact that you are trying to read in special characters (in this case brackets) using your buffered reader. That problem has already been addressed.
see the following approaches:
Read/write .txt file with special characters
Read special characters in java with BufferedReader
I have a java function that is meant to take strings from jlist called "readyList" and pulling data from mysql workbench tables with the intent to write a line for each string in a .csv file. With the current code it sucessfully pulls the data one at a time like i intended but it only writes the last line instead of all the lines. I want to have all the lines written in the .csv file. Please help!
int[] selectedIx = readyList.getSelectedIndices();
for (int i = 0; i < selectedIx.length; i++) {
// while (i < selectedIx.length) {
Object sel = readyList.getModel().getElementAt(selectedIx[i]);
Statement s1 = DBConnect.connection.createStatement();
String selTable01 = "SELECT Sku As s, Qty As q, Orig_Retail As prce, Orig_Sku As orgsk, Store As strcd "
+ "FROM completed_lines WHERE Form_Name = '" + sel + "' AND Warranty = 'true'";
s1.execute(selTable01);
try (ResultSet rs01 = s1.getResultSet()) {
fWriter = new FileWriter("Exports/Transfers/" + /* frmNm.replace(":", "_") */"EBW_" + GtDates.fdate + ".csv", false);
writer = new BufferedWriter(fWriter);
String header = "slip_number,slip_type,out_store,in_store,item_number,quantity,price,comment,to_num";
writer.write(header);
writer.newLine();
while (rs01.next()) {
String strcode = rs01.getString("strcd");
String sku = rs01.getString("s");
String qty = rs01.getString("q");
String price = rs01.getString("prce");
String orgsku = rs01.getString("orgsk");
//System.out.println(frmNm.split("_")[1] + qty + "," + sku + "," + vendor + "," + desc1 + "," + reas + "," + descdmg + "," + orgR + "," + nwsku + "," + desc2 + "," + qtyI);
String line = ""+","+"out"+","+strcode+","+"RTV"+","+sku+","+qty+","+price+","+"EBW"+","+orgsku;
writer.write(line);
writer.newLine();
}
}
// JOptionPane.showMessageDialog(frame, "All Data from Selected Forms has been Exported");
}
// FormCompelted();
writer.close();
}
}
A few issues with this code. The reason you're only getting the last result is because of this line:
fWriter = new FileWriter("Exports/Transfers/" + /* frmNm.replace(":", "_") */"EBW_" + GtDates.fdate + ".csv", false);
This line is inside your loop. The false as the last parameter tells FileWriter not to append. In other words, a false means overwrite the file if it exists. Since this is in your loop, each result overwrites the file that the last result created. You should create the FileWriter outside of your loop, probably in a try with resources. That will allow you to remove your writer.close() call, which should have been in a finally block anyway.
Not related to your original question but something you should be aware of: You're creating a new Statement with each loop iteration. This can be an expensive operation. You should use a PreparedStatement instead. Create it outside your loop and then just set the parameter and execute it inside the loop. It also implements AutoCloseable, so you can create it in a try with resources too, probably the same one you create your FileWriter in.
I am trying to create text file from Select * of access mdb file, I wrote below code to implement same, but while I am trying to read the data I am getting this error "Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid descriptor index"
Not sure if this method will actually work, here's the code:
//=============Extract contents in Access and save it as Text File Format==========================================
//String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\test\\TestEJFolder\\BWC_Ejournal.mdb";
String connectionString ="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\\test\\TestEJFolder\\BWC_Ejournal.mdb;";
DriverManager.getConnection(connectionString, "", "");
Connection conn = DriverManager.getConnection(connectionString, "", "");
String sql = "SELECT * FROM Events";
Statement cmd = conn.createStatement();
cmd.execute(sql);
ResultSet reader = cmd.executeQuery(sql);
//String path = "\\" + time_stmp + "_" + file_name;
File sw = new File(text_dir,file_name);
File ssw = new File(s_path);
sw.createNewFile();
final String format = "{0,-22} {1,-4} {2,-4} {3,-4} {4,-20} {5,-22}";
BufferedWriter output = new BufferedWriter(new FileWriter(sw));
String line = null;
//reader.beforeFirst();
//boolean b = true;
int colCount = rs.getColumnCount();
while (reader.next())
{
//Errors here while trying to read
line = String.format(format, String.format("{0:dd-MM-yyyy HH:mm:ss}", reader.getObject(5)).trim(), reader.getObject(0).toString().trim(), reader.getObject(1).toString().trim(), reader.getObject(2).toString().trim(), reader.getObject(3).toString().trim(), reader.getObject(4).toString().trim());
}
output.write(line);
output.close();
conn.close();
There is a problem at the String.format. Check out Java Tutorial on Strings:
Creating Format Strings
You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of
System.out.printf("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
"and the string is %s",
floatVar, intVar, stringVar);
you can write
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
System.out.println(fs);
Excerpt from your code:
...reader.getObject(0).toString().trim()
AFAICT, you are expected to pass column index starting from 1 to getObject method. I'm not sure what are you trying to get there.
P.S. Next time pay attention to code formatting (remove all of the empty lines, comments, unnecessary statements), post stack trace and highlight clearly the line throwing an exception.
1.Try to separate the test to a small unit of function
1.1 read from DB into object(if you have the time try to use hibernate)
1.2 try to print the object
1.3 try to write to file
see that every unit
i see some problems :
1.the Date should be Date object and not String
2.you have more then one connection