reading hateaos in a microservice error content has private access in org.springframework.hateoas.EntityModel - spring-hateoas

I'm accepting a HATEAOS response in my spring microservice from my API server.
Everything appears golden, when I debug it, I can see the data.
ResponseEntity<CollectionModel<EntityModel<Character>>> m_character = characterProxy.findAll();
I created this to get to copy the data:
List<Character> removeHateaos = new ArrayList<>();
m_character.getBody().getContent().stream().forEach(s -> removeHateaos.add(s.content));
I'm getting this error message Error:(39, 93) java: content has private access in org.springframework.hateoas.EntityModel

I changed the add to .add(s.getContent()). It is working now.

Related

Showing error or success message on same page

this is my first time posting here since I couldn't figure the issue out, please keep in mind im fairly new to Spring and not that good at Java and coding in general.
I'm trying to program a Server application with Java Spring where you're able to create different accounts with specific roles. I want my users to be able to see a success or error message on the same page if the creation of an account succeded or failed.
Right now I'm using the error.param th:if tag from https://spring.io/guides/gs/securing-web/
the specific code in my HTML file is:
<div id="error" th:if="${param.error}">
Benutzername existiert bereits.
</div>
<div id="success" th:if="${param.success}">
Das Konto wurde erfolgreich erstellt.
</div>
Which works when I manually put ?success or ?error behind my URL.
I map my POST to the database by this method:
#PostMapping("/create/lieferant/fahrer")
public String submitDriver(#ModelAttribute Driver driver){
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
return "create/lieferant/fahrer?success";
}
The idea is to check if the username is already registered and if so, returning the create/lieferant/fahrer?error but it says
Error resolving template "create/lieferant/fahrer?error", template
might not exist or might not be accessible by any of the configured
Template Resolvers
and the same for ?success.
What I don't understand is: it's working for the login which I've gotten from the Spring getting started guide and it seems to be working without any heavy configurations or so. Atleast I don't see any.
I'd be glad if anyone could help me figuring my issue out.
Thanks a lot.
You could do something like this:
#PostMapping("/create/lieferant/fahrer")
public ModelAndView submitDriver(#ModelAttribute Driver driver){
ModelAndView mav = new ModelAndView();
mav.setViewName("create/lieferant/fahrer");
try {
if(userRepository.existsByUsername(driver.getUsername())){
return "create/lieferant/fahrer?error";
}
Driver d = new Driver();
User n = new User();
Role r = new Role();
d.setName(driver.getName());
d.setTelnum(driver.getTelnum());
d.setUsername(driver.getUsername());
n.setUsername(driver.getUsername());
n.setPassword(encoder().encode(driver.getPassword()));
r.setUsername(driver.getUsername());
r.setAuthority("LIEFERANT");
userRepository.save(n);
driverRepository.save(d);
roleRepository.save(r);
mav.addObject("success", "All was ok");
} catch (Exception e) {
mav.addObject("error", "Error message to change");
}
return "create/lieferant/fahrer?success";
}
You could retrieve messages on page with the two keys "success" and "error"

Spring RESTful web-service returns 404 AFTER url is successfully called

