Java Examples for javax.microedition.io.file.FileConnection

The following java examples will help you to understand the usage of javax.microedition.io.file.FileConnection. These source code samples are taken from different open source projects.

Example 1
Project: pluotsorbet-master  File: Log.java View source code
/**
     * Opens the {@link FileConnection} and a {@link PrintStream}.
     * 
     * @param filenamePrefix prefix of the filename part of the file path.
     * @param append if <code>true</code> then don't use timestamp in the filename but append to existing log file.
     * @throws IOException if a file could not be created.
     * @throws SecurityException if no permission was given to create a file.
     * @throws NullPointerException if <code>filenamePrefix</code> is <code>null</code>.
     */
private static void openFileConnection(String filenamePrefix, boolean append) throws IOException, SecurityException {
    if (!System.getProperty("microedition.io.file.FileConnection.version").equals("1.0")) {
        // a ClassNotFoundException would have been thrown earlier.
        throw new IOException("FileConnection not available");
    }
    final String filename = createLogFilename(filenamePrefix, !append);
    final String[] pathProperties = { "fileconn.dir.memorycard", "fileconn.dir.recordings" };
    String path = null;
    // system properties in array pathProperties.
    for (int i = 0; i < pathProperties.length; i++) {
        path = System.getProperty(pathProperties[i]);
        // to try.
        try {
            if (path == null) {
                if (i < (pathProperties.length - 1)) {
                    continue;
                } else {
                    throw new IOException("Path not available: " + pathProperties[i]);
                }
            }
            FileConnection fConn = (FileConnection) Connector.open(path + filename, Connector.READ_WRITE);
            OutputStream os = null;
            if (append) {
                if (!fConn.exists()) {
                    fConn.create();
                }
                os = fConn.openOutputStream(fConn.fileSize());
            } else {
                // Assume that createLogFilename creates such a filename
                // that is enough to separate filenames even if they
                // are created in a short interval (seconds).
                fConn.create();
                os = fConn.openOutputStream();
            }
            streams[FILE_INDX] = new PrintStream(os);
            // Opening the connection and stream was successful so don't
            // try other paths.
            fileConn = fConn;
            break;
        } catch (SecurityException se) {
            if (i == (pathProperties.length - 1)) {
                throw se;
            }
        } catch (IOException ioe) {
            if (i == (pathProperties.length - 1)) {
                throw ioe;
            }
        }
    }
}
Example 2
Project: RapidFTR---BlackBerry-Edition-master  File: ImageUtility.java View source code
public static EncodedImage getBitmapImageForPath(String Path) {
    //	String ImagePath = "file://"+ Path;
    String ImagePath = Path;
    FileConnection fconn;
    try {
        fconn = (FileConnection) Connector.open(ImagePath, Connector.READ);
        if (fconn.exists()) {
            byte[] imageBytes = new byte[(int) fconn.fileSize()];
            InputStream inStream = fconn.openInputStream();
            inStream.read(imageBytes);
            inStream.close();
            EncodedImage eimg = EncodedImage.createEncodedImage(imageBytes, 0, (int) fconn.fileSize());
            fconn.close();
            return eimg;
        }
    } catch (IllegalArgumentException e) {
        return EncodedImage.getEncodedImageResource("res\\head.png");
    } catch (IOException e) {
        e.printStackTrace();
        return EncodedImage.getEncodedImageResource("res\\head.png");
    }
    return null;
}
Example 3
Project: AlbiteREADER-master  File: Book.java View source code
protected FileConnection loadUserFile(final String filename) throws IOException {
    try {
        //#debug
        AlbiteMIDlet.LOGGER.log("Opening [" + filename + "]...");
        final FileConnection file = (FileConnection) Connector.open(filename, Connector.READ_WRITE);
        //#debug
        AlbiteMIDlet.LOGGER.log(file != null);
        return file;
    } catch (SecurityException e) {
    } catch (IOException e) {
    }
    return null;
}
Example 4
Project: ned-mobile-client-master  File: NedIOUtils.java View source code
public static String loadFile(String file) {
    FileConnection fc = null;
    InputStream is = null;
    String content = null;
    try {
        fc = (FileConnection) Connector.open(file, Connector.READ);
        if (fc.exists()) {
            is = fc.openInputStream();
            StringBuffer sb = new StringBuffer();
            int chars = 0;
            while ((chars = is.read()) != -1) {
                sb.append((char) chars);
            }
            content = sb.toString();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            if (fc != null) {
                fc.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return content;
}
Example 5
Project: InTheClear-master  File: WipeController.java View source code
public boolean wipeAllRootPaths(WipeListener wl) throws IOException {
    Enumeration drives = FileSystemRegistry.listRoots();
    boolean success = false;
    while (drives.hasMoreElements()) {
        String rootPath = "file:///" + drives.nextElement().toString();
        FileConnection fc = (FileConnection) Connector.open(rootPath, Connector.READ);
        if (fc.exists()) {
            try {
                wipeFilePath(fc.getURL(), wl);
                success = true;
            } catch (Exception e) {
                wl.wipingFileError(fc.getName(), e.getMessage());
            }
        }
    }
    int i = 0;
    try {
        for (i = 0; i < POSSIBLE_WIPE_PATHS.length; i++) {
            FileConnection fc = (FileConnection) Connector.open(POSSIBLE_WIPE_PATHS[i], Connector.READ);
            try {
                if (fc.exists()) {
                    success = wipeFilePath(fc.getURL(), wl);
                }
            } catch (Exception e) {
                wl.wipingFileError(fc.getName(), e.getMessage());
                success = false;
            }
        }
    } catch (Exception e) {
        Logger.error("wipeController", "error wiping files: " + POSSIBLE_WIPE_PATHS[i], e);
    }
    return success;
}
Example 6
Project: maplets-master  File: ReplayMIDlet.java View source code
public void commandAction(Command c, Displayable d) {
    final int sel = choices.getSelectedIndex();
    if (sel == -1)
        quit(true);
    else {
        final String choice = getLocations() + "/" + choices.getString(sel);
        if (c == ok) {
            ((ReplaySource) reader).setPath(choice);
            display.setCurrent(location);
            new Thread(reader).start();
        } else if (c == delete) {
            new Thread(new ExceptionHandler("delete") {

                public void doRun() throws Exception {
                    FileConnection file = (FileConnection) Connector.open(choice);
                    try {
                        file.delete();
                        choices.delete(sel);
                    } finally {
                        file.close();
                    }
                }
            }).start();
        }
    }
}
Example 7
Project: mobilebasic-master  File: Main.java View source code
public void OpenFile(int iocb, String filename, boolean readOnlyFlag) {
    if (iocb >= 0 && iocb < MAXFILES) {
        if (randomAccessFile[iocb] == null && httpConn[iocb] == null && fc[iocb] == null && socketConn[iocb] == null && inputStream[iocb] == null) {
            Class clazz;
            if (filename.startsWith("file:")) {
                try {
                    fc[iocb] = (FileConnection) Connector.open(filename);
                    if (readOnlyFlag) {
                        if (!fc[iocb].exists()) {
                            throw new BasicError(4130, "No file: " + filename);
                        }
                    } else {
                        if (fc[iocb].exists()) {
                            fc[iocb].delete();
                            fc[iocb].close();
                            fc[iocb] = (FileConnection) Connector.open(filename);
                        }
                        fc[iocb].create();
                    }
                    dataInput[iocb] = fc[iocb].openDataInputStream();
                    dataOutput[iocb] = fc[iocb].openDataOutputStream();
                } catch (Exception ex) {
                    clazz = ex.getClass();
                    throw new BasicError(4130, clazz.getName());
                }
            } else if (filename.startsWith("socket:")) {
                try {
                    socketConn[iocb] = (SocketConnection) Connector.open(filename);
                    dataOutput[iocb] = socketConn[iocb].openDataOutputStream();
                    dataInput[iocb] = socketConn[iocb].openDataInputStream();
                } catch (Exception ex) {
                    clazz = ex.getClass();
                    throw new BasicError(4130, clazz.getName());
                }
            } else if (filename.startsWith("http:")) {
                try {
                    httpConn[iocb] = (HttpConnection) Connector.open(filename, 3);
                    if (readOnlyFlag) {
                        httpConn[iocb].setRequestMethod("GET");
                    } else {
                        httpConn[iocb].setRequestMethod("POST");
                        httpConn[iocb].setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    }
                    //httpConn[iocb].setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLCD-1.1 (Mobile BASIC MIDlet 1.9.1 by kiriman & dzanis)");
                    //httpConn[iocb].setRequestProperty("Content-Language", "en-US");
                    //httpConn[iocb].setRequestProperty("Accept", "text/plain");
                    //httpConn[iocb].setRequestProperty("Content-Type", "text/plain");
                    // httpConn[iocb].setRequestProperty("Connection", "close");
                    baos[iocb] = new ByteArrayOutputStream();
                    dataOutput[iocb] = new DataOutputStream(baos[iocb]);
                    dataInput[iocb] = null;
                } catch (Exception ex) {
                    clazz = ex.getClass();
                    throw new BasicError(4131, clazz.getName());
                }
            } else if (filename.startsWith("/")) {
                try {
                    inputStream[iocb] = getClass().getResourceAsStream(filename);
                    dataInput[iocb] = new DataInputStream(inputStream[iocb]);
                    dataOutput[iocb] = null;
                } catch (Exception ex) {
                    throw new BasicError(4133, ex.getClass().getName());
                }
            } else {
                try {
                    randomAccessFile[iocb] = new RandomAccessFile(filename, readOnlyFlag);
                    dataInput[iocb] = randomAccessFile[iocb];
                    dataOutput[iocb] = randomAccessFile[iocb];
                } catch (Exception ex) {
                    randomAccessFile[iocb] = null;
                    dataInput[iocb] = null;
                    dataOutput[iocb] = null;
                    throw new BasicError(4132, ex.getClass().getName());
                }
            }
        } else {
            throw new BasicError(4098, "Channel " + iocb + " already in use");
        }
    } else {
        throw new BasicError(4096, "Invalid channel");
    }
}
Example 8
Project: sharenav-master  File: Trace.java View source code
/**
	 * Starts the LocationProvider in the background
	 */
public void run() {
    try {
        if (running) {
            receiveMessage(Locale.get("trace.GpsStarterRunning"));
            return;
        }
        //#debug info
        logger.info("start thread init locationprovider");
        if (locationProducer != null) {
            receiveMessage(Locale.get("trace.LocProvRunning"));
            return;
        }
        if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE) {
            receiveMessage(Locale.get("trace.NoLocProv"));
            return;
        }
        running = true;
        //#if polish.android
        Configuration.setCfgBitSavedState(Configuration.CFGBIT_GPS_CONNECTED, true);
        currentRotation = getAndroidRotationAngle();
        //#endif
        currentLayoutIsPortrait = deviceLayoutIsPortrait();
        //#if polish.android
        previousAngle = getAndroidRotationAngle();
        //#else
        previousAngle = deviceLayoutIsPortrait() ? 0 : 90;
        //#endif
        startCompass();
        int locprov = Configuration.getLocationProvider();
        //#if polish.android
        receiveMessage(Locale.get("trace.ConnectTo") + /*Connect to */
        Configuration.LOCATIONPROVIDER[locprov]);
        //#else
        if (locprov == Configuration.LOCATIONPROVIDER_GPSD) {
            receiveMessage(Locale.get("trace.ConnectTo") + Configuration.LOCATIONPROVIDER[locprov - 1]);
        } else {
            receiveMessage(Locale.get("trace.ConnectTo") + Configuration.LOCATIONPROVIDER[locprov]);
        }
        if (locprov == Configuration.LOCATIONPROVIDER_GPSD - 1) {
            locprov = Configuration.LOCATIONPROVIDER_GPSD;
        }
        //#endif
        if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_CELLID_STARTUP)) {
            // Don't do initial lookup if we're going to start primary cellid location provider anyway
            if (Configuration.getLocationProvider() != Configuration.LOCATIONPROVIDER_SECELL || !Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
                commandAction(CELLID_LOCATION_CMD);
            }
        }
        switch(locprov) {
            case Configuration.LOCATIONPROVIDER_SIRF:
                locationProducer = new SirfInput();
                break;
            case Configuration.LOCATIONPROVIDER_NMEA:
                locationProducer = new NmeaInput();
                break;
            case Configuration.LOCATIONPROVIDER_GPSD:
                locationProducer = new NmeaInput();
                break;
            case Configuration.LOCATIONPROVIDER_SECELL:
                if (cellIDLocationProducer != null) {
                    cellIDLocationProducer.close();
                }
                locationProducer = new SECellId();
                break;
            case Configuration.LOCATIONPROVIDER_JSR179:
                //#if polish.api.locationapi
                try {
                    String jsr179Version = null;
                    try {
                        jsr179Version = System.getProperty("microedition.location.version");
                    } catch (RuntimeException re) {
                    } catch (Exception e) {
                    }
                    //#else
                    if (jsr179Version != null && jsr179Version.length() > 0) {
                        //#endif
                        Class jsr179Class = Class.forName("net.sharenav.gps.location.Jsr179Input");
                        locationProducer = (LocationMsgProducer) jsr179Class.newInstance();
                    //#if polish.android
                    //#else
                    }
                //#endif
                } catch (ClassNotFoundException cnfe) {
                    locationDecoderEnd();
                    logger.exception(Locale.get("trace.NoJSR179Support"), cnfe);
                    running = false;
                    return;
                }
                // keep Eclipse happy
                if (true) {
                    logger.error(Locale.get("trace.JSR179NotCompiledIn"));
                    running = false;
                    return;
                }
                //#endif
                break;
            case Configuration.LOCATIONPROVIDER_ANDROID:
                //#if polish.android
                try {
                    Class AndroidLocationInputClass = Class.forName("net.sharenav.gps.location.AndroidLocationInput");
                    locationProducer = (LocationMsgProducer) AndroidLocationInputClass.newInstance();
                } catch (ClassNotFoundException cnfe) {
                    locationDecoderEnd();
                    logger.exception(Locale.get("trace.NoAndroidSupport"), cnfe);
                    running = false;
                    return;
                }
                // keep Eclipse happy
                if (true) {
                    logger.error(Locale.get("trace.AndroidNotCompiledIn"));
                    running = false;
                    return;
                }
                //#endif
                break;
        }
        //#if polish.api.fileconnection
        /**
			 * Allow for logging the raw data coming from the gps
			 */
        String url = Configuration.getGpsRawLoggerUrl();
        //logger.error("Raw logging url: " + url);
        if (url != null) {
            try {
                if (Configuration.getGpsRawLoggerEnable()) {
                    logger.info("Raw Location logging to: " + url);
                    url += "rawGpsLog" + HelperRoutines.formatSimpleDateNow() + ".txt";
                    //#if polish.android
                    de.enough.polish.android.io.Connection logCon = Connector.open(url);
                    //#else
                    javax.microedition.io.Connection logCon = Connector.open(url);
                    //#endif
                    if (logCon instanceof FileConnection) {
                        FileConnection fileCon = (FileConnection) logCon;
                        if (!fileCon.exists()) {
                            fileCon.create();
                        }
                        locationProducer.enableRawLogging(((FileConnection) logCon).openOutputStream());
                    } else {
                        logger.info("Raw logging of NMEA is only to filesystem supported");
                    }
                }
                /**
					 * Help out the OpenCellId.org project by gathering and logging
					 * data of cell ids together with current Gps location. This information
					 * can then be uploaded to their web site to determine the position of the
					 * cell towers. It currently only works for SE phones
					 */
                if (Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
                    SECellLocLogger secl = new SECellLocLogger();
                    if (secl.init()) {
                        locationProducer.addLocationMsgReceiver(secl);
                    }
                }
            } catch (IOException ioe) {
                logger.exception(Locale.get("trace.CouldntOpenFileForRawLogging"), ioe);
            } catch (SecurityException se) {
                logger.error(Locale.get("trace.PermissionWritingDataDenied"));
            }
        }
        //#endif
        if (locationProducer == null) {
            logger.error(Locale.get("trace.ChooseDiffLocMethod"));
            running = false;
            return;
        }
        if (!locationProducer.init(this)) {
            logger.info("Failed to initialise location producer");
            running = false;
            return;
        }
        if (!locationProducer.activate(this)) {
            logger.info("Failed to activate location producer");
            running = false;
            return;
        }
        if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
            ShareNav.mNoiseMaker.playSound("CONNECT");
        }
        //#debug debug
        logger.debug("rm connect, add disconnect");
        removeCommand(CMDS[CONNECT_GPS_CMD]);
        addCommand(CMDS[DISCONNECT_GPS_CMD]);
        //#debug info
        logger.info("end startLocationPovider thread");
    //		setTitle("lp="+Configuration.getLocationProvider() + " " + Configuration.getBtUrl());
    } catch (SecurityException se) {
    } catch (OutOfMemoryError oome) {
        logger.fatal(Locale.get("trace.TraceThreadCrashOOM") + oome.getMessage());
        oome.printStackTrace();
    } catch (Exception e) {
        logger.fatal(Locale.get("trace.TraceThreadCrashWith") + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        running = false;
    } finally {
        running = false;
    }
    running = false;
}
Example 9
Project: twim-master  File: FileBrowserCanvas.java View source code
private void browseToDirectory(FileConnection fc) throws IOException {
    Enumeration items = fc.list();
    rootFolders.removeAllElements();
    while (items.hasMoreElements()) {
        String path = (String) items.nextElement();
        rootFolders.addElement(path);
    }
    String[] folders = new String[rootFolders.size() + 1];
    folders[0] = "..";
    for (int i = 0; i < rootFolders.size(); i++) {
        folders[i + 1] = (String) rootFolders.elementAt(i);
    }
    fileMenu.setLabels(folders);
    fileMenu.setTitle("Select file");
}
Example 10
Project: alchemy-os-master  File: Driver.java View source code
public boolean canRead(String file) {
    if (file.length() == 0)
        return true;
    try {
        FileConnection fc = (FileConnection) Connector.open(getNativeURL(file), Connector.READ);
        try {
            return fc.canRead();
        } finally {
            fc.close();
        }
    } catch (IOException e) {
        return false;
    }
}
Example 11
Project: bbssh-master  File: Tools.java View source code
private static DataOutputStream openNewOutputImpl(String name) {
    try {
        FileConnection fconn = (FileConnection) Connector.open(name);
        if (fconn.exists()) {
            fconn.delete();
        }
        fconn.create();
        DataOutputStream s = fconn.openDataOutputStream();
        fconn.close();
        return s;
    } catch (Exception e) {
        Logger.error("Failed openNewOutput " + name + " " + e.getMessage());
    }
    return null;
}
Example 12
Project: devTrac-Blackberry-46-master  File: NetworkCommand.java View source code
private JSONObject readFileData(String filePath) throws Exception {
    FileConnection fileConnection = null;
    try {
        fileConnection = (FileConnection) Connector.open(filePath, Connector.READ);
        long fileSize = fileConnection.fileSize();
        long lastModified = fileConnection.lastModified();
        String fileName = fileConnection.getName();
        InputStream fileStream = fileConnection.openInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        Base64OutputStream base64OutStream = new Base64OutputStream(outStream);
        int byteRead = 0;
        while ((byteRead = fileStream.read()) != -1) {
            base64OutStream.write(byteRead);
        }
        base64OutStream.flush();
        base64OutStream.close();
        outStream.flush();
        String base64Data = outStream.toString();
        outStream.close();
        JSONObject fileData = new JSONObject();
        fileData.put("file", base64Data);
        fileData.put("filename", fileName);
        fileData.put("filesize", fileSize);
        fileData.put("timestamp", lastModified);
        fileData.put("filemime", getMimeType(fileName));
        LogCommand.DEBUG("Successfully read file " + filePath + ". Base 64 Data length is " + base64Data.length());
        return fileData;
    } catch (Exception e) {
        LogCommand.LOG("Fail to read file " + filePath + ". " + e.getMessage());
        throw e;
    } finally {
        if (fileConnection != null && fileConnection.isOpen()) {
            try {
                fileConnection.close();
            } catch (IOException e) {
            }
        }
    }
}
Example 13
Project: devTrac-master  File: NetworkCommand.java View source code
private JSONObject readFileData(String filePath) throws Exception {
    FileConnection fileConnection = null;
    try {
        fileConnection = (FileConnection) Connector.open(filePath, Connector.READ);
        long fileSize = fileConnection.fileSize();
        long lastModified = fileConnection.lastModified();
        String fileName = fileConnection.getName();
        InputStream fileStream = fileConnection.openInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        Base64OutputStream base64OutStream = new Base64OutputStream(outStream);
        int byteRead = 0;
        while ((byteRead = fileStream.read()) != -1) {
            base64OutStream.write(byteRead);
        }
        base64OutStream.flush();
        base64OutStream.close();
        outStream.flush();
        String base64Data = outStream.toString();
        outStream.close();
        JSONObject fileData = new JSONObject();
        fileData.put("file", base64Data);
        fileData.put("filename", fileName);
        fileData.put("filesize", fileSize);
        fileData.put("timestamp", lastModified);
        fileData.put("filemime", getMimeType(fileName));
        LogCommand.DEBUG("Successfully read file " + filePath + ". Base 64 Data length is " + base64Data.length());
        return fileData;
    } catch (Exception e) {
        LogCommand.LOG("Fail to read file " + filePath + ". " + e.getMessage());
        throw e;
    } finally {
        if (fileConnection != null && fileConnection.isOpen()) {
            try {
                fileConnection.close();
            } catch (IOException e) {
            }
        }
    }
}
Example 14
Project: MobScrob-master  File: MP3Player.java View source code
/**
	 * Checks that the file has .mp3 extension, and retrieves a Stream for the
	 * resource from the correct location.
	 * 
	 * @param resourceName
	 * @return
	 * @throws IOException
	 */
