Cloudant AuthCookie may not be null - java

I am currently trying to add entries into Cloudant using this link:
https://github.com/cloudant/java-cloudant#installation-and-usage
Below is my code
package sample;
import java.util.List;
import com.cloudant.client.api.CloudantClient;
public class Cloudant {
public static void main (String[] args){
String password = System.getProperty("gffgasdas");
CloudantClient client = new CloudantClient("wiz.cloudant.com",password);
System.out.println("Connected to Cloudant");
System.out.println("Server Version: " + client.serverVersion());
List<String> databases = client.getAllDbs();
System.out.println("All my databases : ");
for ( String db : databases ) {
System.out.println(db);
}
}
}
I am getting this error:
Exception in thread "main" java.lang.IllegalArgumentException: AuthCookie may not be null.
at org.lightcouch.internal.CouchDbUtil.assertNotEmpty(Unknown Source)
at com.cloudant.client.api.CloudantClient.<init>(Unknown Source)
at sample.Cloudant.main(Cloudant.java:11)
I have all the necessary important imports. Any help would be appreciated thanks.

I'm not sure you're using the right constructor. It looks like you need to use the three-argument constructor CloudantClient(cloudantAccountName, username, password).
Your line:
CloudantClient client = new CloudantClient("wiz.cloudant.com",password);
Needs to be:
CloudantClient client = new CloudantClient("wiz", "wiz", password);
The two-argument version assumes you are passing a cookie rather than a password.

Related

Connecting to Siebel using Java databeans hangs forever

