Using the DAOPattern with authentication - morphia

I'm having some trouble to authenticate now. Try to add the following code to the constructors of my own DAO-classes:
public MyDAO(Morphia morphia, Mongo mongo, String dbName){
super(mongo, morphia, dbName);
// Line below added
mongo.getDB(dbName).authenticate("username", "password".toCharArray());
// Then I tried this
if (mongo.getDB(dbName).isAuthenticated()){
System.out.println("SUCCESS!!!");
}else{
System.out.println("FAILURE");
}
}
Nothing works. I change /etc/mongod.conf file, add auth=true.
FAILURE
com.mongodb.WriteConcernException: { "serverUsed" : "localhost/127.0.0.1:27017" , "err" : "not authorized for upsert on pndTestTemp.myEntity" , "code" : 16538 , "n" : 0 , "connectionId" : 46 , "ok" : 1.0}

Related

g1ant: jsonpath with method length() not implemented

I have problem to get size items of array. Function of jsonPath "length()" not implemented in g1ant, because throwing exception "Array index expected".
Below is sample in g1ant script for test.
addon core version 4.103.0.0
addon language version 4.104.0.0
♥jsonImage = ⟦json⟧‴{ "book" : [ { "name" : "Bambi"} , { "name" : "Cinderella" } ] }‴
♥aaa = ♥jsonImage⟦$.book.length()⟧
dialog ♥aaa
Are there other solutions related to the length of the array?
It's not possible to get the number of json array elements in the way that you are trying. G1ANT is using Newtonsoft.Json library for selecting json tokens where they don't allow expressions like .length() as you can read here.
Here's how you can workaround this issue.
♥jsonImage = ⟦json⟧‴{ "book" : [ { "name" : "Bambi"} , { "name" : "Cinderella" } ] }‴
♥jsonArrLength = 0
♥hasExceptionOccurred = false
while ⊂!♥hasExceptionOccurred⊃
try errorcall NoMoreElements
♥test = ♥jsonImage⟦book[♥jsonArrLength]⟧
♥jsonArrLength = ♥jsonArrLength + 1
end try
end while
dialog ♥jsonArrLength
procedure NoMoreElements
♥hasExceptionOccurred = true
end procedure

PHP InstanceOf works locally but not on host server

