Displaying data in database without using json - mysql

Somehow I got arround with Class.forName("com.mysql.jdbc.Driver");
having class not found exception error but I dont know if it works. I
just added permissions, but now every time i run this app on my
emulator it keeps on catching to SQLException which I set to display
error2.
Why is it not showing my data from my database,,is there something wrong with my code?
public void connDB() {
TextView myTextView = (TextView) findViewById(R.id.text);
try {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
String result = "Database connection success";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Scraped");
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
result += rsmd.getColumnName(1) + ":" + rs.getString(1) + "\n";
result += rsmd.getColumnName(2) + ":" + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ":" + rs.getString(3) + "\n";
result += rsmd.getColumnName(4) + ":" + rs.getString(4) + "\n";
result += rsmd.getColumnName(5) + ":" + rs.getString(5) + "\n";
}
myTextView.setText(result);
} catch (ClassNotFoundException e) {
myTextView.setText("error1");
} catch (SQLException e) {
myTextView.setText("error2");
}
}
EDIT
This is what i found in logcat,,dang,haha so many i did not include the others but what i can understand is it didnt connect to the server or database.
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: at java.lang.reflect.Constructor.newInstance(Native Method)
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
02-11 23:56:13.716 14381-14381/com.example.boneyflesh.connectnapls W/System.err: at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:981)
02-12 00:02:48.386 20185-20185/com.example.boneyflesh.connectnapls W/System.err: Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 3306): connect failed: ECONNREFUSED (Connection refused)
02-11 23:25:37.714 2356-2371/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 02-11 23:25:37.717 2356: 2356 D/ ]
HostConnection::get() New Host Connection established 0xaabfc5c0, tid 2356
[ 02-11 23:25:37.718 2356: 2356 W/ ]
Process pipe failed
[ 02-11 23:25:37.755 2356: 2371 D/ ]
HostConnection::get() New Host Connection established 0xaabfc880, tid 2371
02-11 23:25:37.761 2356-2371/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-11 23:25:37.808 2356-2371/? E/EGL_emulation: tid 2371: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)

Never mind,, i solved it my self tuns out i just need to set my host address to 10.0.2.2 so my url look like this.
private static final String url ="jdbc:mysql://10.0.2.2:3306/db";
As described here

Related

BackBlazeTokenResponse - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "allowed"

I am getting an error while trying to get an BackBlaze Authorization token. It was working fine before, and suddenly I started getting this error message -
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "allowed" (class au.com.polonious.cloud.node.backblaze.BackBlazeTokenResponse), not marked as ignorable (7 known properties: "authorizationToken", "minimumPartSize", "apiUrl", "downloadUrl", "accountId", "absoluteMinimumPartSize", "recommendedPartSize"])
at [Source: {
"absoluteMinimumPartSize": 5000000,
"accountId": "b0c893f558bc",
"allowed": {
"bucketId": null,
"capabilities": [
"all"
],
"namePrefix": null
},
"apiUrl": "https://api001.backblazeb2.com",
"authorizationToken": "4_001b0c893f558bc0000000000_01851d94_6e8e3e_acct_yxmSYWYVETByLq8bwW8HMQSEjlM=",
"downloadUrl": "https://f001.backblazeb2.com",
"minimumPartSize": 100000000,
"recommendedPartSize": 100000000
}
; line: 4, column: 15] (through reference chain: au.com.polonious.cloud.node.backblaze.BackBlazeTokenResponse["allowed"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:62)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:834)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1093)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1489)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1467)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:282)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
Here is my code-
private BackBlazeTokenResponse getBackBlazeAuth(String accountId, String applicationKey)
throws Exception{
HttpURLConnection connection = null;
String headerForAuthorizeAccount = "Basic " + Base64.getEncoder().encodeToString((accountId + ":" + applicationKey).getBytes());
log.info("getBackBlaze Auth - headerForAuthorizeAccount - "+headerForAuthorizeAccount);
BackBlazeTokenResponse backBlazeTokenResponse = new BackBlazeTokenResponse();
String tokenJson="";
try {
URL url = new URL("https://api.backblazeb2.com/b2api/v1/b2_authorize_account");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", headerForAuthorizeAccount);
InputStream in = new BufferedInputStream(connection.getInputStream());
tokenJson = myInputStreamReader(in);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
//log.info("Output JSON:"+tokenJson);
ObjectMapper mapper = new ObjectMapper();
//JSON from file to Object
log.info("tokenJson- "+ tokenJson);
backBlazeTokenResponse = mapper.readValue(tokenJson, BackBlazeTokenResponse.class);
log.info("getAuthorizationToken:"+backBlazeTokenResponse.getAuthorizationToken());
return backBlazeTokenResponse;
}
}
The error is in this line -
backBlazeTokenResponse = mapper.readValue(tokenJson, BackBlazeTokenResponse.class);
Not sure why it suddenly started throwing this error, probably something was changed in BackBlaze API. Please help.
This has solved my issue
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setVisibilityChecker(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));

