copy db operation with mongo java driver when auth is enabled - java

I need to do a copydb operation using mongo java driver. This is my code to do that
String nonce = mongo.getDB("admin").command(new BasicDBObject("copydbgetnonce","1")).get("nonce").toString();
String username = "admin";
String password = "password";
String key = md5(nonce + username + md5(username + ":mongo:" + password));
DBObject copyOp = new BasicDBObject("copydb", "1").
append("fromdb" , "db1").
append("todb" , "db2").
append("username" , username).
append("nonce" , nonce).
append("key" , key);
mongo.getDB("admin").command(copyOp);
It was working when authentication is disabled on the server. With the authentication it fails with unauthorized result.
{ "serverUsed" : "localhost/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "unauthorized"}
I can assure that password and username is correct. Please point me to the correct direction .
PS my mongod instance is tokumx 1.5
Thanks.

Does this work for you?
final DBObject cmd = new BasicDBObject( );
cmd.put( "copydb", "1" );
cmd.put( "slaveOk", true );
cmd.put( "fromdb", "db1" );
cmd.put( "todb", "db2" );
cmd.put( "fromhost", "fromHost" );
BasicDBObject nonceCmd = new BasicDBObject( );
nonceCmd.put( "copydbgetnonce", 1 );
nonceCmd.put( "fromhost", "fromHost" );
final CommandResult nonceResult = mongo.getDB( "admin" ).command( nonceCmd );
final String nonce = nonceResult.getString( "nonce" );
final byte[ ] innerHex =( getUserName( ) + ":mongo:" + String.valueOf( getPassword( ) ) ).getBytes( );
final byte[ ] outerHex = ( nonce + getUserName( ) + Util.hexMD5( innerHex ) ).getBytes( );
cmd.put( "username", getUserName( ) );
cmd.put( "nonce", nonce );
cmd.put( "key", Util.hexMD5( outerHex ) );
final CommandResult res = mongo.getDB( "admin" ).command( cmd );
if ( !res.ok( ) )
{
throw res.getException( ) ;
}

Related

Can't stubbing a query with WireMock

The problem is that my query like:
/pc/odata/api/devices?$top=3000&$skip=0&$format=json&$expand=groups&$select=ID,Name,PrimaryIPAddress,groups/GroupPathLocation&$filter=((groups/Name%20eq%20'OI%20Inventory%20Group'))&timeout=120
can't use for stub with
HTTP ERROR 500
Problem accessing /__files/pc/odata/api/devices.
Reason:
Illegal character in query at index 138:
/not-matched?$top=3000&$skip=0&$format=json&$expand=groups&$select=ID,Name,PrimaryIPAddress,groups/GroupPathLocation&$filter=((groups/Name
eq 'OI Inventory Group'))&timeout=120
The request is valid, and app works with the same query without params.
A method for stub:
public void initialize( Integer D_ITEM_COUNT ) {
writedItemsFile( D_ITEM_COUNT );
ClasspathFileSource responseFiles = new ClasspathFileSource( "." );
dItemService = new WireMockServer( WireMockConfiguration.wireMockConfig()
.port( D_ITEMS_SERVICE_PORT )
.fileSource( responseFiles )
.enableBrowserProxying( false )
.notifier( new ConsoleNotifier( true ) ) );
dItemService.givenThat( get( urlEqualTo( D_D_ITEMS_SERVICE_ENDPOINT ) ).
willReturn( WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBodyFile( "../" + D_ITEMS_SERVICE_RESPONSE_FILE + FILE_EXTENSION )
.withStatus( HttpStatus.SC_OK ) ) );
}

Null Pointer Exception when replacing character " with no text then casting value to Float

I am writing a java program fetching JSON data through HTTP GET methods and it returns the following after I navigate the object tree:
{
"year":"2015",
"period":"M03",
"periodName":"March",
"value":"141178",
"footnotes":[{}]
}
Now I want to take value and caste it to a float, I tried to do this like such:
JSONParser parser = new JSONParser();
try
{
JSONObject
BLSemployment = ( JSONObject ) parser.parse( _RDATA );
BLSemployment = ( ( JSONObject ) BLSemployment.get( "Results" ) );
JSONArray
BLSemploymentseries = ( ( JSONArray ) BLSemployment.get( "series" ) );
BLSemployment = ( ( JSONObject ) BLSemploymentseries.get( 0 ) );
BLSemploymentseries = ( ( JSONArray ) BLSemployment.get( "data" ) );
for( int i = 0; i < 12; i++ )
{
BLSemployment = ( (JSONObject) BLSemploymentseries.get( i ) );
HistoricalNonFarmPayrollData[i] = Float.parseFloat( JSONValue.toJSONString( BLSemployment.get( "value" ) ).replace( "\"" , "" ) );
HistoricalNonFarmPayrollYear[i] = JSONValue.toJSONString( BLSemployment.get( "year" ) );
HistoricalNonFarmPayrollMonth[i] = JSONValue.toJSONString( BLSemployment.get( "periodName" ) );
}
}
catch ( ParseException pe )
{
System.out.println( pe );
}
However Now I get the error:
Exception in thread "main" java.lang.NullPointerException
at BLSFramework.getNonFarmPayrolls(playground.java:354)
at playground.main(playground.java:27)
RESOLVED: occasionally BLS website doesn't send data for periods of time and I was coding during that period of time.

How to iterate DBObject values in Java

I have values that coming from MongoDB stored in a DBObject. and I needed to store that value in a set one by one. As being new to MongoDB I am not actually getting idea coherently how to proceed that.
String date = sdf.format(cal2.getTime());
List<String> dateList = new ArrayList<String>();
for (int i = 0; i < 6; i++) {
Date dateParsed = sdf.parse(date);
dateParsed.setDate(dateParsed.getDate() - i);
dateList.add(sdf.format(dateParsed));
}
Set<String> values2= new HashSet<String>();
for (String str : dateList) {
BasicDBObject find1 = new BasicDBObject("_ky", str);
DBObject values1= someDB.findOne(find1);
Iterator iter = values1.iterator(); /*giving error the method not found (becasue values1 is a dbObject)*/
while (iter.hasNext()) {
values2.add(//???//);
}
}
Any help on how can I iterate the DBObject- values1 and add those values in a set- values2 would be great.
You can call values1.keySet() and iterate over that and get() any values or use values1.toMap() and iterate that Map like you would any other.
The primary abstraction in the Mongo Java Driver is the DBObject which acts like a wrapper around Java's Map<String,Object>.
import java.util.Arrays;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class DBObjectKeySetDemo {
public static void main( String[] args ) {
DBObject dbo = new BasicDBObject( "firstName", "Robert" ).append( "lastName", "Kuhar" );
dbo.put( "age", 49 );
dbo.put( "hobbies", Arrays.asList( "Fly Fishing", "Board Games", "Roller Derby" ) );
DBObject browser = new BasicDBObject( "implementation", "Chrome" );
browser.put( "vendor", "Google" );
BasicDBList bookmarks = new BasicDBList();
bookmarks.add( new BasicDBObject( "name", "StackOverflow" ).append( "URL", "http://stackoverflow.com" ) );
bookmarks.add( new BasicDBObject( "name", "MMS" ).append( "URL", "https://mms.mongodb.com" ) );
browser.put( "bookmarks", bookmarks );
dbo.put( "browser", browser );
for ( String key : dbo.keySet() ) {
System.out.println( "key: " + key + " value: " + dbo.get( key ) );
}
System.out.println( "dbo: " + dbo );
}
}
The "gotcha" is that you can only work directly with "top level" element. For example, in the above example, through the Java API, you have no way to directly reference "browser.vendor". Through the Java API you would have to first get the "browser" sub-document, and then get the "vendor" field.
Clear? As mud? It helped me to just think of the abstraction as a Map<String,Object> where Object, in the case of a sub-document, may itself be a Map<String,Object>.

Returning JSON from Java to Worklight Adapter

I have one class FileHandling in which there is one method called readAllLayouts which will read the all files from specified folder and return the content as JSONArray to worklight adapter.
I have got this type of Error when invoking worklight procedure:
{
"errors": [
"Evaluator: Java class \"org.json.simple.JSONArray\" has no public instance field or method named \"isSuccessful\"."
],
"info": [
],
"isSuccessful": false,
"warnings": [
]
}
and this is the code of my Java method:
public static JSONArray readAllLayoutFiles ( ){
File layoutDir = new File( LAYOUT_PARENT_DIR );
String allFiles[] = layoutDir.list();
System.out.println( "All Files Length : " + allFiles.length );
JSONObject obj = null;//new JSONObject[ allFiles.length ];
JSONArray retArr = new JSONArray();
for ( String f : allFiles ){
obj= new JSONObject();
obj.put( "layoutname", f.replaceAll (".txt", "" ) );
obj.put( "layouthtml", readLayoutFile ( f ) );
retArr.add(obj);
}
obj= new JSONObject();
obj.put( "isSuccessful", true );
retArr.add(obj);
System.out.println( retArr.toString() );
return retArr;
}
Any help would be appreciated.
Why is "isSuccessful" false in the output whereas it is set to true in your code?
Because of the problem I have changed my code that will working, but now It is not returning JSON but returning String that contains JSON.
Here is the code and Working Fine :
public static String readAllLayoutFiles ( ){
File layoutDir = new File( LAYOUT_PARENT_DIR );
String allFiles[] = layoutDir.list();
System.out.println( "All Files Length : " + allFiles.length );
JSONObject obj = null;//new JSONObject[ allFiles.length ];
JSONArray retArr = new JSONArray();
for ( String f : allFiles ){
obj= new JSONObject();
obj.put( "layoutname", f.replaceAll (".txt", "" ) );
obj.put( "layouthtml", readLayoutFile ( f ) );
retArr.add(obj);
}
obj= new JSONObject();
obj.put( "isSuccessful", true );
retArr.add(obj);
System.out.println( retArr.toJSONString() );
return retArr.toJSONString();
}

How to generate multi-domain (UCC) certificate in Java?

Currently I'm using the BouncyCastle library to generate a certificate. Something like this:
X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
certGenerator.setIssuerDN( rootCertificate.getSubjectX500Principal() );
certGenerator.setSignatureAlgorithm( "SHA1withRSA" );
certGenerator.setSerialNumber( serial );
certGenerator.setNotBefore( notBefore );
certGenerator.setNotAfter( notAfter );
certGenerator.setPublicKey( rootCertificate.getPublicKey() );
Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>();
Vector<DERObjectIdentifier> order = new Vector<DERObjectIdentifier>();
attrs.put( X509Principal.C, "RU" );
// other attrs.put() calls here
order.addElement( X509Principal.C );
// other order.addElement() calls here
certGenerator.setSubjectDN( new X509Principal( order, attrs ) );
certGenerator.addExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure( rootCertificate ) );
certGenerator.addExtension( X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure( newKeyPair.getPublic() ) );
return certGenerator.generate( rootPrivateKey, "BC" );
Can I add the SubjectAltNames field to the generated certificate?
To accomplish the task, insert the following just before the certGenerator.generate() call:
ASN1EncodableVector alternativeNames = new ASN1EncodableVector();
for( String domainName : domainNames )
{
alternativeNames.add( new GeneralName( GeneralName.dNSName, domainName ) );
}
certGenerator.addExtension( X509Extensions.SubjectAlternativeName, false, new GeneralNames( new DERSequence( alternativeNames ) ) );
(Answer provided by Double-V).

Categories