add Listener to logger context in logback - logback

I have the following code for adding a listener to my logger context:
private static void configureLoggerContext(String logbackConfigFileUrl) {
File file = new File(logbackConfigFileUrl);
LoggerListener loggerListener = new LoggerListener();
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
loggerContext.addListener(loggerListener);
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
try {
configurator.doConfigure(file);
} catch (JoranException je) {
throw new RuntimeException(je.getMessage());
}
}
Is there anyway so that I won't have to doConfigure after adding listener?
My problem is that I have added a and because two times configuration, my header is printed twice.

Related

Cannot write to csv file using BufferedWriter

I am trying to append a row at the end of my csv file using the code below
public class Register {
public static void add(int k,int m,int id1) throws Exception
{
ClassLoader classLoader = Register.class.getClassLoader();
try{
FileWriter fw = new FileWriter(new File(classLoader.getResource("data/dataset.csv").getFile()),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
I am calling this class from a servlet using a loop as I need to add 5 lines to my csv. Everything runs fine, but nothing gets added to the csv file. Please help.
You need to close the FileWriter object to flush the content into the file as shown below:
FileWriter fw = null;
BufferedWriter bw = null;
try{
fw = new FileWriter(new File(classLoader.
getResource("data/dataset.csv").getFile()),true);
bw = new BufferedWriter(fw);
bw.append("\n");
bw.append(String.valueOf(id1));
bw.append(',');
bw.append(String.valueOf(m));
bw.append(',');
bw.append(String.valueOf(k));
bw.close();
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
} finally {
if(bw != null) {
bw.close();
}
if(fw != null) {
fw.close();
}
}
As a side note, ensure that you are closing the resources (like the writer objects above) inside the finally block (which you are not doing).

HttpAsyncClient isn't making request if setConnectionManagerShared is set to true

For some reason HttpAsyncClient isn't making request if setConnectionManagerShared is set to true. I found this bug but couldn't figure out what I'm missing.
Here is how I create new client
def apply(proxy: Option[HttpHost], cookieStore: Option[CookieStore]) = {
val builder = HttpAsyncClients.custom.
setConnectionManager(connManager).
setConnectionManagerShared(true).
setDefaultCredentialsProvider(credentialsProvider).
setDefaultRequestConfig(defaultRequestConfig).
setSSLStrategy(sslStrategy)
proxy.map(builder.setProxy)
builder.setDefaultCookieStore(cookieStore.getOrElse(new BasicCookieStore)) // Use custom cookie store if necessary.
// Create an HttpClient with the given custom dependencies and configuration.
val client: HttpAsyncClient = new HttpAsyncClient(builder.build)
client
}
Full class is located is here.
What should I change ?
DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
CloseableHttpAsyncClient client1 = HttpAsyncClients.custom()
.setConnectionManager(cm)
.build();
CloseableHttpAsyncClient client2 = HttpAsyncClients.custom()
.setConnectionManager(cm)
.setConnectionManagerShared(true)
.build();
client1.start();
client2.start();
final CountDownLatch latch = new CountDownLatch(2);
FutureCallback callback = new FutureCallback<HttpResponse>() {
#Override
public void completed(HttpResponse result) {
latch.countDown();
System.out.println(result.getStatusLine());
}
#Override
public void failed(Exception ex) {
latch.countDown();
System.out.println(ex.getMessage());
}
#Override
public void cancelled() {
latch.countDown();
}
};
client1.execute(new HttpGet("http://httpbin.org/get"), callback);
client2.execute(new HttpGet("http://httpbin.org/get"), callback);
latch.await();
// I am aware this is sloppy
client1.close();
client2.close();

Cannot create spreadsheet in google drive

I tried to create a spreadsheet in Android. It sent a success message but it wasn't created.
I used the following code to create it:
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("application/vnd.google-apps.spreadsheet").setTitle("MonthExpense").build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(appobject.mGoogleApiClient);
try {
activity.startIntentSenderForResult(intentSender, 56, null, 0, 0, 0);
}
If I use any other mimetype it works correctly can anyone please guide me in the right way.
Edit
If i try any other mime type it works with out problem, So i guess the problem related with "application/vnd.google-apps.spreadsheet"
Try to change application/vnd.google-apps.spreadsheet to application/vnd.ms-excel
Create a WorkBook. This is the end of my working code
final private ResultCallback<DriveContentsResult> driveContentsCallback = new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(final DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
//CREATE YOUR WORKBOOK HERE
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
byte[] bytes = bos.toByteArray();
outputStream.write(bytes);
//WORKBOOK FILENAME
writer.write(fileName);
wb.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(fileName)
.setMimeType("application/vnd.ms-excel")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi
.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet,
driveContents)
.setResultCallback(fileCallback);

SSIS Scripting Component: Get child records for creating Object

Got it working - Posted My solution below but will like to know if there is better way
Hello All
I am trying to create Domain Event for a newly created (after migration) domain object in my database.
for Objects without any internal child objects it worked fine by using Script Component. The problem is in how to get the child rows to add information to event object.
Ex. Customer-> Customer Locations.
I am creating Event in Script Component- as tranformation- (have reference to my Domain event module) and then creating sending serialized information about event as a column value. The input rows currently provide data for the parent object.
Please advise.
Regards,
The Mar
Edit 1
I would like to add that current I am doing processsing in
public override void Input0_ProcessInputRow(Input0Buffer Row)
I am looking for something like create a a data reader in this function
loop through data rows -> create child objecta nd add it to parent colelction
Still on google and PreExecute and ProcessInput Seems something to look at .
This is my solution. I am a total newbie in SSIS , so this may not be the best solution.
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
IDTSConnectionManager100 connectionManager;
SqlCommand cmd = null;
SqlConnection conn = null;
SqlDataReader reader = null;
public override void AcquireConnections(object Transaction)
{
try
{
connectionManager = this.Connections.ScriptConnectionManager;
conn = connectionManager.AcquireConnection(Transaction) as SqlConnection;
// Hard to debug failure- better off logging info to file
//using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt"))
//{
// outfile.Write(conn.ToString());
// outfile.Write(conn.State.ToString());
//}
}
catch (Exception ex)
{
//using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt"))
//{
// outfile.Write(" EEEEEEEEEEEEEEEEEEEE"+ ex.ToString());
//}
}
}
public override void PreExecute()
{
base.PreExecute();
cmd = new SqlCommand("SELECT [CustomerLocation fields] FROM customerlocationView where custid=#CustId", conn);
cmd.Parameters.Add("CustId", SqlDbType.UniqueIdentifier);
}
public override void PostExecute()
{
base.PostExecute();
/*
Add your code here for postprocessing or remove if not needed
You can set read/write variables here, for example:
Variables.MyIntVar = 100
*/
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
Collection<CustomerLocation> locations = new Collection<CustomerLocation>();
cmd.Parameters["CustId"].Value = Row.id;
// Any error always saw that reader reamians open on connection
if (reader != null)
{
if (!reader.IsClosed)
{
reader.Close();
}
}
reader = cmd.ExecuteReader();
if (reader != null)
{
while (reader.Read())
{
// Get Child Details
var customerLocation = new CustomerLocation(....,...,...,);
customerLocation.CustId = Row.id;
locations.Add(customerLocation);
}
}
var newCustomerCreated = new NewCustomerCreated(Row.id,,...,...,locations);
var serializedEvent = JsonConvert.SerializeObject(newCustomerCreated, Formatting.Indented,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
Row.SerializedEvent = serializedEvent;
Row.EventId = newCustomerCreated.EventId;
...
...
...
....
..
.
Row.Version = 1;
// using (StreamWriter outfile =
// new StreamWriter(#"f:\Migration.txt", true))
// {
// if (reader != null)
// {
// outfile.WriteLine(reader.HasRows);
//outfile.WriteLine(serializedEvent);
// }
// else
// {
// outfile.Write("reader is Null");
// }
//}
reader.Close();
}
public override void ReleaseConnections()
{
base.ReleaseConnections();
connectionManager.ReleaseConnection(conn);
}
}
One thing to note is that a different approach to create connection is to
get the connection string from connectionManager and use it to create OLEDB connection.

Java Swing refresh JPanel

I have a Applet class (extends JApplet). Inside the class I am instantiating a JPanel and initializing a JButton whit setEnabled(true). After the user clicks this button in the Panel and does some processing, I call a method inside of the JPanel to update the panel. I then do setEnabled(false) the button clicked on the JPanel.
However, the JPanel is not "refreshing" correctly after I call add(ScrollPane) on main panel. After the processing and setting the JButton to not enabled (and I confirmed that the right data is there etc), the JPanel still is in its initialized form.
In other words, what do I need to do so that calling add(JScrollPane) on a JPanel within a applet actually refreshes the Panel?
Basically i'm wondering: if you update the panel inside a swing component which is nested inside of a JApplet, should the update be visible? What needs to be done to refresh if not?
THIS IS THE CODE:
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (STAMPA_COMMAND.equals(command)) {
stampa.setEnabled(false);
JPanel areaPrint = new JPanel();
JLabel lab = new JLabel("Wait Printing...");
areaPrint.setBackground(Color.magenta);
areaPrint.add(lab);
scrollArea.getViewport().add(areaPrint); // THIS IS THE PROBLEM...THE CHANGE ARE NOT REFRESHED
try {
PrintPdf printPDFFile;
ArrayList assegniDaStampare = new ArrayList();
for (int i = 0; i < assegni.size(); i++) {
DatiAssegno datiAss = (DatiAssegno) assegni.get(i);
if (datiAss != null && datiAss.getStatoAssegno().equals(STATUS_OK)) {
printPDFFile = new PrintPdf("Stampa Assegni", datiAss);
printPDFFile.print();
String servletLocation = "http://localhost/Servlet";
// connect to the servlet
URL studentDBservlet = new URL(servletLocation);
URLConnection servletConnection = studentDBservlet.openConnection();
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
OutputStream outstream = servletConnection.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstream);
oos.writeObject(datiAss.idAssegno);
oos.flush();
oos.close();
ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
try {
String statusSave = (String) inputFromServlet.readObject();
} catch (ClassNotFoundException e4) {
e4.printStackTrace();
}
}
}
JPanel areaPrint2 = new JPanel();
JLabel lab2 = new JLabel("Print Complete");
areaPrint2.setBackground(Color.green);
areaPrint2.add(lab2);
scrollArea.getViewport().add(areaPrint2);
} catch (FileNotFoundException e1) {
//do something
} catch (IOException e2) {
//do something
} catch (PrinterException e3) {
//do something
}
}
if (EXIT_COMMAND.equals(command)) {
JSObject win = JSObject.getWindow(appletParent);
appletParent.stop();
appletParent.destroy();
win.eval("self.close()");
}
}
First off, you shouldn't be opening a connection within the action. Use a SwingWorker or some other executor to do this.
Secondly, try calling revalidate() on the panel after adding the scrollpane. These two fixes should solve the problem.