Example usage for java.lang Integer toOctalString

List of usage examples for java.lang Integer toOctalString

Introduction

In this page you can find the example usage for java.lang Integer toOctalString.

Prototype

public static String toOctalString(int i) 

Source Link

Document

Returns a string representation of the integer argument as an unsigned integer in base 8.

Usage

From source file:com.diffplug.gradle.FileMisc.java

/** Converts a set of {@link PosixFilePermission} to chmod-style octal file mode. */
public static String toOctalFileMode(Set<PosixFilePermission> permissions) {
    int value = toOctalFileModeInt(permissions);
    return Integer.toOctalString(value);
}

From source file:edu.harvard.iq.dvn.ingest.dsb.SubsettableFileChecker.java

/**
 * test this byte buffer against R data file
 *
 *///from   w  w w . j a v  a 2 s .  com
public String testRDAformat(MappedByteBuffer buff) {
    String result = null;
    buff.rewind();

    boolean DEBUG = false;
    if (DEBUG) {
        out.println("applying the RData test\n");
        out.println("buffer capacity=" + buff.capacity());
    }
    if (DEBUG) {
        byte[] rawhdr = new byte[4];
        buff.get(rawhdr, 0, 4);
        for (int j = 0; j < 4; j++) {
            out.printf("%02X ", rawhdr[j]);
        }
        out.println();
        buff.rewind();
    }
    // get the first 4 bytes as an int and check its value; 
    // if it is 0x1F8B0800, then gunzip and its first 4 bytes
    int magicNumber = buff.getInt();

    if (DEBUG) {
        out.println("magicNumber in decimal =" + magicNumber);
        out.println("in binary=" + Integer.toBinaryString(magicNumber));
        out.println("in oct=" + Integer.toOctalString(magicNumber));
        out.println("in hex=" + Integer.toHexString(magicNumber));
    }
    try {
        if (magicNumber == 0x1F8B0800) {
            if (DEBUG) {
                out.println("magicNumber is GZIP");
            }
            // gunzip the first 5 bytes and check their bye-pattern

            // get gzip buffer size

            int gzip_buffer_size = this.getGzipBufferSize(buff);

            byte[] hdr = new byte[gzip_buffer_size];
            buff.get(hdr, 0, gzip_buffer_size);

            GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(hdr));

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < RDA_HEADER_SIZE; i++) {
                sb.append(String.format("%02X", gzin.read()));
            }
            String fisrt5bytes = sb.toString();

            result = this.checkUncompressedFirst5bytes(fisrt5bytes);
            // end of compressed case
        } else {
            // uncompressed case?
            if (DEBUG) {
                out.println("magicNumber is not GZIP:" + magicNumber);
                out.println("test as an uncompressed RData file");
            }

            buff.rewind();
            byte[] uchdr = new byte[5];
            buff.get(uchdr, 0, 5);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < uchdr.length; i++) {
                sb.append(String.format("%02X", uchdr[i]));
            }
            String fisrt5bytes = sb.toString();

            result = this.checkUncompressedFirst5bytes(fisrt5bytes);
            // end of uncompressed case
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return result;
}

From source file:edu.harvard.iq.dataverse.ingest.IngestableDataChecker.java

/**
 * test this byte buffer against R data file
 *
 *//* ww w  .  j a v  a2 s  . com*/
public String testRDAformat(MappedByteBuffer buff) {
    String result = null;
    buff.rewind();

    if (buff.capacity() < 4) {
        return null;
    }

    boolean DEBUG = false;
    if (DEBUG) {
        out.println("applying the RData test\n");
        out.println("buffer capacity=" + buff.capacity());
    }
    if (DEBUG) {
        byte[] rawhdr = new byte[4];
        buff.get(rawhdr, 0, 4);
        for (int j = 0; j < 4; j++) {
            out.printf("%02X ", rawhdr[j]);
        }
        out.println();
        buff.rewind();
    }
    // get the first 4 bytes as an int and check its value; 
    // if it is 0x1F8B0800, then gunzip and its first 4 bytes
    int magicNumber = buff.getInt();

    if (DEBUG) {
        out.println("magicNumber in decimal =" + magicNumber);
        out.println("in binary=" + Integer.toBinaryString(magicNumber));
        out.println("in oct=" + Integer.toOctalString(magicNumber));
        out.println("in hex=" + Integer.toHexString(magicNumber));
    }
    try {
        if (magicNumber == 0x1F8B0800) {
            if (DEBUG) {
                out.println("magicNumber is GZIP");
            }
            // gunzip the first 5 bytes and check their bye-pattern

            // get gzip buffer size

            int gzip_buffer_size = this.getGzipBufferSize(buff);

            byte[] hdr = new byte[gzip_buffer_size];
            buff.get(hdr, 0, gzip_buffer_size);

            GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(hdr));

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < RDA_HEADER_SIZE; i++) {
                sb.append(String.format("%02X", gzin.read()));
            }
            String fisrt5bytes = sb.toString();

            result = this.checkUncompressedFirst5bytes(fisrt5bytes);
            // end of compressed case
        } else {
            // uncompressed case?
            if (DEBUG) {
                out.println("magicNumber is not GZIP:" + magicNumber);
                out.println("test as an uncompressed RData file");
            }

            buff.rewind();
            byte[] uchdr = new byte[5];
            buff.get(uchdr, 0, 5);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < uchdr.length; i++) {
                sb.append(String.format("%02X", uchdr[i]));
            }
            String fisrt5bytes = sb.toString();

            result = this.checkUncompressedFirst5bytes(fisrt5bytes);
            // end of uncompressed case
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return result;
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.java