Hi Below is a sample code I've written:
import com.siebel.data.*;
import com.siebel.data.SiebelException;
public class DataBeanDemo
{
private SiebelDataBean m_dataBean = null;
private SiebelBusObject m_busObject = null;
private SiebelBusComp m_busComp = null;
public static void main(String[] args)
{
DataBeanDemo demo = new DataBeanDemo();
}
public DataBeanDemo()
{
try
{
m_dataBean = new SiebelDataBean();
m_dataBean.login("Siebel://devServerXYZ:7777/XYZ/
ecommunication_enu", ROSADMIN, ROSADMIN, "enu");
System.out.println("Connected");
m_busObject = m_dataBean.getBusObject("Opportunity");
m_busComp = m_busObject.getBusComp("Opportunity");
m_dataBean.logoff();
}
catch (SiebelException e)
{
System.out.println(e.getErrorMessage());
}
}
}
This code executes without issues, but gets stuck at m_dataBean.login(). And never returns.
What could be the issue?
If I try to change connect string (even port name, from 7777 to any other number like 2320, 2321) then I get error could not open a session in 4 attempts SBL-JCA-00200.
3 things to verify
Parameters in the connect string. Gtway server name, OM comp name, port number etc. (Username/Password error is showed immediately but rest others throw generic errors or hung forever)
(This is something that's specific to Siebel) Ensure that Java subsystem profile has classpath pointing to siebel.jar and siebelJI_lang.jar files
Siebel Server is up and running.
If LDAP is true, then such logins cannot be used using Databeans.
In my case it was 1 & 2, that was causing issues. By the way Comp name is case sensitive.

Use router in Rest API - java

package firstREST;
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Restlet;
import org.restlet.data.Protocol;
import org.restlet.routing.Router;
public class Faculty extends Application {
public static void main(String[] args) {
Component comp = new Component();
comp.getServers().add(Protocol.HTTP, 8080);
Application app = new Faculty();
comp.getDefaultHost().attach(app);
try {
comp.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/attendance/faculty/select", Faculty_Get.class);
router.attach("/attendance/faculty/insert", Faculty_Insert.class);
return router;
}
}
the above code is not working. after running the server when i open a url http://localhost:8080/attendance/faculty/select it won't work. How can i make this work? anyone can help?
Faculty_Get Class:
package firstREST;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.*;
public class Faculty_Get extends ServerResource {
#Get ("json")
public String present( String name ) throws Exception {
// Values.
String getName = null;
String getPost = null;
String getCourse = null;
String getDepartment = null;
String getPresents = null;
String getAbsents = null;
// Get values.
String jSonString = getQuery().getValues( "data" );
// Decode jSon.
JSONArray mJsonArray = new JSONArray( jSonString );
JSONObject mJsonObject = new JSONObject();
for ( int i = 0; i < mJsonArray.length(); i++ ) {
mJsonObject = mJsonArray.getJSONObject(i);
getName = mJsonObject.getString( "name" );
}
// Database.
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection myconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/attendance", "root", "");
PreparedStatement ps = myconn.prepareStatement("SELECT * FROM faculty where name = '" + getName + "'");
ResultSet rs = ps.executeQuery();
while( rs.next() )
{
getName = rs.getString( "name" );
getPost = rs.getString( "post" );
getCourse = rs.getString( "course" );
getDepartment = rs.getString( "department" );
getPresents = rs.getString( "presents" );
getAbsents = rs.getString( "absents" );
}
return "name="+getName+"&post="+getPost+"&course="+getCourse+"&department="+getDepartment+"&presents="+getPresents+"&absents="+getAbsents;
}
catch(Exception e)
{
throw e;
}
}
}
Error:
May 18, 2015 6:17:10 PM org.restlet.resource.UniformResource doCatch
WARNING: Exception or error caught in resource
java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:83)
at org.json.JSONArray.<init>(JSONArray.java:145)
at firstREST.Faculty_Get.present(Faculty_Get.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.restlet.resource.ServerResource.doHandle(ServerResource.java:449)
at org.restlet.resource.ServerResource.get(ServerResource.java:648)
at org.restlet.resource.ServerResource.doHandle(ServerResource.java:530)
at org.restlet.resource.ServerResource.doNegotiatedHandle(ServerResource.java:590)
at org.restlet.resource.ServerResource.doConditionalHandle(ServerResource.java:302)
at org.restlet.resource.ServerResource.handle(ServerResource.java:849)
at org.restlet.resource.Finder.handle(Finder.java:513)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Router.doHandle(Router.java:500)
at org.restlet.routing.Router.handle(Router.java:740)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:154)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.engine.ChainHelper.handle(ChainHelper.java:114)
at org.restlet.engine.application.ApplicationHelper.handle(ApplicationHelper.java:75)
at org.restlet.Application.handle(Application.java:391)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Router.doHandle(Router.java:500)
at org.restlet.routing.Router.handle(Router.java:740)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Router.doHandle(Router.java:500)
at org.restlet.routing.Router.handle(Router.java:740)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.engine.application.StatusFilter.doHandle(StatusFilter.java:154)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.routing.Filter.doHandle(Filter.java:159)
at org.restlet.routing.Filter.handle(Filter.java:206)
at org.restlet.engine.ChainHelper.handle(ChainHelper.java:114)
at org.restlet.Component.handle(Component.java:391)
at org.restlet.Server.handle(Server.java:491)
at org.restlet.engine.http.connector.BaseServerHelper.handle(BaseServerHelper.java:161)
at org.restlet.engine.http.connector.BaseServerHelper.handleInbound(BaseServerHelper.java:170)
at org.restlet.engine.http.connector.BaseHelper.handleNextInbound(BaseHelper.java:421)
at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:698)
at org.restlet.engine.http.connector.Controller$2.run(Controller.java:98)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
May 18, 2015 6:17:10 PM org.restlet.engine.log.LogFilter afterHandle
INFO: 2015-05-18 18:17:10 127.0.0.1 - - 8080 GET /attendance/faculty/select - 500 486 0 30 http://localhost:8080 Mozilla/5.0 (Windows NT 6.1; rv:40.0) Gecko/20100101 Firefox/40.0 -
This is the error i am getting when i refresh my browser. I don't know what's causing this issue.
I think that you could make things much simpler and moreover your application isn't really RESTful ;-) I strongly think that using Restlet the right way will contribute to fix your issue. It seems that you use the method getQuery whereas you don't have query string. Moreover such query parameters don't seem to apply in such case.
Before going further, I would recommend you to have a look at this link to design a Web API / RESTful service: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
Here are the comments I would have regarding the code you provided in your questions:
You should use one resource for list resource and one for single resource. So I would something like that:
#Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/attendance/faculty/{name}", FacultyServerResource.class);
router.attach("/attendance/faculty/", FacultyListServerResource.class);
return router;
}
It's not RESTful to use operation names (like select or insert) within the resource path. You should leverage the existing HTTP methods for your needs.
The token {name} corresponds to a path variable. This means that the attached server resource will be called whatever the value. For example, URLs like /attendance/faculty/facultyName1 or /attendance/faculty/facultyName2 will match. In addition, Restlet will automatically set the value within the attribute name. For URL #1, name is facultyName1 and for URL #2, name is facultyName2.
The string you provide as first parameter of the method attach can be seen as a kind of regular expression.
You should use a path variable to specify the criterion (the faculty name) to load your faculty. See the element {name} within the resource path /attendance/faculty/{name}. Restlet will allow you to get simply this hint with its API. So I would adapt the code of your server resource as described below:
public class FacultyServerResource extends ServerResource {
#Get ("json")
public String present() throws Exception {
String facultyName = (String)getAttribute("name");
(...)
}
As a reminder, specifying the value json in the annotation Get allows to configuration content negotiation and says that this method will only be used if the client wants to receive a JSON content.
You should work on bean within the server resource regarding the returned content. You can simply return it from your method present. From your code, I would create a bean like that:
public class Faculty {
private String name;
private String post;
private String course;
private String department;
private List<String> presents;
private List<String> absents;
// Getters and setters
(...)
}
and update the method present:
#Get ("json")
public Faculty present() throws Exception {
(...)
Faculty faculty = new Faculty();
faculty.setName("...");
faculty.setPost("...");
(...)
return faculty;
}
To make work such approach, you simply need to add the extension org.restlet.ext.jackson (and its dependencies) within your classpath.
Something I don't understand in the server resource class is why you use the method getQuery. The latter is made to get hints from query parameters and must be typically used with URLs like this: /attendance/faculty/facultyName?param1=something&param2=somethingelse. You will get the parameter values like this:
String param1Value = getQuery().getValues("param1");
// or
String param2Value = getQueryValue("param2");
In you case, this will be null since you don't have query string / query parameters. I don't understand the purpose of your query parameter data.
Another thing that you should take into account is to use a connection pool since creating a JDBC connection to the database isn't efficient within Web environment. Moreover you can't limit the number of opened connection. There are tools like DBCP or C3P0 that provides such feature.
Hope it will help you and feel free to ask me if something isn't clear!
Thierry

Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "OPENSHIFT_MYSQL_DB_PORT"'

I am trying to deploy my Jersey project on openshift. I have implemented this apple class to test the error in the another class since I guess the problem is with the establishing the database connection. in the Tails log I found this error:
Connecting to database…
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "OPENSHIFT_MYSQL_DB_PORT"'.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
package org.busTracker.serverSide;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Root resource (exposed at "myresource" path)
*/
#Path("myresource")
public class Apple {
//I modified my credients.
String host = "jdbc:mysql://$OPENSHIFT_MYSQL_DB_HOST:OPENSHIFT_MYSQL_DB_PORT/serverside";
String user = "adminBjv5a4k";
String password = "7tvPb1Bx3v8j";
/**
* Method handling HTTP GET requests. The returned object will be sent
* to the client as "text/plain" media type.
*
* #return String that will be returned as a text/plain response.
*/
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database…");
conn = DriverManager.getConnection(host,user,password);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// ignore
}
}
}
return "Hello, from apple class 14.05.15 11:35!";
}
}
Edit: I added the following to the try block after DriverManager.getConnection():
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
I have tried the following but I am still getting the same error:
This solution: https://forums.openshift.com/mysql-51-jboss-app-numberformatexception-mysql-url And add the following jdbc:mysql://${env.OPENSHIFT_MYSQL_DB_HOST}:${env.OPENSHIFT_MYSQL_DB_PORT}/serv‌​erside but nothing changed.
"jdbc:mysql://127.10.310.130:3306 /serverside"; This values are from the phpmyadmin of the app.
the problem is because of this line
String host = "jdbc:mysql://$OPENSHIFT_MYSQL_DB_HOST:OPENSHIFT_MYSQL_DB_PORT/serverside";
to get the environment variable, you need to use the method System.getEnv().get("[the variable name]"). So, in your case, the host variable should looks like this
String host = "jdbc:mysql://"
+ System.getenv().get("OPENSHIFT_MYSQL_DB_HOST")
+ ":"
+ System.getenv().get("OPENSHIFT_MYSQL_DB_PORT")
+ "/serverside";
by the way, your edit does not work because the application already throws an exception before it execute the code. so, to make it work, you need to put it before the DriverManager.getConnection() function.
You could replace those variables as below .
<property name="url"
value="jdbc:mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
yourdatabasename" />
can be replaced as below.
<property name="url"
value="jdbc:mysql://127.12.97.2:3306/yourdatabasename"
/>
jdbc:mysql://127.12.97.2:3306/yourdatabasename"The IP address and the portnumber can be obtained from the openshift phpmyadmin page and they are usually displayed on top of the admin page.
I tried all the above solutions but it didn't solve my problem. So anyone still getting that exception, try this.
The value stored in environment variable $OPENSHIFT_MYSQL_DB_HOST is something like
'jdbc:mysql://adminuname:adminpass#127.02.0.1:3306/appname'
. Therefore, using that value to create the url for DriverManager.getConnection() gives us the exception.
Instead try to know the value stored in $OPENSHIFT_MYSQL_DB_HOST and then hard code the url into a String variable without that username and password. Something like this
'jdbc:mysql://127.02.0.1:3306/appname'
For me it started working after making this modification. All other environment variables can be used as it is.
I found this solution here.

