actframework can't save in database using $.merge - actframework

i'am trying to read data from a form and save it to database.first i read entity from database and use $.merge(formdata).filter("-id").to(entity) .I print the value and it's changed successful.But when i call dao.save it do nothing;
the action code below
#PutAction("{id}")
public void update(#DbBind("id") #NotNull Category cate,Category category, ActionContext context) {
notFoundIfNull(cate);
try {
$.merge(category).filter("-id").to(cate);
System.out.print("name is " + cate.getName());
// cate.setName("test"); // success
this.dao.save(cate);
// redirect("/admin/categories");
} catch (io.ebean.DataIntegrityException e) {
context.flash().error(e.getMessage());
render("edit", category);
}
}
dao.save successful when i call cate.setName("test");
Can someone help me solve this problem?

I solved this problem by myself using the following code
public void mergeTo(Base target){
if(!this.getClass().isAssignableFrom(target.getClass())){
return;
}
Method[] methods = this.getClass().getMethods();
for(Method fromMethod: methods){
if(fromMethod.getDeclaringClass().equals(this.getClass())
&& fromMethod.getName().startsWith("get")){
String fromName = fromMethod.getName();
String toName = fromName.replace("get", "set");
try {
Method toMetod = target.getClass().getMethod(toName, fromMethod.getReturnType());
Object value = fromMethod.invoke(this, (Object[])null);
if(value != null){
toMetod.invoke(target, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Related

Java 8, Optional. throwing Exceptions, and Re-throwing exceptions, preventing null

I have confusing (lack of comprehension) trying to translate some part of my code to Optional on Java 8.
First example mock Code
private void privateMethodOne(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<CustomResponseDto> responseEntity;
try {
responseEntity = callWebClientRequestOne();
} catch (Exception e) {
RuntimeException ex = new CustomClientException(customRequesDto, e.getMessage());
log.error(ex.getMessage());
throw ex;
}
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
}
In the First example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)
if (responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
CustomResponseDto customResponseDto = responseEntity.getBody();
return Optional.ofNullable(customResponseDto).map(CustomResponseDto::getProperty).orElse(null);
How to do the same in a Single line?
Second example mock Code
private void privateMethodTwo(CustomRequesDto customRequesDto) {
// Some lines of code
ResponseEntity<byte[]> responseEntity = null;
try {
responseEntity = callWebClientRequestTwo();
} catch (Exception e) {
mapExceptions.put(customRequesDto, e.getMessage());
}
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
// continue the executions
}
Second example mock Code, I would like to reduce this lines in a single line, using Optional (if it is possible)
try {
if (responseEntity != null && responseEntity.getBody() == null) {
throw new CustomResponseException("myMessage");
}
} catch (Exception e) {
mapExceptions.put(someObject, e.getMessage());
}
How to perform the same in a Single line?

How to list and click on all links found in webpage and how to check if that link is redirecting to 404 page and throw error in selenium? [duplicate]

This question already has answers here:
Error for HttpResponseCode cannot be resolved to a type while checking URL status code for links
(1 answer)
requests.exceptions.MissingSchema: Invalid URL 'None': No schema supplied while trying to find broken links through Selenium and Python
(2 answers)
Closed 3 years ago.
Please check the below code which i tried
Here i want to check if all links are getting opened that should not contain any 404 page
public void alllinks() {
suites.setupEnviroment();
WebDriver driver = suites.getWebDriver();
driver.get(suites.WEB_PATH5);
Dimension d = new Dimension(1455, 900);
driver.manage().window().setSize(d);
try {
List<WebElement> links = driver.findElements(By.tagName("a"));
ArrayList<String> targets = new ArrayList<String>();
// collect targets locations
for (WebElement link : links) {
targets.add(link.getAttribute("href"));
}
for (String target : targets) {
driver.get(target);
try {
((WebDriver) links).getPageSource().contains("404");
} catch (Exception e) {
System.out.println("error");
}
// do what is needed in the target
}
Logger.getLogger("results").log(new LogRecord(Level.INFO,
MethodHandles.lookup().lookupClass().getCanonicalName() != null ? "success" : "failure"));
driver.close();
} catch (Exception e) {
Logger.getLogger("results").log(new LogRecord(Level.INFO,
MethodHandles.lookup().lookupClass().getCanonicalName() == null ? "success" : "failure"));
}
Thanks in advance!
this sample should do the job. Adapt it to your needs.
public class FindBrokenLinks {
private WebDriver driver;
private int invalidLinks = 0;
#BeforeClass
public void setUp() {
driver = new ChromeDriver();
driver.get("http://google.com"); // change the url
}
#Test
public void checkForBrokenLinks() {
try {
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
if (link != null) {
checkLink(link);
}
}
System.out.println("Total broken links: " + invalidLinks);
} catch (Exception e) {
e.printStackTrace();
}
}
#AfterClass
public void tearDown() {
if (driver != null)
driver.quit();
}
public void checkLink(WebElement linkElement) throws IOException {
HttpURLConnection connection = null;
try {
String link = linkElement.getAttribute("href");
URL url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
// change the code for your needs.
if (responseCode == 404) {
// you can trow error also ...
System.out.println("Found invalid link: " + link);
invalidLinks++;
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
if (connection != null) {
connection.getErrorStream().close();
}
}
}
}

JavaFX table row color, too many database connections

I want to to print my row red when book is out of stock but i am getting error like that every time i try new idea to manage that:
"com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Data source rejected establishment of connection, message from
server: "Too many connections"
Even if i try to close all connections in same loop...
So here we go:
private boolean checkIfOutOfStock(BookDetail book) throws SQLException{
String query = "select * from tbl_loan where book_id = " + book.getId() + " ";
dc = new DbConnection();
conn = dc.connect();
PreparedStatement checkPst = conn.prepareStatement(query);
ResultSet checkRs = checkPst.executeQuery(query);
if(checkRs.next()){
checkRs.close();
checkPst.close();
return true;
} else
{
checkRs.close();
checkPst.close();
return false;
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
dc = new DbConnection();
conn = dc.connect();
selectionModel = editTabPane.getSelectionModel();
editTableBooks.setRowFactory(tv -> new TableRow<BookDetail>() {
#Override
public void updateItem(BookDetail item, boolean empty) {
super.updateItem(item, empty) ;
if (item == null) {
setStyle("");
} else
try {
if (checkIfOutOfStock(item)) {
setStyle("-fx-background-color: tomato;");
} else {
setStyle("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
It works fine until i slide up and down table few times... its like everytime i slide table im opening new connection. Any idea how to solve it?
Hey do you mean something like that?
editTableBooks.setRowFactory(tv -> new TableRow<BookDetail>() {
#Override
public void updateItem(BookDetail item, boolean empty) {
super.updateItem(item, empty) ;
Platform.runLater(new Runnable() {
#Override
public void run() {
if (item == null) {
setStyle("");
} else
try {
if (checkIfOutOfStock(item)) {
setStyle("-fx-background-color: tomato;");
} else {
setStyle("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
});
It doesn't change anything or i just didn't get it :P

EWS signature updation error

public void updateSignature(ExchangeService exchange, String signature) {
try {
FolderId f = new FolderId(WellKnownFolderName.Root);
UserConfiguration user = UserConfiguration.bind(exchange,
"OWA.UserOptions", f, UserConfigurationProperties.All);
if (user.getDictionary().containsKey("signaturetext"))
user.getDictionary().setElements("signaturetext", signature);
else
user.getDictionary().addElement("signaturetext", signature);
user.update();
} catch (Exception e) {
e.printStackTrace();
}
}
I am getting a null pointer exception for user.update(); I am able to print the old signature in the console before setting the new one and also the new one after setting it in the dictionary. But, I am not able to update the changes permanently. Thanks in advance
.
in the others code it's using root.parentFolderId not root.
maybe it's that problem:
attached the code
static void SetSigniture(ExchangeService service) throws Exception {
Folder Root = Folder.bind(service, WellKnownFolderName.Root);
UserConfiguration OWAConfig = UserConfiguration.bind(service, "OWA.UserOptions", Root.getParentFolderId(), UserConfigurationProperties.All);
String hsHtmlSigniture = "<img src='http://www.baidu.com/img/baidu_jgylogo3.gif' />";
String stTextSig = "Text sig";
System.out.println(OWAConfig.getDictionary().getElements("timezone"));;
if (OWAConfig.getDictionary().containsKey("signaturehtml")) {
OWAConfig.getDictionary().setElements("signaturehtml", new Object());
} else {
OWAConfig.getDictionary().addElement("signaturehtml", hsHtmlSigniture);
}
if (OWAConfig.getDictionary().containsKey("signaturetext")) {
OWAConfig.getDictionary().setElements("signaturetext", stTextSig);
} else {
OWAConfig.getDictionary().addElement("signaturetext", stTextSig);
}
OWAConfig.update();
}

Http Post with Blackberry 6.0 issue

I am trying to post some data to our webservice(written in c#) and get the response. The response is in JSON format.
I am using the Blackberry Code Sample which is BlockingSenderDestination Sample. When I request a page it returns with no problem. But when I send my data to our webservice it does not return anything.
The code part that I added is :
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
What am i doing wrong? And what is the alternatives or more efficients way to do Post with Blackberry.
Regards.
Here is my whole code:
class BlockingSenderSample extends MainScreen implements FieldChangeListener {
ButtonField _btnBlock = new ButtonField(Field.FIELD_HCENTER);
private static UiApplication _app = UiApplication.getUiApplication();
private String _result;
public BlockingSenderSample()
{
_btnBlock.setChangeListener(this);
_btnBlock.setLabel("Fetch page");
add(_btnBlock);
}
public void fieldChanged(Field button, int unused)
{
if(button == _btnBlock)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://192.168.1.250/mobileServiceOrjinal.aspx"; //our webservice address
//String uriStr = "http://www.blackberry.com";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("name", URI.create(uriStr));//name for context is name. is it true?
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("ender"),
URI.create(uriStr)
);
}
//Dialog.inform( "1" );
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
if(response != null)
{
BSDResponse(response);
}
}
catch(Exception e)
{
//Dialog.inform( "ex" );
// process the error
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
}
private void BSDResponse(Message msg)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result = new String(data);
}
}
_app.invokeLater(new Runnable() {
public void run() {
_app.pushScreen(new HTTPOutputScreen(_result));
}
});
}
}
..
class HTTPOutputScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public HTTPOutputScreen(String message)
{
_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
showContents(message);
}
// After the data has been retrieved, display it
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
HttpMessage does not extend ByteMessage so when you do:
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
it throws a ClassCastException. Here's a rough outline of what I would do instead. Note that this is just example code, I'm ignoring exceptions and such.
//Note: the URL will need to be appended with appropriate connection settings
HttpConnection httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
OutputStream out = httpConn.openOutputStream();
out.write(<YOUR DATA HERE>);
out.flush();
out.close();
InputStream in = httpConn.openInputStream();
//Read in the input stream if you want to get the response from the server
if(httpConn.getResponseCode() != HttpConnection.OK)
{
//Do error handling here.
}