Response code Null (0) today, app was working yesterday (API Integration) - asana

I have integrated Asana task lists into my company's website for our development team. All was going well until today - the page I created now errors out with a response code of NULL (or 0). In my very limited experience, this is an issue with the Asana connection, correct? Is this something I can fix on my side or is Asana API currently down (considering this worked up until today)?
We are using the API key, not OAuth, as everyone who has access to this task list is on the same workspace.
Edit:
I have 2 api keys that I am working with - 1 for production, 1 for development. I switch them out when I hand over a branch for my boss to merge in.
Testing API key works just fine.
Production API key does not work - always a response code null when trying to pull back tasks.
I am brand new to API development and I do not know how to use curl to make these calls. I am using a library found here:
https://github.com/ajimix/asana-api-php-class/blob/master/asana.php
More specifically, here is my code:
/*
* We are only interested in the JVZoo workspace
* Unless we are testing, in which we will use Faith In Motion workspace
*/
$JVZ_workspace_id = 18868754507673;
$FIM_workspace_id = 47486153348950;
/*
* Which one are we using right now?
*/
$workspace = $FIM_workspace_id;
/*
* Now lets do the same thing with Projects
* There should only be one project - JVZoo.com
* Unless we are testing - More JVZoo Testing
*
* We do need to dynamically show the project name
* This will help on confusion if we are accidently in the
* wrong project
*
* Then start building an array with these pieces
*/
$JVZ_project = array();
$JVZ_project['id'] = 53244927972665;
$JVZ_project['name'] = "JVZoo.com";
$FIM_project = array();
$FIM_project['id'] = 54787074465868;
$FIM_project['name'] = "More JVZoo Testing";
/*
* Which one are we using?
*/
$project = $FIM_project;
/*
* In order to help reduce load time even more,
* we are not going to return the project name
*
* This way we do not need to ask Asana for the project information
* This does change the layout of the view, however
*
* And finally grab all tasks for each project
* Connection check
*
* Return all tasks from this workspace and hand-filter
* to show both assigned and followed tasks
*/
$tasksJson = $asana->getProjectTasks($project['id']);
if ($asana->responseCode != '200' || is_null($tasksJson))
{
$this->session->set_flashdata('error', 'Error while trying to get tasks from Asana, response code: ' . $asana->responseCode);
redirect_and_continue_processing('/dashboard');
return;
}
FIM is my test environment.
JVZ is my production environment.
/**
* Returns all unarchived tasks of a given project
*
* #param string $projectId
* #param array $opt Array of options to pass
* (#see https://asana.com/developers/documentation/getting-started/input-output-options)
*
* #return string JSON or null
*/
public function getProjectTasks($projectId, array $opts = array())
{
$options = http_build_query($opts);
return $this->askAsana($this->taskUrl . '?project=' . $projectId . '&' . $options);
}
I did a PR on the parameter passed in to line that is returned above. In my FIM environment, I get this:
https://app.asana.com/api/1.0/tasks?project=54787074465868&
For my production environment:
https://app.asana.com/api/1.0/tasks?project=53244927972665&

Related

Is there any way to run perticular scenario in karate more than one time if specific condition met true?

I want to run my perticular scenario or feature file more than one time.
Let's say if user enter 5 then i want my url to be hit 5 times.
is it possible in karate? Any help would be appreciated
Yes, read the docs: https://github.com/intuit/karate#loops
But also see example below using dynamic scenario outlines:
EDIT: using a Background will not work in Karate 1.3.0 onwards, please refer to this example: https://stackoverflow.com/a/75155712/143475
Background:
* def fun = function(i){ return { name: 'User ' + (i + 1) } }
* def data = karate.repeat(5, fun)
Scenario Outline:
* url 'http://httpbin.org/anything'
* request __row
* method post
Examples:
| data |
So run this, see how it works and study how it works as well.
Note that data driven features is an alternate approach where you can call a second feature file in a loop. So for example after using karate.repeat() 5 times like in the above Background, you use data as the argument to a second feature file that hits your url.

API to publish articles on Joomla and Drupal