public InputStream getResourceAsStream(String resourceName) throws IOException {
    final String methodName = "6";
    InputStream is = null;
    // check we are getting an MP3 file
    if (!resourceName.endsWith(MP3)) {
        throw new IOException("Incompatible resource: " + resourceName + "\r\n    Can only play MP3.");
    }
    if (resourceName == null) {
        String msg = "Null resource type";
        log.error(methodName, msg);
        throw new IOException(msg);
    } else if (resourceName.startsWith(RESOURCE)) {
        int index = resourceName.indexOf(':');
        String trimmed = resourceName.substring(index + 1);
        log.debug(methodName, "Getting jar resource " + trimmed);
        is = this.getClass().getResourceAsStream(trimmed);
        log.info(methodName, "Got resource as stream, " + (is == null ? "stream is null" : "stream not null"));
    } else if (resourceName.startsWith(FILE)) {
        log.info(methodName, "Opening MP3 file stream");
        FileConnection fc = (FileConnection) Connector.open(resourceName);
        if (!fc.exists()) {
            throw new IOException("Resource " + resourceName + " cannot be found");
        }
        is = fc.openInputStream();
        log.info(methodName, "Got file as stream, " + (is == null ? "stream is null" : "stream not null"));
    } else {
        String msg = "Unknown resource type: " + resourceName;
        // unknown resource type
        log.error(methodName, msg);
        throw new IOException(msg);
    }
    return is;
}
Example 15
Project: Android-MQTT-Websocket-Client-master  File: MqttDefaultMicroFilePersistence.java View source code
public void open(String clientId, String theConnection) throws MqttPersistenceException {
    if (dataDir.exists() && !dataDir.isDirectory()) {
        throw new MqttPersistenceException();
    } else if (!dataDir.exists()) {
        try {
            dataDir.mkdir();
        } catch (Exception e) {
            throw new MqttPersistenceException();
        }
    }
    if (!dataDir.canWrite()) {
        throw new MqttPersistenceException();
    }
    StringBuffer keyBuffer = new StringBuffer();
    for (int i = 0; i < clientId.length(); i++) {
        char c = clientId.charAt(i);
        if (isSafeChar(c)) {
            keyBuffer.append(c);
        }
    }
    keyBuffer.append("-");
    for (int i = 0; i < theConnection.length(); i++) {
        char c = theConnection.charAt(i);
        if (isSafeChar(c)) {
            keyBuffer.append(c);
        }
    }
    String key = keyBuffer.toString();
    try {
        clientDir = (FileConnection) Connector.open(dataDir.getURL() + key);
    } catch (IOException e1) {
        throw new MqttPersistenceException();
    }
    if (!clientDir.exists()) {
        try {
            clientDir.mkdir();
        } catch (IOException e) {
            throw new MqttPersistenceException();
        }
    }
    try {
    // TODO: Implement File Locking
    } catch (Exception e) {
        throw new MqttPersistenceException(MqttPersistenceException.REASON_CODE_PERSISTENCE_IN_USE);
    }
    // Scan the directory for .backup files. These will
    // still exist if the JVM exited during addMessage, before
    // the new message was written to disk and the backup removed.
    restoreBackups(clientDir);
}
Example 16
Project: blackberry-commons-master  File: FileAppender.java View source code
/* (non-Javadoc)
	 * @see com.monits.blackberry.commons.logger.appender.Appender#logEvent(java.lang.String, int, java.lang.String, java.lang.Throwable)
	 */
