I am using android aws dependency com.amazonaws:aws-android-sdk-s3:2.6.+
While uploading Image getting error as bellow
com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied
(Service: Amazon S3; Status Code: 403; Error Code: AccessDenied;
Request ID: XXXXXXXXXXX), S3 Extended Request ID:XXXXXXXXXXXX
Here is the Code for uploading Image
private void beginUpload(String filePath, final String mediaCaption,
Message message,boolean isThumb,final
UploadFileToStorageCompletionListener listener) {
getLogger().log(Strings.TAG, "########## 3: " + filePath);
//construct a bucket path
final String fullBucketPath =
constructBucketPath(message.getMediaType(), message.getId(),
isThumb);
File file = new File(filePath);
mObserver = mTransferUtility.upload(fullBucketPath, mediaCaption,
file);
mObserver.setTransferListener(new TransferListener() {
#Override
public void onStateChanged(int id, TransferState state) {
getLogger().log(Strings.TAG," onStateChanged() " + state);
if (state.equals(TransferState.COMPLETED)) {
listener.onUploadSuccess(fullBucketPath);
}
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
getLogger().log(Strings.TAG,"onProgressChanged() " + bytesCurrent + "/" + bytesTotal);
dismissProgressDialog();
}
#Override
public void onError(int id, Exception ex) {
listener.onDatabaseError(new FirebaseFailure(ex));
getLogger().log(Strings.TAG, "onError() " + ex.getMessage());
}
});
}
First, need to check the permissions for the s3 bucket. And go to the bucket policy and check the json object which is permissions for put, get and post.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:PutObject",
"s3:GetObject"
],
"Resource": "arn:aws:s3:::{FILE NAME}/*"
}
]
}
Try the above permissions.
You need to check whether the user [ Access Key & Secret Key ] for the current configs you are using has the permission to use the S3. You can check the detail information, or goto your IAM for changing permissions, for detail regarding IAM visit this
For the starter try with S3 Full Access
Hope this helps
Related
Hello i have create an RDS on AWS, and created a policy
with this permission based on this link
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"rds-db:connect"
],
"Resource": [
"arn:aws:rds-db:us-east-2:1234567890:dbuser:db-ABCDEFGHIJKL01234/db_user"
]
}
]
}
I've have a general user that defined with a spesific password
i tried login with the user but instead of the password i tried to set
auth token link in this guide
private static Properties setMySqlConnectionProperties() {
Properties mysqlConnectionProperties = new Properties();
mysqlConnectionProperties.setProperty("verifyServerCertificate","true");
mysqlConnectionProperties.setProperty("useSSL", "true");
mysqlConnectionProperties.setProperty("user",DB_USER);
mysqlConnectionProperties.setProperty("password",generateAuthToken());
return mysqlConnectionProperties;
}
public static String generateAuthToken(String region, String hostName, int port, String username) {
RdsIamAuthTokenGenerator generator = RdsIamAuthTokenGenerator.builder()
.credentials(new DefaultAWSCredentialsProviderChain())
.region(region)
.build();
String authToken = generator.getAuthToken(
GetIamAuthTokenRequest.builder()
.hostname(hostName)
.port(port)
.userName(username)
.build());
return authToken;
}
Im using in my case with postgresql
and it result this error
"FATAL: password authentication failed for user \"root\"","error.stack_trace":"org.postgresql.util.PSQLException: FATAL: password authentication failed for user \"root\"
my root user should support with IAM, what can i validate in order to fix it
below you can see from AWS, that my policy is defined
First all i had a bug - i used the db name instead DBI resource ID
This is the expected format:
arn:aws:rds-db:region:account-id:dbuser:DbiResourceId/db-user-name
and here is the code
data "aws_iam_policy_document" "policy_fooweb_job" {
statement {
actions = [
"rds-db:connect"
]
effect = "Allow"
resources = [
"arn:aws:rds-db:${var.region}:${data.aws_caller_identity.current.account_id}:dbuser:${data.aws_db_instance.database.resource_id}/someUser"
]
}
}
## get the db instance
data "aws_db_instance" "database" {
db_instance_identifier = "company-oltp1"
}
I am trying to get some really simple syncing between a couchbase lite mobile app and a couchbase server via a sync gateway. I have gotten the sync gateway to communicate with the server as using curl REST calls towards the gateway will sync with the main server.
However when attempting to sync with couchbase-lite, couchbase-lite simply does not sync.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "LOG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the database (and create it if it doesn’t exist).
DatabaseConfiguration config = new DatabaseConfiguration(getApplicationContext());
Database database = null;
try {
database = new Database("mydb", config);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
// Create a new document (i.e. a record) in the database.
MutableDocument mutableDoc = new MutableDocument()
.setFloat("version", 2.0F)
.setString("type", "SDK");
// Save it to the database.
try {
database.save(mutableDoc);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
// Update a document.
mutableDoc = database.getDocument(mutableDoc.getId()).toMutable();
mutableDoc.setString("language", "Java");
try {
database.save(mutableDoc);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
Document document = database.getDocument(mutableDoc.getId());
// Log the document ID (generated by the database) and properties
Log.i(TAG, "Document ID :: " + document.getId());
Log.i(TAG, "Learning " + document.getString("language"));
// Create a query to fetch documents of type SDK.
Query query = QueryBuilder.select(SelectResult.all())
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("SDK")));
ResultSet result = null;
try {
result = query.execute();
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
Log.i(TAG, "Number of rows :: " + result.allResults().size());
// Create replicators to push and pull changes to and from the cloud.
Endpoint targetEndpoint = null;
try {
targetEndpoint = new URLEndpoint(new URI("ws://10.0.2.2:4984/demobucket"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
ReplicatorConfiguration replConfig = new ReplicatorConfiguration(database, targetEndpoint);
replConfig.setReplicatorType(ReplicatorConfiguration.ReplicatorType.PUSH_AND_PULL);
// Add authentication.
replConfig.setAuthenticator(new BasicAuthenticator("admin", "pass"));
// Create replicator.
Replicator replicator = new Replicator(replConfig);
// Listen to replicator change events.
replicator.addChangeListener(change -> {
if (change.getStatus().getError() != null) {
Log.i(TAG, "Error code :: " + change.getStatus().getError().getCode());
}
});
// Start replication.
replicator.start();
}
}
This code was literally pasted from the couchbase doc site https://docs.couchbase.com/couchbase-lite/current/java.html, yet does not work.
I get the error 11001, which equates to " // Peer has to close, e.g. because host app is quitting" which occurs in the replicator listener.
The sync gateway config file I use is as follows:
{
"interface":":4984",
"logging": {
"log_file_path": "/var/tmp/sglogs",
"console": {
"log_level": "debug",
"log_keys": ["*"]
},
"error": {
"enabled": true,
"rotation": {
"max_size": 20,
"max_age": 180
}
},
"warn": {
"enabled": true,
"rotation": {
"max_size": 20,
"max_age": 90
}
},
"info": {
"enabled": false
},
"debug": {
"enabled": false
}
},
"databases": {
"demobucket": {
"import_docs": "continuous",
"enable_shared_bucket_access":true,
"bucket":"demobucket",
"server": "http://cb-server:8091",
"username": "admin",
"password": "password",
"num_index_replicas":0,
"users":{
"GUEST": {"disabled":true},
"admin": {"password": "password", "admin_channels": ["*"]}
},
"revs_limit":20
}
}
}
#Jay has the answer, in his comment. Replicator replicator is a local variable. As soon as the Activity is stopped, the replicator is eligible for garbage collection. That appears to the peer as if the host was stopping.
JAVA CODE:-
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://sikkimexpress.itstunner.com/api/homenewslist/topnews", new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
for (int i = 0; i<jsonArray.length();i++){
JSONObject homenews = jsonArray.getJSONObject(i) ;
String newsId = homenews.getString("NewsId");
String dateTime = homenews.getString("DateTime");
String newsType = homenews.getString("NewsType");
String title = homenews.getString("Title");
String description = homenews.getString("Description");
String mainImageURL = homenews.getString("MainImageThumbnail");
System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
});
requestQueue.add(jsonObjectRequest);
JSON:-
{
"Status": 0,
"Message": "Sucess"
"HomeNews": [
{
"NewsId": 13,
"DateTime": null,
"NewsType": "latest",
"Title": "Jat quota row: Haryana CM calls all-party meet as stir continues",
"Description": "<p>Jat students block the Rohtak-Delhi road in Rohtak as part of the quota agitation. (Manoj Dhaka/HindustanTimes ). Share. Share. Share.</p>",
"MainImageThumbnail": "http://ste.india.com/sites/default/files/2016/02/19/461939-haryana-jat-protest.jpg",
"ReferenceURL": ""
},
{
"NewsId": 15,
"DateTime": null,
"NewsType": "latest",
"Title": "Sports quiz of the week",
"Description": "<p>Which snooker player competing at the Welsh Open said: \"I get so bored at these tournaments. Maybe they should stick an adult creche here to keep us entertained because I just want to go home now.\r\n\r\n\"Today I've had a haircut, I've been in the Chinese, I've been for a coffee, I went to Bill's cafe for a couple of hours, I've had a kip, I went to Marks' and bought a bit of grub. What a day. It's certainly not glamorous.\"?</p>",
"MainImageThumbnail": "http://news.files.bbci.co.uk/vj/live/idt-images/quizzes-sports_weekly_quiz_week7/Snooker_comp_getty_k4960.jpg",
"ReferenceURL": ""
},
]
}
I want to parse the json but always its coming to the Response.ErrorListener. If the status = 0 and the message is success then the value of NewsId, DateTime, title, description will be retrieve. Can anybody help, please? I take permission of Internet and I check the URL and it's working.
I am able to get correct response. If you are getting error, how about logging
Log.e("VOLLEY", error.getMessage());
One issue might be you are not using correct constructor for JsonObjectRequest. You should ideally use, where for you 3rd argument jsonRequest could be passed as null.
com.android.volley.toolbox.JsonObjectRequest.JsonObjectRequest(int
method, String url, JSONObject jsonRequest, Listener<JSONObject>
listener, ErrorListener errorListener)
Else everything is in workable condition.
How can i get all the uploaded videos from a certain channel?
i know that the GET request is
https://www.googleapis.com/youtube/v3/search?key=key&channelId=UC-9-kyTW8ZkZNDHQJ6FgpwQ&part=snippet,id&order=date&maxResults=20
but I want to use Java Youtube APi (v3)
and when i am trying to do this
try {
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest arg0) throws IOException {}
}).setApplicationName("youtube-cmdline-myuploads-sample").build();
YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
channelRequest.setId("UC-9-kyTW8ZkZNDHQJ6FgpwQ"); //youtube channel id
channelRequest.setKey(key);
channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo");
ChannelListResponse channelResult = channelRequest.execute();
List<Channel> channelsList = channelResult.getItems();
if (channelsList != null) {
String uploadPlaylistId =
channelsList.get(0).getContentDetails().getRelatedPlaylists().getUploads();
System.out.println(uploadPlaylistId);
List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
YouTube.PlaylistItems.List playlistItemRequest =
youtube.playlistItems().list("id,contentDetails,snippet");
playlistItemRequest.setPlaylistId(uploadPlaylistId);
playlistItemRequest.setFields(
"items(contentDetails/videoId,snippet/title,snippet/publishedAt),nextPageToken,pageInfo");
String nextToken = "";
do {
playlistItemRequest.setPageToken(nextToken);
PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
playlistItemList.addAll(playlistItemResult.getItems());
nextToken = playlistItemResult.getNextPageToken();
} while (nextToken != null);
printVideos(playlistItemList.size(), playlistItemList.iterator());
}
} catch (GoogleJsonResponseException e) {
e.printStackTrace();
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
Im getting forbidden 403 . what am i doing wrong?
"code" : 403,
"errors" : [ {
"domain" : "usageLimits",
"message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"reason" : "dailyLimitExceededUnreg",
"extendedHelp" : "https://code.google.com/apis/console"
} ],
"message" : "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
That error seems perfectly descriptive. You are not authenticating your request, so from Youtube's perspective, you are attempting to call this API too frequently while not logged in.
If you sign your request with real credentials of a valid Youtube account you should be fine.
I'm stuck trying to send JSON data to by Struts2 REST server using the struts2-rest-plugin.
It works with XML, but I can't seem to figure out the right JSON format to send it in.
Anybody has any experience with this?
Thanks,
Shaun
Update:
Sorry I wasn't clear. The problem is that Struts2 doesn't seem to be mapping the JSON data I send in to my model in the controller.
Here's the code:
Controller:
public class ClientfeatureController extends ControllerParent implements ModelDriven<Object> {
private ClientFeatureService clientFeatureService;
private ClientFeature clientFeature = new ClientFeature();
private List<ClientFeature> clientFeatureList;
//Client ID
private String id;
public ClientfeatureController() {
super(ClientfeatureController.class);
}
#Override
public Object getModel() {
return (clientFeatureList != null ? clientFeatureList : clientFeature);
}
/**
* #return clientFeatureList through Struts2 model-driven design
*/
public HttpHeaders show() {
//logic to return all client features here. this works fine..
//todo: add ETag and lastModified information for client caching purposes
return new DefaultHttpHeaders("show").disableCaching();
}
// PUT request
public String update() {
logger.info("client id: " + clientFeature.getClientId());
logger.info("clientFeature updated: " + clientFeature.getFeature().getDescription());
return "update";
}
public HttpHeaders create() {
logger.info("client id: " + clientFeature.getClientId());
logger.info("feature description: " + clientFeature.getFeature().getDescription());
return new DefaultHttpHeaders("create");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setClientFeatureService(ClientFeatureService clientFeatureService) {
this.clientFeatureService = clientFeatureService;
}
public List<ClientFeature> getClientFeatureList() {
return clientFeatureList;
}
public void setClientFeatureList(List<ClientFeature> clientFeatureList) {
this.clientFeatureList = clientFeatureList;
}
public ClientFeature getClientFeature() {
return clientFeature;
}
public void setClientFeature(ClientFeature clientFeature) {
this.clientFeature = clientFeature;
}
}
This is the URL I'm making the request to:
..http://localhost:8080/coreserviceswrapper/clientfeature.json
-Method: POST or PUT (tried both, POST maps to create() and PUT maps to update())
-Header: Content-Type: application/json
Payload:
{"clientFeature":{
"feature": {
"id": 2,
"enabled": true,
"description": "description1",
"type": "type1"
},
"countries": ["SG"],
"clientId": 10}
}
And the output in the Struts2 logs when I make the request:
1356436 [http-bio-8080-exec-5] WARN net.sf.json.JSONObject - Tried to assign property clientFeature:java.lang.Object to bean of class com.foo.bar.entity.ClientFeature
1359043 [http-bio-8080-exec-5] INFO com.foo.bar.rest.ClientfeatureController - client id: null
Let me also add that XML requests work just fine:
URL: ..http://localhost:8080/coreserviceswrapper/clientfeature.xml
Method: POST/PUT
Content-Type: text/xml
Payload:
<com.foo.bar.entity.ClientFeature>
<clientId>100</clientId>
<feature>
<description>test</description>
</feature>
</com.foo.bar.entity.ClientFeature>
Output:
1738685 [http-bio-8080-exec-7] INFO com.foo.bar.rest.ClientfeatureController - client id: 100
1738685 [http-bio-8080-exec-7] INFO com.foo.bar.rest.ClientfeatureController - feature description: test
1738717 [http-bio-8080-exec-7] INFO org.apache.struts2.rest.RestActionInvocation - Executed action [/clientfeature!create!xml!200] took 1466 ms (execution: 1436 ms, result: 30 ms)
I also encounter same issue, my environment is:
Structs 2.3.16.3, Jquery 1.11, Struts-rest-plugin
symptom: post json data, rest controller not parse json data to model.
solution:
since the controller is modeldriven, browser client just post Json string is OK. but seems you have to force jquery to change conenttype of ajax call.
_self.update= function(model, callback) {
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: 'PUT',
url: this.svrUrl+"/"+ model.id + this.extension,
data: JSON.stringify(model), // '{"name":"' + model.name + '"}',
//contentType: this.contentType,
//dataType: this.dataType,
processData: false,
success: callback,
error: function(req, status, ex) {},
timeout:60000
});
};
the model data format is :
var model = {"id":"2",
"name":"name2",
"author":"author2",
"key":"key2"
}
when you put or post data whit "Content-Type"="application/json", the plugin will handle it with Jsonhandler automatically.
I got such a problem. Strange but got solved by changing the name 'clientFeature' to 'model'