Can't load classes from dir. with jars while can do loading classes when jars unzipped/unpacked - classloader

community! Would be great if u could help me w/ my issue.
I got a custom class loader which is gonna to be java.system.class.loader - it holds
urls where to find classes. Like this:
public class TestSystemClassLoader extends URLClassLoader {
public TestSystemClassLoader(ClassLoader parent) {
super(classpath(), parent);
}
private static URL[] classpath() {
try {
// I got junit-4.8.2.jar under this url.
URL url = new File("D:\\Work\\lib\\junit-4\\").toURI().toURL();
return new URL[] { url };
}
catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
}
Then I run the java(JDK6) with -Djava.system.class.loader=TestSystemClassLoader eg.TestMain,
where eg.TestMain' main:
public static void main(String[] args) throws Exception {
// here I got system CL which is what I want.
ClassLoader cl = Thread.currentThread().getContextClassLoader();
// here I got: "Exception in thread "main" java.lang.ClassNotFoundException: org.junit.runners.JUnit4"
Class<?> clazz = Class.forName("org.junit.runners.JUnit4", true, cl);
}
The thing which makes me mad is that if I unpack/unzip/unjar the junit-4.8.2.jar - then
eg.TestMain would work!
The question is - how to tell java(JDK6) that I want whole directory to be in classpath,
i.e. any file residing in the directory.
Thanks in advance!

Find all the jars and add them:
private static URL[] classpath() {
try {
File file = new File("D:\\Work\\lib\\junit-4\\");
List<URL> urls = new ArrayList<URL>();
for (File f : file.listFiles()) {
if (f.isFile() && f.getName().endsWith(".jar")) {
urls.add(f.toURI().toURL());
}
}
return urls.toArray(new URL[0]);
}
catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}

Related

AddSingleton won't accept AddSerilog

I'm facing an issue where I'm trying to write a more smart console app with logging and configuration available.
This is what I have so far:
namespace Client
{
public class Program
{
public static IConfigurationRoot Configuration;
private static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.CreateLogger();
try
{
MainAsync(args).ConfigureAwait(false);
return 0;
}
catch
{
return 1;
}
}
private static async Task MainAsync(string[] args)
{
// Create service collection
Log.Information("Creating service collection");
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// Create service provider
Log.Information("Building service provider");
IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
try
{
Log.Information("Starting service");
await serviceProvider.GetService<App>().Run();
Log.Information("Ending service");
}
catch (Exception ex)
{
Log.Fatal(ex, "Error running service");
throw;
}
finally
{
Log.CloseAndFlush();
}
}
private static void ConfigureServices(IServiceCollection services)
{
// Add logging
services.AddSingleton(
LoggerFactory.Create(
builder => { builder.AddSerilog(dispose: true); }));
services.AddLogging();
// Build configuration
Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
.AddJsonFile("appSettings.json", false)
.Build();
// Add access to generic IConfigurationRoot
services.AddSingleton(Configuration);
// Add app
services.AddTransient<App>();
}
}
}
I'm facing an issue in ConfigureServices method on line builder.AddSerilog for the life of me, I cannot figure out why it is not able to resolve AddSerilog
I was missing a package: Serilog.Extensions.Logging
For some reason, VS or even Resharper was not able to suggest this.

Change Activity into Fragment

I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();

Playframework 1.2.7 interceptors

There is a problem with PlayF 1.2.7 interceptors.
I have a controller AuthCtl with #Before annotation.
And another controller class AlarmCtl which uses #With(AuthCtl.class).
public class AuthCtl extends Controller {
public static final String KMK_AUTH_TOKEN = "KMK_AUTH_TOKEN";
public static final String KMK_USER_ID = "KMK_USER_ID";
#Before
static void checkAuthorization() throws KomekException {
if (request.cookies.containsKey(AuthCtl.KMK_AUTH_TOKEN) &&
request.cookies.containsKey(AuthCtl.KMK_USER_ID)) {
//Something
} else {
throw new UnauthorizedException();
}
}
#Catch
static void handleExceptions(Throwable t) {
response.status = ((KomekException)t).getErrorCode();
response.accessControl("*");
response.contentType = "application/json";
renderText(t.toString());
}
}
#With(AuthCtl.class)
public class AlarmCtl extends Controller {
//Something
}
So when I'm throwing exception in the checkAuthorization method my handleExceptions method doesn't intercept it. What's the problem?
You need to specify what type of exception(s) you want to catch.
So in your case it would need to be written like this:
#Catch(KomekException.class)
static void handleExceptions(Throwable t) {
response.status = ((KomekException)t).getErrorCode();
response.accessControl("*");
response.contentType = "application/json";
renderText(t.toString());
}
Or, for a general (kind of dirty) catch all, use the root Exception class:
#Catch(Exception.class)
static void handleExceptions(Throwable t) {
response.status = ((KomekException)t).getErrorCode();
response.accessControl("*");
response.contentType = "application/json";
renderText(t.toString());
}