@Override
public String put(final FlowFile flowFile, final String path, final String filename, final InputStream content)
        throws IOException {
    final FTPClient client = getClient(flowFile);

    final String fullPath;
    if (path == null) {
        fullPath = filename;//from  w w  w.jav a  2s. c om
    } else {
        final String workingDir = setAndGetWorkingDirectory(path);
        fullPath = workingDir.endsWith("/") ? workingDir + filename : workingDir + "/" + filename;
    }

    String tempFilename = ctx.getProperty(TEMP_FILENAME).evaluateAttributeExpressions(flowFile).getValue();
    if (tempFilename == null) {
        final boolean dotRename = ctx.getProperty(DOT_RENAME).asBoolean();
        tempFilename = dotRename ? "." + filename : filename;
    }

    final boolean storeSuccessful = client.storeFile(tempFilename, content);
    if (!storeSuccessful) {
        throw new IOException("Failed to store file " + tempFilename + " to " + fullPath + " due to: "
                + client.getReplyString());
    }

    final String lastModifiedTime = ctx.getProperty(LAST_MODIFIED_TIME).evaluateAttributeExpressions(flowFile)
            .getValue();
    if (lastModifiedTime != null && !lastModifiedTime.trim().isEmpty()) {
        try {
            final DateFormat informat = new SimpleDateFormat(FILE_MODIFY_DATE_ATTR_FORMAT, Locale.US);
            final Date fileModifyTime = informat.parse(lastModifiedTime);
            final DateFormat outformat = new SimpleDateFormat(FTP_TIMEVAL_FORMAT, Locale.US);
            final String time = outformat.format(fileModifyTime);
            if (!client.setModificationTime(tempFilename, time)) {
                // FTP server probably doesn't support MFMT command
                logger.warn("Could not set lastModifiedTime on {} to {}",
                        new Object[] { flowFile, lastModifiedTime });
            }
        } catch (final Exception e) {
            logger.error("Failed to set lastModifiedTime on {} to {} due to {}",
                    new Object[] { flowFile, lastModifiedTime, e });
        }
    }
    final String permissions = ctx.getProperty(PERMISSIONS).evaluateAttributeExpressions(flowFile).getValue();
    if (permissions != null && !permissions.trim().isEmpty()) {
        try {
            int perms = numberPermissions(permissions);
            if (perms >= 0) {
                if (!client.sendSiteCommand("chmod " + Integer.toOctalString(perms) + " " + tempFilename)) {
                    logger.warn("Could not set permission on {} to {}", new Object[] { flowFile, permissions });
                }
            }
        } catch (final Exception e) {
            logger.error("Failed to set permission on {} to {} due to {}",
                    new Object[] { flowFile, permissions, e });
        }
    }

    if (!filename.equals(tempFilename)) {
        try {
            logger.debug("Renaming remote path from {} to {} for {}",
                    new Object[] { tempFilename, filename, flowFile });
            final boolean renameSuccessful = client.rename(tempFilename, filename);
            if (!renameSuccessful) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " due to: " + client.getReplyString());
            }
        } catch (final IOException e) {
            try {
                client.deleteFile(tempFilename);
                throw e;
            } catch (final IOException e1) {
                throw new IOException("Failed to rename temporary file " + tempFilename + " to " + fullPath
                        + " and failed to delete it when attempting to clean up", e1);
            }
        }
    }

    return fullPath;
}

From source file:biz.bokhorst.xprivacy.Util.java

public static void setPermissions(String path, int mode, int uid, int gid) {
    try {/*from  www  .j  av  a2s.  c om*/
        // frameworks/base/core/java/android/os/FileUtils.java
        Class<?> fileUtils = Class.forName("android.os.FileUtils");
        Method setPermissions = fileUtils.getMethod("setPermissions", String.class, int.class, int.class,
                int.class);
        setPermissions.invoke(null, path, mode, uid, gid);
        Util.log(null, Log.WARN, "Changed permission path=" + path + " mode=" + Integer.toOctalString(mode)
                + " uid=" + uid + " gid=" + gid);
    } catch (Throwable ex) {
        Util.bug(null, ex);
    }
}

