Java

99K

Solutions

33K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi,
I have the following code :
 String imageUrl1 = "https://zeta-s3-bucket-temporary-staging.s3.amazonaws.com/fe6e3c46-3098-4135-be73-eae0b9fff837";
    BufferedImage mergedImage = ImageUtils.mergeImages(imageUrl1, imageUrl1);
    String type = Doc.DocType.KYC_FORM.toString();
    DocUploadEntry docUploadEntry = new DocUploadEntry().applicationId(1564).ifi(140793L).type(Doc.DocType.KYC_FORM).fileName("8178717991_POA.jpg");
    SftpCommandService sftpCommandService = new SftpCommandService(20);
    String filePath = getFilePath(docUploadEntry);
    ChannelSftp channelSftp = getChannel().toCompletableFuture().join();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    String data = null;
    try {
      ImageIO.write(mergedImage, "jpg", byteArrayOutputStream);
      byteArrayOutputStream.flush();
      data = new String(byteArrayOutputStream.toByteArray());
      byteArrayOutputStream.close();

    } catch (IOException e) {

    }

    sftpCommandService.uploadFile(data, filePath, channelSftp).toCompletableFuture().join();

Open in new window


Here I am using ByteArrayOutputStream to convert and Image object to byte array and then to string.
And then SFTP that string data. Although the data is geting stfp'd and i do see a file there.
But when i download the file locally and open it - it gives an error corrupted file.

It looks like probably ByteArrayOutPutStream is not a correct way to convert an Image object.
How do I convert it ?
Thanks
0
Become a Microsoft Certified Solutions Expert
LVL 13
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

HI,
I am using a spring application in that...
I have two image urls - https:// something...
Its an amazon s3 url.
I want to combine both the images.
The final image should appear side by side as a single image.
How can i do it in java ?

Thanks
0
I have this mongo shell that works:

db.nytimes.aggregate([ { $addFields: { docs: { $filter: { input: "$docs", as: "doc", cond:  {                     "$and": [
         { "$eq": [ "$$doc.section_name", "Technology" ] },                       { "$eq": [ "$$doc.document_type", "article" ] }
            ]                   }  } } } } ]).pretty();

How do I change this to make it work in java.
NYTimes.json
0
Hi Folks,

I have an issue with a library in Groovy script. The issue is very strange, I don't see any direct reference to any of the classes of the library "org.apache.camel.Attachment" in my groovy script, but still I keep getting this error. PFA is the place where I get this error in my groovy script  and also find the code for my groovy script. Please give me suggestions on how to fix this. As I cant share the other jar files. I am giving the Base64Encoded strings for the libraries used in the script. and also the code which decodes the string and generates the corresponding jar files.

Tester.groovy is the script in which I have the issue.
Script1.groovy is the script which is called inside Tester.groovy
Base64Decode.groovy is the script for decoding the encoded string to generate the .jar file for the libraries.



Regards
Kalyan.
2019-03-18_15-38-46.png
Base64Decoder.txt
Script1.txt
Tester.txt
com.sap.gateway.ip.core.customdev.ut.txt
com.sap.gateway.ip.core.customdev.pr.txt
0
Hi,

So, I'm going to use Javascript for my game client. I can do the server in Java, thanks to local legends. I need a listener waiting for user directives on the game window and sending an activity packet for each frame.
It's going to be a platform style multiplayer.
I'm going to treat it like an RTS, UDP over TCP, for fast delivery of info in UDP packets over reliable TCP sends.
Does Javascript block for GameWindow activity? How is it queried?

What should I know? I got it done in Java be4 w Threads
Thanks
0
Hi,
This is more of a non technical question probably. I am a Senior Software engineer working mainly on Java.
I want to grow and become a Lead but i am unable to rise to it.
I am confused what do i have to do to land there.
I want some people here to share there experience how they rose from a senior software engineer to a Lead.
Some people say you should own things.
The company i am in currently they just assign some tasks and i think if i just keep on solving them i will stay at a Senior Software Engineer level.
Its nothing interesting. I need to somehow pick up things myself and work on them so as to prove myself and get some interesting work.
But i dont understand how am i going to do that. Its easy to say and think that i am only responsible for my growth but for that i need to prove myself and do something interesting.
Moreover i also get confused between somethings
1) Like there is one regular type of work where your manager assigns you tasks and thats very boring
2) Other thing is you figure out something in the codebase refactor it or do something with it. But how am i gonna do that and whether these type of tasks will be valuable to the company or not ?

Something challenging and which grows me rather than doing routine work i need to figure out how to do it in office and work on it so that it keeps my interest and i grow as well.
Please provide some tips and insights into it.
Any books or videos also on this topic will help. I really want to do …
1
Hi,
I want to build an api that given a stock id provides the high, low, open, close values for it at the end of the day.
Now i thought of two approaches
1) Keep all the data in memory in a Map<String, Stock> where String is the stockId
2) Upload all data to an Excel file and clients can fetch that file.