public void logEvent(String loggerName, int logLevel, String formatedMessage, Throwable t) {
    if ((minimumLogLevel >= logLevel) && loggerName.startsWith(clazzToLog)) {
        try {
            StringUtils su = new StringUtils();
            Vector vector = su.split(filename, '/');
            // Check if the file is in a directory.
            if (vector.size() > 1) {
                String hierarchy = "";
                // Exclude the filename.
                for (int i = 0; i < (vector.size() - 1); i++) {
                    hierarchy += vector.elementAt(i) + "/";
                    FileConnection fc = (FileConnection) Connector.open(SD_CARD + hierarchy, Connector.READ_WRITE);
                    if (!fc.exists()) {
                        fc.mkdir();
                    }
                }
            }
            FileConnection fc = (FileConnection) Connector.open(SD_CARD + filename, Connector.READ_WRITE);
            // The file may or may not exist.
            if (!fc.exists()) {
                // create the file if it doesn't exist
                fc.create();
            }
            // Open stream moving cursor to the end of file (AKA append)
            OutputStream os = fc.openOutputStream(fc.fileSize());
            if (t != null) {
                os.write((formatedMessage + "\n" + t.toString() + "\n").getBytes());
            } else {
                os.write((formatedMessage + "\n").getBytes());
            }
            os.close();
            fc.close();
        } catch (IOException ioe) {
        }
    }
}
Example 17
Project: callback-blackberry-master  File: FileManager.java View source code
/**
     * Changes the length of the specified file. If shortening, data beyond new
     * length is discarded.
     * 
     * @param fileName
     *            The full path of the file to truncate
     * @param size
     *            The size to which the length of the file is to be adjusted
     * @return PluginResult containing new file size or an error code if an
     *         error occurred
     */
