Example usage for java.util.logging Level FINER

List of usage examples for java.util.logging Level FINER

Introduction

In this page you can find the example usage for java.util.logging Level FINER.

Prototype

Level FINER

To view the source code for java.util.logging Level FINER.

Click Source Link

Document

FINER indicates a fairly detailed tracing message.

Usage

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

/**
 * For each extension specified, call the extension's
 * {@link IExtensionInitializer#initialize} method.  Note that this
 * can cause additional extensions to be registered though the
 * {@link ExtensionRegistrar}./*from  w  w  w  .  j  a va2 s .  com*/
 *
 * @param extensions The list of extensions to initialize
 * @param reg The extension registrar.
 */
protected void callExtensionInitializers(Iterable<IAggregatorExtension> extensions, ExtensionRegistrar reg) {
    final String sourceMethod = "callextensionInitializers"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { extensions, reg });
    }
    for (IAggregatorExtension extension : extensions) {
        Object instance = extension.getInstance();
        if (instance instanceof IExtensionInitializer) {
            ((IExtensionInitializer) instance).initialize(this, extension, reg);
        }
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 * Creates and returns a map containing all of the deployed application names.
 *
 * @return a list of all the deployed applications in the service grid.
 *///from w  w  w . ja  v a  2  s  .c  o m
@JsonResponseExample(status = "success", responseBody = "[\"petclinic\", \"travel\"]", comments = "In the example, the deployed applications in the service grid are petclinic and travel")
@PossibleResponseStatuses(responseStatuses = {
        @PossibleResponseStatus(code = HTTP_OK, description = "success") })
@RequestMapping(value = "/applications", method = RequestMethod.GET)
@PreAuthorize("isFullyAuthenticated()")
@PostFilter("hasPermission(filterObject, 'view')")
@ResponseBody
public Map<String, Object> getApplicationNamesList() {
    if (logger.isLoggable(Level.FINER)) {
        logger.finer("received request to list applications");
    }

    final Applications apps = admin.getApplications();
    final Map<String, Object> resultsMap = new HashMap<String, Object>();
    for (final Application app : apps) {
        if (!app.getName().equals(CloudifyConstants.MANAGEMENT_APPLICATION_NAME)) {
            for (final ProcessingUnit pu : app.getProcessingUnits().getProcessingUnits()) {
                if (pu != null) {
                    final String authGroups = pu.getBeanLevelProperties().getContextProperties()
                            .getProperty(CloudifyConstants.CONTEXT_PROPERTY_AUTH_GROUPS);
                    resultsMap.put(app.getName(), authGroups);
                    break;
                }
            }
        }
    }

    return successStatus(resultsMap);
}

From source file:edu.umass.cs.gigapaxos.PaxosInstanceStateMachine.java

private MessagingTask[] handleAccept(AcceptPacket accept) {
    this.paxosManager.heardFrom(accept.ballot.coordinatorID); // FD
    RequestInstrumenter.received(accept, accept.sender, this.getMyID());

    // if(!accept.hasRequestValue())
    // DelayProfiler.updateCount("C_DIGESTED_ACCEPTS_RCVD",
    // accept.batchSize()+1);

    AcceptPacket copy = accept;/*from w w w .  j a va  2s.  c  o  m*/
    if (DIGEST_REQUESTS && !accept.hasRequestValue() && (accept = this.paxosManager.match(accept)) == null) {
        log.log(Level.FINE, "{0} received unmatched accept ",
                new Object[] { this, copy.getSummary(log.isLoggable(Level.FINE)) });
        // if(this.paxosState.getSlot() - copy.slot > 0)
        // DelayProfiler.updateCount("C_EXECD_ACCEPTS_RCVD",
        // copy.batchSize()+1);
        return new MessagingTask[0];
    } else
        log.log(Level.FINER, "{0} received matching accept ", new Object[] { this, accept.getSummary() });

    // DelayProfiler.updateCount("C_ACCEPTS_RCVD", accept.batchSize()+1);
    assert (accept.hasRequestValue());

    if (instrument(10))
        DelayProfiler.updateMovAvg("#batched", accept.batchSize() + 1);
    if ((this.paxosState.getAccept(accept.slot) == null) && (this.paxosState.getSlot() - accept.slot <= 0))
        this.paxosManager.incrOutstanding(accept.addDebugInfoDeep("a")); // stats

    if (EXECUTE_UPON_ACCEPT) { // only for testing
        PaxosInstanceStateMachine.execute(this, getPaxosManager(), this.getApp(), accept, false);
        if (Util.oneIn(10))
            log.info(DelayProfiler.getStats());
        // return null;
    }

    // have acceptor handle accept
    Ballot ballot = null;
    PValuePacket prev = this.paxosState.getAccept(accept.slot);
    try {
        ballot = !EXECUTE_UPON_ACCEPT ? this.paxosState.acceptAndUpdateBallot(accept, this.getMyID())
                : this.paxosState.getBallot();
    } catch (Error e) {
        log.severe(this + " : " + e.getMessage());
        Util.suicide(e.getMessage());
    }
    if (ballot == null)
        return null; // can happen only if acceptor is stopped.

    this.garbageCollectAccepted(accept.getMedianCheckpointedSlot());
    if (accept.isRecovery())
        return null; // recovery ACCEPTS do not need any reply

    AcceptReplyPacket acceptReply = new AcceptReplyPacket(this.getMyID(), ballot, accept.slot,
            GC_MAJORITY_EXECUTED ? this.paxosState.getSlot() - 1
                    : lastCheckpointSlot(this.paxosState.getSlot() - 1, accept.getPaxosID()),
            accept.requestID);

    // no logging if NACking anyway
    AcceptPacket toLog = (accept.ballot.compareTo(ballot) >= 0
            // no logging if already garbage collected or previously accepted
            && accept.slot - this.paxosState.getGCSlot() > 0
            && (prev == null || prev.ballot.compareTo(accept.ballot) < 0)) ? accept : null;

    MessagingTask acceptReplyTask = accept.isRecovery() ? new LogMessagingTask(toLog)
            : toLog != null ? new LogMessagingTask(accept.sender, acceptReply, toLog)
                    : new MessagingTask(accept.sender, acceptReply);
    RequestInstrumenter.sent(acceptReply, this.getMyID(), accept.sender);

    // might release some meta-commits
    PValuePacket reconstructedDecision = this.paxosState.reconstructDecision(accept.slot);
    MessagingTask commitTask = reconstructedDecision != null
            ? this.handleCommittedRequest(reconstructedDecision)
            : null;

    MessagingTask[] mtasks = { acceptReplyTask, commitTask };

    return mtasks;
}

From source file:com.npower.dm.server.session.ManagementSessionHandler.java

/**
 * Processes the given management message.
 *
 * @param syncRequest the message to be processed
 *
 * @return the response message//  w  w w.jav a 2  s  .c o m
 *
 * @throws ProtocolException
 */
private SyncML processManagementMessage(SyncML request) throws ProtocolException, ManagementException {

    //
    // If the client sent a MD5/HMAC Chal, store the server next nonce
    //
    storeServerNonce(ProtocolUtil.getStatusChal(request));

    actions = new ManagementActions(request.getSyncHdr(), request.getSyncBody());

    actions.setClientAuthType(clientAuthType);
    actions.setIdGenerator(engine.getCommandIdGenerator());

    //
    // If the server uses the HMAC and the client not sends the chal with the next nonce or
    //  if the client uses the HMAC but the value received is not correct, the server abort the session
    //
    boolean serverAbortRequired = false;

    if (Constants.AUTH_TYPE_HMAC.equalsIgnoreCase(serverAuthType)) {
        //
        // Checks if the client has sent the next nonce
        //
        Chal chal = getMessageChal(request);
        if (chal == null) {
            //
            // The server must abort the session (see OMA-SyncML-DMSecurity)
            //
            if (log.isLoggable(Level.FINEST)) {
                log.finest("Server abort the session because the client has not sent the next nonce");
            }

            //serverAbortRequired = true;
        }
    }

    //
    // If the client uses the HMAC the server must check again the credential
    // and generate new nonce
    //
    Cred clientCred = null;
    if (Constants.AUTH_TYPE_HMAC.equalsIgnoreCase(clientAuthType)) {
        //
        // Generate new nonce
        //
        NextNonce nonce = ProtocolUtil.generateNextNonce();
        sessionState.device.setClientNonce(nonce.getValue());
        actions.setNextNonce(nonce);
        engine.storeDevice(sessionState.device);

        //
        // Checks if the credential is valid
        //
        clientCred = request.getSyncHdr().getCred();
        Officer officer = engine.getOfficer();

        if (!officer.authenticate(clientCred)) {

            if (log.isLoggable(Level.FINEST)) {
                log.finest("Server abort the session because the credential sent by the client is not valid");
            }

            serverAbortRequired = true;
        }
    }

    if (serverAbortRequired) {
        //
        // We must abort the session
        //
        //
        // Set server credentials if required
        //
        if (sessionState.serverAuthenticationState != AUTH_ACCEPTED) {
            actions.setServerCredentials(engine.getServerCredentials(getChal(request), sessionState.device));
        }
        actions.setFlag(Flags.FLAG_SERVER_ABORT_REQUIRED);
        actions.setFlag(Flags.FLAG_FINAL_MESSAGE);

        sessionState.nextTimestamp.end = System.currentTimeMillis();
        sessionState.dmstate.state = DeviceDMState.STATE_ABORTED;
        endSession();
        moveTo(STATE_SESSION_ABORTED);
        SyncML response = actions.getResponse(msgIdGenerator.current());
        response.setLastMessage(true);
        return response;

    }

    //
    // Add Generic alerts to Cache
    //
    Alert[] alertsToCache = ProtocolUtil.searchGenericAlertCommands(request.getSyncBody());
    sessionState.addGenericAlert(alertsToCache);

    boolean alertCode1222sentFromTheClient = false;
    boolean alertCode1222requiredFromTheClient = false;

    //
    // Caches the status/results of the client
    //
    List commandToCache = ProtocolUtil.filterCommands(request.getSyncBody().getCommands(),
            new String[] { Status.COMMAND_NAME, Results.COMMAND_NAME, Alert.COMMAND_NAME });

    Alert[] removedAlerts = removeAlerts(commandToCache);

    checkForReceivedLargeObject(commandToCache);

    sessionState.addClientCommands((AbstractCommand[]) commandToCache.toArray(new AbstractCommand[0]));

    //
    // If the request is not final and there isn't an alert with code 1222, the server must answer
    // with a 1222 alert code without new commands and caches, if there is, large object
    //
    if (!request.getSyncBody().isFinalMsg()) {

        //
        // Check if in the request there is a 1222 alert code. If there is it
        // then we check if there is a large object to send
        //
        //
        Alert alert = ProtocolUtil.searchAlertCommand(request.getSyncBody(), AlertCode.MORE_DATA);
        if (alert != null) {
            //
            // The client wants more data
            //
            alertCode1222sentFromTheClient = true;
        } else {
            //
            // The client has not sent all status/results
            //
            actions.setFlag(Flags.FLAG_MORE_MSG_REQUIRED);
            alertCode1222requiredFromTheClient = true;

            Item itemWithLargeObject = ProtocolUtil.getLargeObject(commandToCache);

            if (itemWithLargeObject != null) {
                sessionState.setReceivedLargeObject(itemWithLargeObject.getData().getData());
                Long size = sync4j.framework.core.Util.getItemSize(itemWithLargeObject);
                if (size != null) {
                    sessionState.setSizeOfReceivedLargeObject(size);
                } else {
                    if (sessionState.getSizeOfReceivedLargeObject() == null) {
                        // Sets size to -1 so the ManagementActions knows when
                        // a large object is sent from the client without the meta size
                        sessionState.setSizeOfReceivedLargeObject(new Long(-1));
                    }
                }
            } else {
                //
                // If the request is final, the large object in cache not must
                // be more used
                //
                sessionState.setReceivedLargeObject(null);
                sessionState.setSizeOfReceivedLargeObject(null);
            }
        }

    } else {
        actions.setFlag(Flags.FLAG_FINAL_MESSAGE);
        //
        // Set the clientCommands with the client commands in cache
        //
        if (removedAlerts == null || removedAlerts.length == 0) {
            actions.setClientCommands(sessionState.getClientCommands());
        } else {
            //
            // We should add the removed alerts because otherwise the server
            // doesn't return the Status for that
            //
            AbstractCommand[] commands = new AbstractCommand[sessionState.getClientCommands().length
                    + removedAlerts.length];

            System.arraycopy(sessionState.getClientCommands(), 0, commands, 0,
                    sessionState.getClientCommands().length);

            System.arraycopy(removedAlerts, 0, commands, sessionState.getClientCommands().length,
                    removedAlerts.length);

            actions.setClientCommands(commands);
        }

        //
        // If the cache is empty we call the setOperationResults with all results
        //
        if (sessionState.getCmdOut() == null || sessionState.getCmdOut().size() == 0) {
            //
            // Gets the client Status and Results commands and merge them in
            // in a corresponding array of ManagementOperationResult objects.
            // The so returned array can then be passed to the management
            // processor.
            //
            AbstractCommand[] clientCommands = actions.getClientCommands();

            //
            // The status without a command descriptor must be removed
            //
            clientCommands = removeStatusWithoutCommandDescriptor(clientCommands,
                    sessionState.managementCommandDescriptors);

            processor.setOperationResults(
                    Util.operationResults(clientCommands, String.valueOf(StatusCode.CHUNKED_ITEM_ACCEPTED)));
            sessionState.clearClientCommands();

            //
            // Set Generic alerts and clear cache
            //
            Alert[] genericAlerts = sessionState.getGenericAlert();
            if (genericAlerts != null || genericAlerts.length > 0) {
                if (log.isLoggable(Level.FINER)) {
                    log.finer("Call setGenericAlert with " + genericAlerts.length + " generic alerts");
                }
                processor.setGenericAlert(genericAlerts);
                sessionState.clearGenericAlert();
            }

        }

        // If the client sent a final message, the previous data is removed from the
        // sessionState because it is already merge with new data
        sessionState.setReceivedLargeObject(null);
    }

    actions.setFlag(Flags.FLAG_ALL_RESPONSES_REQUIRED);

    //
    // If the session is aborted or the server is awaiting for more msg or the
    // client is awaiting for more data, no commands must be added to the response
    //
    if (!actions.isSessionAbortRequired() && !alertCode1222requiredFromTheClient
            && !alertCode1222sentFromTheClient) {
        //
        // Checks if there are command in cache
        //
        List commandInCache = sessionState.getCmdOut();
        if (log.isLoggable(Level.FINER)) {
            log.finer("command in cache: " + commandInCache.size());
        }
        if (commandInCache.size() != 0) {
            AbstractCommand[] newCommands = (AbstractCommand[]) commandInCache
                    .toArray(new AbstractCommand[] {});
            actions.setManagementCommands(newCommands);
            //
            // remove the commands from the cache
            //
            sessionState.removeCmdOut(commandInCache);
            if (log.isLoggable(Level.FINER)) {
                log.finer("Num. of managementCommands in actions: " + actions.getManagementCommands().length);
            }
        } else {
            //
            // Gets the next available operations from the processor
            //
            if (log.isLoggable(Level.FINER)) {
                log.finer("Call getNextOperations for new operation");
            }

            actions.setManagementCommands(Util.managementOperations2commands(processor.getNextOperations(),
                    engine.getCommandIdGenerator(), mimeType));
        }
    } else if (alertCode1222sentFromTheClient) {
        //
        // We must check if there is previous command splitted on more
        // message (large object)
        //
        AbstractCommand previousCommand = sessionState.getSplittedCommand();

        if (previousCommand == null) {
            throw new ProtocolException("No more data to send");
        }
        //
        // If previousCmd is not null then it is a ItemizedCommand
        // (only ItemizedCommand are splittabled)
        // with only one item
        //
        Item item = (Item) ((ItemizedCommand) previousCommand).getItems().get(0);
        item.getData().setData(sessionState.getNextDataToSend());

        //
        // The dimension of the data is already sent to the client in the previous message.
        // Then remove meta size information from the item
        //
        Meta meta = item.getMeta();
        if (meta != null) {
            meta.setSize(null);
        }

        // Sets more data to false
        item.setMoreData(Boolean.FALSE);

        List commandInCache = sessionState.getCmdOut();

        //
        // Put the command in cache so tha actions manage all command
        //
        commandInCache.add(0, previousCommand);

        AbstractCommand[] newCommands = (AbstractCommand[]) commandInCache.toArray(new AbstractCommand[] {});
        actions.setManagementCommands(newCommands);
    }

    //
    // Set server credentials if required
    //
    if (sessionState.serverAuthenticationState != AUTH_ACCEPTED) {
        actions.setServerCredentials(engine.getServerCredentials(getChal(request), sessionState.device));
    }

    actions.setMimeType(mimeType);
    SyncML response = actions.getResponse(msgIdGenerator.current());

    if (alertCode1222requiredFromTheClient) {
        //
        // Returns the response without checks the dimension because the
        // response must contain only status for header and alert code 1222
        //
        return response;
    }

    //
    // Cache the commands to send in the next message
    //
    clearCache();
    cacheCommands(response);

    //
    // Calculate size of response message
    //
    SyncHdr syncHdr = response.getSyncHdr();
    SyncBody syncBody = response.getSyncBody();
    long sizeSyncHdr = 0, sizeSyncBody = 0;

    /**
     * The test case suite currently send only ds mime type, then we must check
     * also MIMETYPE_SYNCMLDS_WBXML and MIMETYPE_SYNCMLDS_XML
     */
    if (Constants.MIMETYPE_SYNCMLDM_WBXML.equals(mimeType)
            || Constants.MIMETYPE_SYNCMLDS_WBXML.equals(mimeType)) {
        sizeSyncHdr = SizeCalculator.getWBXMLSize(syncHdr);
        sizeSyncBody = SizeCalculator.getWBXMLSize(syncBody);
    } else if (Constants.MIMETYPE_SYNCMLDM_XML.equals(mimeType)
            || Constants.MIMETYPE_SYNCMLDS_XML.equals(mimeType)) {
        sizeSyncHdr = SizeCalculator.getXMLSize(syncHdr);
        sizeSyncBody = SizeCalculator.getXMLSize(syncBody);
    }

    if (log.isLoggable(Level.FINER)) {
        log.finer("maxMsgSize: " + sessionState.getMaxMsgSize());
        log.finer("sizeSyncHdr: " + sizeSyncHdr);
        log.finer("sizeSyncBody: " + sizeSyncBody);
    }

    sessionState.setOverheadHdr(sizeSyncHdr);
    maxSizeAvailable = (int) (sessionState.getMaxMsgSize() * TOLLERANCE_MAX_MSG_SIZE);

    //
    // If the dimension of the response is < maxSizeAvailable or maxSizeAvailable is = 0
    // and there aren't the status/alerts/cmds cached then returns the response.
    // Else caches the commands of the response and re-create it.
    //
    if ((maxSizeAvailable >= sizeSyncHdr + sizeSyncBody || maxSizeAvailable == 0)
            && sessionState.getStatusCmdOut().size() == 0 && sessionState.getAlertCmdOut().size() == 0
            && sessionState.getCmdOut().size() == 0) {
        return response;
    }

    //
    // The size of the answer is greater then the allowed MaxMsgSize
    // Calculate size of the single commands of the response.
    // Create one answer of the allowed dimension.
    //
    try {
        response = createNextMsg(response);
    } catch (Sync4jException e) {
        throw new ProtocolException(e);
    }

    return response;
}

From source file:foodsimulationmodel.pathmapping.Route.java

/**
 * Calculates the coordinates required to move an agent from their current position to the destination along a given
 * road. The algorithm to do this is as follows:
 * <ol>/*from w  ww .j  a v  a  2 s.c  o m*/
 * <li>Starting from the destination coordinate, record each vertex and check inside the booundary of each line
 * segment until the destination point is found.</li>
 * <li>Return all but the last vertex, this is the route to the destination.</li>
 * </ol>
 * A boolean allows for two cases: heading towards a junction (the endpoint of the line) or heading away from the
 * endpoint of the line (this function can't be used to go to two midpoints on a line)
 * 
 * @param currentCoord
 * @param destinationCoord
 * @param road
 * @param toJunction
 *            whether or not we're travelling towards or away from a Junction
 * @param coordList
 *            A list which will be populated with the coordinates that the agent should follow to move along the
 *            road.
 * @param roadList
 *            A list of roads associated with each coordinate.
 * @throws Exception
 */
private void getCoordsAlongRoad(Coordinate currentCoord, Coordinate destinationCoord, Road road,
        boolean toJunction, List<Coordinate> coordList) throws RoutingException {

    Route.checkNotNull(currentCoord, destinationCoord, road, coordList);

    double time = System.nanoTime();
    Coordinate[] roadCoords = ContextManager.roadProjection.getGeometry(road).getCoordinates();

    // Check that the either the destination or current coordinate are actually part of the road
    boolean currentCorrect = false, destinationCorrect = false;
    for (int i = 0; i < roadCoords.length; i++) {
        if (toJunction && destinationCoord.equals(roadCoords[i])) {
            destinationCorrect = true;
            break;
        } else if (!toJunction && currentCoord.equals(roadCoords[i])) {
            currentCorrect = true;
            break;
        }
    } // for

    if (!(destinationCorrect || currentCorrect)) {
        String roadCoordsString = "";
        for (Coordinate c : roadCoords)
            roadCoordsString += c.toString() + " - ";
        throw new RoutingException("Neigher the origin or destination nor the current"
                + "coordinate are part of the road '" + road.toString() + "' (person '" + this.agent.toString()
                + "').\n" + "Road coords: " + roadCoordsString + "\n" + "\tOrigin: " + currentCoord.toString()
                + "\n" + "\tDestination: " + destinationCoord.toString() + " ( "
                + this.destinationAgent.toString() + " )\n " + "Heading " + (toJunction ? "to" : "away from")
                + " a junction, so " + (toJunction ? "destination" : "origin")
                + " should be part of a road segment");
    }

    // Might need to reverse the order of the road coordinates
    if (toJunction && !destinationCoord.equals(roadCoords[roadCoords.length - 1])) {
        // If heading towards a junction, destination coordinate must be at end of road segment
        ArrayUtils.reverse(roadCoords);
    } else if (!toJunction && !currentCoord.equals(roadCoords[0])) {
        // If heading away form junction current coord must be at beginning of road segment
        ArrayUtils.reverse(roadCoords);
    }
    GeometryFactory geomFac = new GeometryFactory();
    Point destinationPointGeom = geomFac.createPoint(destinationCoord);
    Point currentPointGeom = geomFac.createPoint(currentCoord);
    // If still false at end then algorithm hasn't worked
    boolean foundAllCoords = false;
    search: for (int i = 0; i < roadCoords.length - 1; i++) {
        Coordinate[] segmentCoords = new Coordinate[] { roadCoords[i], roadCoords[i + 1] };
        // Draw a small buffer around the line segment and look for the coordinate within the buffer
        Geometry buffer = geomFac.createLineString(segmentCoords)
                .buffer(GlobalVars.GEOGRAPHY_PARAMS.BUFFER_DISTANCE.SMALL.dist);
        if (!toJunction) {
            /* If heading away from a junction, keep adding road coords until we find the destination */
            coordList.add(roadCoords[i]);
            if (destinationPointGeom.within(buffer)) {
                coordList.add(destinationCoord);
                foundAllCoords = true;
                break search;
            }
        } else if (toJunction) {
            /*
             * If heading towards a junction: find the curent coord, add it to the route, then add all the remaining
             * coords which make up the road segment
             */
            if (currentPointGeom.within(buffer)) {
                for (int j = i + 1; j < roadCoords.length; j++) {
                    coordList.add(roadCoords[j]);
                }
                coordList.add(destinationCoord);
                foundAllCoords = true;
                break search;
            }
        }
    } // for
    if (foundAllCoords) {
        LOGGER.log(Level.FINER, "getCoordsAlongRoad (" + (0.000001 * (System.nanoTime() - time)) + "ms)");
        return;
    } else { // If we get here then the route hasn't been created
        // A load of debugging info
        String error = "Route: getCoordsAlongRoad: could not find destination coordinates "
                + "along the road.\n\tHeading *" + (toJunction ? "towards" : "away from")
                + "* a junction.\n\t Person: " + this.agent.toString() + ")\n\tDestination building: "
                + destinationAgent.toString() + "\n\tRoad causing problems: " + road.toString()
                + "\n\tRoad vertex coordinates: " + Arrays.toString(roadCoords);
        throw new RoutingException(error);
        /*
         * Hack: ignore the error, printing a message and just returning the origin destination and coordinates.
         * This means agent will jump to/from the junction but I can't figure out why the fuck it occasionally
         * doesn't work!! It's so rare that hopefully this isn't a problem.
         */
        // TempLogger.err("Route: getCoordsAlongRoad: error... (not debugging).");
        // List<Coord> coords = new ArrayList<Coord>();
        // coords.add(currentCoord);
        // coords.add(destinationCoord);
        // for (Coord c : coords)
        // this.roads.put(c, road); // Remember the roads each coord is
        // // part of
        // return coords;

    }
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.dta.DTAFileReader.java

private void decodeData(BufferedInputStream stream) throws IOException {

    dbgLog.fine("\n***** decodeData(): start *****");

    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }//  w  w  w  . j a  va2 s  .com

    int nvar = (Integer) smd.getFileInformation().get("varQnty");
    int nobs = (Integer) smd.getFileInformation().get("caseQnty");
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("data diminsion[rxc]=(" + nobs + "," + nvar + ")");
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("bytes per row=" + bytes_per_row + " bytes");

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("variableTypelList=" + Arrays.deepToString(variableTypelList));
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("StringVariableTable=" + StringVariableTable);

    FileOutputStream fileOutTab = null;
    PrintWriter pwout = null;

    // create a File object to save the tab-delimited data file
    File tabDelimitedDataFile = File.createTempFile("tempTabfile.", ".tab");

    String tabDelimitedDataFileName = tabDelimitedDataFile.getAbsolutePath();

    // save the temp file name in the metadata object
    smd.getFileInformation().put("tabDelimitedDataFileLocation", tabDelimitedDataFileName);

    fileOutTab = new FileOutputStream(tabDelimitedDataFile);

    pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);

    // data storage
    // Object[][] dataTable = new Object[nobs][nvar];
    // for later variable-wise calculations of statistics
    // dataTable2 sotres cut-out data columnwise
    Object[][] dataTable2 = new Object[nvar][nobs];
    String[][] dateFormat = new String[nvar][nobs];

    for (int i = 0; i < nobs; i++) {
        byte[] dataRowBytes = new byte[bytes_per_row];
        Object[] dataRow = new Object[nvar];

        int nbytes = stream.read(dataRowBytes, 0, bytes_per_row);

        if (nbytes == 0) {
            String errorMessage = "reading data: no data were read at(" + i + "th row)";
            throw new IOException(errorMessage);
        }
        // decoding each row
        int byte_offset = 0;
        for (int columnCounter = 0; columnCounter < variableTypelList.length; columnCounter++) {

            Integer varType = variableTypeMap.get(variableTypelList[columnCounter]);

            String variableFormat = variableFormats[columnCounter];

            boolean isDateTimeDatum = isDateTimeDatumList[columnCounter];

            switch (varType != null ? varType : 256) {
            case -5:
                // Byte case
                // note: 1 byte signed
                byte byte_datum = dataRowBytes[byte_offset];

                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column byte =" + byte_datum);
                if (byte_datum >= BYTE_MISSING_VALUE) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column byte MV=" + byte_datum);
                    dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                } else {
                    dataRow[columnCounter] = byte_datum;
                    dataTable2[columnCounter][i] = byte_datum;
                }

                byte_offset++;
                break;
            case -4:
                // Stata-int (=java's short: 2byte) case
                // note: 2-byte signed int, not java's int
                ByteBuffer int_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 2);
                if (isLittleEndian) {
                    int_buffer.order(ByteOrder.LITTLE_ENDIAN);

                }
                short short_datum = int_buffer.getShort();

                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column stata int =" + short_datum);
                if (short_datum >= INT_MISSIG_VALUE) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column stata long missing value="
                                + short_datum);
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }
                } else {

                    if (isDateTimeDatum) {

                        DecodedDateTime ddt = decodeDateTimeData("short", variableFormat,
                                Short.toString(short_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];

                    } else {
                        dataTable2[columnCounter][i] = short_datum;
                        dataRow[columnCounter] = short_datum;
                    }
                }
                byte_offset += 2;
                break;
            case -3:
                // stata-Long (= java's int: 4 byte) case
                // note: 4-byte singed, not java's long
                dbgLog.fine("DATreader: stata long");

                ByteBuffer long_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 4);
                if (isLittleEndian) {
                    long_buffer.order(ByteOrder.LITTLE_ENDIAN);

                }
                int int_datum = long_buffer.getInt();

                if (dbgLog.isLoggable(Level.FINE))
                    dbgLog.fine(i + "-th row " + columnCounter + "=th column stata long =" + int_datum);
                if (int_datum >= LONG_MISSING_VALUE) {
                    if (dbgLog.isLoggable(Level.FINE))
                        dbgLog.fine(i + "-th row " + columnCounter + "=th column stata long missing value="
                                + int_datum);
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }
                } else {
                    if (isDateTimeDatum) {
                        DecodedDateTime ddt = decodeDateTimeData("int", variableFormat,
                                Integer.toString(int_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];

                    } else {
                        dataTable2[columnCounter][i] = int_datum;
                        dataRow[columnCounter] = int_datum;
                    }

                }
                byte_offset += 4;
                break;
            case -2:
                // float case
                // note: 4-byte
                ByteBuffer float_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 4);
                if (isLittleEndian) {
                    float_buffer.order(ByteOrder.LITTLE_ENDIAN);
                }
                float float_datum = float_buffer.getFloat();

                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column float =" + float_datum);
                if (FLOAT_MISSING_VALUE_SET.contains(float_datum)) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column float missing value="
                                + float_datum);
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }

                } else {

                    if (isDateTimeDatum) {
                        DecodedDateTime ddt = decodeDateTimeData("float", variableFormat,
                                doubleNumberFormatter.format(float_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];
                    } else {
                        dataTable2[columnCounter][i] = float_datum;
                        dataRow[columnCounter] = float_datum;
                    }

                }
                byte_offset += 4;
                break;
            case -1:
                // double case
                // note: 8-byte
                ByteBuffer double_buffer = ByteBuffer.wrap(dataRowBytes, byte_offset, 8);
                if (isLittleEndian) {
                    double_buffer.order(ByteOrder.LITTLE_ENDIAN);
                }
                double double_datum = double_buffer.getDouble();

                if (DOUBLE_MISSING_VALUE_SET.contains(double_datum)) {
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column double missing value="
                                + double_datum);
                    if (isDateTimeDatum) {
                        dataRow[columnCounter] = MissingValueForTextDataFileString;
                    } else {
                        dataRow[columnCounter] = MissingValueForTextDataFileNumeric;
                    }
                } else {

                    if (isDateTimeDatum) {
                        DecodedDateTime ddt = decodeDateTimeData("double", variableFormat,
                                doubleNumberFormatter.format(double_datum));
                        if (dbgLog.isLoggable(Level.FINER))
                            dbgLog.finer(i + "-th row , decodedDateTime " + ddt.decodedDateTime + ", format="
                                    + ddt.format);
                        dataRow[columnCounter] = ddt.decodedDateTime;
                        dateFormat[columnCounter][i] = ddt.format;
                        dataTable2[columnCounter][i] = dataRow[columnCounter];
                    } else {
                        dataTable2[columnCounter][i] = double_datum;
                        dataRow[columnCounter] = doubleNumberFormatter.format(double_datum);
                    }

                }
                byte_offset += 8;
                break;
            case 0:
                // String case
                int strVarLength = StringVariableTable.get(columnCounter);
                String raw_datum = new String(
                        Arrays.copyOfRange(dataRowBytes, byte_offset, (byte_offset + strVarLength)),
                        "ISO-8859-1");
                String string_datum = getNullStrippedString(raw_datum);
                if (dbgLog.isLoggable(Level.FINER))
                    dbgLog.finer(i + "-th row " + columnCounter + "=th column string =" + string_datum);
                if (string_datum.equals("")) {
                    if (dbgLog.isLoggable(Level.FINER))
                        dbgLog.finer(i + "-th row " + columnCounter + "=th column string missing value="
                                + string_datum);
                    dataRow[columnCounter] = MissingValueForTextDataFileString;
                    dataTable2[columnCounter][i] = null; //use null reference to indicate missing value in data that is passed to UNF
                } else {
                    String escapedString = string_datum.replaceAll("\"", Matcher.quoteReplacement("\\\""));
                    /*
                     * Fixing the bug we've had in the Stata reader for 
                     * a longest time: new lines and tabs need to 
                     * be escaped too - otherwise it breaks our 
                     * TAB file structure! -- L.A. 
                     */
                    escapedString = escapedString.replaceAll("\t", Matcher.quoteReplacement("\\t"));
                    escapedString = escapedString.replaceAll("\n", Matcher.quoteReplacement("\\n"));
                    escapedString = escapedString.replaceAll("\r", Matcher.quoteReplacement("\\r"));
                    // the escaped version of the string will be 
                    // stored in the tab file: 
                    dataRow[columnCounter] = "\"" + escapedString + "\"";
                    // but note that the "raw" version of it is 
                    // used for the UNF:
                    dataTable2[columnCounter][i] = string_datum;
                }
                byte_offset += strVarLength;
                break;
            default:
                dbgLog.fine("unknown variable type found");
                String errorMessage = "unknow variable Type found at data section";
                throw new InvalidObjectException(errorMessage);
            } // switch
        } // for-columnCounter

        // dump the row of data to the external file
        pwout.println(StringUtils.join(dataRow, "\t"));

        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine(i + "-th row's data={" + StringUtils.join(dataRow, ",") + "};");

    } // for- i (row)

    pwout.close();
    if (dbgLog.isLoggable(Level.FINER)) {
        dbgLog.finer("\ndataTable2(variable-wise):\n");
        dbgLog.finer(Arrays.deepToString(dataTable2));
        dbgLog.finer("\ndateFormat(variable-wise):\n");
        dbgLog.finer(Arrays.deepToString(dateFormat));
    }
    if (dbgLog.isLoggable(Level.FINE)) {
        dbgLog.fine("variableTypelList:\n" + Arrays.deepToString(variableTypelList));
        dbgLog.fine("variableTypelListFinal:\n" + Arrays.deepToString(variableTypelListFinal));
    }
    String[] unfValues = new String[nvar];

    for (int j = 0; j < nvar; j++) {
        String variableType_j = variableTypelListFinal[j];

        unfValues[j] = getUNF(dataTable2[j], dateFormat[j], variableType_j, unfVersionNumber, j);
        if (dbgLog.isLoggable(Level.FINE))
            dbgLog.fine(j + "th unf value" + unfValues[j]);

    }

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("unf set:\n" + Arrays.deepToString(unfValues));

    fileUnfValue = UNF5Util.calculateUNF(unfValues);

    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("file-unf=" + fileUnfValue);

    stataDataSection.setUnf(unfValues);

    stataDataSection.setFileUnf(fileUnfValue);

    smd.setVariableUNF(unfValues);

    smd.getFileInformation().put("fileUNF", fileUnfValue);
    if (dbgLog.isLoggable(Level.FINE))
        dbgLog.fine("unf values:\n" + unfValues);

    stataDataSection.setData(dataTable2);

    // close the stream

    dbgLog.fine("***** decodeData(): end *****\n\n");

}

