What is log4J's equivalent of java.util.logging.Handler - log4j

I like to intercept some (the most important) log messages and display them inside the GUI or check if any errors where logged. Normally I use java.util.logging and here the java.util.logging.Handler with and java.util.logging.Formatter.
However the current project uses Log4J (2.x) and there every feature has different names and seems to be at least four times as complex.
Can anybody give me some hints on how to archive something like this with Log4J:
/**
* <p>
* logs error so they can be returned to the server (and tested in unit tests)
* </p>
*
* #author "Martin Krischik" <martin.krischik#noser.com>
* #version 1.0 $Revision: 2229 $
* #see java.util.logging.Handler
* #since 1.0
*/
#SuppressWarnings ("synthetic-access")
protected final class LogHandler
extends
java.util.logging.Handler
{
/**
* <p>
* A very simple formatter which displays only what is relevant to end users. Developer
* should look at the log file
* </p>
*
* #author "Martin Krischik" <martin.krischik#noser.com>
* #version 1.0 $Revision: 2229 $
* #see java.util.logging.Formatter
* #since 1.0
*/
private class LogFormatter
extends
java.util.logging.Formatter
{
/**
* <p>
* line separator
* </p>
*/
private final String lineSeparator = System.getProperty ("line.separator");
/**
* <p>
* Format the given LogRecord.
* </p>
*
* #param record
* the log record to be formatted.
* #return a formatted log record
* #see java.util.logging.Formatter#format(java.util.logging.LogRecord)
*/
#Override
public synchronized String format (final java.util.logging.LogRecord record)
{
final StringBuilder retval = new StringBuilder (4096);
final String message = this.formatMessage (record);
final java.util.logging.Level level = record.getLevel ();
retval.append (level.getLocalizedName ());
retval.append (": ");
retval.append (message);
retval.append (this.lineSeparator);
return retval.toString ();
} // format
} // LogFormatter
/**
* <p>
* A very simple formatter which displays only what is relevant to end users. Developer
* should look at the log file
* </p>
*/
private final DBUpdate.LogHandler.LogFormatter formatter =
new DBUpdate.LogHandler.LogFormatter ();
/**
* #throws SecurityException
* some severity error
* #see java.util.logging.Handler#close()
*/
#Override
public void close ()
throws SecurityException
{
return;
} // close
/**
* #see java.util.logging.Handler#flush()
*/
#Override
public void flush ()
{
return;
} // flush
/**
* #param record
* record to log.
* #see java.util.logging.Handler#publish(java.util.logging.LogRecord)
*/
#Override
public void publish (final java.util.logging.LogRecord record)
{
if (record.getLevel ().intValue () >= this.getLevel ().intValue ())
{
REST_Responce.this.errorMessages.add (this.formatter.format (record));
} // if
return;
} // publish
} // LogHandler

You could try to subclass AbstractAppender.
Appender maps to Handler
Layout maps to Formatter
ErrorHandler maps to ErrorManager

Related

StreamingMessageSource keeps firing when a filter is applied