I have a Spring MVC 4 app with Spring Security 4 and is deployed on Tomcat 8 running under jdk 1.8. The web-service has the controller defined as such:
#RequestMapping(value = "/build", method = RequestMethod.POST, produces = "application/json", headers =
{ "Accept=*/*", "Content-Type=*/*" })
public SubjectEntity build(#RequestBody SubjectImportDTO subjectImportDTO)
{
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = null;
if (principal instanceof User)
{
user = ((User) principal);
}
SubjectEntity entity = service.build(subjectImportDTO);
System.out.println("FINISH: build");
return entity;
}
I am getting a csrf token, I have that setup correctly. I know the url is getting called correctly because I can see that in the logs when I get there. The service on the back-end is running, data is correctly entered into the database, I correctly get the write object, and using the Jackson Mapper, the object 'SubjectEntity' should be translated into JSON and sent back to the requesting client. This web-service has been unit tested under the Spring Web Test framework, and it works great!
So, I am familiar with an HTTP 404 error in not finding a URL when the wrong parameters are passed in, or you're trying to do a POST when it's a GET, etc. So many reasons why we can get a 404 error ...
BUT ... IN THIS CASE ... We've already gotten to the URL, executed the code, and then it has the data it needs. Since the Controller says we have content-type / and it produces application/json, I don't know what else could be wrong?
Any ideas?
You should add #ResponseBodyto your method. without this, Spring mvc tries to find another handler method which can send a response.
NB: #RestController automatically add #ResponseBody on each method in a controller.

quickfixj Integration with External OMS

I am doing a development to integrate a non Java OMS system with QuickFIX/J to send buy/sell orders to multiple brokerage systems .
I have written the belog logic to send the messages
I have written this under main function which is in the same class created by implementing Application "public class Initiator implements Application"
InputStream inp = InitiatorSocket.class.getResourceAsStream("test.cfg");
SessionSettings sessionSetting = new SessionSettings(inp);
Application myApp = new Initiator();
FileStoreFactory factory = new FileStoreFactory(sessionSetting);
ScreenLogFactory sfactory = new ScreenLogFactory(sessionSetting);
DefaultMessageFactory defaultMsgFactory = new DefaultMessageFactory();
initiator = new SocketInitiator(myApp, factory, sessionSetting,sfactory,defaultMsgFactory);
initiator.start();
SessionID sessionId = initiator.getSessions().get(0);
I am using the below code to send messages after continuously listening a directory using while Loop.
while(true)
{
readFilefromSrcDirectory();
prepareFixMessage();
Session.sendToTarget(fixMessage, sessionId);
}
My above code is getting executed while debugging but when I run it normally, the Session.sendToTarget(fixMessage, sessionId); and other file read related logic which is next to initiator.start(); is not getting executed.
Kindly note that the same above code is getting executed if we add some console print statements such as System.out.print("Test");
Please help me.
Are your test.cfg settings between debug and run different? I would add console print statements everywhere and work out exactly where the runtime is failing.

Unable to update collaboration, using update collaboration API in box-java-sdk-v2

I am trying to integrate Box with Kerika using box-java-sdk-v2. Library is added as maven dependency (net.box:boxjavalibv2) in the project.
Everything is working fine, except the update collaboration API. API call from the project looks like follow:
BoxCollabRequestObject requestObject = BoxCollabRequestObject.updateCollaborationObject(permission);
return client().getCollaborationsManager().
updateCollaboration(collaborationId, requestObject);
I searched google a lot to find the solution of this. But, I didn't get any. So, I have logged the issue at box-java-sdk-v2 issues on GitLab.
After spending some more time after a day a found that issue is with the Java library itself. There isn't any problem with Box API. I concluded this by accessing REST API directly from Advanced REST Client instead of Java library, and it worked.
So, as work around (Until the bug from the Java SDK is not officially fixed and release), I have updated my code as follows:
// As client library update function is not working properly so I have written custom code to deal with it.
BoxCollabRequestObject requestObject = BoxCollabRequestObject.updateCollabObjects(permission);
BoxCollaborationsManagerImpl boxCollaborationsManager = (BoxCollaborationsManagerImpl)client().getCollaborationsManager();
BoxUpdateCollaborationRequest request = new BoxUpdateCollaborationRequest(boxCollaborationsManager.getConfig(), boxCollaborationsManager.getJSONParser(), collaborationId, requestObject);
return (BoxCollaboration) boxCollaborationsManager.getResponseAndParseAndTryCast(request, BoxResourceType.COLLABORATION, boxCollaborationsManager.getJSONParser());
and the BoxUpdateCollaborationRequest class in the above code is self made. It looks like as follow:
public class BoxUpdateCollaborationRequest extends DefaultBoxRequest
{
private static final String URI = "/collaborations/%s";
public BoxUpdateCollaborationRequest(IBoxConfig config, IBoxJSONParser parser, String id, BoxCollabRequestObject requestObject) throws BoxRestException
{
super(config, parser, getUri(id), RestMethod.PUT, requestObject);
}
public static String getUri(final String id) {
return String.format(URI, id);
}
}
I noticed that the real problem in their original implementation is just the constant. It should be
private static final String URI = "/collaborations/%s";
Instead of
private static final String URI = "/collaboration/%s";
I am filing this issue here to help others who is having the same issue and searching Stack Overflow for the solution.

JavaMail SMTPSendFailedException

I am writing a bulk email program using the JavaMail api. I have a Microsoft Exhange server which I am trying to send the emails in to. When I run my program I get the following error:
**com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1100)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.postMail(SendEmail.java:100)
at EmailGenerator.main(EmailGenerator.java:52)**
The part of my code trying to send the message is as follows:
Properties props = new Properties();
props.put("mail.smtp.host", email_server);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", true);
class EmailAuthenticator extends Authenticator {
String user;
String pw;
EmailAuthenticator (String FROM, String PASSWORD)
{
super();
this.user = FROM;
this.pw = PASSWORD;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
Session session = Session.getInstance(props, new EmailAuthenticator(USER, PASSWORD));
session.setDebug(debug);
System.out.println("Session created");
.. CREATED MESSAGE HERE...
Transport transport = session.getTransport("smtp");
transport.connect(exchange_server,user,password);
transport.send(msg);
transport.close();
I wonder am I missing some configuration on the Exchange server side, or is an issue with my code?
OK I figured out where I was going wrong here and am posting up the answer incase anybody else can get some value out of it. I had the following line of code:
props.put("mail.smtp.auth", true);
This was telling my application that it needed to authenticate to the SMTP server, when in fact it didnt. This was causing my application from logging into the SMTP server and sending the email and thus producing the error message. Setting this property to false or not having this line of code fixed the issue for me. This line of code is only necessary for SMTP servers that require you to login, which my Exchange server didnt.