AccessControlException while trying to create a directory on Azure - java

I'm trying this to Create Directory in azureDataLake using azure data lake dependency
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-data-lake-store-sdk</artifactId>
<version>2.1.5</version>
</dependency>
Using the following method:
private ADLStoreClient client;
public boolean createDirectory(String path) {
try {
// create directory
client.createDirectory(path);
} catch (ADLException ex) {
printExceptionDetails(ex);
return false;
} catch (Exception ex) {
log.error(" Exception in createDirectory : {}", ex);
return false;
}
return true;
}
and I got this exception:
Error creating directory /gx-zweappdhd004/home/azhdipaasssh2/ADH/Compta/1458/1533632735200/RAPPORTS/
Operation MKDIRS failed with HTTP403 : AccessControlException
I checked the permission and I have all of them, so it's not related to the permissions.
Update:
To be more specefic the problem happening inside the method isSuccessfulResponse(), and exactlly in this line HttpTransport.java#L137 because the httpResponseCode equals to 403, can anybody explain this.
Update2:
I found that this line is returning the 403 status : HttpTransport.java#L288, I also tried to evaluate conn.getErrorStream().read() and I got this stream is closed, FYI this is bug occures sometimes and not always.

I didn't reproduce your issue,you could refer to my working code:
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
import com.microsoft.azure.datalake.store.ADLStoreClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CreateDirectory {
static ADLStoreClient client;
public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
setup();
}
public static void setup() throws IOException, ExecutionException, InterruptedException {
String APP_ID = "<your app id>";
String APP_SECRET = "<your app secret>";
String dirName = "/jay";
String StoreAcct = "jaygong";
String authority = "https://login.microsoftonline.com/<your tenant id>";
String resourcUrl = "https://management.core.windows.net/";
ExecutorService service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authority, true, service);
// Acquire Token
Future<AuthenticationResult> result = context.acquireToken(
resourcUrl,
new ClientCredential(APP_ID, APP_SECRET),
null
);
String token = result.get().getAccessToken();
System.out.println(token);
String account = StoreAcct + ".azuredatalakestore.net";
client = ADLStoreClient.createClient(account, token);
client.createDirectory(dirName);
System.out.println("finish.....");
}
}
Don't forget grant access ADL permissons to your client.
Hope it helps you.

Related

Zookeeper connection in java

The below code(not mine) is supposed to check the connection status of a zookeeper by using the znode_exists() method. I want to use it at a producerAPI before a message publish. But i am getting an error at defining the ZooKeeperConnection object. I have added the possible classes and libraries.
import java.io.IOException;
//import org.apache.zookeeper.*; adding this doesn't help
import org.apache.zookeeper.ZooKeeperMain;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.data.Stat;
public class ZKExists {
private static ZooKeeper zk;
private static ZooKeeperConnection conn; // Object cannot be resolve to a type
// Method to check existence of znode and its status, if znode is available.
public static Stat znode_exists(String path) throws
KeeperException,InterruptedException {
return zk.exists(path, true);
}
public static void main(String[] args) throws InterruptedException,KeeperException {
String path = "/Znode_path"; // Assign znode to the specified path
try {
ZooKeeperConnection conn = new ZooKeeperConnection();
zk = conn.connect("localhost");
Stat stat = znode_exists(path); // Stat checks the path of the znode
if(stat != null) {
System.out.println("Node exists and the node version is " +
stat.getVersion());
} else {
System.out.println("Node does not exists");
}
} catch(Exception e) {
System.out.println(e.getMessage()); // Catches error messages
}
}
}
Which library am i missing to make the object valid ?

how calling a person vi asterisk-java