I have an issue with PHP 7's instanceof statement that is only happening on certain conditions.
It seems that instanceof works locally on my dev machine (MAMP Pro running PHP 7.0.13) but not on my Hosted Server (HostEurope, PHP 7).
I have tried the following :
downgrading to PHP 5.6
using is_a instead
Using fully qualified name e.g. \Site\Ad
but they all exhibit the same behaviour.
I've tried Googling "PHP instanceof not working" and variations of it but I haven't found anything relevant.
I was wondering if anyone had experienced something similar or possible solutions to try?
The Code in question is:
<?php
namespace Site;
require_once(__DIR__."/../interface/IOutput.php");
require_once(__DIR__."/../lib/Lib.php");
require_once(__DIR__."/../site/AdMediumRectangle.php");
require_once(__DIR__."/../site/AdSnapBanner.php");
require_once(__DIR__."/../const/Const.php");
class AdFactory
{
/**
* Define(AD_BANNER, 0);
* Define(AD_RECTANGE, 1);
* Define(AD_SUPERBANNER, 2);
* Define(AD_SKYSCRAPER, 3);
**/
/**
* #param $object
* #return AdMediumRectangle|AdSnapBanner|string
*/
public static function CreateObject($object)
{
$ad = wire(pages)->get("/ads/")->children->getRandom();
if ($ad == null)
return new \Exception("No Random Ad found");
switch ($object) {
case AD_BANNER:
echo "AD_Banner Selected\r\n";
$adSnapBanner = new AdSnapBanner($ad);
return $adSnapBanner;
break;
case AD_RECTANGLE:
echo "AD Rectangle Created\r\n";
$adRectangle = new AdMediumRectangle($ad);
return $adRectangle;
break;
case AD_SUPERBANNER:
case AD_SKYSCRAPER:
default:
echo "AdFactory BlankObject created";
return "";
break;
}
}
public static function Markup($object)
{
$obj = AdFactory::CreateObject($object);
if (($obj instanceof AdSnapBanner) || ($obj instanceof AdMediumRectangle)) {
echo "InstanceOf worked";
return $obj->Markup();
}
else {
echo "return blankString";
return "";
}
}
}
Update : This is the code that calls the above AdFactory class
<?php
namespace Site;
require_once(__DIR__."/../interface/IOutput.php");
require_once(__DIR__."/../lib/Lib.php");
require_once(__DIR__."/../factory/AdFactory.php");
require_once (__DIR__."/../const/Const.php");
class AdInjector
{
public static function Inject($page, $ad_pos)
{
//Select an Ad from /Ads/ according to criteria
//$ads = wire(pages)->get("/ads/")->children;
$count = 1; //$ads->count();
if ($count > 0) {
$mod = $page->id % 3;
echo "mod=" . $mod . "\r\n";
if ($mod == $ad_pos) {
switch ($mod) {
case AD_POS_TITLE;
case AD_POS_BANNER:
//Pick an Snap Banner
echo "Banner Injected (banner):" . AD_BANNER . "\r\n";
return AdFactory::Markup(AD_BANNER);
break;
case AD_POS_SIBLINGS:
echo "Banner Injected (rect):" . AD_RECTANGLE . "\r\n";
//Pick an Ad Rectangle
return AdFactory::Markup(AD_RECTANGLE);
break;
default:
return "";
break;
}
} else
return "";
} else
return "";
}
}
instanceof is a language construct which is so essential to PHP that it is de facto impossible not to work properly.
The code you provided is not enough to tell where the issue might be happening.
Chances are, you have a folder not readable on your online server and simply get somewhere a null value instead of an expected object along your code. Ask yourself: "If it is not the object I expect, what else is it?"
Use var_dump() or printf() to investigate what your variables actually contain and you will find the error soon.
For your code, PHPUnit tests would be a benefit, or at least the use of assert() here and there in your code.
Turns out there was a bug in 1 of the API calls I was making to the Processwire CMS.
$ad = wire(pages)->get("/ads/")->children->getRandom();
And my local and server instance of Processwire was not the same version, which was news to me. I normally have it synchronised, including any modules I use.
I also suspect my null check is not correct PHP, to add to the problem.
It has to do with namespaces used in the code:
Locally (Code with no namespaces) I used this, working fine:
if ($xmlornot instanceof SimpleXMLElement) { }
But on the server (code with namespaces) only this worked:
if ($xmlornot instanceof \SimpleXMLElement) { }
See also this question/answer: instanceof operator returns false for true condition

BigQuery: Encountered an error while globbing file pattern

I queried a federated table with data in Google spreadsheet. Following recommendations in issue 720
https://code.google.com/p/google-bigquery/issues/detail?id=720
I've created following code:
Set<String> scopes = new HashSet<>();
scopes.add(BigqueryScopes.BIGQUERY);
scopes.add("https://www.googleapis.com/auth/drive");
scopes.add("https://www.googleapis.com/auth/spreadsheets");
final HttpTransport transport= new NetHttpTransport();
final JsonFactory jsonFactory= new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(transport).setJsonFactory(jsonFactory)
.setServiceAccountId(GC_CREDENTIALS_ACCOUNT_EMAIL)
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKey(getPrivateKey())
.build();
String omgsql = "SELECT * FROM [<myproject>:<mydataset>.failures] LIMIT 1000";
JobReference jobIdomg = startQuery(bigquery, "<myproject>", omgsql);
// Poll for Query Results, return result output
Job completedJobomg = checkQueryResults(bigquery, "<myproject>", jobIdomg);
GetQueryResultsResponse queryResultomg = bigquery.jobs()
.getQueryResults(
"<myproject>", completedJobomg
.getJobReference()
.getJobId()
).execute();
List<TableRow> rowsomg = queryResultomg.getRows();
Without https://www.googleapis.com/auth/drive scope job fails immediately after inserting, with it - fails on completion.
Inserting Query Job: SELECT * FROM [<myproject>:<mydataset>.failures] LIMIT 1000
Job ID of Query Job is: job_S3-fY5jrb4P3UhVgNGeRkDYQofg
Job status (194ms) job_S3-fY5jrb4P3UhVgNGeRkDYQofg: RUNNING
Job status (1493ms) job_S3-fY5jrb4P3UhVgNGeRkDYQofg: RUNNING
Job status (2686ms) job_S3-fY5jrb4P3UhVgNGeRkDYQofg: RUNNING
...
Job status (29881ms) job_S3-fY5jrb4P3UhVgNGeRkDYQofg: DONE
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"location" : "/gdrive/id/1T4qNgi9vFJF4blK4jddYf8XlfT6uDiqNpTExWf1NMyY",
"locationType" : "other",
"message" : "Encountered an error while globbing file pattern.",
"reason" : "invalid"
} ],
"message" : "Encountered an error while globbing file pattern."
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
So the question here - what else am I missing? Or is it just a bigquery bug?
Ok, after a day of experiments - the account you are using to obtain Google Credential should have access to the file(s) on which external table is created. Hope this will help someone.