From source file:io.sloeber.core.managers.InternalPackageManager.java

private static void chmod(File file, int mode) throws IOException, InterruptedException {
    String octal = Integer.toOctalString(mode);
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        boolean ownerExecute = (((mode / (8 * 8)) & 1) == 1);
        boolean ownerRead = (((mode / (8 * 8)) & 4) == 4);
        boolean ownerWrite = (((mode / (8 * 8)) & 2) == 2);
        boolean everyoneExecute = (((mode / 8) & 1) == 1);
        boolean everyoneRead = (((mode / 8) & 4) == 4);
        boolean everyoneWrite = (((mode / 8) & 2) == 2);
        file.setWritable(true, false);//from   w  w  w  .jav  a 2s . co m
        file.setExecutable(ownerExecute, !everyoneExecute);
        file.setReadable(ownerRead, !everyoneRead);
        file.setWritable(ownerWrite, !everyoneWrite);
    } else {
        Process process = Runtime.getRuntime().exec(new String[] { "chmod", octal, file.getAbsolutePath() }, //$NON-NLS-1$
                null, null);
        process.waitFor();
    }
}

From source file:com.mucommander.file.impl.ftp.FTPFile.java

/**
 * Changes permissions using the SITE CHMOD FTP command.
 *
 * This command is optional but seems to be supported by modern FTP servers such as ProFTPd or PureFTP Server.
 * But it may as well not be supported by the remote FTP server as it is not part of the basic FTP command set.
 *
 * Implementation note: FTPFile.setPermission only changes the instance's permissions, but doesn't change it on the
 * server-side./*from   ww  w  .  j  a  v a 2 s .  co  m*/
 */
@Override
public void changePermissions(int permissions) throws IOException, UnsupportedFileOperationException {
    FTPConnectionHandler connHandler = null;
    try {
        // Retrieve a ConnectionHandler and lock it
        connHandler = (FTPConnectionHandler) ConnectionPool.getConnectionHandler(this, fileURL, true);

        // Return if we know the CHMOD command is not supported by the server
        if (!connHandler.chmodCommandSupported)
            throw new UnsupportedFileOperationException(FileOperation.CHANGE_PERMISSION);

        // Makes sure the connection is started, if not starts it
        connHandler.checkConnection();

        FileLogger.finer("sending SITE CHMOD " + Integer.toOctalString(permissions) + " " + absPath);
        boolean success = connHandler.ftpClient
                .sendSiteCommand("CHMOD " + Integer.toOctalString(permissions) + " " + absPath);
        FileLogger.finer("server reply: " + connHandler.ftpClient.getReplyString());

        if (!success) {
            int replyCode = connHandler.ftpClient.getReplyCode();

            // If server reported that the command is not supported, mark it in the ConnectionHandler so that
            // we don't try it anymore
            if (replyCode == FTPReply.UNRECOGNIZED_COMMAND || replyCode == FTPReply.COMMAND_NOT_IMPLEMENTED
                    || replyCode == FTPReply.COMMAND_NOT_IMPLEMENTED_FOR_PARAMETER) {

                FileLogger.fine("marking CHMOD command as unsupported");
                connHandler.chmodCommandSupported = false;
            }

            throw new IOException();
        }
    } catch (IOException e) {
        // Checks if the IOException corresponds to a socket error and in that case, closes the connection
        if (connHandler != null)
            connHandler.checkSocketException(e);

        throw e;
    } finally {
        // Release the lock on the ConnectionHandler
        if (connHandler != null)
            connHandler.releaseLock();
    }
}

From source file:com.mucommander.commons.file.impl.ftp.FTPFile.java

/**
 * Changes permissions using the SITE CHMOD FTP command.
 *
 * This command is optional but seems to be supported by modern FTP servers such as ProFTPd or PureFTP Server.
 * But it may as well not be supported by the remote FTP server as it is not part of the basic FTP command set.
 *
 * Implementation note: FTPFile.setPermission only changes the instance's permissions, but doesn't change it on the
 * server-side.//from  w  w w  . j a  va 2  s .c o m
 */