protected static PluginResult truncateFile(String filePath, long size) {
    long fileSize = 0;
    FileConnection fconn = null;
    try {
        fconn = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
        if (!fconn.exists()) {
            Logger.log(FileManager.class.getName() + ": path not found " + filePath);
            return new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR);
        }
        if (size >= 0) {
            fconn.truncate(size);
        }
        fileSize = fconn.fileSize();
    } catch (IOException e) {
        Logger.log(FileManager.class.getName() + ": " + e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, NO_MODIFICATION_ALLOWED_ERR);
    } finally {
        try {
            if (fconn != null)
                fconn.close();
        } catch (IOException e) {
            Logger.log(FileManager.class.getName() + ": " + e);
        }
    }
    return new PluginResult(PluginResult.Status.OK, fileSize);
}
Example 18
Project: Citation-Application-master  File: TicketNumberHandler.java View source code
/**
 * read tickets and store in class ticket storage array
 */
private void readCurrentTickets() {
    try {
        FolderCreateIfItDoesntExist("file:///store/home/user/Cite");
        FileConnection ticketFile = FileOpenForReading("file:///store/home/user/Cite/ticketFile");
        if (ticketFile != null) {
            usableTicketNumbers = readTicketsFromFileReturnStringArray(ticketFile);
            ticketFile.delete();
        }
    } catch (IOException e) {
    }
}
Example 19
Project: gcf-master  File: ReadOnlyFileTest.java View source code
public void testReadOnlyFile() throws Exception {
    String path = _classesFolderName + "testfile.txt";
    String url = "file://" + path;
    FileConnection file = (FileConnection) Connector.open(url, Connector.READ);
    assertTrue("file url is not parsed correctly", file.exists());
    assertEquals("invalid file size", 62L, file.fileSize());
    file.canRead();
    file.canWrite();
    assertEquals("invalid file name", "testfile.txt", file.getName());
    assertEquals("invalid file path", path, file.getPath());
    assertEquals("invalid file url", url, file.getURL());
    assertFalse("file is not recognised correctly", file.isDirectory());
    assertFalse("file attributes are not recognised", file.isHidden());
    try {
        file.create();
        fail("create: mode check failed");
    } catch (Exception e) {
        assertEquals("create: mode check failed", e.getClass(), IllegalModeException.class);
    }
    try {
        file.delete();
        fail("delete: mode check failed");
    } catch (Exception e) {
        assertEquals("delete: mode check failed", e.getClass(), IllegalModeException.class);
    }
    try {
        file.setReadable(false);
        fail("setReadable: mode check failed");
    } catch (Exception e) {
        assertEquals("setReadable: mode check failed", e.getClass(), IllegalModeException.class);
    }
    try {
        file.setWritable(false);
        fail("setWritable: mode check failed");
    } catch (Exception e) {
        assertEquals("setWritable: mode check failed", e.getClass(), IllegalModeException.class);
    }
    try {
        file.truncate(0);
        fail("truncate: mode check failed");
    } catch (Exception e) {
        assertEquals("truncate: mode check failed", e.getClass(), IllegalModeException.class);
    }
    if (file.availableSize() < 0) {
        fail("invalid available size");
    }
    if (file.totalSize() < 0) {
        fail("invalid total size");
    }
    file.close();
}
Example 20
Project: hestia-engine-dev-master  File: MqttDefaultMicroFilePersistence.java View source code
public void open(String clientId, String theConnection) throws MqttPersistenceException {
    if (dataDir.exists() && !dataDir.isDirectory()) {
        throw new MqttPersistenceException();
    } else if (!dataDir.exists()) {
        try {
            dataDir.mkdir();
        } catch (Exception e) {
            throw new MqttPersistenceException();
        }
    }
    if (!dataDir.canWrite()) {
        throw new MqttPersistenceException();
    }
    StringBuffer keyBuffer = new StringBuffer();
    for (int i = 0; i < clientId.length(); i++) {
        char c = clientId.charAt(i);
        if (isSafeChar(c)) {
            keyBuffer.append(c);
        }
    }
    keyBuffer.append("-");
    for (int i = 0; i < theConnection.length(); i++) {
        char c = theConnection.charAt(i);
        if (isSafeChar(c)) {
            keyBuffer.append(c);
        }
    }
    String key = keyBuffer.toString();
    try {
        clientDir = (FileConnection) Connector.open(dataDir.getURL() + key);
    } catch (IOException e1) {
        throw new MqttPersistenceException();
    }
    if (!clientDir.exists()) {
        try {
            clientDir.mkdir();
        } catch (IOException e) {
            throw new MqttPersistenceException();
        }
    }
    try {
    // TODO: Implement File Locking
    } catch (Exception e) {
        throw new MqttPersistenceException(MqttPersistenceException.REASON_CODE_PERSISTENCE_IN_USE);
    }
    // Scan the directory for .backup files. These will
    // still exist if the JVM exited during addMessage, before
    // the new message was written to disk and the backup removed.
    restoreBackups(clientDir);
}
Example 21
Project: maps-lib-nutiteq-master  File: JSR75FileSystem.java View source code
/**
   * Read a file using JSR-75 API.
   * 
   * @param filename
   *          fully-qualified file path following "file:///" qualifier
   * @return file data
   * @throws IOException
   *           if an exception occurs
   */
