platformRequest not working in J2ME - java-me

I'm triyng to play .mp3 file using platformRequest(). I verified the file path and it is correct. And I'm using Nokia 210 for testing. Please help me to fix this issue.

try {
platformRequest("file:///C:/song.mp3");
} catch (ConnectionNotFoundException ex) {
ex.printStackTrace();
}
I know you have already verified whether there is file or not. though check my below code once and post comment with results.
Added -
public boolean isFileExisted(String path) {
boolean isExisted = false;
FileConnection filecon = null;
try {
filecon = (FileConnection) Connector.open(path, Connector.READ);
isExisted = filecon.exists();
} catch (java.lang.SecurityException e) {
} catch (Exception e) {
} finally {
try {
if (filecon != null) {
filecon.close();
}
catch (Exception e) {
}
}
return isExisted;
}
}
public void playFileFromSDCard() {
String path1 = "file:///C:/song.mp3";
String path2 = "file:///E:/song.mp3";
if (isFileExisted(path1)) {
try {
System.out.println("path1 exist -> calling platform request " + path1);
platformRequest(path1);
} catch (ConnectionNotFoundException ex) {
ex.printStackTrace();
}
}
else if (isFileExisted(path2)) {
try {
System.out.println("path2 exist -> calling platform request " + path2);
platformRequest(path2);
} catch (ConnectionNotFoundException ex) {
ex.printStackTrace();
}
}
else {
System.out.println("both path doesnt exists");
}
}

After so many searches i found some reasons for the issue. This may help for people in future who is having the same problem. refer the following links.
Open file with MIDlet.platformRequest() ,
How to play media file in System media player in j2me????

Related

Why is my Java Discord Bot not connecting to my sqlite dadabase?