From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java

/**
 * Returns a collection of the names of synthetic modules that may be used by the transport.
 * Module names provided here will be assigned module name unique ids and can be requested by
 * the client using module id encoding.//www .  jav a  2s .  c  o m
 * <p>
 * Synthetic modules are those which don't have physical source files that will be discovered
 * when building the dependency map.
 *
 * @return the collection of synthetic names used by the transport
 */
protected Collection<String> getSyntheticModuleNames() {
    final String methodName = "getSyntheticModuleNames"; //$NON-NLS-1$
    boolean traceLogging = log.isLoggable(Level.FINER);
    if (traceLogging) {
        log.entering(AbstractHttpTransport.class.getName(), methodName);
    }
    Collection<String> result = new HashSet<String>();
    result.add(getAggregatorTextPluginName());
    if (traceLogging) {
        log.exiting(AbstractHttpTransport.class.getName(), methodName, result);
    }
    return result;
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

/**
 * Creates and returns a map containing all of the deployed service names installed under a specific application
 * context./* www  .  j ava2  s.  c  o  m*/
 *
 * @param applicationName
 *            .
 * @return a list of the deployed services in the service grid that were deployed as a part of a specific
 *         application.
 * @throws RestErrorException
 *             When application is not found.
 */
@JsonResponseExample(status = "sucess", responseBody = "[\"service1\",\"service2\"]")
@PossibleResponseStatuses(responseStatuses = { @PossibleResponseStatus(code = HTTP_OK, description = "success"),
        @PossibleResponseStatus(code = HTTP_INTERNAL_SERVER_ERROR, description = "failed_to_locate_app") })
@RequestMapping(value = "/applications/{applicationName}/services", method = RequestMethod.GET)
@PreAuthorize("isFullyAuthenticated()")
@PostFilter("hasPermission(filterObject, 'view')")
@ResponseBody
public Map<String, Object> getServicesList(@PathVariable final String applicationName)
        throws RestErrorException {
    if (logger.isLoggable(Level.FINER)) {
        logger.finer("received request to list applications");
    }
    final Application app = admin.getApplications().waitFor(applicationName, 5, TimeUnit.SECONDS);
    if (app == null) {
        throw new RestErrorException(FAILED_TO_LOCATE_APP, applicationName);
    }
    final ProcessingUnits pus = app.getProcessingUnits();
    final List<String> serviceNames = new ArrayList<String>(pus.getSize());
    for (final ProcessingUnit pu : pus) {
        serviceNames.add(ServiceUtils.getApplicationServiceName(pu.getName(), applicationName));
    }
    return successStatus(serviceNames);
}

From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransport.java

/**
 * Returns the JavaScript code for calling the client-side module name id registration function
 * to register name ids for the transport synthetic modules.
 *
 * @return the registration JavaScript or an empty string if no synthetic modules.
 *///from www  .j a  v  a2s .com
protected String clientRegisterSyntheticModules() {
    final String methodName = "clientRegisterSyntheticModules"; //$NON-NLS-1$
    boolean traceLogging = log.isLoggable(Level.FINER);
    if (traceLogging) {
        log.entering(AbstractHttpTransport.class.getName(), methodName);
    }
    StringBuffer sb = new StringBuffer();
    Map<String, Integer> map = getModuleIdMap();
    if (map != null && getModuleIdRegFunctionName() != null) {
        Collection<String> names = getSyntheticModuleNames();
        if (names != null && names.size() > 0) {
            // register the text plugin name (combo/text) and name id with the client
            sb.append(getModuleIdRegFunctionName()).append("([[["); //$NON-NLS-1$
            int i = 0;
            for (String name : names) {
                if (map.get(name) != null) {
                    sb.append(i++ == 0 ? "" : ",").append("\"").append(name).append("\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                }
            }
            sb.append("]],[["); //$NON-NLS-1$
            i = 0;
            for (String name : names) {
                Integer id = map.get(name);
                if (id != null) {
                    sb.append(i++ == 0 ? "" : ",").append(id.intValue()); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            sb.append("]]]);"); //$NON-NLS-1$
        }
    }
    if (traceLogging) {
        log.exiting(AbstractHttpTransport.class.getName(), methodName, sb.toString());
    }
    return sb.toString();
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

/**
 * Returns the working directory for this aggregator.
 * <p>//from ww  w  .  j  a  v  a  2  s . c  o m
 * This method is called during aggregator intialization. Subclasses may override this method to
 * initialize the aggregator using a different working directory. Use the public
 * {@link #getWorkingDirectory()} method to get the working directory from an initialized
 * aggregator.
 * <p>
 * The working directory returned by this method will be located at
 * <code>&lt;defaultLocation&gt;/&lt;versionString&gt;/&lt;aggregator name&gt;</code>
 * <p>
 * If the directory <code>&lt;defaultLocation&gt;/&lt;versionString&gt;</code> does not already
 * exist when this method is called, then any files in <code>defaultLocation</code> and any
 * subdirectories in <code>defaultLocation</code> that are not listed in
 * <code>retaindedVersions</code> <strong>WILL BE DELETED</strong>.
 *
 * @param defaultLocation
 *            The default, unversioned, directory location. The aggregator assumes that it owns
 *            this directory and all the files in it.
 * @param configMap
 *            the map of config name/value pairs
 * @param versionString
 *            the version string to qualify the directory location
 * @param retainedVersions
 *            collection of versions to retain when deleting stale version subdirectories.
 *
 * @return The {@code File} object for the working directory
 * @throws FileNotFoundException
 */
protected File initWorkingDirectory(File defaultLocation, Map<String, String> configMap, String versionString,
        Collection<String> retainedVersions) throws FileNotFoundException {

    final String sourceMethod = "initWorkingDirectory"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod,
                new Object[] { defaultLocation, configMap, versionString, retainedVersions });
    }
    String dirName = getOptions().getCacheDirectory();
    File dirFile = null;
    if (dirName == null) {
        dirFile = defaultLocation;
    } else {
        // Make sure the path exists
        dirFile = new File(dirName);
        dirFile.mkdirs();
    }
    if (!dirFile.exists()) {
        throw new FileNotFoundException(dirFile.toString());
    }
    if (versionString == null || versionString.length() == 0) {
        versionString = "default"; //$NON-NLS-1$
    }
    // Create a directory using the alias name within the contributing bundle's working
    // directory
    File versionDir = new File(dirFile, versionString);
    if (!versionDir.exists()) {
        // Iterate through the default directory, deleting subdirectories who's names are not
        // included in retainedVersions
        File[] files = dirFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if (!retainedVersions.contains(file.getName())) {
                    if (isTraceLogging) {
                        log.finer("deleting directory " + file.getAbsolutePath()); //$NON-NLS-1$
                    }
                    FileUtils.deleteQuietly(file);
                }
            } else {
                // loose file in top level directory.  Delete it
                if (isTraceLogging) {
                    log.finer("Deleting file " + file.getAbsolutePath()); //$NON-NLS-1$
                }
                file.delete();
            }
        }
    }

    File servletDir = null;
    try {
        servletDir = new File(versionDir, URLEncoder.encode(getName(), "UTF-8")); //$NON-NLS-1$
    } catch (UnsupportedEncodingException e) {
        // Should never happen
        throw new RuntimeException(e);
    }
    servletDir.mkdirs();
    if (!servletDir.exists()) {
        throw new FileNotFoundException(servletDir.getAbsolutePath());
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod, servletDir);
    }
    return servletDir;
}