Now i can use a mix of the solutions  -
A client can either want one stock value or it can want all the values.
In the first case i will use the map.
In the second case i have a choice
1) Either to return the whole map as a json
2) Provide client a url to download the file.

Although both seems similar as at the end all we are doing is sharing data.

What are the pros and cons of both the approaches.
I can think of the following :
File uploading
1) File uploading will need  a s3 bucket setup an extra thing.
2) Benefit is that we can store older copies of the file and clients can easily access older copies if they want

Json
1) No need for anything extra. Its just plain and simple return the whole json from the map.

Please confirm if above what i wrote is correct. And also any other pros and cons you see.

Thanks
0
Hi,
Here is an example from Java concurrency in practice :

Screen-Shot-2019-03-13-at-6.26.39-PM.png
public class ThisEscape {
    public ThisEscape(EventSource source) {
} }
source.registerListener(
    new EventListener() {
        public void onEvent(Event e) {
            doSomething(e);
} });

Open in new window

As per my understanding
The above code has the following problem :
1) Since we are making an anonymous class it will contain the this object with it.
2) This is done inside a constructor before the constructor completes the execution and so the object may not be in a proper state.
So there could be a case due to very lucky timing that this was extracted out of Evenlistener and its a corrupted this.
Although once the constructor completes i think this should automatically be pointing to the complete object.

Now the book gives another example to avoid this escape of this


public class SafeListener {
    private final EventListener listener;
    private SafeListener() {
        listener = new EventListener() {
            public void onEvent(Event e) {
                doSomething(e);
} };
}
    public static SafeListener newInstance(EventSource source) {
        SafeListener safe = new SafeListener();
        source.registerListener(safe.listener);
        return safe;
} }

Open in new window


I dont quite understand how this is not escaped here.
Because here again we are using anonymous class to create an object in the same way as earlier.
So here also this should have escaped.
Please clarify.

Thanks
0
Hi,
Here is an example from java concurrency in practice making a class Thread Safe.


Screen-Shot-2019-03-11-at-6.27.15-PM.pngI want to understand the following in it -
1) Why is synchronized required on get method ?
Logically it looks like if any time set is called since its synchronized so the
value variable should also be visible to other threads. The latest updated value.

Then why is the get method required to be synchronized ?
Any example where thread safety might break if we dont synchronize get method ?

2) Whats the use of @GuardedBy annotation is it mandatory or optional ?
Is it just a marker thing to tell that its access is inside synchronized method ??

Thanks
0
I'm looking for some good learning resources for Json and Java to shorten some tasks.  Also looking for something on Node and Java.  Any suggested books or websites to learn this stuff?  By the way what application does Json and Node have?


Thanks!
0
OWASP: Avoiding Hacker Tricks
LVL 13
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

I want to develop a RESTful web service in java which accepts payment transactions, debit and credit both. Assume, thousands of transaction requests are expected every second and response should be sent back immediately. This means, my web service should be asynchronous. I want it RESTful and I will be using spring boot for developing it. Can anyone suggest the best design to make it asynchronous so that transaction requests are accepted immediately as they come and payments are processed concurrently? Payment processing could be a complex process which may involve further interacting with many systems and databases. But I am more worried about the entry point. Customers should able to send transaction requests swiftly without any blocking. They could be using an Android or iOS app to do this activity. Thanks.
0
Can we use "fetch first 1 rows only" criteria within NamedQuery? I used it but it does not filter resultset. It returns all records. But, when I use the same query in NativeNamedQuery, it works. It does filter the resultset and returns only 1 record from DB2. Can anyone confirm if this is expected behavior?
0
I am facing Problem when converting xml file to soap message for making a call to web service attaching my code and request  

following is the error

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:wsdl="http://xmlns.qtel.com.qa/B2B/WSDL" 
xmlns:par="http://www.tibco.com/namespaces/bc/2002/04/partyinfo.xsd">
   
   <soapenv:Header>
      <wsdl:TxInfo>
         <wsdl:Created>2018-06-10T11:07:20.953+03:00</wsdl:Created>
         <wsdl:Source>POS101</wsdl:Source>
         <wsdl:Lang>EN</wsdl:Lang>
      </wsdl:TxInfo>
      <par:PartyInfo>
         <from>
            <name>RQ</name>
         </from>
         <to>
            <name>Qtel</name>
         </to>
         <operationID>Qtel.Gateway/1.0/CheckLineStatus</operationID>
         <operationType>syncRequestResponse</operationType>
         <transactionID>RQJAV270220190000000010</transactionID>
      </par:PartyInfo>
   </soapenv:Header>


   <soapenv:Body>
      <wsdl:CheckLineStatusRequest>
         <wsdl:Request>RQ</wsdl:Request>
      </wsdl:CheckLineStatusRequest>
   </soapenv:Body>