I programmed a discord bot with java for some minecraft project I am going to make.
I bought a KVM V-Server, installed all I needed and uploaded my bot's files including my prepared sqlite database.
But the problem is: When I execute my start.sh, there is an error code.
root#5030 /home/Bot $ ./start.sh
java.sql.SQLException: No suitable driver found for jdbc:sqlite:Datenbank.db
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at de.nameddaniel.bot.main.LiteSQL.connect(LiteSQL.java:35)
at de.nameddaniel.bot.main.Main.<init>(Main.java:50)
at de.nameddaniel.bot.main.Main.main(Main.java:42)
Exception in thread "main" java.lang.NullPointerException
at de.nameddaniel.bot.main.LiteSQL.onUpdate(LiteSQL.java:64)
at de.nameddaniel.bot.main.SQLManager.onCreate(SQLManager.java:9)
at de.nameddaniel.bot.main.Main.<init>(Main.java:51)
at de.nameddaniel.bot.main.Main.main(Main.java:42)
I searched on google for help. There, in some forums, people said, that you should insert Class.forName(); before connecting to the database.
I did so but it did not help:
public static void connect() {
c = null;
try {
File file = new File("Datenbank.db");
if(!file.exists()) {
file.createNewFile();
}
String url = "jdbc:sqlite:" + file.getPath();
try {
Class.forName(LiteSQL.class.getName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c = DriverManager.getConnection(url);
System.out.println("Verbindung zu Datenbank hergestellt.");
s = c.createStatement();
}
catch(SQLException | IOException e) {
e.printStackTrace();
}
}
I am executing connect() in my Main class:
public Main() {
instance = this;
LiteSQL.connect();
SQLManager.onCreate();
try {
jda = JDABuilder.createDefault(BotToken.token).build();
} catch (LoginException e) {
e.printStackTrace();
}
jda.getPresence().setActivity(Activity.watching("dir zu."));
jda.getPresence().setStatus(OnlineStatus.ONLINE);
// audioPlayerManager = new DefaultAudioPlayerManager();
// playermanager = new PlayerManager();
cmdMan = new CommandManager();
jda.addEventListener(new CommandListener());
jda.addEventListener(new VoiceListener());
jda.addEventListener(new ReactionListener());
jda.addEventListener(new RoleListener());
jda.addEventListener(new JoinListener());
jda.addEventListener(new NicknameListener());
jda.addEventListener(new AvatarChangeListener());
jda.addEventListener(new BanListener());
System.out.println("Bot wurde hochgefahren");
// AudioSourceManagers.registerRemoteSources(audioPlayerManager);
// audioPlayerManager.getConfiguration().setFilterHotSwapEnabled(true);
shutdown();
runLoop();
}
So, how do I fix that?
If there is any information missing, please tell me. As well if you need translations.
Hope you can help me,
Daniel :D

Testing for file upload in Spring MVC

Project setup:
<java.version>1.8</java.version>
<spring.version>4.3.9.RELEASE</spring.version>
<spring.boot.version>1.4.3.RELEASE</spring.boot.version>
We have a REST controller that has a method to upload file like this:
#PostMapping("/spreadsheet/upload")
public ResponseEntity<?> uploadSpreadsheet(#RequestBody MultipartFile file) {
if (null == file || file.isEmpty()) {
return new ResponseEntity<>("please select a file!", HttpStatus.NO_CONTENT);
} else if (blueCostService.isDuplicateSpreadsheetUploaded(file.getOriginalFilename())) {
return new ResponseEntity<>("Duplicate Spreadsheet. Please select a different file to upload",
HttpStatus.CONFLICT);
} else {
try {
saveUploadedFiles(Arrays.asList(file));
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity("Successfully uploaded - " + file.getOriginalFilename(), new HttpHeaders(),
HttpStatus.OK);
}
}
UPDATE:
I've tried this approach from an old example I found, but it doesn't compile cleanly, the MockMvcRequestBuilders.multipart method is not defined....
#Test
public void testUploadSpreadsheet_Empty() throws Exception {
String fileName = "EmptySpreadsheet.xls";
String content = "";
MockMultipartFile mockMultipartFile = new MockMultipartFile(
"emptyFile",
fileName,
"text/plain",
content.getBytes());
System.out.println("emptyFile content is '" + mockMultipartFile.toString() + "'.");
mockMvc.perform(MockMvcRequestBuilders.multipart("/bluecost/spreadsheet/upload")
.file("file", mockMultipartFile.getBytes())
.characterEncoding("UTF-8"))
.andExpect(status().isOk());
}
I believe MockMvcRequestBuilders.multipart() is only available since Spring 5. What you want is MockMvcRequestBuilders.fileUpload() that is available in Spring 4.

C++/CLI code doesn't enter .then part of the create_task function

This is the code that I have:
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
XTRACE(L"=========================================will start onNavigated ");
auto mediaCapture = ref new Windows::Media::Capture::MediaCapture();
m_mediaCaptureMgr = mediaCapture;
IAsyncAction ^asyncAction = m_mediaCaptureMgr->InitializeAsync();
try
{
create_task(asyncAction).then([this](task<void> initTask)
{
XTRACE(L"=========================================will start onNavigated 2");
try
{
initTask.get();
auto mediaCapture = m_mediaCaptureMgr.Get();
if (mediaCapture->MediaCaptureSettings->VideoDeviceId != nullptr && mediaCapture->MediaCaptureSettings->AudioDeviceId != nullptr)
{
String ^fileName;
fileName = VIDEO_FILE_NAME;
XTRACE(L"=================================Device initialized successful\n");
create_task(KnownFolders::VideosLibrary->CreateFileAsync(fileName, Windows::Storage::CreationCollisionOption::GenerateUniqueName))
.then([this](task<StorageFile^> fileTask)
{
XTRACE(L"=================================Create record file successful\n");
m_recordStorageFile = fileTask.get();
MediaEncodingProfile^ recordProfile = nullptr;
recordProfile = MediaEncodingProfile::CreateMp4(Windows::Media::MediaProperties::VideoEncodingQuality::Auto);
stream = ref new InMemoryRandomAccessStream();
return m_mediaCaptureMgr->StartRecordToStreamAsync(recordProfile, stream);
}).then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Start Record successful\n");
}
catch (Exception ^e)
{
XTRACE(L"======ERRROR is : %d", e);
}
});
}
else
{
XTRACE(L"=================================No VideoDevice/AudioDevice Found\n");
}
XTRACE(L"=================================WILL EXIT \n");
}
catch (Exception ^ e)
{
XTRACE(L"============================================ERROR IS: %d\n", e);
}
}
);
}
catch (Exception ^ e)
{
XTRACE(L"============================================before create task ERROR IS: %d\n", e);
}
XTRACE(L"=================================SLEEP 20000====================================\n");
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
XTRACE(L"=================================TIME ENDED====================================\n");
// stop device detection
try
{
XTRACE(L"=================================Stopping Record\n");
create_task(m_mediaCaptureMgr->StopRecordAsync())
.then([this](task<void> recordTask)
{
try
{
recordTask.get();
XTRACE(L"=================================Stop record successful: %d\n", stream->Size);
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR while stoping 2: %d\n", e);
}
});
}
catch (Exception ^e)
{
XTRACE(L"=================================ERROR try catch 3 stoping: %d\n", e);
}
CloseHandle(ghEvent);
// destruct the device manager
XTRACE(L"=====================================================================END\n");
}
In the log I see:
=========================================will start onNavigated
And then directly:
=====================================================================
=================================SLEEP 20000====================================
What is strange is that I had this code in a unittest and it worked, I created a new windows phone project with a UI and it doesn't work
Apparently it was because of the ThreadSleep:
std::chrono::milliseconds dura(20000);
std::this_thread::sleep_for(dura);
In the library project where I was working I was using a different sleep, provided by the library, and that would work. So this was the line that would cause the application to block itself.
I worked my way around this by including 2 buttons in the app, for the start and stop recording.