public byte[] readFile(final String filename) throws IOException {
    Log.debug("Loading file:///" + filename);
    FileConnection fconn = null;
    InputStream is = null;
    try {
        fconn = (FileConnection) Connector.open("file:///" + filename, Connector.READ);
        // commented to speed up
        // if (!fconn.exists() || !fconn.canRead())
        //   throw new Exception("File does not exist");
        final int sz = (int) fconn.fileSize();
        final byte[] result = new byte[sz];
        is = fconn.openInputStream();
        // multiple bytes
        int ch = 0;
        int rd = 0;
        while ((rd != sz) && (ch != -1)) {
            ch = is.read(result, rd, sz - rd);
            if (ch > 0) {
                rd += ch;
            }
        }
        return result;
    } finally {
        IOUtils.closeStream(is);
        IOUtils.closeConnection(fconn);
    }
}
Example 22
Project: mediaphone-javame-master  File: PlayNarrativeForm.java View source code
private void playAudio(String fileName) {
    try {
        closePlayer();
        mFileConnection = (FileConnection) Connector.open(fileName, Connector.READ);
        mInputStream = mFileConnection.openInputStream();
        mPlayer = Manager.createPlayer(mInputStream, "audio/amr");
        if (mPlayer != null) {
            mPlayer.prefetch();
            mPlayer.start();
        }
    } catch (Exception e) {
        if (MediaPhone.DEBUG) {
            mAudioLabel.setText("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Example 23
Project: paho.mqtt.java-master  File: MqttDefaultMicroFilePersistence.java View source code
public void open(String clientId, String theConnection) throws MqttPersistenceException {
    if (dataDir.exists() && !dataDir.isDirectory()) {
        throw new MqttPersistenceException();
    } else if (!dataDir.exists()) {
        try {
            dataDir.mkdir();
        } catch (Exception e) {
            throw new MqttPersistenceException();
        }
    }
    if (!dataDir.canWrite()) {
        throw new MqttPersistenceException();
    }
    StringBuffer keyBuffer = new StringBuffer();
    for (int i = 0; i < clientId.length(); i++) {
        char c = clientId.charAt(i);
        if (isSafeChar(c)) {
            keyBuffer.append(c);
        }
    }
    keyBuffer.append("-");
    for (int i = 0; i < theConnection.length(); i++) {
        char c = theConnection.charAt(i);
        if (isSafeChar(c)) {
            keyBuffer.append(c);
        }
    }
    String key = keyBuffer.toString();
    try {
        clientDir = (FileConnection) Connector.open(dataDir.getURL() + key);
    } catch (IOException e1) {
        throw new MqttPersistenceException();
    }
    if (!clientDir.exists()) {
        try {
            clientDir.mkdir();
        } catch (IOException e) {
            throw new MqttPersistenceException();
        }
    }
    try {
    // TODO: Implement File Locking
    } catch (Exception e) {
        throw new MqttPersistenceException(MqttPersistenceException.REASON_CODE_PERSISTENCE_IN_USE);
    }
    // Scan the directory for .backup files. These will
    // still exist if the JVM exited during addMessage, before
    // the new message was written to disk and the backup removed.
    restoreBackups(clientDir);
}
Example 24
Project: phonegap-blackberry-webworks-master  File: FileManager.java View source code
/**
     * Changes the length of the specified file. If shortening, data beyond new
     * length is discarded.
     * 
     * @param fileName
     *            The full path of the file to truncate
     * @param size
     *            The size to which the length of the file is to be adjusted
     * @return PluginResult containing new file size or an error code if an
     *         error occurred
     */
protected static PluginResult truncateFile(String filePath, long size) {
    long fileSize = 0;
    FileConnection fconn = null;
    try {
        fconn = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
        if (!fconn.exists()) {
            Logger.log(FileManager.class.getName() + ": path not found " + filePath);
            return new PluginResult(PluginResult.Status.IOEXCEPTION, NOT_FOUND_ERR);
        }
        if (size >= 0) {
            fconn.truncate(size);
        }
        fileSize = fconn.fileSize();
    } catch (IOException e) {
        Logger.log(FileManager.class.getName() + ": " + e);
        return new PluginResult(PluginResult.Status.IOEXCEPTION, NO_MODIFICATION_ALLOWED_ERR);
    } finally {
        try {
            if (fconn != null)
                fconn.close();
        } catch (IOException e) {
            Logger.log(FileManager.class.getName() + ": " + e);
        }
    }
    return new PluginResult(PluginResult.Status.OK, fileSize);
}
Example 25
Project: XCTrack-master  File: DemoGps.java View source code
private String findIGC() {
    Enumeration roots = FileSystemRegistry.listRoots();
    Enumeration files;
    FileConnection fconn = null;
    Vector dirs = new Vector();
    while (roots.hasMoreElements()) {
        String root = (String) roots.nextElement();
        if (root.length() == 0 || root.charAt(root.length() - 1) != '/')
            root += "/";
        dirs.addElement(root);
        dirs.addElement(root + "Document/");
        dirs.addElement(root + "Other/");
    }
    for (int i = 0; i < dirs.size(); i++) {
        String dir = (String) dirs.elementAt(i);
        Log.info("DemoIGC: searching " + dir);
        try {
            fconn = (FileConnection) Connector.open("file:///" + dir);
            if (fconn.exists()) {
                files = fconn.list();
                while (files.hasMoreElements()) {
                    String fn = (String) files.nextElement();
                    if (fn.toLowerCase().endsWith(".igc")) {
                        Log.info("DemoIGC: found " + dir + fn);
                        return "file:///" + dir + fn;
                    }
                }
            }
            fconn.close();
        } catch (SecurityException e) {
            Log.error("DemoIGC: error searching for file", e);
            if (fconn != null) {
                try {
                    fconn.close();
                } catch (IOException e1) {
                }
            }
        } catch (IOException e) {
            Log.error("DemoIGC: error searching for file", e);
            if (fconn != null) {
                try {
                    fconn.close();
                } catch (IOException e1) {
                }
            }
        }
    }
    return null;
}
Example 26
Project: hecl-master  File: FileCmds.java View source code
public Thing operate(int cmd, Interp interp, Thing[] argv) throws HeclException {
    String fname = null;
    /* These commands are platform agnostic - we'll handle them first. */
    switch(cmd) {
        /* Note that FILESPLIT is much more platform dependent, so
	       it is below, in the two sections of ifdef'ed code.  */
        case FILEJOIN:
            {
                Vector filenamelist = ListThing.get(argv[1]);
                /* Takes a list like {a b c} and converts it to a
		   filename such as a/b/c. */
                StringBuffer res = new StringBuffer("");
                boolean first = true;
                for (int i = 0; i < filenamelist.size(); i++) {
                    if (first == false) {
                        res.append(Interp.fileseparator);
                    } else {
                        /* FIXME - broken on windows */
                        if (!filenamelist.elementAt(i).toString().equals("/")) {
                            first = false;
                        }
                    }
                    res.append(filenamelist.elementAt(i).toString());
                }
                return new Thing(res.toString());
            }
        case SOURCE:
            {
                HeclFileUtils.sourceFile(interp, argv[1].toString());
                return null;
            }
        case CURRENTFILE:
            {
                return interp.currentFile;
            }
        case GETCWD:
            return new Thing(System.getProperty("user.dir"));
        case CD:
            {
                //#if javaversion >= 1.5
                return new Thing(System.setProperty("user.dir", argv[1].toString()));
            //#endif
            }
    }
    /* 'Regular' Java uses File, J2ME uses FileConnection. */
    //#if javaversion >= 1.5
    File tfile = null;
    if (cmd != LISTROOTS && cmd != SOCKET) {
        fname = StringThing.get(argv[1]);
        tfile = new File(fname);
    }
    //#else
    FileConnection fconn = null;
    if (cmd != LISTROOTS && cmd != SOCKET) {
        fname = StringThing.get(argv[1]);
        try {
            fconn = (FileConnection) Connector.open(fname);
        } catch (IOException e) {
            throw new HeclException("IO Exception in " + argv[0].toString() + ": " + e.toString());
        }
    }
    //#if javaversion >= 1.5
    switch(cmd) {
        case OPEN:
            {
                boolean write = false;
                if (argv.length == 3) {
                    String perms = argv[2].toString();
                    if (perms.indexOf('w') > -1) {
                        write = true;
                    }
                }
                HeclChannel retval;
                try {
                    if (write) {
                        retval = new HeclChannel(new DataOutputStream(new FileOutputStream(new File(fname))));
                    } else {
                        retval = new HeclChannel(new DataInputStream(new FileInputStream(new File(fname))));
                    }
                } catch (IOException ioe) {
                    throw new HeclException("Error opening '" + fname + "' :" + ioe.toString());
                }
                return ObjectThing.create(retval);
            }
        case SOCKET:
            {
                InetSocketAddress isa = null;
                try {
                    isa = new InetSocketAddress(argv[1].toString(), IntThing.get(argv[2]));
                    Socket sock = new Socket();
                    sock.connect(isa);
                    HeclChannel retval = new HeclChannel(new DataInputStream(sock.getInputStream()), new DataOutputStream(sock.getOutputStream()));
                    return ObjectThing.create(retval);
                } catch (IOException ioe) {
                    throw new HeclException("Error opening: " + isa + " " + ioe.toString());
                }
            }
        case READABLE:
            {
                /* 		    if (argv.length == 3) {
		    boolean readable = IntThing.get(argv[2]) == 1;
		    fconn.setReadable(readable);
		    }  */
                return IntThing.create(tfile.canRead());
            }
        case WRITABLE:
            {
                /* 		    if (argv.length == 3) {
		    boolean writable = IntThing.get(argv[2]) == 1;
		    fconn.setWritable(writable);
		    }  */
                return IntThing.create(tfile.canWrite());
            }
        case HIDDEN:
            {
                /* 		    if (argv.length == 3) {
		    boolean hidden = IntThing.get(argv[2]) == 1;
		    fconn.setHidden(hidden);
		    }  */
                return IntThing.create(tfile.isHidden());
            }
        case EXISTS:
            return IntThing.create(tfile.exists());
        case DELETE:
            return IntThing.create(tfile.delete());
        case SIZE:
            return LongThing.create(tfile.length());
        case NAME:
            return new Thing(tfile.getName());
        case PATH:
            return new Thing(tfile.getPath());
        case ABSPATH:
            return new Thing(tfile.getAbsolutePath());
        case CANONPATH:
            try {
                return new Thing(tfile.getCanonicalPath());
            } catch (Exception e) {
                throw new HeclException("I/O error for file '" + tfile.toString() + ",: " + e.toString());
            }
        case ISABSOLUTE:
            return IntThing.create(tfile.isAbsolute());
        case MTIME:
            return LongThing.create(tfile.lastModified());
        case ISDIRECTORY:
            return IntThing.create(tfile.isDirectory());
        case ISOPEN:
            throw new HeclException("not implemented");
        case LIST:
            {
                Vector v = new Vector();
                String[] filenames = tfile.list();
                for (int i = 0; i < filenames.length; i++) {
                    v.addElement(new Thing(filenames[i]));
                }
                return ListThing.create(v);
            }
        case LISTROOTS:
            {
                Vector v = new Vector();
                File[] roots = File.listRoots();
                for (int i = 0; i < roots.length; i++) {
                    v.addElement(new Thing(roots[i].getName()));
                }
                return ListThing.create(v);
            }
        case MKDIR:
            {
                tfile.mkdir();
                return new Thing(fname);
            }
        case RENAME:
            {
                tfile.renameTo(new File(argv[2].toString()));
                return argv[2];
            }
        case TRUNCATE:
            {
                /* FIXME */
                throw new HeclException("not implemented");
            }
        case DU:
            {
                //#if javaversion >= 1.6
                Hashtable du = new Hashtable();
                du.put("total", LongThing.create(tfile.getTotalSpace()));
                du.put("used", LongThing.create(tfile.getUsableSpace()));
                return HashThing.create(du);
                //#else
                throw new HeclException("not implemented");
            //#endif
            }
        case FILESPLIT:
            {
                Vector resultv = new Vector();
                Vector reversed = new Vector();
                File fn = new File(fname);
                File pf = fn.getParentFile();
                String fns;
                String pfs;
                /* Walk through all elements, compare the element with
		 * its parent, and tack the difference onto the
		 * Vector.  */
                String ss = null;
                while (pf != null) {
                    fns = fn.toString();
                    pfs = pf.toString();
                    ss = fns.substring(pfs.length(), fns.length());
                    /* The 'diff' operation leaves path components
		     * with a leading slash.  Remove it. */
                    if (ss.charAt(0) == File.separatorChar) {
                        ss = ss.substring(1, ss.length());
                    }
                    reversed.addElement(new Thing(ss));
                    fn = pf;
                    pf = pf.getParentFile();
                }
                reversed.addElement(new Thing(fn.toString()));
                /* Ok, now we correct the order of the list by
		 * reversing it. */
                int j = 0;
                for (int i = reversed.size() - 1; i >= 0; i--) {
                    Thing t = (Thing) reversed.elementAt(i);
                    resultv.addElement(t);
                    j++;
                }
                return ListThing.create(resultv);
            }
        default:
            throw new HeclException("Unknown file command '" + argv[0].toString() + "' with code '" + cmd + "'.");
    }
    try {
        switch(cmd) {
            case OPEN:
                {
                    boolean write = false;
                    if (argv.length == 3) {
                        String perms = argv[2].toString();
                        if (perms.indexOf('w') > -1) {
                            write = true;
                        }
                    }
                    HeclChannel retval;
                    if (write) {
                        if (!fconn.exists()) {
                            fconn.create();
                        }
                        retval = new HeclChannel(fconn.openDataOutputStream());
                    } else {
                        retval = new HeclChannel(fconn.openDataInputStream());
                    }
                    return ObjectThing.create(retval);
                }
            case SOCKET:
                {
                    String uri = "socket://" + argv[1].toString() + ":" + argv[2].toString();
                    try {
                        StreamConnection sc = (StreamConnection) Connector.open(uri);
                        HeclChannel retval = new HeclChannel(new DataInputStream(sc.openInputStream()), new DataOutputStream(sc.openOutputStream()));
                        return ObjectThing.create(retval);
                    } catch (IOException ioe) {
                        throw new HeclException("Error opening: " + uri + " " + ioe.toString());
                    }
                }
            case READABLE:
                {
                    if (argv.length == 3) {
                        boolean readable = IntThing.get(argv[2]) == 1;
                        fconn.setReadable(readable);
                    }
                    return IntThing.create(fconn.canRead());
                }
            case WRITABLE:
                {
                    if (argv.length == 3) {
                        boolean writable = IntThing.get(argv[2]) == 1;
                        fconn.setWritable(writable);
                    }
                    return IntThing.create(fconn.canWrite());
                }
            case HIDDEN:
                {
                    if (argv.length == 3) {
                        boolean hidden = IntThing.get(argv[2]) == 1;
                        fconn.setHidden(hidden);
                    }
                    return IntThing.create(fconn.isHidden());
                }
            case EXISTS:
                {
                    return IntThing.create(fconn.exists());
                }
            case DELETE:
                {
                    fconn.delete();
                    return Thing.emptyThing();
                }
            case SIZE:
                {
                    return LongThing.create(fconn.fileSize());
                }
            case NAME:
                {
                    return new Thing(fconn.getName());
                }
            case MTIME:
                {
                    return LongThing.create(fconn.lastModified());
                }
            case ISDIRECTORY:
                {
                    return IntThing.create(fconn.isDirectory());
                }
            case ISOPEN:
                {
                    return IntThing.create(fconn.isOpen());
                }
            case LIST:
                {
                    Vector v = new Vector();
                    for (Enumeration e = fconn.list(); e.hasMoreElements(); ) {
                        v.addElement(new Thing((String) e.nextElement()));
                    }
                    return ListThing.create(v);
                }
            case LISTROOTS:
                {
                    Vector v = new Vector();
                    for (Enumeration e = FileSystemRegistry.listRoots(); e.hasMoreElements(); ) {
                        v.addElement(new Thing((String) e.nextElement()));
                    }
                    return ListThing.create(v);
                }
            case MKDIR:
                {
                    fconn.mkdir();
                    return new Thing(fname);
                }
            case RENAME:
                {
                    fconn.rename(argv[2].toString());
                    return argv[2];
                }
            case TRUNCATE:
                {
                    fconn.truncate(LongThing.get(argv[2]));
                }
            case DU:
                {
                    Hashtable du = new Hashtable();
                    du.put("total", LongThing.create(fconn.totalSize()));
                    du.put("used", LongThing.create(fconn.usedSize()));
                    return HashThing.create(du);
                }
            case FILESPLIT:
                {
                    /* This isn't very good, but it's basically the *
		       best we can do with what's available on mobile
		       devices. */
                    return ListThing.stringSplit(fname, Interp.fileseparator);
                }
            default:
                throw new HeclException("Unknown file command '" + argv[0].toString() + "' with code '" + cmd + "'.");
        }
    } catch (IOException e) {
        throw new HeclException("IO Exception: " + HeclException.argvToString(argv) + " : " + e.toString());
    }
//#endif
}
Example 27
Project: JDE-Samples-master  File: LimitedRateStreamingSource.java View source code
/**
     * Open a connection to the locator
     * 
     * @throws IOException
     *             Thrown if the firewall disallows a connection that is not
     *             btspp or comm or if save file could not be created
     */
public void connect() throws IOException {
    // Open the connection to the remote file
    _contentConnection = (ContentConnection) Connector.open(getLocator(), Connector.READ);
    // Cache a reference to the locator
    final String locator = getLocator();
    // Report status
    System.out.println("Loading: " + locator);
    System.out.println("Size: " + _contentConnection.getLength());
    // The name of the remote file begins after the last forward slash
    final int filenameStart = locator.lastIndexOf('/');
    // The file name ends at the first instance of a semicolon
    int paramStart = locator.indexOf(';');
    // If there is no semicolon, the file name ends at the end of the line
    if (paramStart < 0) {
        paramStart = locator.length();
    }
    // Extract the file name
    final String filename = locator.substring(filenameStart, paramStart);
    System.out.println("Filename: " + filename);
    // Open a local save file with the same name as the remote file
    _saveFile = (FileConnection) Connector.open("file:///SDCard/blackberry/music" + filename, Connector.READ_WRITE);
    // If the file doesn't already exist, create it
    if (!_saveFile.exists()) {
        _saveFile.create();
    }
    // Open the file for writing
    _saveFile.setReadable(true);
    // Open a shared input stream to the local save file to
    // allow many simultaneous readers.
    final SharedInputStream fileStream = SharedInputStream.getSharedInputStream(_saveFile.openInputStream());
    // Begin reading at the beginning of the file
    fileStream.setCurrentPosition(0);
    // If the local file is smaller than the remote file...
    if (_saveFile.fileSize() < _contentConnection.getLength()) {
        // Did not get the entire file, set the system to try again
        _saveFile.setWritable(true);
        // A non-null save stream is used as a flag later to indicate that
        // the file download was incomplete.
        _saveStream = _saveFile.openOutputStream();
        // Use a new shared input stream for buffered reading
        _readAhead = SharedInputStream.getSharedInputStream(_contentConnection.openInputStream());
    } else {
        // The download is complete
        _downloadComplete = true;
        // We can use the initial input stream to read the buffered media
        _readAhead = fileStream;
        // We can close the remote connection
        _contentConnection.close();
    }
    if (_forcedContentType != null) {
        // Use the user-defined content type if it is set
        _feedToPlayer = new LimitedRateSourceStream(_readAhead, _forcedContentType);
    } else {
        // Otherwise, use the MIME types of the remote file
        _feedToPlayer = new LimitedRateSourceStream(_readAhead, _contentConnection.getType());
    }
}
Example 28
Project: N300FP-master  File: CameraCommand.java View source code
public void fileJournalChanged() {
    long USN = FileSystemJournal.getNextUSN();
    for (long i = USN - 1; i >= lastUSN; --i) {
        FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
        if (entry != null) {
            if (entry.getEvent() == FileSystemJournalEntry.FILE_CHANGED) {
                if (entry.getPath().indexOf(".jpg") != -1) {
                    lastUSN = USN;
                    photoPath = entry.getPath();
                    InputStream theImage;
                    byte[] imageBytes;
                    Base64OutputStream base64OutputStream = null;
                    try {
                        FileConnection fconn = (FileConnection) Connector.open("file://" + photoPath);
                        imageBytes = new byte[(int) fconn.fileSize()];
                        theImage = fconn.openInputStream();
                        theImage.read(imageBytes);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(imageBytes.length);
                        base64OutputStream = new Base64OutputStream(byteArrayOutputStream);
                        base64OutputStream.write(imageBytes);
                        base64OutputStream.flush();
                        base64OutputStream.close();
                        byteArrayOutputStream.flush();
                        byteArrayOutputStream.close();
                        //int sizeofbase64 = byteArrayOutputStream.toString().length();
                        returnVal = ";if (navigator.camera.onSuccess) { navigator.camera.onSuccess('" + byteArrayOutputStream.toString() + "'); }";
                    } catch (IOException e) {
                        e.printStackTrace();
                        returnVal = CAMERA_ERROR_CALLBACK;
                    }
                    berryGap.pendingResponses.addElement(returnVal);
                    closeCamera();
                }
            }
        }
    }
    lastUSN = USN;
}
Example 29
Project: signingserver-bb-master  File: NarstService.java View source code
public static String[] getAllCods(String directory) throws Exception {
    FileConnection fileConnection = null;
    try {
        fileConnection = (FileConnection) Connector.open(directory);
        if (!fileConnection.exists() || !fileConnection.isDirectory()) {
            return null;
        }
        Vector files = new Vector();
        Enumeration enumerator = fileConnection.list("*.cod", false);
        while (enumerator.hasMoreElements()) {
            files.addElement(enumerator.nextElement());
        }
        String[] _files = new String[files.size()];
        files.copyInto(_files);
        return _files;
    } finally {
        IOUtility.safeClose(fileConnection);
    }
}
Example 30
Project: WebWorks-master  File: SystemExtension.java View source code
// Not sure if it's a published API, there is no this API in WebWorks
// API reference. It returns UNDEFINED in old style java code.
/**
     * Set background of home screen
     * @param filepath - path of image file
     * @throws Exception
     */
public void setHomeScreenBackground(String filePath) throws Exception {
    FileConnection fileConnection = null;
    try {
        Connection con = Connector.open(filePath);
        if (con != null && con instanceof FileConnection) {
            fileConnection = (FileConnection) con;
            if (!fileConnection.exists() || fileConnection.isDirectory()) {
                throw new Exception("Invalid file URI");
            }
            // set home screen background
            HomeScreen.setBackgroundImage(filePath);
        }
    } finally {
        if (fileConnection != null) {
            fileConnection.close();
        }
    }
}
Example 31
Project: phonegap-blackberry-widget-master  File: FileManager.java View source code
/**
     * Writes data to the specified file.
     * @param filePath  Full path of file to be written to
     * @param data      Data to be written
     * @param position  Position at which to begin writing
     */
protected int writeFile(String filePath, String data, int position) throws IOException {
    FileConnection fconn = null;
    OutputStream os = null;
    byte[] bytes = data.getBytes();
    try {
        fconn = (FileConnection) Connector.open(filePath, Connector.READ_WRITE);
        if (!fconn.exists()) {
            fconn.create();
        }
        os = fconn.openOutputStream(position);
        os.write(bytes);
    } finally {
        try {
            if (os != null)
                os.close();
            if (fconn != null)
                fconn.close();
        } catch (IOException e) {
            Logger.log(this.getClass().getName() + ": " + e);
        }
    }
    return bytes.length;
}
Example 32
Project: LEADT-master  File: URLHandler.java View source code
/** Open file or URL.  Give error if there is a problem with the URL/file.*/
public void handleOpen(String url, String username, String password) throws IOException, Exception {
    try {
        if (url.startsWith("file://")) {
            //#ifdef DJSR75
            /*
				 * Open an FileConnection with the file system 
				 */
            boolean loaded = false;
            m_fc = (FileConnection) Connector.open(url, Connector.READ);
            m_lastMod = m_fc.lastModified();
            m_inputStream = m_fc.openInputStream();
            loaded = true;
            /*
				 * Open an InputConnection with the file system.
				 * The trick is knowing the URL.
				 */
            if (!loaded) {
                m_ic = (InputConnection) Connector.open(url, Connector.READ);
                m_inputStream = m_ic.openInputStream();
            }
        //#endif
        } else if (url.startsWith("jar://")) {
            // If testing, allow opening of files in the jar.
            m_inputStream = this.getClass().getResourceAsStream(url.substring(6));
            if (m_inputStream == null) {
                new IOException("No file found in jar:  " + url);
            }
            int dotPos = url.lastIndexOf('.');
            if (dotPos >= 0) {
                m_contentType = url.substring(dotPos + 1);
            }
        } else {
            /**
				 * Open an HttpConnection or HttpsConnection with the Web server
				 * The default request method is GET
				 */
            if (url.startsWith("https:")) {
                //#ifdef DMIDP20
                m_hc = (HttpsConnection) Connector.open(url);
                //#else
                // If not supporting https, allow method to throw the
                // error.  Some implementations do allow this to work.
                m_hc = (HttpConnection) Connector.open(url);
            //#endif
            } else {
                m_hc = (HttpConnection) Connector.open(url);
            }
            m_hc.setRequestMethod(HttpConnection.GET);
            /** Some web servers requires these properties */
            m_hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
            m_hc.setRequestProperty("Content-Length", "0");
            m_hc.setRequestProperty("Connection", "close");
            /** Add credentials if they are defined */
            if (username.length() > 0) {
                /** 
					 * Add authentication header in HTTP request. Basic authentication
					 * should be formatted like this:
					 *     Authorization: Basic QWRtaW46Zm9vYmFy
					 */
                String userPass;
                Base64 b64 = new Base64();
                userPass = username + ":" + password;
                userPass = b64.encode(userPass.getBytes());
                m_hc.setRequestProperty("Authorization", "Basic " + userPass);
            }
            int respCode = m_hc.getResponseCode();
            m_inputStream = m_hc.openInputStream();
            String respMsg = m_hc.getResponseMessage();
            m_lastMod = m_hc.getLastModified();
            m_contentType = m_hc.getHeaderField("content-type");
            m_location = m_hc.getHeaderField("location");
            //#ifdef DLOGGING
            if (fineLoggable) {
                logger.fine("responce code=" + respCode);
            }
            if (fineLoggable) {
                logger.fine("responce message=" + respMsg);
            }
            if (fineLoggable) {
                logger.fine("responce location=" + m_hc.getHeaderField("location"));
            }
            if (finestLoggable) {
                for (int ic = 0; ic < 20; ic++) {
                    logger.finest("hk=" + ic + "," + m_hc.getHeaderFieldKey(ic));
                    logger.finest("hf=" + ic + "," + m_hc.getHeaderField(ic));
                }
            }
            // Don't do HTML redirect as wa may want to process an HTML.
            if ((respCode == HttpConnection.HTTP_NOT_FOUND) || (respCode == HttpConnection.HTTP_INTERNAL_ERROR) || (respCode == HttpConnection.HTTP_FORBIDDEN)) {
                throw new IOException("HTTP error " + respCode + ((respMsg == null) ? "" : " " + respMsg));
            }
            if ((((respCode == HttpConnection.HTTP_MOVED_TEMP) || (respCode == HttpConnection.HTTP_MOVED_PERM) || (respCode == HttpConnection.HTTP_TEMP_REDIRECT) || (respCode == HttpConnection.HTTP_SEE_OTHER)) || ((respCode == HttpConnection.HTTP_OK) && respMsg.equals("Moved Temporarily"))) && (m_location != null)) {
                m_needRedirect = true;
                return;
            }
        }
        //#ifdef DLOGGING
        if (finestLoggable) {
            logger.finest("m_contentType=" + m_contentType);
        }
    //#endif
    } catch (IllegalArgumentException e) {
        logger.severe("handleOpen possible bad url error with " + url, e);
        if ((url != null) && url.startsWith("file://")) {
            System.err.println("Cannot process file.");
        }
        throw new CauseException("Error while parsing RSS data:  " + url, e);
    } catch (ConnectionNotFoundException e) {
        logger.severe("handleOpen connection error with " + url, e);
        if ((url != null) && url.startsWith("file://")) {
            System.err.println("Cannot process file.");
        }
        throw new CauseException("Bad URL/File or protocol error while " + "opening: " + url, e);
    } catch (CertificateException e) {
        logger.severe("handleOpen https security error with " + url, e);
        if ((url != null) && url.startsWith("file://")) {
            System.err.println("Cannot process file.");
        }
        throw new CauseException("Bad URL/File or protocol error or " + "certifacate error while opening: " + url, e);
    } catch (IOException e) {
        throw e;
    } catch (SecurityException e) {
        logger.severe("handleOpen security error with " + url, e);
        if ((url != null) && url.startsWith("file://")) {
            System.err.println("Cannot process file.");
        }
        throw new CauseException("Security error while oening " + ": " + url, e);
    } catch (Exception e) {
        logger.severe("handleOpen internal error with " + url, e);
        if ((url != null) && (url.startsWith("file://"))) {
            System.err.println("Cannot process file.");
        }
        throw new CauseException("Internal error while parsing " + ": " + url, e);
    } catch (Throwable t) {
        logger.severe("handleOpen internal error with " + url, t);
        t.printStackTrace();
        throw new CauseException("Internal error while parsing RSS data " + ":l" + url, t);
    }
}
Example 33
Project: LiveFootball-master  File: Log.java View source code
/**
     * Default method for creating the output writer into which we write, this method
     * creates a simple log file using the file connector
     * 
     * @return writer object
     * @throws IOException when thrown by the connector
     */
protected Writer createWriter() throws IOException {
    try {
        if (instance.getFileURL() == null) {
            instance.setFileURL("file:///" + FileSystemRegistry.listRoots().nextElement() + "/lwuit.log");
        }
        FileConnection con = (FileConnection) Connector.open(instance.getFileURL(), Connector.READ_WRITE);
        if (con.exists()) {
            return new OutputStreamWriter(con.openOutputStream(con.fileSize()));
        }
        con.create();
        return new OutputStreamWriter(con.openOutputStream());
    } catch (Exception err) {
        setFileWriteEnabled(false);
        return new OutputStreamWriter(new ByteArrayOutputStream());
    }
}
Example 34
Project: lwuit-master  File: MIDPImpl.java View source code
/**
     * @inheritDoc
     */
public OutputStream openOutputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        FileConnection fc = (FileConnection) Connector.open((String) connection, Connector.READ_WRITE);
        if (!fc.exists()) {
            fc.create();
        }
        BufferedOutputStream o = new BufferedOutputStream(fc.openOutputStream(), (String) connection);
        o.setConnection(fc);
        return o;
    }
    return new BufferedOutputStream(((HttpConnection) connection).openOutputStream(), ((HttpConnection) connection).getURL());
}
Example 35
Project: Tutorial_ZXingConAndroid-master  File: ZXingLMMainScreen.java View source code
public void run() {
    FileConnection file = null;
    InputStream is = null;
    Image capturedImage = null;
    try {
        file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE);
        is = file.openInputStream();
        capturedImage = Image.createImage(is);
    } catch (IOException e) {
        Log.error("Problem creating image: " + e);
        removeProgressBar();
        invalidate();
        showMessage("An error occured processing the image.");
        return;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (file != null && file.exists()) {
                if (file.isOpen()) {
                    file.delete();
                    file.close();
                }
                Log.info("Deleted image file.");
            }
        } catch (IOException ioe) {
            Log.error("Error while closing file: " + ioe);
        }
    }
    if (capturedImage != null) {
        Log.info("Got image...");
        LuminanceSource source = new LCDUIImageLuminanceSource(capturedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
        Result result;
        ReasonableTimer decodingTimer = null;
        try {
            decodingTimer = new ReasonableTimer();
            Log.info("Attempting to decode image...");
            result = reader.decode(bitmap, readerHints);
            decodingTimer.finished();
        } catch (ReaderException e) {
            Log.error("Could not decode image: " + e);
            decodingTimer.finished();
            removeProgressBar();
            invalidate();
            boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue();
            if (showResolutionMsg) {
                showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480).");
            } else {
                showMessage("A QR Code was not found in the image.");
            }
            return;
        }
        if (result != null) {
            String resultText = result.getText();
            Log.info("result: " + resultText);
            if (isURI(resultText)) {
                resultText = URLDecoder.decode(resultText);
                removeProgressBar();
                invalidate();
                if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) {
                    showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480).");
                }
                DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText));
                invokeBrowser(resultText);
                return;
            }
        } else {
            removeProgressBar();
            invalidate();
            showMessage("A QR Code was not found in the image.");
            return;
        }
    }
    removeProgressBar();
    invalidate();
}
Example 36
Project: zxing-iphone-master  File: ZXingLMMainScreen.java View source code
public void run() {
    FileConnection file = null;
    InputStream is = null;
    Image capturedImage = null;
    try {
        file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE);
        is = file.openInputStream();
        capturedImage = Image.createImage(is);
    } catch (IOException e) {
        Log.error("Problem creating image: " + e);
        removeProgressBar();
        invalidate();
        showMessage("An error occured processing the image.");
        return;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (file != null && file.exists()) {
                if (file.isOpen()) {
                    file.close();
                }
                file.delete();
                Log.info("Deleted image file.");
            }
        } catch (IOException ioe) {
            Log.error("Error while closing file: " + ioe);
        }
    }
    if (capturedImage != null) {
        Log.info("Got image...");
        LuminanceSource source = new LCDUIImageLuminanceSource(capturedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
        Result result;
        ReasonableTimer decodingTimer = null;
        try {
            decodingTimer = new ReasonableTimer();
            Log.info("Attempting to decode image...");
            result = reader.decode(bitmap, readerHints);
            decodingTimer.finished();
        } catch (ReaderException e) {
            Log.error("Could not decode image: " + e);
            decodingTimer.finished();
            removeProgressBar();
            invalidate();
            boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue();
            if (showResolutionMsg) {
                showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480).");
            } else {
                showMessage("A QR Code was not found in the image.");
            }
            return;
        }
        if (result != null) {
            String resultText = result.getText();
            Log.info("result: " + resultText);
            if (isURI(resultText)) {
                resultText = URLDecoder.decode(resultText);
                removeProgressBar();
                invalidate();
                if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) {
                    showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480).");
                }
                DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText));
                invokeBrowser(resultText);
                return;
            }
        } else {
            removeProgressBar();
            invalidate();
            showMessage("A QR Code was not found in the image.");
            return;
        }
    }
    removeProgressBar();
    invalidate();
}
Example 37
Project: phoneme-qtopia-master  File: PIMDatabase.java View source code
/**
     *  Gets the list of names for given list type.
     *
     * @param listType - CONTACT_LIST, EVENT_LIST or  TODO_LIST
     *
     * @return array of names
     */
