Example usage for java.net URI getAuthority

List of usage examples for java.net URI getAuthority

Introduction

In this page you can find the example usage for java.net URI getAuthority.

Prototype

public String getAuthority() 

Source Link

Document

Returns the decoded authority component of this URI.

Usage

From source file:edu.stanford.junction.provider.bluetooth.Junction.java

public Junction(URI uri, ActivityScript script, final JunctionActor actor, BluetoothSwitchboardConfig config)
        throws JunctionException {
    mConfig = config;// www  .ja v a  2s  . com
    mActivityScript = script;
    mUri = uri;
    mSwitchboard = uri.getAuthority();

    setActor(actor);
    if (DBG)
        Log.d(TAG, "doing bluetooth");
    if (mSwitchboard.equals(mBtAdapter.getAddress())) {
        Log.d(TAG, "starting new junction hub");
        mIsHub = true;
        mSession = mConfig.getUuid().toString();
        mConnections = new HashSet<ConnectedThread>();
        mRemoveConnections = new HashSet<ConnectedThread>();
        mAcceptThread = new AcceptThread();
        mAcceptThread.start();
    } else {
        Log.d(TAG, "connecting to junction hub: " + mSwitchboard);
        mIsHub = false;
        mSession = uri.getPath().substring(1);
        BluetoothDevice hub = mBtAdapter.getRemoteDevice(mSwitchboard);
        mConnectThread = new ConnectThread(hub, UUID.fromString(mSession));
        mConnectThread.start();
    }
    if (mIsHub) {
        triggerActorJoin(mIsHub);
    } else {
        synchronized (mJoinLock) {
            if (!mJoinComplete) {
                try {
                    mJoinLock.wait(12000);
                } catch (InterruptedException e) {
                    // Ignored
                }
            }
            if (mJoinComplete) {
                triggerActorJoin(mIsActivityCreator);
            } else {
                throw new JunctionException("Failed to join session, handshake not complete.");
            }
        }
    }
}

From source file:nl.kpmg.lcm.server.backend.AbstractBackend.java

private List getDataItems(String uri) {
    URI parsedUri = parseUri(uri);

    if (parsedUri == null) {
        return null;
    }//w  w w  .  ja  v a  2s  .c o  m

    String path = processPath(parsedUri);
    String subPath = "";
    int index = StringUtils.lastIndexOf(path, "/");
    if (index != -1) {
        subPath = path.substring(0, index);
    }
    if (subPath.contains("*")) {
        LOGGER.error(
                "Error! URI has invalid syntax. Wildcard symbol is used in the path:" + parsedUri.toString());
        return null;
    }

    String storageName = parsedUri.getHost() != null ? parsedUri.getHost() : parsedUri.getAuthority();

    try {
        return loadDataItems(storageName, subPath);
    } catch (Exception ex) {
        LOGGER.warn("Unable to load data items for storage: " + storageName + " and subPath: " + subPath
                + ". Error message: " + ex.getMessage());
        return null;
    }
}

From source file:org.apache.hadoop.fs.ceph.CephFileSystem.java

/**
 * Should be called after constructing a CephFileSystem but before calling
 * any other methods./*w ww  . j  av a  2 s. c o m*/
 * Starts up the connection to Ceph, reads in configuraton options, etc.
 * @param uri The URI for this filesystem.
 * @param conf The Hadoop Configuration to retrieve properties from.
 * @throws IOException if necessary properties are unset.
 */