Getting code from all (closed) files in solution in Visual Studio SDK

I'm trying to get and edit the code of all the html-files in the project
i found a way to loop over all ProjectItems
IEnumerator Projects = _applicationObject.Solution.Projects.GetEnumerator();
while (Projects.MoveNext())
{
IEnumerator Items = ((Project)Projects.Current).ProjectItems.GetEnumerator();
Queue<ProjectItem> ProjectItems = new Queue<ProjectItem>();
while (Items.MoveNext())
{
ProjectItem SubItem = (ProjectItem)Items.Current;
try
{
if (SubItem.Document != null) DocumentIndex.Add(SubItem.Document);
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
ProjectItems.Enqueue(SubItem);
}
//follow the tree down
while (ProjectItems.Count != 0)
{
ProjectItem ProjectItem = ProjectItems.Dequeue();
if (ProjectItem.ProjectItems != null)
{
foreach (ProjectItem SubItem in ProjectItem.ProjectItems)
{
ProjectItems.Enqueue(SubItem);
try
{
try
{
SubItem.Open(SubItem.Kind);
DocumentIndex.Add(SubItem.Document);
}catch(Exception Ex){
Console.WriteLine(Ex.Message);
}
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
}
}
}
}
now i can't get to the code of the files that are not open in an editor window.
how do i get and edit the code of "not opened" projectItems?
how do i detect if a file is a code file? (eg: .cs, .html, .htm, .asp, ....
You must open the ProjectItem that you want to read or edit
DTE dte = (DTE)Package.GetGlobalService(typeof(DTE));
var project = dte.Solution.Projects.Item(1);
var projectItems = project.ProjectItems;
var anyItem = projectItems.Item(0);
Window anyItemWindow = anyItem.open()
var selection = anyItem.Document.Selection as TextSelection;
selection.SelectAll();
Console.WriteLine(selection.Text) // All code
anyItem.Document.Close() //Close Document
if you don't open the ProjectItem anyItem.Doument is null.
Note: selection.Insert("") can be used to change the code

handling file not found exception?

I made this code to empty some files that I regularly delete, such as temp files in Windows. Several friends may wish to use the same application and I am working on the best way to handle the file not found exception.
How can this best be handled for use by multiple users?
public void Deletefiles()
{
try
{
string[] DirectoryList = Directory.GetDirectories("C:\\Users\\user\\Desktop\\1");
string[] FileList = Directory.GetFiles("C:\\Users\\user\\Desktop\\1");
foreach (string x in DirectoryList)
{
Directory.Delete(x, true);
FoldersCounter++;
}
foreach (string y in FileList)
{
File.Delete(y);
FilesCounter++;
}
MessageBox.Show("Done...\nFiles deleted - " + FileList.Length + "\nDirectories deleted - " + DirectoryList.Length + "\n" + FilesCounter + "\n", "message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception z)
{
if (z.Message.Contains("NotFound"))
{
MessageBox.Show("File Not Found");
}
else
{
throw (z);
}
//throw new FileNotFoundException();
}
}
Modifying you code as little as possible, you could simply wrap your Delete calls in a try/catch:
foreach (string x in DirectoryList)
{
try {
Directory.Delete(x, true);
}
catch (DirectoryNotFoundException e)
{
// do something, or not...
}
FoldersCounter++;
}
foreach (string y in FileList)
{
try
{
File.Delete(y);
}
catch (FileNotFoundException e)
{
// do something, or not...
}
FilesCounter++;
}
Remove the top level try/catch and just let the foreach statements cycle through -- trying and catching any exceptions as they come.
You don't necessarily need to alert the user that the file wasn't found. It is there it is going to be deleted, so the fact that it isn't there doesn't really effect the outcome of the program.
This isn't the most resource friendly method, but it is a simple enough application to not cause an issue.

Resources