public String[] getListNames(int listType) {
    Vector vect_names = new Vector();
    Enumeration enListType = null;
    FileConnection tmpDir;
    Protocol conn = new Protocol();
    try {
        tmpDir = (FileConnection) conn.openPrim(classSecurityToken, getTypeDir(listType));
        enListType = tmpDir.list();
        tmpDir.close();
    } catch (IOException e) {
        if (Logging.TRACE_ENABLED) {
            Logging.trace(e, "getListNames: FileConnection problem");
        }
    }
    while (enListType.hasMoreElements()) {
        String curr_name = (enListType.nextElement()).toString();
        if (// The last symbol is "/"
        curr_name.endsWith(fileSep)) {
            vect_names.addElement(curr_name.substring(0, // save the list name
            curr_name.length() - 1));
        }
    }
    String[] names = new String[vect_names.size()];
    Enumeration dir_names = vect_names.elements();
    int i;
    for (i = 0; i < names.length; i++) {
        names[i] = (dir_names.nextElement()).toString();
    }
    return names;
}
Example 38
Project: CodenameOne-master  File: GameCanvasImplementation.java View source code
/**
     * @inheritDoc
     */
public OutputStream openOutputStream(Object connection) throws IOException {
    if (connection instanceof String) {
        FileConnection fc = (FileConnection) Connector.open((String) connection, Connector.READ_WRITE);
        if (!fc.exists()) {
            fc.create();
        }
        BufferedOutputStream o = new BufferedOutputStream(fc.openOutputStream(), (String) connection);
        o.setConnection(fc);
        return o;
    }
    return new BufferedOutputStream(((HttpConnection) connection).openOutputStream(), ((HttpConnection) connection).getURL());
}
Example 39
Project: jimm-multi-master  File: FileSystem.java View source code
private static boolean supportJSR75() {
    try {
        return Class.forName("javax.microedition.io.file.FileConnection") != null;
    } catch (ClassNotFoundException ignored) {
    }
    return false;
}