Do Joomla and Drupal provide any kind of APIs to publish articles?
I have Ruby on Rails application for content authoring and need to publish articles to different sites which are runs on Joomla and Drupal.
It can be done via for example a CLI script running on a Joomla site using the articles Model.
One suggestion would be to publish an RSS or XML feed that you can then import periodically via a Joomla CLI script. An example CLI script is given below. Points to note:
In the below example data is imported from a CSV file you would have to modify this for whatever your data source is.
The catid is hardcoded - you may wish to post your articles to different categories in which case you would need to do more work to potentially look up category IDs.
It doesn't include tags etc
Is only a solution for Joomla not Drupal
I could go on but this is a Q&A site not a consultancy opportunity...;-)
<?php
/**
* #package Joomla.Cli
*
* #copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE.txt
*/
// Initialize Joomla framework
const _JEXEC = 1;
// Load system defines
if (file_exists(dirname(__DIR__) . '/defines.php'))
{
require_once dirname(__DIR__) . '/defines.php';
}
if (!defined('_JDEFINES'))
{
define('JPATH_BASE', dirname(__DIR__));
require_once JPATH_BASE . '/includes/defines.php';
}
// Get the framework.
require_once JPATH_LIBRARIES . '/import.legacy.php';
// Bootstrap the CMS libraries.
require_once JPATH_LIBRARIES . '/cms.php';
/**
* Cron job to import data into articles
*
* #since 2.5
*/
class ImportArticlesCron extends JApplicationCli
{
/**
* Entry point for the script
*
* #return void
*
* #since 2.5
*/
public function doExecute()
{
// Import articles model
JControllerForm::addModelPath(JPATH_ADMINISTRATOR . '/components/com_content/models');
// Get an instance of the content model
$model = $this->getModel('Article', 'ContentModel');
// This example is using a csv file but there's no reason you couldn't import an XML file here
while (($line = fgetcsv($handle, 0, $delimiter = '|')) !== FALSE)
{
$data = array();
$data['introtext'] = '';
$data['fulltext'] = $output;
$data['id'] = '';
$data['state'] = ($line[1] == 'True') ? 1 : 0;
$data['title'] = iconv("ISO-8859-1", "UTF-8//TRANSLIT", $line[3]);
$data['created'] = $line[2];
$data['catid'] = 38;
$data['language'] = 'en-GB';
$data['metadesc'] = '';
$data['metakey'] = '';
//$data['publish_up'] = date('Y-m-d', strtotime($line[14]));
//$data['publish_down'] = date('Y-m-d', strtotime($line[15]));
$model = $this->getModel('Article', 'ContentModel');
if (!$model->save($data))
{
$error = $model->getError();
}
}
}
}
JApplicationCli::getInstance('ImportArticlesCron')->execute();
?>
The answer to the question for Joomla is no, there's no web API to publish articles from remote.
I never had to implement such a solution so I don't have a proven answer.
Being a developer, my first thought would be to build a custom API component.
Maybe, before that, I would look into the JED to see if someone already did it.

Parse a report with powershell

I'm trying to gather some statistics using powershell.
I have about 4,000 reports that look like this (all in their own Report.txt files - some have more fields. I've sniped it):
What I would like to do (thinking out loud) is take each [ ] and make that a csv header and then add each item under that header under it. Then I can run simple count statements against it and pull out some data. Maybe there is a better/easier way?
The idea is to have some like:
Requested Permissions: android.permission.INTERNET 3,562 of 4,000
Requested Permissions: android.permission.READ_SMS 1 of 4,000
etc...
So far i've stripped down the string so it no longer has white spaces and *.
[ Package name ]
* com.software.application
[ Requested Permissions ]
* android.permission.INTERNET
* android.permission.READ_PHONE_STATE
* android.permission.READ_SMS
* android.permission.RECEIVE_SMS
* android.permission.SEND_SMS
* android.permission.WAKE_LOCK
* android.permission.WRITE_EXTERNAL_STORAGE
* com.google.android.c2dm.permission.RECEIVE
* com.software.application.permission.C2D_MESSAGE
[ Responsible API calls for used Permissions ]
* android/app/NotificationManager;->notify
* android/content/Context;->sendBroadcast
* android/content/Context;->startService
* android/os/PowerManager$WakeLock;->acquire
* android/os/PowerManager$WakeLock;->release
* android/telephony/SmsManager;->sendTextMessage
[ Potentially dangerous Calls ]
* getSystemService
* HttpPost
* sendSMS
Current output example:
[PotentiallydangerousCalls]
getSystemService
HttpPost
sendSMS
So it's a bit cleaner now...
I will put some code if I have time, but here is a roadbook :
1) Write a function (CsvToObject) that take the path and name of a csv file and return a PSObject with a property with each [value]
This function can take advantage of switch ... case PowerShell structure with regex and file usage.
2) Take every *.csv file (Get-ChildItem) , call your function and pipe the result in Export-CSV
Your current output example is structured like an ini file. This Scripting Guy post on ini files might be useful. Some regex help here and here.

How to implement pagination when using amazon Dynamo DB in rails