@Override
public void initialize(URI uri, Configuration conf) throws IOException {
    super.initialize(uri, conf);
    setConf(conf);
    this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
    if (ceph == null) {
        ceph = new CephTalker(conf, LOG);
    }

    CEPH_NAMESERVER = conf.get(CEPH_NAMESERVER_KEY, CEPH_NAMESERVER_DEFAULT);

    // build up the arguments for Ceph
    String arguments = "CephFSInterface";

    arguments += conf.get("fs.ceph.commandLine", "");
    if (conf.get("fs.ceph.clientDebug") != null) {
        arguments += " --debug_client ";
        arguments += conf.get("fs.ceph.clientDebug");
    }
    if (conf.get("fs.ceph.messengerDebug") != null) {
        arguments += " --debug_ms ";
        arguments += conf.get("fs.ceph.messengerDebug");
    }
    if (conf.get("fs.ceph.monAddr") != null) {
        arguments += " -m ";
        arguments += conf.get("fs.ceph.monAddr");
    }
    arguments += " --client-readahead-max-periods=" + conf.get("fs.ceph.readahead", "1");
    // make sure they gave us a ceph monitor address or conf file
    LOG.info("initialize:Ceph initialization arguments: " + arguments);
    if ((conf.get("fs.ceph.monAddr") == null) && (arguments.indexOf("-m") == -1)
            && (arguments.indexOf("-c") == -1)) {
        LOG.fatal("initialize:You need to specify a Ceph monitor address.");
        throw new IOException("You must specify a Ceph monitor address or config file!");
    }
    // Initialize the client
    if (!ceph.ceph_initializeClient(arguments, conf.getInt("fs.ceph.blockSize", 1 << 26))) {
        LOG.fatal("initialize:Ceph initialization failed!");
        throw new IOException("Ceph initialization failed!");
    }
    LOG.info("initialize:Ceph initialized client. Setting cwd to /");
    ceph.ceph_setcwd("/");
    LOG.debug("initialize:exit");

    this.workingDir = getHomeDirectory();
}

From source file:org.apache.oozie.service.ShareLibService.java

/**
 * Recursively change permissions.//w w  w . ja va  2 s.c  o  m
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void updateLauncherLib() throws IOException {
    if (isShipLauncherEnabled) {
        if (fs == null) {
            Path launcherlibPath = getLauncherlibPath();
            HadoopAccessorService has = Services.get().get(HadoopAccessorService.class);
            URI uri = launcherlibPath.toUri();
            fs = FileSystem.get(has.createJobConf(uri.getAuthority()));
        }
        Path launcherlibPath = getLauncherlibPath();
        setupLauncherLibPath(fs, launcherlibPath);
        recursiveChangePermissions(fs, launcherlibPath, FsPermission.valueOf(PERMISSION_STRING));
    }

}

From source file:org.wso2.iot.agent.services.FileDownloadService.java

/**
 * This method splits the provided URL to get user information for downloadFile
 * and uploadFile methods./*from w  w w  . ja  v a2  s .c  o  m*/
 *
 * @param fileURL  - URL to split.
 * @param isUpload - fileURL corresponds to uploadFile or downloadFile operation.
 * @return - an array of ftpUserName, fileDirectory, host, serverPort, protocol &
 * fileName ( optional for isUpload = false ).
 * @throws URISyntaxException - Malformed URL.
 */
public String[] urlSplitter(Operation operation, String fileURL, boolean isUpload)
        throws URISyntaxException, AndroidAgentException {
    String serverPort = null;
    URI url = new URI(fileURL);
    String protocol = url.getScheme();
    String host = null;
    String ftpUserName = null; // for anonymous FTP login.
    if (protocol != null) {
        if (protocol.equals(Constants.FileTransfer.FTP)) {
            serverPort = String.valueOf(21);
        } else if (protocol.equals(Constants.FileTransfer.SFTP)) {
            serverPort = String.valueOf(22);
        }
        if (url.getAuthority() != null) {
            String[] authority = url.getAuthority().split("@"); //provides username@hostname
            // Since hostname cannot contain any '@' signs, it should be last element.
            host = authority[authority.length - 1];
            if (authority.length > 1) {
                ftpUserName = url.getAuthority().substring(0, url.getAuthority().lastIndexOf(host) - 1);
            } else {
                ftpUserName = "anonymous"; // for anonymous FTP login.
            }
        }
        if (host != null && host.contains(":")) {
            serverPort = String.valueOf(host.split(":")[1]);
            host = host.split(":")[0];
        }
    } else {
        handleOperationError(operation, "Invalid URL", null);
    }
    if (isUpload) {
        return new String[] { ftpUserName, url.getPath(), host, serverPort, protocol };
    } else {
        File file = new File(url.getPath());
        return new String[] { ftpUserName, file.getParent(), host, serverPort, protocol, file.getName() };
    }
}