I created in manager.conf a user manager named : mark , in "sip.conf" user named "utilisateur"
i want to call user : "utilisateur" via Asterisk-java , i tried this code :
import java.io.IOException;
import org.asteriskjava.manager.AuthenticationFailedException;
import org.asteriskjava.manager.ManagerConnection;
import org.asteriskjava.manager.ManagerConnectionFactory;
import org.asteriskjava.manager.TimeoutException;
import org.asteriskjava.manager.action.OriginateAction;
import org.asteriskjava.manager.response.ManagerResponse;
public class HelloManager
{
private ManagerConnection managerConnection;
public HelloManager() throws IOException
{
ManagerConnectionFactory factory = new ManagerConnectionFactory(
"localhost", "mark", "1234");
this.managerConnection = factory.createManagerConnection();
}
public void run() throws IOException, AuthenticationFailedException,
TimeoutException
{
OriginateAction originateAction;
ManagerResponse originateResponse;
originateAction = new OriginateAction();
originateAction.setChannel("SIP/utilisateur");
originateAction.setContext("default");
originateAction.setExten("2222");
originateAction.setPriority(new Integer(1));
originateAction.setTimeout(new Integer(30000));
// connect to Asterisk and log in
managerConnection.login();
// send the originate action and wait for a maximum of 30 seconds for Asterisk
// to send a reply
originateResponse = managerConnection.sendAction(originateAction, 30000);
// print out whether the originate succeeded or not
System.out.println(originateResponse.getResponse());
// and finally log off and disconnect
managerConnection.logoff();
}
public static void main(String[] args) throws Exception
{
HelloManager helloManager;
helloManager = new HelloManager();
helloManager.run();
}
}
And in extension.conf i added this extension :
[default]
exten => 2222,1,Dial(SIP/utilisateur)
exten => 2222,2,Answer
and i get this error fromasterisk server so could somone help me :
Exception in thread "main" org.asteriskjava.manager.TimeoutException: Timeout waiting for response to Originate
at org.asteriskjava.manager.internal.ManagerConnectionImpl.sendAction(ManagerConnectionImpl.java:809)
at org.asteriskjava.manager.DefaultManagerConnection.sendAction(DefaultManagerConnection.java:289)
at HelloManager.run(HelloManager.java:40)
at HelloManager.main(HelloManager.java:54)
You are not setting the number to call in the outbound caller.
originateAction.setCallerId(<phonenumber>);

I tried to make connection for Google BigQuery in java, and get following error?