uploading file from backberry to web service = JVM error 104 Uncaught NullPointerException?

I am developing a small blackberry project.
Here are the step that it is supposed to be:
User clicks Speak! button. The application record speech voice. [No Problem]
When user finishes speaking, click Stop! button. Once the stop button is clicked, the speech voice will be saved on BB as an AMR file. Then, the file will be sent to web service via ksoap2. Web service will return response as a string of file name. The problem is web service return nothing and there is an error occur: JVM error 104: Uncaught NullPointerException I wonder if I placed the code on the right place, or I did something wrong with ksoap2??
here is the code for web service
namespace VoiceServer
{
/// <summary>
/// Converting AMR to WAV
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public string UploadFile(String receivedByte, String location, String fileName)
{
String filepath = fileName;
/*don't worry about receivedByte and location, I will work on them after the problem is solved :) */
return "Success"+filepath;
}
private void InitializeComponent()
{
}
}
}
Below is the code running on Eclipse, I'm not sure if I placed the code for sending file to web service on the right place.
public class MyAudio extends MainScreen {
private ButtonField _startRecordingButton;
private ButtonField _stopRecordingButton;
private HorizontalFieldManager _fieldManagerButtons;
private VoiceNotesRecorderThread _voiceRecorder;
private LabelField _myAudioTextField;
private DateField hourMin;
private long _initTime;
public MyAudio() {
_startRecordingButton = new ButtonField("Speak!", ButtonField.CONSUME_CLICK);
_stopRecordingButton = new ButtonField("Stop!", ButtonField.CONSUME_CLICK);
_fieldManagerButtons = new HorizontalFieldManager();
_voiceRecorder = new VoiceNotesRecorderThread(500000,"file:///store/home/user/voicefile.amr",this);
_voiceRecorder.start();
myButtonFieldChangeListener buttonFieldChangeListener = new myButtonFieldChangeListener();
_startRecordingButton.setChangeListener(buttonFieldChangeListener);
_stopRecordingButton.setChangeListener(buttonFieldChangeListener);
_fieldManagerButtons.add(_startRecordingButton);
_fieldManagerButtons.add(_stopRecordingButton);
_myAudioTextField = new LabelField(" Welcome to VoiceSMS!!!" );
add(_fieldManagerButtons);
add(_myAudioTextField);
SimpleDateFormat sdF = new SimpleDateFormat("ss");
hourMin = new DateField("", 0, sdF);
hourMin.setEditable(false);
hourMin.select(false);
_initTime = System.currentTimeMillis();
add(hourMin);
}
public void setAudioTextField(String text) {
_myAudioTextField.setText(text);
}
public void startTime() {
_initTime = System.currentTimeMillis();
hourMin.setDate(0);
}
public void updateTime() {
hourMin.setDate((System.currentTimeMillis()-_initTime));
}
class myButtonFieldChangeListener implements FieldChangeListener{
public void fieldChanged(Field field, int context) {
if(field == _startRecordingButton) {
try {
_voiceRecorder.startRecording();
} catch (IOException e) {
e.printStackTrace();
}
}else if(field == _stopRecordingButton) {
_voiceRecorder.stopRecording();
//----------Send AMR to Web Service-------------//
Object response = null;
String URL = "http://http://localhost:portnumber/Service1.asmx";
String method = "UploadFile";
String NameSpace = "http://tempuri.org/";
FileConnection fc = null;
byte [] ary = null;
try
{
fc = (FileConnection)Connector.open("file:///store/home/user/voicefile.amr",Connector.READ_WRITE);
int size = (int) fc.fileSize();
//String a = Integer.toString(size);
//Dialog.alert(a);
ary = new byte[size];
fc.openDataInputStream().read(ary);
fc.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
SoapObject client = new SoapObject(NameSpace,method);
client.addProperty("receivedByte",new SoapPrimitive(SoapEnvelope.ENC,"base64",Base64.encode(ary)));
client.addProperty("location","Test/");
client.addProperty("fileName","file:///store/home/user/voicefile.amr");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = client;
HttpTransport http = new HttpTransport(URL);
try
{
http.call(method,envelope);
}
catch(InterruptedIOException io)
{
io.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
catch (XmlPullParserException e)
{
System.err.println(e);
}
catch(OutOfMemoryError e)
{
System.out.println(e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
response = envelope.getResponse();
Dialog.alert(response.toString());
}
catch (SoapFault e)
{
System.err.println(e);
System.out.println("Soap Fault");
}
catch(NullPointerException ne)
{
System.err.println(ne);
}
Dialog.alert(response.toString());
//Dialog.alert("Send Success");
//----------End of Upload-to-Web-Service--------//
}
}
}
}
I don't know if the file is not sent to web service, or web service has got the file and produce no response??? I am a real newbie for BB programming. Please let me know if I did anything wrong.
Thanks in advance!!!
There is a typo in your URL variable value.
"http://" typed twice
String URL = "http://http://localhost:portnumber/Service1.asmx";
Hooray!!! Problem Solved!
just changed URL as Rafael suggested and added [WebMethod] above "public string UploadFile" in the web service code

Loading .eml files into javax.mail.Messages

I'm trying to unit test a method which processes javax.mail.Message instances.
I am writing a converter to change emails which arrive in different formats and are then converted into a consistent internal format (MyMessage). This conversion will usually depend on the from-address or reply-address of the email, and the parts of the email, the subject, and the from- and reply-addresses will be required for creating the new MyMessage.
I have a collection of raw emails which are saved locally as .eml files, and I'd like to make a unit test which loads the .eml files from the classpath and converts them to javax.mail.Message instances. Is this possible, and if so, how would it be done?
After a few tests, I finally successfully loaded a message using the MimeMessage(Session, InputStream) public constructor (as opposed to the Folder-based protected one cited in the other response).
import java.io.FileInputStream;
import java.io.InputStream;
import javax.mail.internet.MimeMessage;
public class LoadEML {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(args[0]);
MimeMessage mime = new MimeMessage(null, is);
System.out.println("Subject: " + mime.getSubject());
}
}
My problem came from using Mockito to mock the javax.mail.Folder required by javax.mail.internet.MimeMessage's constructor MimeMessage(Folder, InputStream, int). This calls the constructor for javax.mail.Message Message(Folder, int) which then accesses folder.store.session. This resulted in a NullPointerException being thrown by the constructor for MimeMessage.
Solution:
class ClasspathMimeMessage extends MimeMessage {
private ClasspathMimeMessage(Folder folder, InputStream is, int msgnum) throws MessagingException {
super(folder, is, 0);
}
public static MimeMessage create(String resourceName) {
Class<PopEmailMmsReceiverTest> loaderClass = PopEmailMmsReceiverTest.class;
InputStream is = loaderClass.getResourceAsStream(resourceName);
Folder inbox = new MyFolder();
try {
return new ClasspathMimeMessage(inbox, is, 0);
} catch (MessagingException ex) {
throw new RuntimeException("Unable to load email from classpath at " + loaderClass.getResource(resourceName).toString());
}
}
}
class MyFolder extends Folder {
MyFolder() {
super(createMockStore());
}
private static Store createMockStore() {
return mock(Store.class);
}
public void appendMessages(Message[] msgs) throws MessagingException {
}
public void close(boolean expunge) throws MessagingException {
}
public boolean create(int type) throws MessagingException {
return false;
}
public boolean delete(boolean recurse) throws MessagingException {
return false;
}
public boolean exists() throws MessagingException {
return false;
}
public Message[] expunge() throws MessagingException {
return null;
}
public Folder getFolder(String name) throws MessagingException {
return null;
}
public String getFullName() {
return null;
}
public Message getMessage(int msgnum) throws MessagingException {
return null;
}
public int getMessageCount() throws MessagingException {
return 0;
}
public String getName() {
return null;
}
public Folder getParent() throws MessagingException {
return null;
}
public Flags getPermanentFlags() {
return null;
}
public char getSeparator() throws MessagingException {
return 0;
}
public int getType() throws MessagingException {
return 0;
}
public boolean hasNewMessages() throws MessagingException {
return false;
}
public boolean isOpen() {
return false;
}
public Folder[] list(String pattern) throws MessagingException {
return null;
}
public void open(int mode) throws MessagingException {
}
public boolean renameTo(Folder f) throws MessagingException {
return false;
}
}
This looks very ugly to me, so if anyone has a better suggestion, I'd be delighted to hear it.