</soapenv:Envelope>
ContentDescription >> null
Soap Header        >> [soapenv:Header: null]
Soap Part          >> com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPPart1_1Impl@37f8bb67
SOAP Body          >> [soapenv:Body: null]

Open in new window

SoapEnv.java
sample_rq.xml
0
So my instructor gave us this code to convert the password entered by the user to a series of letters and numbers. For example, if I pass in "alphabet soup" , then it should return 108de81c31bf9c622f76876b74e9285f

To make sure I'm passing in the correct password, which is "alphabet soup" , I tested returning the variables original and userpassword. They both displayed "alphabet soup"
however when I returned the sb.toString(); I get 6cfa0a0071bb0f00ad9db9f5b8240d61 instead of 108de81c31bf9c622f76876b74e9285f

Also, if I manually type "alphabet soup" into the code below for the original variable, sb.toString(); returns the correct value of 108de81c31bf9c622f76876b74e9285f.

Why am I getting the wrong value when I pass the value in via the parameter, even though everything I see seems to be right?

public static String MD5Digest(String userPassword)throws Exception{
        
        String original = userPassword;  //Replace "password" with the actual password inputted by the user
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(original.getBytes());
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
            
            //System.out.println("original:" + userPassword);
            //System.out.println("digested:" + sb.toString());
      
        }
        return sb.toString(); 
        //return 

Open in new window

0
All,

Attached is the screenshot of my code and the results. All I'm doing is asking a user to input username and password, and then I show the results of what I type in. However if I type a password like "good job", it only displays        "good



Please help!
0
Hi,

Am trying to create a solution to convert spring boot microservices to AWS Lambda. Am getting mixed opinions on if spring boots should even be considered suitable for aws lambda.
Under what circumstances would it make sense for me to go ahead with the conversion?
What type of assessment checks should I do before I try to re-write a Java based microservice to a serverless function?
0
Hi Experts,
how to validate xml using java
i dont want any data from the xml just need validate it as valid xml or not
0
All,

I'm a beginner Java programmer. I'm trying to write an authentication program that asks a user to enter credentials in the Main method, and then pass the info the a second method called openCredentials. In the openCredentials method, I first tried to open the credentials file, and then I was going to try and compare input from the Main to what's in the openCredentials method. The file in the openCredentials method is called credentials.txt. I get an error trying to open it. Also I get error with the parameters I'm trying to pass info to. Below is what I have so far. Please help me get started down the right path.

package authenticationsystem;
import java.util.Scanner;
import java.io.*;
import java.util.*;