//error-
Not Found
Exception in thread "main" com.google.api.client.http.HttpResponseException: 404 Not Found
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:209)
at BigQuerySample.main(BigQuerySample.java:25) */
// this is my code
import com.google.api.client.googleapis.*;
import com.google.api.client.googleapis.auth.clientlogin.*;
import com.google.api.client.googleapis.json.*;
import com.google.api.client.http.*;
import java.io.IOException;
public class BigQuerySample {
public static void main(String[] args) throws IOException {
HttpTransport transport = GoogleTransport.create();
transport.addParser(new JsonCParser());
try {
// authenticate with ClientLogin
ClientLogin authenticator = new ClientLogin();
authenticator.authTokenType = "ndev";
authenticator.username = "*********#gmail.com";
authenticator.password = "**********";
authenticator.authenticate().setAuthorizationHeader(transport);
// make query request
HttpRequest request = transport.buildGetRequest();
request.setUrl("https://www.googleapis.com/bigquery/v1/query");
request.url.put("q","SELECT TOP(word, 50), COUNT(*) FROM publicdata:samples.shakespeare");
System.out.println(request.execute().parseAsString());
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
}
}
You're querying a URL that doesn't exist. Going to that URL returns "Not Found" which is what the exception is telling you. Use a valid URL and then see if your code works (there may be absolutely nothing wrong with your code).
Google BigQuery doesn't support ClientLogin auth. Where did you get that sample?

How to call Fedora Commons findObjects method (web service)

I'm trying to make a search through the Fedora Commons web service. I'm interested in the findObjects method. How can I make a search in Java equal to the example described on the findObjects syntax documentation.
I'm particularly interested in this type of request:
http://localhost:8080/fedora/search?terms=fedora&pid=true&title=true
I'll attach some code, I have a class that can call my Fedora service already.
package test.fedora;
import info.fedora.definitions._1._0.types.DatastreamDef;
import info.fedora.definitions._1._0.types.MIMETypedStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.w3c.dom.Document;
public class FedoraAccessor {
info.fedora.definitions._1._0.api.FedoraAPIAService service;
info.fedora.definitions._1._0.api.FedoraAPIA port;
final String username = "xxxx";
final String password = "yyyy";
public FedoraAClient() {
service = new info.fedora.definitions._1._0.api.FedoraAPIAService();
port = service.getFedoraAPIAServiceHTTPPort();
((BindingProvider) port.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
public List findObjects() {
//how?
}
public List<DatastreamDef> listDatastreams(String pid, String asOfTime) {
List<DatastreamDef> result = null;
try {
result = port.listDatastreams(pid, asOfTime);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
It's easier using the client from mediashelf (http://mediashelf.github.com/fedora-client/). Here's an example searching for objects containing the string foobar in the title:
#Test
public void doTest() throws FedoraClientException {
connect();
FindObjectsResponse response = null;
response = findObjects().pid().title().query("title~foobar").execute(fedoraClient);
List<String> pids = response.getPids();
List<String> titles = new ArrayList<String>();
for (String pid : pids) {
titles.add(response.getObjectField(pid, "title").get(0));
}
assertEquals(7, titles.size());
}

java getSession().setAttribute() [duplicate]

This question already has answers here:
NullPointerException when setting attribute?
(5 answers)
Closed 7 years ago.
I have to make a litle change to an existing project(tomcat and java WebApplication).
now, in loginForm, if users type correct login and password, it is Ok,
to users wil be shown main page. But when any user types incorrect password,
or may be his account is temporarily locked, so to user again wil be shown loginform,
user can not know why he cannot log in, by what cause he can not login.
(for example "invalid username/password","user account locked",...).
now i want to insert the session error message that includes also causes of why user cannot log in.
insert(save) to session an attribute named "LoggingError".
i am writing as:
request.getSession().setAttribute("LoggingError", message);
but when running application, in this line
request.getSession().setAttribute("LoggingError", message);
occurs error in web page:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
com.se.eee.security.EeeAuthenticationProvider.authenticate(EeeAuthenticationProvider.java:153)
net.sf.acegisecurity.providers.ProviderManager.doAuthentication(ProviderManager.java:159)
net.sf.acegisecurity.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:49)
net.sf.ace
...
...
here java code of EeeAuthenticationProvider.java
package com.se.eee.security;
import net.sf.acegisecurity.*;
import net.sf.acegisecurity.providers.AuthenticationProvider;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.providers.dao.User;
import net.sf.acegisecurity.providers.dao.UsernameNotFoundException;
import net.sf.acegisecurity.providers.dao.event.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import com.se.eee.bus.*;
import com.se.eee.bus.SecurityManager;
import com.se.spring.datasource.core.MakeConnectionException;
import com.se.spring.ext.CurrentRequestContext;
import com.opensymphony.webwork.interceptor.SessionAware;
import com.opensymphony.webwork.interceptor.ServletRequestAware;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class EeeAuthenticationProvider implements AuthenticationProvider, SessionAware, ServletRequestAware {
private static Log log = LogFactory.getLog(EeeAuthenticationProvider.class);
private JDBCProperties jdbcProp;
private ApplicationContext context;
private SecurityManager securityManager;
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest req) {
this.request = req;
}
public void setSession(Map session) {
//To change body of implemented methods use File | Settings | File Templates.
}
public void setSecurityManager(SecurityManager securityManager) {
this.securityManager = securityManager;
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
public void setJdbcProp(JDBCProperties jdbcProp) {
this.jdbcProp = jdbcProp;
}
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// Determine username
// log.warn((authentication.isAuthenticated()?"Already Authenticated. Skip it!":"")+"authenticate: "+authentication);
if(authentication.isAuthenticated()) {
//log.warn("Already Authenticated. Skip it!");
return authentication;
}
String username = "NONE_PROVIDED";
if (authentication.getPrincipal() != null) {
username = authentication.getPrincipal().toString();
}
if (authentication.getPrincipal() instanceof UserDetails) {
username = ((UserDetails) authentication.getPrincipal()).getUsername();
}
UserDetails user = null;
com.se.eee.bus.User principal=null;
try
{
JDBCProperties props = jdbcProp.deserialize();
String input_passwords= authentication.getCredentials().toString();
String[] psd = input_passwords.split(":");
Filial fil = props.getFilial(psd[1]);
String sgn = input_passwords;
int i= sgn.indexOf(":", 1);
sgn = sgn.substring(i+1,sgn.length());
i= sgn.indexOf(":", 1);
sgn = sgn.substring(i+1,sgn.length());
if(fil==null)username=null;
securityManager.makeConnect(username, psd[0], fil);
user=new User(username, "skipped",true,true,true,true, new GrantedAuthority[]{new GrantedAuthorityImpl("ROLE_USER")});
//set connection for DataSource
ContextDataBean dataBean=(ContextDataBean)CurrentRequestContext.get();
dataBean.setUserKey(username+fil.id);
principal=securityManager.getUserByLogin(username.toUpperCase());
if(principal == null) throw new UsernameNotFoundException("Couldn't login.");
principal.setLogin(username);
principal.setPassword("******");
//principal.setBranch(fil.id);
if (principal.getBanktype().equals("055"))
{
if ( sgn!=null && sgn.length() != 0)
{
securityManager.insUserKey(principal.getBranch(), principal.getId(), sgn);
com.se.eee.bus.Document docum = new com.se.eee.bus.Document();
docum.setBranch(principal.getBranch());
docum.setEmpId(principal.getId());
docum.setErrCode("991");
docum = securityManager.getAnswerUserKey(docum);
if (!docum.getErrCode().equals("000")) throw new UsernameNotFoundException("Key code error. User: "+principal.getLogin());
}
else
{
throw new UsernameNotFoundException("error while inserting test key code. please touch i-key or check loginform.ftl. user: "+principal.getLogin());
}
}
}
catch (MakeConnectionException mex)
{
log.error(mex.getMessage());
if (this.context != null) {
context.publishEvent(new AuthenticationFailureUsernameOrPasswordEvent(authentication, new User("".equals(username)? "EMPTY_STRING_PROVIDED" : username, "*****", false, false, false, false, new GrantedAuthority[0])));
}
throw new BadCredentialsException("Couldn't login connection problem.");
}
catch(Exception ex)
{
Throwable cause=ex.getCause();
String message=null;
if(cause!=null)message = cause.getMessage();
else message = ex.toString();
log.error(message);
// здес я пытаюс написать в session
request.getSession().setAttribute("LoggingError", message);
// но код не компилируется
throw new UsernameNotFoundException("Couldn't login.");
}
return createSuccessAuthentication(principal, authentication, user);
}
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
result.setDetails((authentication.getDetails() != null) ? authentication.getDetails() : null);
result.setAuthenticated(true);
return result;
}
public boolean supports(Class aClass) {
if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass)) return true;
return false;
}
}
If your request object is a HttpServletRequest object then this should work.
If this isn't the problem can you send the exact code snippet (shouldn't need the whole program) and the exact error message?
this should work.
request.getSession(true).setAttribute("LoggingError", message);
Is your authentication provider specified as prototype scope bean? Not sure how Struts / WebWork is exactly integrated with Spring, but if your bean is singleton, it can not work.
In other words, make sure setServletRequest is called.
And by the way this application must be pretty old, if it has such package names as it has.

Categories

Resources