No valid credentials provided (Mechanism level: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)) httpclient

I am trying to download pdf file from server using http client using ntlm Auth Scheme.
but I am getting below error when. The file is getting downloaded when I used wget with username and password as parameters but if I use same username and password it fails with 401 using java code. I am using httpclient 4.2.2
Authentication error: No valid credentials provided (Mechanism level: No valid credentials provided
(Mechanism level: Failed to find any Kerberos tgt))
Below is my code to download pdf using auth.
public ByteArrayOutputStream getFile1(String resourceURL) throws CRMBusinessException {
DefaultHttpClient httpclient = new DefaultHttpClient();
ByteArrayOutputStream tmpOut = null;
try {
ICRMConfigCache cache = CacheUtil.getCRMConfigCache();
String host = cache.getConfigValue(ConfigEnum.DOCUMENT_SOURCE_HOST_NAME.toString());
String user = cache.getConfigValue(ConfigEnum.HTTP_USER_NAME.toString());
String password = cache.getConfigValue(ConfigEnum.HTTP_PASSWORD.toString());
String workstation = cache.getConfigValue(ConfigEnum.CLIENT_HOST_NAME.toString());
// Prerequisites
PreCondition.checkEmptyString(resourceURL, "'resourceURL' cannot be empty or null");
PreCondition.checkEmptyString(host, ConfigEnum.DOCUMENT_SOURCE_HOST_NAME + " property is not set in database");
PreCondition.checkEmptyString(user, ConfigEnum.HTTP_USER_NAME + " property is not set in database");
PreCondition.checkEmptyString(password, ConfigEnum.HTTP_PASSWORD + " property is not set in database");
PreCondition.checkEmptyString(workstation, ConfigEnum.CLIENT_HOST_NAME + " property is not set in database");
// NTLM authentication across all hosts and ports
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_HOST),
new NTCredentials(user, password, workstation, MY_DOMAIN));
httpclient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
// Execute the GET request
HttpGet httpget = new HttpGet(resourceURL);
HttpResponse httpresponse = httpclient.execute(httpget);
if (httpresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
tmpOut = new ByteArrayOutputStream();
InputStream in = httpresponse.getEntity().getContent();
byte[] buf = new byte[1024];
int len;
while (true) {
len = in.read(buf);
if (len == -1) {
break;
}
tmpOut.write(buf, 0, len);
}
tmpOut.close();
}
aLog.debug( "IntranetFileDownloaderImpl - getFile - End - " + resourceURL);
return tmpOut;
} catch (Exception e) {
aLog.error("IntranetFileDownloaderImpl - getFile - Error while downloading " + resourceURL + "[" + e.getMessage() + "]", e);
throw new CRMBusinessException(e);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
Has anyone faced this kind of issue before while using httpclient?
What does "Failed to find any Kerberos tgt" mean?
Anybody has any clue on it?
Using kotlin and httpclient version 4.5.8:
val credentialsProvider = BasicCredentialsProvider().apply {
setCredentials(
AuthScope(AuthScope.ANY),
NTCredentials(user, password, null, domain))
}
val requestConfig = RequestConfig.custom().setTargetPreferredAuthSchemes(listOf(AuthSchemes.NTLM)).build()
return HttpClients.custom()
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultRequestConfig(requestConfig)
.build()
Below code worked for me with http client version 4.2.2.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("url");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new NTCredentials("username", "pwd", "", "domain"));
List<String> authtypes = new ArrayList<String>();
authtypes.add(AuthPolicy.NTLM);
httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF,authtypes);
localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity=response.getEntity();

Java error: The url cannot be null ( netbeans and wampserver)