@Override
public void changePermissions(int permissions) throws IOException, UnsupportedFileOperationException {
    FTPConnectionHandler connHandler = null;
    try {
        // Retrieve a ConnectionHandler and lock it
        connHandler = (FTPConnectionHandler) ConnectionPool.getConnectionHandler(this, fileURL, true);

        // Return if we know the CHMOD command is not supported by the server
        if (!connHandler.chmodCommandSupported)
            throw new UnsupportedFileOperationException(FileOperation.CHANGE_PERMISSION);

        // Makes sure the connection is started, if not starts it
        connHandler.checkConnection();

        LOGGER.info("sending SITE CHMOD {} {}", Integer.toOctalString(permissions), absPath);
        boolean success = connHandler.ftpClient
                .sendSiteCommand("CHMOD " + Integer.toOctalString(permissions) + " " + absPath);
        LOGGER.info("server reply: {}", connHandler.ftpClient.getReplyString());

        if (!success) {
            int replyCode = connHandler.ftpClient.getReplyCode();

            // If server reported that the command is not supported, mark it in the ConnectionHandler so that
            // we don't try it anymore
            if (replyCode == FTPReply.UNRECOGNIZED_COMMAND || replyCode == FTPReply.COMMAND_NOT_IMPLEMENTED
                    || replyCode == FTPReply.COMMAND_NOT_IMPLEMENTED_FOR_PARAMETER) {

                LOGGER.info("marking CHMOD command as unsupported");
                connHandler.chmodCommandSupported = false;
            }

            throw new IOException();
        }
    } catch (IOException e) {
        // Checks if the IOException corresponds to a socket error and in that case, closes the connection
        if (connHandler != null)
            connHandler.checkSocketException(e);

        throw e;
    } finally {
        // Release the lock on the ConnectionHandler
        if (connHandler != null)
            connHandler.releaseLock();
    }
}

From source file:hudson.Util.java

private static void _chmodAnt(File f, int mask) {
    Chmod chmodTask = new Chmod();
    chmodTask.setProject(new Project());
    chmodTask.setFile(f);//w w w  .  j  ava2s  . c o m
    chmodTask.setPerm(Integer.toOctalString(mask));
    chmodTask.execute();
}

From source file:org.apache.hive.hcatalog.mapreduce.SpecialCases.java

/**
 * Method to do any file-format specific special casing while
 * instantiating a storage handler to write. We set any parameters
 * we want to be visible to the job in jobProperties, and this will
 * be available to the job via jobconf at run time.
 *
 * This is mostly intended to be used by StorageHandlers that wrap
 * File-based OutputFormats such as FosterStorageHandler that wraps
 * RCFile, ORC, etc.//w ww  . ja va  2  s .c  o  m
 *
 * @param jobProperties : map to write to
 * @param jobInfo : information about this output job to read from
 * @param ofclass : the output format in use
 */
public static void addSpecialCasesParametersToOutputJobProperties(Map<String, String> jobProperties,
        OutputJobInfo jobInfo, Class<? extends OutputFormat> ofclass) {
    if (ofclass == RCFileOutputFormat.class) {
        // RCFile specific parameter
        jobProperties.put(HiveConf.ConfVars.HIVE_RCFILE_COLUMN_NUMBER_CONF.varname,
                Integer.toOctalString(jobInfo.getOutputSchema().getFields().size()));
    } else if (ofclass == OrcOutputFormat.class) {
        // Special cases for ORC
        // We need to check table properties to see if a couple of parameters,
        // such as compression parameters are defined. If they are, then we copy
        // them to job properties, so that it will be available in jobconf at runtime
        // See HIVE-5504 for details
        Map<String, String> tableProps = jobInfo.getTableInfo().getTable().getParameters();
        for (OrcConf property : OrcConf.values()) {
            String propName = property.getAttribute();
            if (tableProps.containsKey(propName)) {
                jobProperties.put(propName, tableProps.get(propName));
            }
        }
    } else if (ofclass == AvroContainerOutputFormat.class) {
        // Special cases for Avro. As with ORC, we make table properties that
        // Avro is interested in available in jobconf at runtime
        Map<String, String> tableProps = jobInfo.getTableInfo().getTable().getParameters();
        for (AvroSerdeUtils.AvroTableProperties property : AvroSerdeUtils.AvroTableProperties.values()) {
            String propName = property.getPropName();
            if (tableProps.containsKey(propName)) {
                String propVal = tableProps.get(propName);
                jobProperties.put(propName, tableProps.get(propName));
            }
        }

        Properties properties = new Properties();
        properties.put("name", jobInfo.getTableName());

        List<String> colNames = jobInfo.getOutputSchema().getFieldNames();
        List<TypeInfo> colTypes = new ArrayList<TypeInfo>();
        for (HCatFieldSchema field : jobInfo.getOutputSchema().getFields()) {
            colTypes.add(TypeInfoUtils.getTypeInfoFromTypeString(field.getTypeString()));
        }

        jobProperties.put(AvroSerdeUtils.AvroTableProperties.SCHEMA_LITERAL.getPropName(),
                AvroSerDe.getSchemaFromCols(properties, colNames, colTypes, null).toString());

        for (String propName : jobProperties.keySet()) {
            String propVal = jobProperties.get(propName);
        }

    }
}