I want to use amazon Dynamo DB with rails.But I have not found a way to implement pagination.
I will use AWS::Record::HashModel as ORM.
This ORM supports limits like this:
People.limit(10).each {|person| ... }
But I could not figured out how to implement following MySql query in Dynamo DB.
SELECT *
FROM `People`
LIMIT 1 , 30
You issue queries using LIMIT. If the subset returned does not contain the full table, a LastEvaluatedKey value is returned. You use this value as the ExclusiveStartKey in the next query. And so on...
From the DynamoDB Developer Guide.
You can provide 'page-size' in you query to set the result set size.
The response of DynamoDB contains 'LastEvaluatedKey' which will indicate the last key as per the page size. If response does't contain 'LastEvaluatedKey' it means there are no results left to fetch.
Use the 'LastEvaluatedKey' as 'ExclusiveStartKey' while fetching next time.
I hope this helps.
DynamoDB Pagination
Here's a simple copy-paste-run proof of concept (Node.js) for stateless forward/reverse navigation with dynamodb. In summary; each response includes the navigation history, allowing user to explicitly and consistently request either the next or previous page (while next/prev params exist):
GET /accounts -> first page
GET /accounts?next=A3r0ijKJ8 -> next page
GET /accounts?prev=R4tY69kUI -> previous page
Considerations:
If your ids are large and/or users might do a lot of navigation, then the potential size of the next/prev params might become too large.
Yes you do have to store the entire reverse path - if you only store the previous page marker (per some other answers) you will only be able to go back one page.
It won't handle changing pageSize midway, consider baking pageSize into the next/prev value.
base64 encode the next/prev values, and you could also encrypt.
Scans are inefficient, while this suited my current requirement it won't suit all!
// demo.js
const mockTable = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
const getPagedItems = (pageSize = 5, cursor = {}) => {
// Parse cursor
const keys = cursor.next || cursor.prev || [] // fwd first
let key = keys[keys.length-1] || null // eg ddb's PK
// Mock query (mimic dynamodb response)
const Items = mockTable.slice(parseInt(key) || 0, pageSize+key)
const LastEvaluatedKey = Items[Items.length-1] < mockTable.length
? Items[Items.length-1] : null
// Build response
const res = {items:Items}
if (keys.length > 0) // add reverse nav keys (if any)
res.prev = keys.slice(0, keys.length-1)
if (LastEvaluatedKey) // add forward nav keys (if any)
res.next = [...keys, LastEvaluatedKey]
return res
}
// Run test ------------------------------------
const runTest = () => {
const PAGE_SIZE = 6
let x = {}, i = 0
// Page to end
while (i == 0 || x.next) {
x = getPagedItems(PAGE_SIZE, {next:x.next})
console.log(`Page ${++i}: `, x.items)
}
// Page back to start
while (x.prev) {
x = getPagedItems(PAGE_SIZE, {prev:x.prev})
console.log(`Page ${--i}: `, x.items)
}
}
runTest()
I faced a similar problem.
The generic pagination approach is, use "start index" or "start page" and the "page length". 
The "ExclusiveStartKey" and "LastEvaluatedKey" based approach is very DynamoDB specific.
I feel this DynamoDB specific implementation of pagination should be hidden from the API client/UI.
Also in case, the application is serverless, using service like Lambda, it will be not be possible to maintain the state on the server. The other side is the client implementation will become very complex.
I came with a different approach, which I think is generic ( and not specific to DynamoDB)
When the API client specifies the start index, fetch all the keys from
the table and store it into an array.
Find out the key for the start index from the array, which is
specified by the client.
Make use of the ExclusiveStartKey and fetch the number of records, as
specified in the page length.
If the start index parameter is not present, the above steps are not
needed, we don't need to specify the ExclusiveStartKey in the scan
operation.
This solution has some drawbacks -
We will need to fetch all the keys when the user needs pagination with
start index.
We will need additional memory to store the Ids and the indexes.
Additional database scan operations ( one or multiple to fetch the
keys )
But I feel this will be very easy approach for the clients, which are using our APIs. The backward scan will work seamlessly. If the user wants to see "nth" page, this will be possible.
In fact I faced the same problem and I noticed that LastEvaluatedKey and ExclusiveStartKey are not working well especially when using Scan So I solved Like this.
GET/?page_no=1&page_size=10 =====> first page
response will contain count of records and first 10 records
retry and increase number of page until all record come.
Code is below
PS: I am using python
first_index = ((page_no-1)*page_size)
second_index = (page_no*page_size)
if (second_index > len(response['Items'])):
second_index = len(response['Items'])
return {
'statusCode': 200,
'count': response['Count'],
'response': response['Items'][first_index:second_index]
}

solr sanitizing query

I am using solr with ruby on rails.
It's all working well, I just need to know if there's any existing code to sanitize user input, like a query starting with ? or *
I don't know any code that does this, but theoretically it could be done by looking at the parsing code in Lucene and searching for throw new ParseException (only 16 matches!).
In practice, I think you're better off just catching any solr exceptions in your code and showing an "invalid query" message or something like that.
EDIT: Here are a couple of "sanitizers":
http://pivotallabs.com/users/zach/blog/articles/937-sanitizing-solr-requests
http://github.com/jvoorhis/lucene_query
http://e-mats.org/2010/01/escaping-characters-in-a-solr-query-solr-url/
If you are using Solarium with PHP then you can use the Solarium_Escape::term() method.
/**
* Escape a term
*
* A term is a single word.
* All characters that have a special meaning in a Solr query are escaped.
*
* If you want to use the input as a phrase please use the {#link phrase()}
* method, because a phrase requires much less escaping.\
*
* #link http://lucene.apache.org/java/docs/queryparsersyntax.html#Escaping%20Special%20Characters
*
* #param string $input
* #return string
*/
static public function term($input)
{
$pattern = '/(\+|-|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';
return preg_replace($pattern, '\\\$1', $input);
}

Resources