yii2 fixtures doesn't work properly

I have a problem with fixtures in yii2 , I just created all required file according to this document but it's not working.
let me explain , I have a module called Authyii and inside this module I have a model named User .
this is my directory structure :
my fixture file is like this :
namespace app\modules\Authyii\tests\fixtures;
use app\modules\Authyii\models;
use yii\test\ActiveFixture;
use yii\test\Fixture;
class UserFixture extends ActiveFixture
{
public $modelClass = 'app\modules\Aythyii\models\User';
public $tableName = 'authyii_user';
}
this is my command line :
but after I type 'yes' and command line says :
but when I check my database there is not new record inside authyii_user tables .
what I missed ?
File User.php id data dir must have table name authyii_user.php. In framework source code in file ActiveFixture.php line with code:
$dataFile = dirname($class->getFileName()) . '/data/'
. $this->getTableSchema()->fullName . '.php';
Best regards.
There is method getFixturesConfig() in \vendor\yiisoft\yii2\console\controllers\FixtureController.php
private function getFixturesConfig($fixtures)
{
$config = [];
foreach ($fixtures as $fixture) {
$isNamespaced = (strpos($fixture, '\\') !== false);
$fullClassName = $isNamespaced ? $fixture . 'Fixture' : $this->namespace . '\\' . $fixture . 'Fixture';
if (class_exists($fullClassName)) { // <<< I think you lose your UserFixture here
$config[] = $fullClassName;
}
}
return $config;
}
You should check what $fullClassName Yii expects it to be (for example logging or echoing it) and tweak your UserFixture's namespace accordingly.

Calling a Metro based Security Token Service from an Axis2 STS Client

I want to call a Security Token Service which was created and deployed using Metro 2.2 framework from an Axis 2 STS Client. I'm trying to do the same but getting issues like the one below: -
java.lang.RuntimeException:Incorrect inclusion value: -1
I went deep into the source code and saw that in SecureConversationTokenBuilder class code is wriiten something like this:-
String inclusionValue = attribute.getAttributeValue().trim();
conversationToken.setInclusion(SP11Constants.getInclusionFromAttributeValue(inclusionValue));
then I went into the SP11Constants.getInclusionFromAttributeValue(inclusionValue) and saw the following piece of code:-
public static int getInclusionFromAttributeValue(String value ) {
if (INCLUDE_ALWAYS.equals(value)) {
return SPConstants.INCLUDE_TOEKN_ALWAYS;
} else if (INCLUDE_ALWAYS_TO_RECIPIENT.equals(value)) {
return SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT;
} else if (INCLUDE_NEVER.equals(value)) {
return SPConstants.INCLUDE_TOKEN_NEVER;
} else if (INCLUDE_ONCE.equals(value)) {
return SPConstants.INCLUDE_TOKEN_ONCE;
} else {
return -1;
}
}
as INCLUDE_ALWAYS = "http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/Always" which is not equal to what is defined by metro in policy.xml like
http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/Always
Therefore the above code always return -1 and in turn throws a runtime exception as below:-
public void setInclusion(int inclusion) {
if(SPConstants.INCLUDE_TOEKN_ALWAYS == inclusion ||
SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == inclusion ||
SPConstants.INCLUDE_TOEKN_ALWAYS_TO_INITIATOR == inclusion ||
SPConstants.INCLUDE_TOKEN_NEVER == inclusion ||
SPConstants.INCLUDE_TOKEN_ONCE == inclusion ) {
this.inclusion = inclusion;
} else {
//TODO replace this with a proper (WSSPolicyException) exception
throw new RuntimeException("Incorrect inclusion value: " + inclusion);
}
}
Just wanted to know whether it is possible to get token from Security Token Service (STS) created in Metro Framework invoked from an Axis2 based STS Client.Please advise as I'm stuck in between.
Thanks in advance.