public class AuthenticationSystem {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner scnr = new Scanner (System.in);
        String UserName = "";
        String PassWord = "";
        System.out.println("Please enter your username. For example: John.Doe"); //Here I'm asking for credentials.
        UserName = scnr.next();
        System.out.println("You entered: " + UserName);
        System.out.println("Please enter your password.");
        PassWord = scnr.next();
    }
    private Scanner X;
    public openCredentials(String userName, String passWord){
        try{
        X = new Scanner (new File ("credentials.txt"));
        }
        catch(Exception e){
0
I am writting a mule flow below,the flow fails at runtime with "java.lang.IllegalStateException: This transformer needs a valid endpoint"Can anyone please help?

<when expression="#[message.inboundProperties['http.relative.path'] =='/graphql']"> 

           <component class="gf.parameters.AppendQueryParameters" doc:name="AppendQueryParameters"/>
           <remove-property doc:name="Remove MULE properties" propertyName="MULE_*"/>           
      </when>

Open in new window

0
Announcing the Winners!
LVL 13
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

I have a code in java and need to write it in C # please help me. Thank you

import org.junit.Assert;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.RemoteWebDriver;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class BrowserProfile {
    public static void main(String[] args) throws Exception {
        BrowserProfile bp = new BrowserProfile();
        //TODO replace with existing profile ID. Define the ID of the browser profile, where the code will be executed.
        String profileId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

        //Define DesiredCapabilities
        DesiredCapabilities dc = new DesiredCapabilities();

        //Instantiate the Remote Web Driver to connect to the browser profile launched by startProfile method
        RemoteWebDriver driver = new RemoteWebDriver(new URL(bp.startProfile(profileId)), dc);

        //Perform automation
        driver.get("https://multilogin.com/");
        Assert.assertEquals("Multilogin - Replace Multiple Computers With Virtual Browser Profiles - Multilogin",driver.getTitle());
        driver.quit();
    }

    private String startProfile(String profileId) throws Exception {
        /*Send GET request to start the browser profile by profileId. Returns response in the following format:
        '{"status":"OK","value":"http://127.0.0.1:XXXXX"}', where XXXXX is the 

Open in new window

0
I am trying to load some .cer files in to a java .keystore file, using the keytool command. For one of the .cer file, I am expecting to import it as a PrivateKeyEntry. However, the result of "keytool -list" command shows that all certificate are imported as trustedCertEntry.

In the "keytool -importcert" command I toggled off the -trustcacerts (idea from https://stackoverflow.com/questions/24974324/import-certificate-as-privatekeyentry ), but it didn't make a difference on the result for me.

Can you help me on clarifying these questions:
1. can "keytool -importcert" import PrivateKeyEntry into the .keystore file?
2. Is the type (PrivateKeyEntry/trustedCertEntry) of the imported certificates in .keystore decided by the way of importing? or by the .cer file itself?
3. If decided by the way of importing, how to do that?
4. If by the .cer file itself, how to check which type it is?

Thank you!
0
I am working on the following homework solution:

Many program written with inheritance could be written with composition instead and vice versa. Rewrite class BasePlusCommissionEmployee (fig9.11 ) of the commissionEmployeeBasePlusCommissionEmployee hierarchy to use composition rather than inheritance.

Please see this link from the exact same question previously posted on ExpertExchange: https://www.experts-exchange.com/questions/26429370/java-program.html

I'm being told there are three .java files needed for this assignment instead of two (BasePlusCommissionEmployee.java and BasePlusCommissionEmployeeTest.java). What is the third file needed? Is it the CommissionEmployee.java file? I tried running the CommissionEmployee.java with the BasePlusCommissionEmployeeTest.java file and I received the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: BasePlusCommissionEmployee
        at BasePlusCommissionEmployeeTest.main(BasePlusCommissionEmployeeTest.java:10)
Caused by: java.lang.ClassNotFoundException: BasePlusCommissionEmployee
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
        ... 1 more
Press any key to continue . . .

Open in new window


Can someone explain to me what I'm doing wrong?
0
I am trying to add an action to a NSButton but it is not working

I create my NSButtton programmatically:

-(NSView *)rowTable:(CGFloat) heightOnPanel :(NSString *) textValue: (CGFloat) width: (CGFloat) height :(int) intColor{
    NSView *viewce = [[NSView alloc] initWithFrame:CGRectMake(0, heightOnPanel, 320, 40)];
    NSButton *layerBt = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, width, height)];

    [layerBt setTitle:textValue];

    [layerBt setButtonType:NSMomentaryPushInButton];
    [layerBt setTarget:nil];
    [layerBt setAction:@selector(buttonPressed:)];
    [viewce addSubview:layerBt];

    return viewce;
}

Open in new window



and here is IBAction method:


- (IBAction)buttonPressed:(id) sender{
    NSLog(@"hello world");
}

Open in new window


Could you point me to what I am missing?

Thanks
0
I am running a cucumber test suite using Jenkins

I am finding that if my test suite launches in multiple servers concurrently that test on server A may cause test on server B to fail because it’s changing database settings that should be blocked from modification until a given test has finished running

Is there a way to lock resources or block tests from running until it’s their turn to enter the critical zone to avoid this conflict?

Any assistance appreciated
0
on linux centos 7 this: https://www.midvisioncloud.com/ibm-websphere-on-microsoft-azure/ibm-bpm-microsoft-azure/
i try to install DB2 Developer https://www.ibm.com/it-it/marketplace/ibm-db2-direct-and-developer-editions

I have configure GUI for server using this web resource: https://linuxconfig.org/how-to-install-gui-gnome-on-centos-7-linux-system

I install xrdp and I started server with GUI and xrdp server
I open firewall ports 3389 and I login in server with rdp access

when i try to install DB2 Developer setup i found:

[root@OpificioBPM server_dec]# ./db2setup
DBI1190I  db2setup is preparing the DB2 Setup wizard which will guide
      you through the program setup process. Please wait.


Exception in thread "main" java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
      at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:217)
      at java.awt.Window.<init>(Window.java:547)
      at java.awt.Frame.<init>(Frame.java:431)
      at java.awt.Frame.<init>(Frame.java:396)
      at LoadingGraphic.<init>(Unknown Source)
      at LoadingGraphic.main(Unknown Source)

The DISPLAY variable is not set properly.  Ensure that the DISPLAY variable is set properly and that permissions are set properly to open windows on the display specified, then rerun the command.

I try to set DISPLAY variable with this values:
export DISPLAY=IP SERVER:0.0
export DISPLAY=localhost:0.0
export DISPLAY=localhost:0
0

Java

99K

Solutions

33K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.