From source file:org.apache.oozie.service.ShareLibService.java

/**
 * Update share lib cache./*from w w  w. j  a va2s . c o  m*/
 *
 * @return the map
 * @throws IOException Signals that an I/O exception has occurred.
 */
public Map<String, String> updateShareLib() throws IOException {
    Map<String, String> status = new HashMap<String, String>();

    if (fs == null) {
        Path launcherlibPath = getLauncherlibPath();
        HadoopAccessorService has = Services.get().get(HadoopAccessorService.class);
        URI uri = launcherlibPath.toUri();
        fs = FileSystem.get(has.createJobConf(uri.getAuthority()));
    }

    Map<String, List<Path>> tempShareLibMap = new HashMap<String, List<Path>>();
    Map<String, Map<Path, Path>> tmpSymlinkMapping = new HashMap<String, Map<Path, Path>>();
    Map<String, Map<Path, Configuration>> tmpShareLibConfigMap = new HashMap<String, Map<Path, Configuration>>();

    if (!StringUtils.isEmpty(sharelibMappingFile.trim())) {
        String sharelibMetaFileNewTimeStamp = JsonUtils.formatDateRfc822(
                new Date(fs.getFileStatus(new Path(sharelibMappingFile)).getModificationTime()), "GMT");
        loadShareLibMetaFile(tempShareLibMap, tmpSymlinkMapping, tmpShareLibConfigMap, sharelibMappingFile,
                null);
        status.put("sharelibMetaFile", sharelibMappingFile);
        status.put("sharelibMetaFileNewTimeStamp", sharelibMetaFileNewTimeStamp);
        status.put("sharelibMetaFileOldTimeStamp", sharelibMetaFileOldTimeStamp);
        sharelibMetaFileOldTimeStamp = sharelibMetaFileNewTimeStamp;
    } else {
        Path shareLibpath = getLatestLibPath(services.get(WorkflowAppService.class).getSystemLibPath(),
                SHARE_LIB_PREFIX);
        loadShareLibfromDFS(tempShareLibMap, shareLibpath, tmpShareLibConfigMap);

        if (shareLibpath != null) {
            status.put("sharelibDirNew", shareLibpath.toString());
            status.put("sharelibDirOld", sharelibDirOld);
            sharelibDirOld = shareLibpath.toString();
        }

    }
    shareLibMap = tempShareLibMap;
    symlinkMapping = tmpSymlinkMapping;
    shareLibConfigMap = tmpShareLibConfigMap;
    return status;
}

From source file:org.apache.distributedlog.impl.BKNamespaceDriver.java

@Override
public synchronized NamespaceDriver initialize(DistributedLogConfiguration conf,
        DynamicDistributedLogConfiguration dynConf, URI namespace, OrderedScheduler scheduler,
        FeatureProvider featureProvider, AsyncFailureInjector failureInjector, StatsLogger statsLogger,
        StatsLogger perLogStatsLogger, String clientId, int regionId) throws IOException {
    if (initialized) {
        return this;
    }/*  w  ww. j  ava 2s.c o m*/
    // validate the namespace
    if ((null == namespace) || (null == namespace.getAuthority()) || (null == namespace.getPath())) {
        throw new IOException("Incorrect distributedlog namespace : " + namespace);
    }

    // initialize the resources
    this.conf = conf;
    this.dynConf = dynConf;
    this.namespace = namespace;
    this.scheduler = scheduler;
    this.featureProvider = featureProvider;
    this.failureInjector = failureInjector;
    this.statsLogger = statsLogger;
    this.perLogStatsLogger = perLogStatsLogger;
    this.clientId = clientId;
    this.regionId = regionId;

    // initialize the zookeeper clients
    initializeZooKeeperClients();

    // initialize the bookkeeper clients
    initializeBookKeeperClients();

    // propagate bkdlConfig to configuration
    BKDLConfig.propagateConfiguration(bkdlConfig, conf);

    // initialize the log metadata & stream metadata store
    initializeLogStreamMetadataStores();

    // initialize other resources
    initializeOtherResources();

    initialized = true;

    LOG.info("Initialized BK namespace driver: clientId = {}, regionId = {}, federated = {}.",
            new Object[] { clientId, regionId, bkdlConfig.isFederatedNamespace() });
    return this;
}