I am trying to poll an FTP directory for a certain kind of file, the polling of a directory works, but whenever I try to apply a filter to filter the files by extension, the messagesource keeps spamming messages about the file with no regard to the polling delay. Without the filters everything works fine, once I enable them my application authenticates with the FTP, downloads the file and sends the message nonstop over and over again. I have the following beans:
/**
* Factory that creates the remote connection
*
* #return DefaultSftpSessionFactory
*/
#Bean
public DefaultSftpSessionFactory sftpSessionFactory(#Value("${ftp.host}") String ftpHost,
#Value("${ftp.port}") int ftpPort,
#Value("${ftp.user}") String ftpUser,
#Value("${ftp.pass}") String ftpPass) {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setAllowUnknownKeys(true);
factory.setHost(ftpHost);
factory.setPort(ftpPort);
factory.setUser(ftpUser);
factory.setPassword(ftpPass);
return factory;
}
/**
* Template to handle remote files
*
* #param sessionFactory SessionFactory bean
* #return SftpRemoteFileTemplate
*/
#Bean
public SftpRemoteFileTemplate fileTemplate(DefaultSftpSessionFactory sessionFactory) {
SftpRemoteFileTemplate template = new SftpRemoteFileTemplate(sessionFactory);
template.setAutoCreateDirectory(true);
template.setUseTemporaryFileName(false);
return template;
}
/**
* To listen to multiple directories, declare multiples of this bean with the same inbound channel
*
* #param fileTemplate FileTemplate bean
* #return MessageSource
*/
#Bean
#InboundChannelAdapter(channel = "deeplinkAutomated", poller = #Poller(fixedDelay = "6000", maxMessagesPerPoll = "-1"))
public MessageSource inboundChannelAdapter(SftpRemoteFileTemplate fileTemplate) {
SftpStreamingMessageSource source = new SftpStreamingMessageSource(fileTemplate);
source.setRemoteDirectory("/upload");
source.setFilter(new CompositeFileListFilter<>(
Arrays.asList(new AcceptOnceFileListFilter<>(), new SftpSimplePatternFileListFilter("*.trg"))
));
return source;
}
/**
* Listener that activates on new messages on the specified input channel
*
* #return MessageHandler
*/
#Bean
#ServiceActivator(inputChannel = "deeplinkAutomated")
public MessageHandler handler(JobLauncher jobLauncher, Job deeplinkBatch) {
return message -> {
Gson gson = new Gson();
SFTPFileInfo info = gson.fromJson((String) message.getHeaders().get("file_remoteFileInfo"), SFTPFileInfo.class);
System.out.println("File to download: " + info.getFilename().replace(".trg", ".xml"));
};
}
I think AcceptOnceFileListFilter is not suitable for SFTP files. The returned LsEntry doesn't match previously stored in the HashSet: just their hashes are different!
Consider to use a SftpPersistentAcceptOnceFileListFilter instead.
Also it would be better to configure a DefaultSftpSessionFactory for the isSharedSession:
/**
* #param isSharedSession true if the session is to be shared.
*/
public DefaultSftpSessionFactory(boolean isSharedSession) {
To avoid session recreation on each polling task.
you don't have a 6 seconds delay between calls because you have a maxMessagesPerPoll = "-1". That means poll remote files until they are there in remote dir. In your case with the AcceptOnceFileListFilter you always end up with the same file by the hash reason.

Read Azure Function Setting from Configuration

I am using Azure Functions with Attributes to define functionality.
public static class PostPublishTimerTrigger
{
[FunctionName("PostPublishTimerTrigger")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer,
TraceWriter log,
[Queue("post-published")] ICollector<string> postPublishedQueue)
{
// Additional code here
}
}
Is there a way to pull the Schedule 0 */5 * * * * for a configuration setting, be it with Configuration Manager or Environment Variables?
Thanks!
Yes, you can do
[TimerTrigger("%schedule%")]
and then add a setting called schedule with value 0 */5 * * * *

How to render twig templates into a service. Is it Best practice?

I have the following Symfony 3 controller:
public function register(Request $request)
{
$username=$request->get('username');
$password=$request->get('password');
$email=$request->get('email');
$captchaResponse=$request->get('g-recaptcha-response');
$session =$request->getSession();
$res1 = new Response();
$response_data=array('status'=>0);
if($session->get('captcha')===$captchaResponse)
{
$en = $this->container->get('user_model');
$data=$en->register($username,$password,$email);
$res1->headers->set('Content-Type','text/json');
if($data['status']===false)
{
$response_data['data']="An Internal error Happened";
error_log($data['data']);
}
else if($data['status']===-1)
{
$response_data['data']=$data['data'];
}
else
{
$response_data['status']=1;
$response_data['data']="Please check your mail to confirm your registration.";
/*Send Email*/
$message = \Swift_Message::newInstance()
->setSubject('Please confirm your registration')
->setFrom('symphotest#openmailbox.org')
->setTo($email)
->setBody($this->renderView('emails/confirm.html.twig',array('token'=>$data['data'])))
->addPart(
$this->renderView('emails/registration.txt.twig',array('token'=>$data['data'])),
'text/plain'
);
$this->get('mailer')->send($message);
}
}
else
{
$response_data['data']="You have not given a correct captcha";
}
$res1->setContent(json_encode($response_data));
$session->set('captcha',uniqid());//Generate gibberish in order not to reuse the very same captcha again
return $res1;
}
And I have made the following service:
namespace AppBundle\Models;
use Doctrine\ORM\EntityManager;
use AppBundle\Util\ModelStatus;
use AppBundle\Exceptions\InvalidArgumentException;
use \SwiftMessage;
class UserModel
{
/** #var EntityManager */
private $em;
/** #var \Swift_Mailer */
private $mailer;
/** #var \Twig_Environment */
private $twig;
/**
*
* #param EntityManager $em
* #param \Swift_Mailer $mailer
* #param \Twig_Environment $twig
*/
public function construct(EntityManager $em, \Swift_Mailer $mailer,\Twig_Environment $twig)
{
$this->em=$em;
$this->$mailer=$mailer;
}
/**
* Performs the actions needed for Registration
*
* #param unknown $username
* #param unknown $password
* #param unknown $email
* #param \Swift_Message $registrationMessage
*
* #return ModelStatus
*/
public function register($username,$password,$email)
{
$modelStatus=new ModelStatus();
try
{
/** #var \AppBundle\Entity\UserRepository */
$repository=$this->em->getRepository('AppBundle::Users');
$token=$repository->register($username,$password,$email);
$modelStatus->setData($token);
$modelStatus->setStatus(ModelStatus::STATUS_SUCCESS);
$this->mailer->send($registrationMessage);
$message = Swift_Message::newInstance()
->setSubject('Please confirm your registration')
->setFrom('symphotest#openmailbox.org')
->setTo($email)
->setBody($this->twig->//->renderView('emails/confirm.html.twig',array('token'=>$data['data'])))
->addPart(
$this->renderView('emails/registration.txt.twig',array('token'=>$data['data'])),
'text/plain'
);
$this->get('mailer')->send($message);
}
catch(InvalidArgumentException $arg)
{
$modelStatus->setStatus(ModelStatus::STATUS_FAILURE);
$modelStatus->setMessage($arg->getMessage());
}
catch (\Exception $e)
{
$modelStatus->setStatus(ModelStatus::STATUS_FAILURE);
$modelStatus->setMessage($e->getMessage());
}
return $modelStatus;
}
}
And I am refactoring the following section:
$message = \Swift_Message::newInstance()
->setSubject('Please confirm your registration')
->setFrom('symphotest#openmailbox.org')
->setTo($email)
->setBody($this->renderView('emails/confirm.html.twig',array('token'=>$data['data'])))
->addPart(
$this->renderView('emails/registration.txt.twig',array('token'=>$data['data'])),
'text/plain'
);
$this->get('mailer')->send($message);
Into the Model method register.
But As you can see I render some twig templates and I do know the best Option on how to do it. So far I thought the following options:
To render the templates as string and pass them to the the register method, create and send the email there.
Load the twig rendering service into the model and the render into the model. If not exists create one.
In the second bullet I may need to load the Twig rendering engine into a service. How can I do that?
In the end having the constructor like this:
public function __construct(EntityManager $em, \Swift_Mailer $mailer,\Twig_Environment $twig)
{
$this->em=$em;
$this->mailer=$mailer;
$this->twig=$twig;
}
And loading the service like this:
user_model:
class: AppBundle\Models\UserModel
arguments: ['#doctrine.orm.entity_manager','#mailer','#twig']
Seems that solved the problem.

Facebook integration with blackberry

I am new in Blackberry. I want to post information on wall in Facebook from my application. I read some documents. What are the steps to integrate with Facebook? Would anyone have a working example Java code for this? How to get api_key,secret_key,application_id?
Thanks
visit the below link. Here you can download the Facebook SDK for blackberry. also you can download the samples which demonstrates clearly about facebook integration into your native bb app.
Find Facebook SDK from GITGUB here
#krishna Check out the following code. This is basically used to post messages on wall.
/**
* Copyright (c) E.Y. Baskoro, Research In Motion Limited.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This License shall be included in all copies or substantial
* portions of the Software.
*
* The name(s) of the above copyright holders shall not be used
* in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*
*/
package samples.strawberry;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;
import net.sf.blackberry.facebook.FBUser;
import net.sf.blackberry.facebook.FacebookContext;
import net.sf.blackberry.facebook.User;
import net.sf.blackberry.facebook.ui.FacebookScreen;
final class PostWallScreen extends FacebookScreen {
// List of actions:
static final String ACTION_ENTER = "postWall";
static final String ACTION_SUCCESS = "posted";
static final String ACTION_ERROR = "error";
// List of labels:
private static final String LABEL_TITLE = "Post To Wall";
private static final String LABEL_USERS = "Post wall to";
private static final String LABEL_NAME = "Title:";
private static final String LABEL_LINK = "Link:";
private static final String LABEL_CAPTION = "Caption:";
private static final String LABEL_CONTENT = "Content:";
private static final String LABEL_POST = "Post";
private User[] users = null;
private ObjectChoiceField objectChoiceField;
private EditField titleEditField;
private EditField hrefEditField;
private EditField captionEditField;
private EditField descriptionEditField;
private ButtonField buttonField;
/**
* Default constructor.
*
*/
PostWallScreen(FacebookContext pfbc) {
super(pfbc);
setTitle(new LabelField(LABEL_TITLE, LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH));
objectChoiceField = new ObjectChoiceField();
objectChoiceField.setLabel(LABEL_USERS);
add(objectChoiceField);
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
titleEditField = new EditField(LABEL_NAME, "", 80, LabelField.USE_ALL_WIDTH);
add(titleEditField);
hrefEditField = new EditField(LABEL_LINK, "", 80, LabelField.USE_ALL_WIDTH);
add(hrefEditField);
captionEditField = new EditField(LABEL_CAPTION, "", 80, LabelField.USE_ALL_WIDTH);
add(captionEditField);
descriptionEditField = new EditField(LABEL_CONTENT, "", 255, LabelField.USE_ALL_WIDTH);
add(descriptionEditField);
buttonField = new ButtonField(LABEL_POST);
buttonField.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if (users == null) {
return;
}
try {
users[objectChoiceField.getSelectedIndex()].publishStream(descriptionEditField.getText(), hrefEditField.getText(), titleEditField.getText(), descriptionEditField.getText(), captionEditField.getText());
fireAction(ACTION_SUCCESS);
} catch (Exception e) {
fireAction(ACTION_ERROR, e.getMessage());
}
}
});
add(buttonField);
}
/**
* Load list of users comprising of friends and self.
*
*/
void loadList() {
try {
User[] friends = new FBUser("me", fbc.getAccessToken()).getFriends();
if (friends == null) {
users = new User[1];
} else {
users = new User[friends.length + 1];
}
users[0] = new FBUser("me", fbc.getAccessToken());
for (int i = 1; i < (friends.length + 1); i++) {
users[i] = friends[i - 1];
}
objectChoiceField.setChoices(users);
} catch (Exception e) {
fireAction(ACTION_ERROR, e.getMessage());
}
}
}