I'm creating a Java application (stock management) with NetBeans and WampServer, I create the stock_db_connection class and the Login class, and I want to test if it's work or not, when I click run file, the login window appear; I enter the username and password but when I click "Login", I get the following error:
The url cannot be null
The url cannot be null
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at stockmanagment.Stock_db_connection.exectionQuery(Stock_db_connection.java:58)
at stockmanagment.Stock_db_connection.querySelectAll(Stock_db_connection.java:97)
at database.Login.loginActionPerformed(Login.java:117)
at database.Login.access$200(Login.java:10)
at database.Login$3.actionPerformed(Login.java:79)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6527)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6292)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4883)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
I don't know what is the problem, please can you help me...
This is the code of Login button.
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
rs = db.querySelectAll("utilisateur", "username='" + txt_username.getText()
+ "' and password='" + txt_password.getText() + " '");
try {
while (rs.next()) {
username1 = rs.getString("username");
password1 = rs.getString("password");
hak = rs.getString("type");
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
if (username1 == null && password1 == null) {
JOptionPane.showMessageDialog(this, "le nom utilisateur ou le mots de pass est incorrect");
} else {
if (hak.equals("directeur")) {
Produits h = new Produits();
h.setVisible(true);
this.dispose();
} else {
Chauffeurs k = new Chauffeurs();
k.setVisible(true);
this.dispose();
}
}
}

getting error to send mail in cakephp

Hi i am trying to send mail in cakephp but getting below error message:
stream_socket_client(): SSL operation failed with code 1. OpenSSL
Error messages: error:140770FC:SSL
routines:SSL23_GET_SERVER_HELLO:unknown protocol
stream_socket_client(): Failed to enable crypto
stream_socket_client(): unable to connect to ssl://smtp.gmail.com:25
(Unknown error)
And here is my controller code:-
public function contact(){
//$this->loadModel('Contact');
if($this->request->is(array('put','post'))){
$this->set('data', $this->request->data);
$this->Email->from = $this->data['Page']['email'];
$this->Email->to = 'staff#mailinator.com';
$this->Email->subject = 'Contact';
$this->Email->template = 'contact';
$this->Email->sendAs = 'html';
$this->Email->smtpOptions = array(
'post'=>465,
'host'=>'ssl://smtp.gmail.com',
'username'=>'staff#gmail.com',
'password'=>'123456',
'client'=>'gmail.com');
$this->Email->delivery = 'smtp';
//$this->Email->send();
if($this->Email->send()) {
$this->redirect(array('controller'=>'pages','action'=>'index'));
}
else{
CakeLog::write('debug', $this->Email->smtpError);
}
}
}
there should be 'port'=>465 not 'post'=>465 . please correct

Arduino to Xively JSON Error 400 The Feed is Empty

I am trying to upload data from an Aurdino to Xively. I can connect to Xively and even get the PUT request showing up on the Xively Request Log.
But i get the error 400 Bad Request
{"title":"JSON Parser Error","errors":"The feed is empty"}
I think the problem may be here
data = data + "\n" + "{\"version\":\"1.0.0\",\"datastreams\" : [ {\"id\" : \"Reading\",\"current_value\" : \"" + String(reading) + "\"}]}";
Any tips would be much appreciated.
Cheers and thanks
///////////////////////
// Saving to Xively ///
///////////////////////
int savetoxively(String reading, char* feedID) {
//getting the IP address for the xively website.
ip = 0;
Serial.print(WEBSITE); Serial.print(F(" -> "));
while (ip == 0) {
if (! cc3000.getHostByName(WEBSITE, &ip)) {
Serial.println(F("Couldn't resolve!"));
}
delay(500);
}
cc3000.printIPdotsRev(ip);
// formatting the data for the xively website.
int length = 0;
String data = ""; //the problem might be here, the serial monitor says the length is 0. should have something ing it.
data = data + "\n" + "{\"version\":\"1.0.0\",\"datastreams\" : [ {\"id\" : \"Reading\",\"current_value\" : \"" + String(reading) + "\"}]}";
length = data.length();
Serial.print("Data length");
Serial.println(length);
Serial.println();
// Print request for debug purposes
Serial.print("PUT /v2/feeds/");
Serial.print(feedID); //serial monitor shows the correct feedID here
Serial.println(".json HTTP/1.1");
Serial.println("Host: api.xively.com");
Serial.print("X-ApiKey: ");
Serial.println(API_key); //serial monitor shows the correct API key
Serial.print("Content-Length: ");
Serial.println(length, DEC);
Serial.print("Connection: close");
Serial.println();
Serial.print("Reading: ");
Serial.println(reading); //serial monitor shows the correct reading
Serial.println();
// connecting with the xively server
Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
if (client.connected()) {
Serial.println("Connected!");
Serial.print("feedID: ");
Serial.println(feedID);
client.print("PUT /v2/feeds/");
client.print(feedID);
client.println(".json HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");
client.println(API_key);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
client.println(length);
client.print("Connection: close");
client.println();
client.print(data);
client.println();
Serial.println("data sent");
}
while (client.connected()) { //printing connection status
while (client.available()) { //HTTP/1.1 400 Bad Request
char c = client.read(); //Date: Sat, 15 Mar 2014 19:33:38 GMT
Serial.print(c); //Content-Type: application/json; charset=utf-8
//Content-Length: 58
//Connection: close
//X-Request-Id: f48494a26daa2a5f0979dc4460264d233103f0f5
//{"title":"JSON Parser Error","errors":"The feed is empty"}
}
}
client.close(); // closes the connection with xively
cc3000.disconnect(); //disconnects the Wifi network
return 1;
}