From source file:org.apache.hadoop.contrib.bkjournal.BookKeeperJournalManager.java

/**
 * Construct a Bookkeeper journal manager.
 *//*from w w  w  . j  a  v  a  2s. c o  m*/
public BookKeeperJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo) throws IOException {
    this.conf = conf;
    this.nsInfo = nsInfo;

    String zkConnect = uri.getAuthority().replace(";", ",");
    basePath = uri.getPath();
    ensembleSize = conf.getInt(BKJM_BOOKKEEPER_ENSEMBLE_SIZE, BKJM_BOOKKEEPER_ENSEMBLE_SIZE_DEFAULT);
    quorumSize = conf.getInt(BKJM_BOOKKEEPER_QUORUM_SIZE, BKJM_BOOKKEEPER_QUORUM_SIZE_DEFAULT);
    ackQuorumSize = conf.getInt(BKJM_BOOKKEEPER_ACK_QUORUM_SIZE, quorumSize);
    addEntryTimeout = conf.getInt(BKJM_BOOKKEEPER_ADD_ENTRY_TIMEOUT_SEC,
            BKJM_BOOKKEEPER_ADD_ENTRY_TIMEOUT_DEFAULT);
    speculativeReadTimeout = conf.getInt(BKJM_BOOKKEEPER_SPECULATIVE_READ_TIMEOUT_MS,
            BKJM_BOOKKEEPER_SPECULATIVE_READ_TIMEOUT_DEFAULT);
    readEntryTimeout = conf.getInt(BKJM_BOOKKEEPER_READ_ENTRY_TIMEOUT_SEC,
            BKJM_BOOKKEEPER_READ_ENTRY_TIMEOUT_DEFAULT);

    ledgerPath = basePath + "/ledgers";
    String maxTxIdPath = basePath + "/maxtxid";
    String currentInprogressNodePath = basePath + "/CurrentInprogress";
    versionPath = basePath + "/version";
    digestpw = conf.get(BKJM_BOOKKEEPER_DIGEST_PW, BKJM_BOOKKEEPER_DIGEST_PW_DEFAULT);

    try {
        zkConnectLatch = new CountDownLatch(1);
        int bkjmZKSessionTimeout = conf.getInt(BKJM_ZK_SESSION_TIMEOUT, BKJM_ZK_SESSION_TIMEOUT_DEFAULT);
        zkc = new ZooKeeper(zkConnect, bkjmZKSessionTimeout, new ZkConnectionWatcher());
        // Configured zk session timeout + some extra grace period (here
        // BKJM_ZK_SESSION_TIMEOUT_DEFAULT used as grace period)
        int zkConnectionLatchTimeout = bkjmZKSessionTimeout + BKJM_ZK_SESSION_TIMEOUT_DEFAULT;
        if (!zkConnectLatch.await(zkConnectionLatchTimeout, TimeUnit.MILLISECONDS)) {
            throw new IOException("Error connecting to zookeeper");
        }

        prepareBookKeeperEnv();
        ClientConfiguration clientConf = new ClientConfiguration();
        clientConf.setSpeculativeReadTimeout(speculativeReadTimeout);
        clientConf.setReadEntryTimeout(readEntryTimeout);
        clientConf.setAddEntryTimeout(addEntryTimeout);
        bkc = new BookKeeper(clientConf, zkc);
    } catch (KeeperException e) {
        throw new IOException("Error initializing zk", e);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new IOException("Interrupted while initializing bk journal manager", ie);
    }

    ci = new CurrentInprogress(zkc, currentInprogressNodePath);
    maxTxId = new MaxTxId(zkc, maxTxIdPath);
}