connecting to magento api using soap java

magento api using soap doesn't work due to missing magento-api.properties files, can someone help?
public class testConnection {
public static void main(String[] args) throws AxisFault {
String user = "rajeshvishnani";
String pass = "123456";
String host = "http://cypherincorporated.co.in/magento/index.php/api/soap?wsdl";
SoapConfig soapConfig = new SoapConfig(user, pass, host);
MagentoSoapClient magentoSoapClient = MagentoSoapClient.getInstance(soapConfig);
magentoSoapClient.setConfig(soapConfig);
}
}
Exception in thread "main" java.lang.IllegalArgumentException: could not load [magento-api.properties] as a classloader resource
at com.google.code.magja.utils.PropertyLoader.loadProperties(PropertyLoader.java:106)
at com.google.code.magja.utils.PropertyLoader.loadProperties(PropertyLoader.java:123)
at com.google.code.magja.soap.MagentoSoapClient.getInstance(MagentoSoapClient.java:69)
at magentomanager.testConnection.main(testConnection.java:15)
Try changing the url to 'http://yoursite.com/api/v2_soap/index?wsdl=1'.
Please provide more details.
Not sure about java exception but you can try following link.
Link

Cassandra Astyanax documentation

I am trying to use Astyanax for Cassandra with Java. I tried the example at https://github.com/Netflix/astyanax/wiki/Getting-Started. I have the code which I have just copied from this link:
package def;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.OperationResult;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;
public class sample {
public static void main(String[] args) throws Exception{
AstyanaxContext<Keyspace> context = new AstyanaxContext.Builder()
.forCluster("Test Cluster")
.forKeyspace("KeyspaceName")
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl()
.setDiscoveryType(NodeDiscoveryType.NONE)
)
.withConnectionPoolConfiguration(new ConnectionPoolConfigurationImpl("MyConnectionPool")
.setPort(9160)
.setMaxConnsPerHost(10)
.setSeeds("127.0.0.1:9160")
)
.withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
context.start();
Keyspace keyspace = context.getEntity();
ColumnFamily<String, String> CF_USER_INFO =
new ColumnFamily<String, String>(
"Standard1", // Column Family Name
StringSerializer.get(), // Key Serializer
StringSerializer.get()); // Column Serializer
// Inserting data
MutationBatch m = keyspace.prepareMutationBatch();
m.withRow(CF_USER_INFO, "acct1234")
.putColumn("firstname", "john", null)
.putColumn("lastname", "smith", null)
.putColumn("address", "555 Elm St", null)
.putColumn("age", 30, null);
m.withRow(CF_USER_INFO, "acct1234")
.incrementCounterColumn("loginCount", 1);
try {
OperationResult<Void> result = m.execute();
} catch (ConnectionException e) {
}
System.out.println("completed the task!!!");
OperationResult<ColumnList<String>> result =
keyspace.prepareQuery(CF_USER_INFO)
.getKey("Key1")
.execute();
ColumnList<String> columns = result.getResult();
// Lookup columns in response by name
int age = columns.getColumnByName("age").getIntegerValue();
long counter = columns.getColumnByName("loginCount").getLongValue();
String address = columns.getColumnByName("address").getStringValue();
// Or, iterate through the columns
for (Column<String> c : result.getResult()) {
System.out.println(c.getName());
}
}
}
But when I run this I am getting an exception:
log4j:WARN No appenders could be found for logger (com.netflix.astyanax.connectionpool.impl.ConnectionPoolMBeanManager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
completed the task!!!
Exception in thread "main" com.netflix.astyanax.connectionpool.exceptions.BadRequestException: BadRequestException: [host=127.0.0.1(127.0.0.1):9160, latency=0(0), attempts=1] InvalidRequestException(why:Keyspace KeyspaceName does not exist)
at com.netflix.astyanax.thrift.ThriftConverter.ToConnectionPoolException(ThriftConverter.java:159)
at com.netflix.astyanax.thrift.ThriftSyncConnectionFactoryImpl$1.execute(ThriftSyncConnectionFactoryImpl.java:119)
at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:52)
at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:229)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$1.execute(ThriftColumnFamilyQueryImpl.java:180)
at def.sample.main(sample.java:68)
Caused by: InvalidRequestException(why:Keyspace KeyspaceName does not exist)
at org.apache.cassandra.thrift.Cassandra$set_keyspace_result.read(Cassandra.java:4874)
at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:78)
at org.apache.cassandra.thrift.Cassandra$Client.recv_set_keyspace(Cassandra.java:489)
at org.apache.cassandra.thrift.Cassandra$Client.set_keyspace(Cassandra.java:476)
at com.netflix.astyanax.thrift.ThriftSyncConnectionFactoryImpl$1.execute(ThriftSyncConnectionFactoryImpl.java:109)
... 4 more
Can anyone tell me what's wrong with this? There is no proper documentation also available for this. So, can you just help me out. And even give me some links where I can get more examples on it.
why:Keyspace KeyspaceName does not exist
The error above is pretty self explanatory. The keyspace does not exists when the application connect to the localhost. So ensure that you create the keyspace and then re-run your application.
From the comment, I think you want to look into this . Excerpt from the thread,
The Keyspace serves as a client only and does not create the keyspace
or column family on cassandra. You can use the AsytanaxContext.Builder
to construct a Cluster interface through which you can actually create
the keyspace and column families.
This unit test in this link should provide you sufficient information on how to create keyspace in your cluster.
Your code sample is written to talk to a running instance of a Cassandra server on your localhost at 127.0.0.1. If you have Cassandra running elsewhere, or not at all, then you'll need to install and set up that server environment prior to executing your code.

Categories