GWT cross-domain rpc

I need to call a GWT application service from javascript which is running on different domain.
How could this be done? How do I point from my applicaton to the javascript url?
Thank you.
The idea behind a cross domain request is the your java script creats a script tag which loads a generated java script from the forgein url. When loaded the generated java script is evaluated and calls a callback function you created.
The following code ist not testet and shows the idea:
public class CrossSiteDomainRequest {
/** Counter to create unique ids for callback function. */
private static int idCounter = 0;
/** Url to load the javascript from. */
private String url;
/**
* Creates a new loader with the given <code>url</code>.
* #param url to load the java script from {#link #url}.
*/
public CrossSiteDomainRequest(String url) {
this.url = url;
}
/**
* Uses the {#link #url} to load the data from another url.
*/
public void load() {
String callbackId = "callbackId" + idCounter++;
String prepend = url.indexOf("?") != -1 ? "&" : "?";
String u = url + prepend + "callback=" + callbackId// Add more Parameters
createCallback(this, transId);
Element script = DOM.createElement("script");
script.setAttribute("src", u);
script.setAttribute("id", callbackId);
script.setAttribute("type", "text/javascript");
script.setAttribute("language", "JavaScript");
getHead().appendChild(script);
}
/**
* Destroys the callback with the given <code>id</code>.
* #param id of the script tag and native javascript callback function which should be destroyed.
*/
protected void destroyCallbackmethod(String id) {
getHead().removeChild(DOM.getElementById(id));
removeCallback(id);
}
/**
* This method is invoked by the callback to handel the loaded data.
* #param callbackId DOM-Id of the callback whick invoked this method.
* #param jso Object that encapsultes the loaded data.
*/
#SuppressWarnings("unchecked")
protected void onReceivedData(String callbackId, JavaScriptObject jso) {
try {
// Read data
} catch (Exception e) {
// Handle Error
}
destroyCallbackmethod(callbackId);
}
/**
* Creates a native javascript callback.
* #param cscr to invoke the {#link #onReceivedData(String, com.google.gwt.core.client.JavaScriptObject)} on when the data has been loaded.
* #param callbackId DOM-Id to create the callback back.
*/
private native void createCallback(CrossSiteDomainRequest cscr, String callbackId) /*-{
$wnd[callbackId] = function(j) {
proxy.#com.test.package.client.CrossSiteDomainRequest::onReceivedData(Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(callbackId, j);
};
}-*/;
private native void removeCallback(String callbackId) /*-{
$wnd[callbackId] = null;
}-*/;
public static native Element getHead() /*-{
return $doc.getElementsByTagName('head')[0];
}-*/;
}
If you create a CrossSiteDomainRequest Object for the URL http://www.test.com/loadXDR.js
you have to evaluate the callbackId parameter and generate a java script which may looks like this:
callbackId({"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}});
The callbackId has to be replaced accordingly.

Resources