From source file:com.google.android.testing.nativedriver.server.AndroidNativeDriver.java

/**
 * Takes a string that looks like a URL and performs an operation based on the
 * contents of the URL. Currently only starting activities is supported.
 * <p>//  ww  w . j av  a 2  s . c o m
 * Supported URL type follows:
 * <ul>
 * <li>{@code and-activity://<Activity class name>}<br>
 * start specified activity
 * </ul>
 */
@Override
public void get(String url) {
    URI dest;
    try {
        dest = new URI(url);
    } catch (URISyntaxException exception) {
        throw new IllegalArgumentException(exception);
    }

    if (!"and-activity".equals(dest.getScheme())) {
        throw new WebDriverException("Unrecognized scheme in URI: " + dest.toString());
    } else if (!Strings.isNullOrEmpty(dest.getPath())) {
        throw new WebDriverException("Unrecognized path in URI: " + dest.toString());
    }

    Class<?> clazz;
    try {
        clazz = Class.forName(dest.getAuthority());
    } catch (ClassNotFoundException exception) {
        throw new WebDriverException("The specified Activity class does not exist: " + dest.getAuthority(),
                exception);
    }

    for (NameValuePair nvp : URLEncodedUtils.parse(dest, "utf8")) {
        if ("id".equals(nvp.getName())) {
            // This is to prevent people from recycling the same URL they got from
            // getCurrentUrl() and expecting to return to an arbitrary running
            // activity. It is not supported in the Android user interface so we
            // don't expose this functionality.
            throw new WebDriverException("Moving to the specified activity is not supported.");
        }
    }
    startActivity(clazz);
}

From source file:org.apache.oozie.service.ShareLibService.java

@Override
public void init(Services services) throws ServiceException {
    this.services = services;
    sharelibMappingFile = ConfigurationService.get(services.getConf(), SHARELIB_MAPPING_FILE);
    isShipLauncherEnabled = ConfigurationService.getBoolean(services.getConf(), SHIP_LAUNCHER_JAR);
    boolean failOnfailure = ConfigurationService.getBoolean(services.getConf(), FAIL_FAST_ON_STARTUP);
    Path launcherlibPath = getLauncherlibPath();
    HadoopAccessorService has = Services.get().get(HadoopAccessorService.class);
    URI uri = launcherlibPath.toUri();
    try {/*  w w w  .  j ava2s  . com*/
        fs = FileSystem.get(has.createJobConf(uri.getAuthority()));
        //cache action key sharelib conf list
        cacheActionKeySharelibConfList();
        updateLauncherLib();
        updateShareLib();
    } catch (Throwable e) {
        if (failOnfailure) {
            LOG.error("Sharelib initialization fails", e);
            throw new ServiceException(ErrorCode.E0104, getClass().getName(), "Sharelib initialization fails. ",
                    e);
        } else {
            // We don't want to actually fail init by throwing an Exception, so only create the ServiceException and
            // log it
            ServiceException se = new ServiceException(ErrorCode.E0104, getClass().getName(),
                    "Not able to cache sharelib. An Admin needs to install the sharelib with oozie-setup.sh and issue the "
                            + "'oozie admin' CLI command to update the sharelib",
                    e);
            LOG.error(se);
        }
    }
    Runnable purgeLibsRunnable = new Runnable() {
        @Override
        public void run() {
            System.out.flush();
            try {
                // Only one server should purge sharelib
                if (Services.get().get(JobsConcurrencyService.class).isLeader()) {
                    final Date current = Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime();
                    purgeLibs(fs, LAUNCHER_LIB_PREFIX, current);
                    purgeLibs(fs, SHARE_LIB_PREFIX, current);
                }
            } catch (IOException e) {
                LOG.error("There was an issue purging the sharelib", e);
            }
        }
    };
    services.get(SchedulerService.class).schedule(purgeLibsRunnable, 10,
            ConfigurationService.getInt(services.getConf(), PURGE_INTERVAL) * 60 * 60 * 24,
            SchedulerService.Unit.SEC);
}