Example usage for java.lang ArrayIndexOutOfBoundsException printStackTrace

List of usage examples for java.lang ArrayIndexOutOfBoundsException printStackTrace

Introduction

In this page you can find the example usage for java.lang ArrayIndexOutOfBoundsException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:bbcdataservice.BBCDataService.java

private ArrayList<Channel> getChannelListFromFile(String url) {

    final ArrayList<Channel> channels = new ArrayList<Channel>();

    BufferedInputStream stream = null;
    try {//from  w  w w .  ja  va  2s  .com
        URL sourceUrl = new URL(url);
        stream = new BufferedInputStream(sourceUrl.openStream());

        InputStream gIn = IOUtilities.openSaveGZipInputStream(stream);
        BufferedReader reader = new BufferedReader(new InputStreamReader(gIn, "ISO-8859-15"));

        int lineCount = 1;

        String line = reader.readLine();
        String[] tokens;
        while (line != null) {
            tokens = line.split(";");

            String country = null, timezone = null, id = null, name = null, copyright = null, webpage = null,
                    iconUrl = null, categoryStr = null, unescapedname = null;
            try {
                country = tokens[0];
                timezone = tokens[1];
                id = tokens[2];
                name = tokens[3];
                copyright = tokens[4];
                webpage = tokens[5];
                iconUrl = tokens[6];
                categoryStr = tokens[7];
                if (tokens.length > 8) {
                    unescapedname = name;
                    name = StringEscapeUtils.unescapeHtml(tokens[8]);
                }

            } catch (ArrayIndexOutOfBoundsException e) {
                // ignore
            }

            int categories = Channel.CATEGORY_NONE;
            if (categoryStr != null) {
                try {
                    categories = Integer.parseInt(categoryStr);
                } catch (NumberFormatException e) {
                    categories = Channel.CATEGORY_NONE;
                }
            }
            Channel channel = new Channel(BBCDataService.this, name, id, TimeZone.getTimeZone(timezone),
                    country, copyright, webpage, CHANNEL_GROUP, null, categories, unescapedname);

            channels.add(channel);
            lineCount++;
            line = reader.readLine();
        }

        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException exc) {
            }
        }
    }
    return channels;

}

From source file:com.android.messaging.mmslib.pdu.PduComposer.java

/**
 * Make message body.//from ww w  . j a v a  2 s .  co  m
 */
private int makeMessageBody() {
    // 1. add body informations
    mStack.newbuf(); // Switching buffer because we need to

    final PositionMarker ctStart = mStack.mark();

    // This contentTypeIdentifier should be used for type of attachment...
    final String contentType = new String(mPduHeader.getTextString(PduHeaders.CONTENT_TYPE));
    final Integer contentTypeIdentifier = mContentTypeMap.get(contentType);
    if (contentTypeIdentifier == null) {
        // content type is mandatory
        return PDU_COMPOSE_CONTENT_ERROR;
    }

    appendShortInteger(contentTypeIdentifier.intValue());

    // content-type parameter: start
    final PduBody body = ((SendReq) mPdu).getBody();
    if (null == body || body.getPartsNum() == 0) {
        // empty message
        appendUintvarInteger(0);
        mStack.pop();
        mStack.copy();
        return PDU_COMPOSE_SUCCESS;
    }

    PduPart part;
    try {
        part = body.getPart(0);

        final byte[] start = part.getContentId();
        if (start != null) {
            appendOctet(PduPart.P_DEP_START);
            if (('<' == start[0]) && ('>' == start[start.length - 1])) {
                appendTextString(start);
            } else {
                appendTextString("<" + new String(start) + ">");
            }
        }

        // content-type parameter: type
        appendOctet(PduPart.P_CT_MR_TYPE);
        appendTextString(part.getContentType());
    } catch (final ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    }

    final int ctLength = ctStart.getLength();
    mStack.pop();
    appendValueLength(ctLength);
    mStack.copy();

    // 3. add content
    final int partNum = body.getPartsNum();
    appendUintvarInteger(partNum);
    for (int i = 0; i < partNum; i++) {
        part = body.getPart(i);
        mStack.newbuf(); // Leaving space for header lengh and data length
        final PositionMarker attachment = mStack.mark();

        mStack.newbuf(); // Leaving space for Content-Type length
        final PositionMarker contentTypeBegin = mStack.mark();

        final byte[] partContentType = part.getContentType();

        if (partContentType == null) {
            // content type is mandatory
            return PDU_COMPOSE_CONTENT_ERROR;
        }

        // content-type value
        final Integer partContentTypeIdentifier = mContentTypeMap.get(new String(partContentType));
        if (partContentTypeIdentifier == null) {
            appendTextString(partContentType);
        } else {
            appendShortInteger(partContentTypeIdentifier.intValue());
        }

        /* Content-type parameter : name.
         * The value of name, filename, content-location is the same.
         * Just one of them is enough for this PDU.
         */
        byte[] name = part.getName();

        if (null == name) {
            name = part.getFilename();

            if (null == name) {
                name = part.getContentLocation();

                if (null == name) {
                    /* at lease one of name, filename, Content-location
                     * should be available.
                     */
                    // I found that an mms received from tmomail.net will include a SMIL part
                    // that has no name. That would cause the code here to return
                    // PDU_COMPOSE_CONTENT_ERROR when a user tried to forward the message. The
                    // message would never send and the user would be stuck in a retry
                    // situation. Simply jam in any old name here to fix the problem.
                    name = "smil.xml".getBytes();
                }
            }
        }
        appendOctet(PduPart.P_DEP_NAME);
        appendTextString(name);

        // content-type parameter : charset
        final int charset = part.getCharset();
        if (charset != 0) {
            appendOctet(PduPart.P_CHARSET);
            appendShortInteger(charset);
        }

        final int contentTypeLength = contentTypeBegin.getLength();
        mStack.pop();
        appendValueLength(contentTypeLength);
        mStack.copy();

        // content id
        final byte[] contentId = part.getContentId();

        if (null != contentId) {
            appendOctet(PduPart.P_CONTENT_ID);
            if (('<' == contentId[0]) && ('>' == contentId[contentId.length - 1])) {
                appendQuotedString(contentId);
            } else {
                appendQuotedString("<" + new String(contentId) + ">");
            }
        }

        // content-location
        final byte[] contentLocation = part.getContentLocation();
        if (null != contentLocation) {
            appendOctet(PduPart.P_CONTENT_LOCATION);
            appendTextString(contentLocation);
        }

        // content
        final int headerLength = attachment.getLength();

        int dataLength = 0; // Just for safety...
        final byte[] partData = part.getData();

        if (partData != null) {
            arraycopy(partData, 0, partData.length);
            dataLength = partData.length;
        } else {
            InputStream cr = null;
            try {
                final byte[] buffer = new byte[PDU_COMPOSER_BLOCK_SIZE];
                cr = mResolver.openInputStream(part.getDataUri());
                int len = 0;
                while ((len = cr.read(buffer)) != -1) {
                    mMessage.write(buffer, 0, len);
                    mPosition += len;
                    dataLength += len;
                }
            } catch (final FileNotFoundException e) {
                return PDU_COMPOSE_CONTENT_ERROR;
            } catch (final IOException e) {
                return PDU_COMPOSE_CONTENT_ERROR;
            } catch (final RuntimeException e) {
                return PDU_COMPOSE_CONTENT_ERROR;
            } finally {
                if (cr != null) {
                    try {
                        cr.close();
                    } catch (final IOException e) {
                        // Nothing to do
                    }
                }
            }
        }

        if (dataLength != (attachment.getLength() - headerLength)) {
            throw new RuntimeException("BUG: Length sanity check failed");
        }

        mStack.pop();
        appendUintvarInteger(headerLength);
        appendUintvarInteger(dataLength);
        mStack.copy();
    }

    return PDU_COMPOSE_SUCCESS;
}

From source file:com.klinker.android.launcher.addons.view.ViewDragHelper.java

private void clearMotionHistory(int pointerId) {
    if (mInitialMotionX == null) {
        return;//from w  ww .ja  v  a2 s  .  c  o  m
    }
    try {
        mInitialMotionX[pointerId] = 0;
        mInitialMotionY[pointerId] = 0;
        mLastMotionX[pointerId] = 0;
        mLastMotionY[pointerId] = 0;
        mInitialEdgesTouched[pointerId] = 0;
        mEdgeDragsInProgress[pointerId] = 0;
        mEdgeDragsLocked[pointerId] = 0;
        mPointersDown &= ~(1 << pointerId);
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    }
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentController.java

/**
 * Used to include the html for the qc table in an ext panel (without using a tag) (This method should probably be
 * in a service?)//from  w  w w  .  j  a  v  a 2s .  c  o  m
 */
public String getQCTagHTML(ExpressionExperiment ee) {
    ExperimentQCTag qc = new ExperimentQCTag();
    qc.setEe(ee.getId());
    qc.setEeManagerId(ee.getId() + "-eemanager");
    qc.setHasCorrMat(sampleCoexpressionAnalysisService.hasAnalysis(ee));
    qc.setHasNodeDegreeDist(ExpressionExperimentQCUtils.hasNodeDegreeDistFile(ee));
    qc.setHasPCA(svdService.hasPca(ee.getId()));
    qc.setNumFactors(ExpressionExperimentQCUtils.numFactors(ee));
    qc.setHasMeanVariance(meanVarianceService.hasMeanVariance(ee));
    qc.setHasCorrDist(this.coexpressionAnalysisService.hasCoexpCorrelationDistribution(ee));
    qc.setNumOutliersRemoved(this.numOutliersRemoved(ee));
    try {
        qc.setNumPossibleOutliers(this.numPossibleOutliers(ee));
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
        ExpressionExperimentController.log.fatal(e);
        e.printStackTrace();
    }
    return qc.getQChtml();
}

From source file:psidev.psi.mi.filemakers.xsd.AbstractXsdTreeStruct.java

public void redoChoice(String path, String choice) {
    try {//from  w w w.j a v  a  2  s  .c o  m
        XsdNode currentNode = rootNode;
        /* never a choice on rootNode */
        String nextIndexes = path.substring(path.indexOf(".") + 1);
        int index = 0;
        Annotated annotated = (Annotated) (currentNode.getUserObject());
        /* for each element on the path */
        while (nextIndexes.length() > 0 && nextIndexes != "-1") {
            /* if choice do it */
            annotated = (Annotated) (currentNode.getUserObject());
            /* if not extended, do it */
            if (!currentNode.isExtended) {
                extendPath(currentNode);
            } else {
                if (nextIndexes.indexOf(".") >= 0) {
                    index = Integer.parseInt(nextIndexes.substring(0, nextIndexes.indexOf(".")));
                    nextIndexes = nextIndexes.substring(nextIndexes.indexOf(".") + 1);
                    try {
                        currentNode = (XsdNode) currentNode.getChildAt(index);
                    } catch (java.lang.ArrayIndexOutOfBoundsException aiobe) {
                        /*
                         * to keep compatibility: if mapping done without auto-duplication of nodes and
                         * applied without this option, an exception will be raised if the node has not
                         * been manually duplicated. In this case try to duplicate "upper" node.
                         */
                        /* get upper node's index */
                        log.error("Index: " + path + " -> " + choice + " , " + index);
                        duplicateNode((XsdNode) currentNode.getChildAt(index - 1));
                        currentNode = (XsdNode) currentNode.getChildAt(index);
                        aiobe.printStackTrace();
                    }
                } else {

                    index = Integer.parseInt(nextIndexes);
                    nextIndexes = "-1";
                    try {
                        currentNode = (XsdNode) currentNode.getChildAt(index);
                    } catch (ArrayIndexOutOfBoundsException e) {
                        e.printStackTrace();
                        return;
                    }
                }
            }
        }

        /* add choice */
        annotated = (Annotated) (currentNode.getUserObject());
        Group g = (Group) annotated;
        try {
            if (g.getOrder().getType() == Order.CHOICE && manageChoices) {
                XsdNode parent = (XsdNode) currentNode.getParent();
                int position = parent.getIndex(currentNode);
                ArrayList<Annotated> choices = getChoices(g);
                ArrayList<String> possibilities = new ArrayList<String>();
                for (int i = 0; i < choices.size(); i++) {
                    try {
                        possibilities.add(((ElementDecl) choices.get(i)).getName());
                    } catch (ClassCastException e) {
                        /* a group: give an overview */
                        possibilities.add(XsdNode.choiceToString((Group) choices.get(i)));
                    }
                }
                XsdNode newNode;

                newNode = new XsdNode(choices.get(possibilities.indexOf(choice)));
                newNode.isRequired = currentNode.isRequired;

                /**
                 * If the max occurs is specified, transfer it to the child.
                 */
                /**
                 * TODO: check if we should verify that max/min is indedd specified for the
                 * group.
                 */
                newNode.min = g.getMinOccurs(); // node.min;
                newNode.max = g.getMaxOccurs(); // node.max;

                //
                // newNode.min = currentNode.min;
                // newNode.max = currentNode.max;
                newNode.originalParent = currentNode;

                currentNode.transparent = true;
                currentNode.isExtended = true;
                currentNode.add(newNode);

                currentNode = newNode;
            }
        } catch (StringIndexOutOfBoundsException e) {
            e.printStackTrace();
            return;
        }

    } catch (ArrayIndexOutOfBoundsException aioobe) {
        log.error("Restore choice, path not found: " + path);
        throw aioobe;
    }
    check((XsdNode) treeModel.getRoot());
    treeModel.reload((XsdNode) treeModel.getRoot());

    expendChoices.add(path);
    expendChoices.add(choice);
}

From source file:es.itecban.deployment.executionmanager.gui.swf.service.PlanCreationManager.java

public boolean map(RequestContext context, DeploymentGroup[] groups, String[] containers, String planNameUniq)
        throws Exception {

    String lock = "map_lock";
    boolean isOk = false;
    synchronized (lock) {
        Calendar map1 = Calendar.getInstance();
        String environmentName = (String) context.getFlowScope().get(Constants.FLOW_SELECTED_ENV);
        DeploymentTargetType environment = this.environmentManager.getEnvironment(environmentName);
        DependencyGraph graph = this.common.getDependencyGraph(context, environment.getName());
        PlanContextBrowser browser = new PlanContextBrowser(environment, graph);

        logger.fine("Starting Mapping");
        String stActionsToDo = context.getRequestParameters().get("actionsToDo");
        if (stActionsToDo == null || stActionsToDo.equals("")) {
            ErrorUtils.createMessageError(context, "running.error.noSelectedContainer", null);
            throw new Exception();
        }/*from w ww.ja  va 2s  .  co m*/
        // check if they are less because come of the units are already
        // installed
        String[] actionsToDoArray = stActionsToDo.split(",");
        List<InstalledUnit> installedUnitList = (List<InstalledUnit>) context.getFlowScope()
                .get("installedUnitList");
        int numberOfAssignedUnits = 0;
        // look for the non assigned groups
        // get the unique groups of assignment
        Set<String> uniqueGroups = new HashSet<String>();
        for (String action : actionsToDoArray) {
            String assignedGroup = action.substring(0, action.indexOf('|'));
            uniqueGroups.add(assignedGroup);
        }
        // if any of the group has not been assigned check if it is already
        // installed in the environment
        String[] uniqueGroupsArray = uniqueGroups.toArray(new String[uniqueGroups.size()]);
        Arrays.sort(uniqueGroupsArray);
        if (uniqueGroups.size() < groups.length) {
            for (int i = 0, k = 0; i < groups.length; i++) {
                boolean notAssigned = false;
                int groupNumber = -1;
                try {
                    groupNumber = Integer.parseInt(uniqueGroupsArray[k]);
                } catch (ArrayIndexOutOfBoundsException e) {
                    notAssigned = true;
                }
                if (notAssigned || groupNumber != i) {
                    // group number not assigned, necessary to check if this
                    // group is already installed
                    DeploymentGroup groupNotAssigned = groups[i];
                    List<DeploymentUnit> unitList = groupNotAssigned.getUnits();
                    for (DeploymentUnit unit : unitList) {
                        String unitName = unit.getName();
                        String unitVersion = unit.getVersion();
                        // check against the installed units
                        for (InstalledUnit installedUnit : installedUnitList) {
                            if (installedUnit.getUnitName().equals(unitName)
                                    && installedUnit.getUnitVersion().equals(unitVersion)) {
                                // the unit is installed, it is not necessary to
                                // install it again
                                numberOfAssignedUnits++;
                                break;
                            }
                        }
                    }
                }
                if (groupNumber == i)
                    k = k + 1;
            }
        }
        if (uniqueGroupsArray.length + numberOfAssignedUnits < groups.length) {
            ErrorUtils.createMessageError(context, "running.error.noSelectedAllContainer", null);
            throw new Exception();
        }
        String[] aActionsToDo = stActionsToDo.split(",");

        for (int i = 0; i < aActionsToDo.length; i++) {
            String[] actioni = aActionsToDo[i].split("\\|");
            int g = Integer.parseInt(actioni[0]);
            DeploymentGroup group = groups[g];
            String containeri = actioni[1];
            try {
                Map<DeploymentGroup, String> groupsToContainer = this.common.assignGroupToContainer(group,
                        containeri, false, context, browser);
                context.getFlowScope().put(Constants.FLOW_GROUPS_TO_CONTAINER, groupsToContainer);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        Calendar map2 = Calendar.getInstance();
        Utils.getTimeOfExecution(map1, map2, "Time of executing map: ");
        isOk = this.common.validatePlan(context, environment, graph);
    }
    lock = null;
    return isOk;
}

From source file:org.jmlspecs.util.QDoxUtil.java

private static void handlingCrosscutSpecs(File file, JavaMethod javaMeth, String currentMeth,
        JavaClass ownerType) throws PositionedError {
    boolean isAspect = false;
    //      boolean isCrosscutSpec = false;
    //      Annotation xciAnno = null;
    for (int i = 0; i < ownerType.getAnnotations().length; i++) {
        if (ownerType.getAnnotations()[i].toString().startsWith("@org.aspectj.lang.annotation.Aspect")) {
            isAspect = true;/*from  ww  w  .jav a2 s. c o m*/
        }
        //         if(ownerType.getAnnotations()[i].toString().startsWith("@org.jmlspecs.lang.annotation.AspectXCS")){
        //            isCrosscutSpec = true;
        //            xciAnno = ownerType.getAnnotations()[i];
        //         }
    }
    //      if(isAspect && isCrosscutSpec){
    //         System.out.println("parsedMethTmp = "+currentMeth);
    //         if(!ownerType.isInner()){
    //            TokenReference tref = TokenReference.build(file, xciAnno.getLineNumber());
    //            throw new PositionedError(tref, JmlMessages.INVALID_XCS_ANNOTATION_LOCATION, "");
    //         }
    //         // is to handle crosscut specs?
    //         if(Main.aRacOptions.crosscuttingContractSpecifications()){
    //            JavaDocBuilder qDoxJavaMethodParserForCrosscutSpecs = new JavaDocBuilder();
    //            qDoxJavaMethodParserForCrosscutSpecs.addSource(new StringReader("public class JMethodParser{\n"+currentMeth+"\n}"));
    //            JavaClass parsedClassTmp = qDoxJavaMethodParserForCrosscutSpecs.getClassByName("JMethodParser");
    //            if(parsedClassTmp.getMethods().length == 1){
    //               JavaMethod parsedMethTmp = parsedClassTmp.getMethods()[0];
    //               parsedMethTmp.setAnnotations(javaMeth.getAnnotations());
    //               parsedMethTmp.setParentClass(ownerType);
    //               boolean isToInclude = false;
    //               for (int i = 0; i < parsedMethTmp.getAnnotations().length; i++) {
    //                  if(parsedMethTmp.getAnnotations()[i].toString().startsWith("@org.aspectj.lang.annotation")){
    //                     isToInclude = true;
    //                  }
    //               }
    //               if(isToInclude){
    //                  AspectUtil.getInstance().appendCrosscutSpecMeth(parsedMethTmp);
    //               }
    //            }
    //         }
    //      }
    if (isAspect) {
        // means that we can have advice and pointcuts but is not a part of the crosscutting contract specification
        if (Main.aRacOptions != null) {
            if (Main.aRacOptions.adviceChecking()) {
                AspectUtil.getInstance().appendAspectDecl(ownerType);
                JavaDocBuilder qDoxJavaMethodParserForCrosscutSpecs = new JavaDocBuilder();
                qDoxJavaMethodParserForCrosscutSpecs
                        .addSource(new StringReader("public class JMethodParser{\n" + currentMeth + "\n}"));
                // adding Java imports
                for (int i = 0; i < ownerType.getSource().getImports().length; i++) {
                    qDoxJavaMethodParserForCrosscutSpecs.getSources()[0]
                            .addImport(ownerType.getSource().getImports()[i]);
                }
                JavaClass parsedClassTmp = qDoxJavaMethodParserForCrosscutSpecs.getClassByName("JMethodParser");
                if (parsedClassTmp.getMethods().length == 1) {
                    JavaMethod parsedMethTmp = parsedClassTmp.getMethods()[0];
                    parsedMethTmp.setAnnotations(javaMeth.getAnnotations());
                    parsedMethTmp.setParentClass(ownerType);
                    // handling advice specs --- [[[hemr]
                    boolean isToInclude = false;
                    for (int i = 0; i < parsedMethTmp.getAnnotations().length; i++) {
                        if (parsedMethTmp.getAnnotations()[i].toString()
                                .startsWith("@org.aspectj.lang.annotation.A")) {
                            isToInclude = true;
                        }
                        if (parsedMethTmp.getAnnotations()[i].toString()
                                .startsWith("@org.aspectj.lang.annotation.Before")) {
                            isToInclude = true;
                        }
                    }
                    if (isToInclude) {
                        AspectUtil.getInstance().appendAspectAdvice(parsedMethTmp);
                    }
                    // handling crosscutting contract specs for advice --- [[[hemr]
                    isToInclude = false;
                    boolean isPC = false;
                    for (int i = 0; i < parsedMethTmp.getAnnotations().length; i++) {
                        if (parsedMethTmp.getAnnotations()[i].toString()
                                .startsWith("@org.aspectj.lang.annotation.Pointcut")) {
                            isPC = true;
                        }
                    }
                    isToInclude = isPC;
                    if (isToInclude) {
                        AspectUtil.getInstance().appendCrosscutSpecMeth(parsedMethTmp);
                    }
                }
            }
        }
    } else {
        // is to handle crosscut specs?
        if (Main.aRacOptions != null) {
            if (Main.aRacOptions.crosscuttingContractSpecifications()) {
                JavaDocBuilder qDoxJavaMethodParserForCrosscutSpecs = new JavaDocBuilder();
                try {
                    qDoxJavaMethodParserForCrosscutSpecs
                            .addSource(new StringReader("public class JMethodParser{\n" + currentMeth + "\n}"));
                } catch (java.lang.ArrayIndexOutOfBoundsException e) {
                    // ignore for now...
                } catch (Exception e) {
                    //                  System.out.println("owner = "+javaMeth.getParentClass().getName());
                    //                  System.out.println("file = "+file.getAbsolutePath());
                    //                  System.out.println("currentMeth = "+currentMeth);
                    e.printStackTrace();
                }
                // adding Java imports
                for (int i = 0; i < ownerType.getSource().getImports().length; i++) {
                    qDoxJavaMethodParserForCrosscutSpecs.getSources()[0]
                            .addImport(ownerType.getSource().getImports()[i]);
                }
                JavaClass parsedClassTmp = qDoxJavaMethodParserForCrosscutSpecs.getClassByName("JMethodParser");
                if (parsedClassTmp.getMethods().length == 1) {
                    JavaMethod parsedMethTmp = parsedClassTmp.getMethods()[0];
                    parsedMethTmp.setAnnotations(javaMeth.getAnnotations());
                    parsedMethTmp.setParentClass(ownerType);
                    boolean isToInclude = false;
                    boolean isPC = false;
                    for (int i = 0; i < parsedMethTmp.getAnnotations().length; i++) {
                        if (parsedMethTmp.getAnnotations()[i].toString()
                                .startsWith("@org.aspectj.lang.annotation.Pointcut")) {
                            isPC = true;
                        }
                    }
                    isToInclude = isPC;
                    if (isToInclude) {
                        AspectUtil.getInstance().appendCrosscutSpecMeth(parsedMethTmp);
                    }
                }
            }
        }
    }
}

From source file:playground.meisterk.org.matsim.run.facilities.ShopsOf2005ToFacilities.java

private static void shopsToTXT(Config config) {

    ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
    ActivityFacilities shopsOf2005 = scenario.getActivityFacilities();
    shopsOf2005.setName("shopsOf2005");
    ArrayList<String> txtLines = new ArrayList<String>();
    ShopId shopId = null;// w  ww  .j ava 2 s.c o m
    String aShopLine = null;
    String facilityId = null;

    Day[] days = Day.values();
    OpeningTimeImpl opentime = null;

    // write header line
    aShopLine = "retailer" + ShopsOf2005ToFacilities.FIELD_DELIM + "businessRegion"
            + ShopsOf2005ToFacilities.FIELD_DELIM + "shopType" + ShopsOf2005ToFacilities.FIELD_DELIM
            + "shopDescription" + ShopsOf2005ToFacilities.FIELD_DELIM + "street"
            + ShopsOf2005ToFacilities.FIELD_DELIM + "postcode" + ShopsOf2005ToFacilities.FIELD_DELIM + "city"
            + ShopsOf2005ToFacilities.FIELD_DELIM + "CH1903_X" + ShopsOf2005ToFacilities.FIELD_DELIM
            + "CH1903_Y";

    for (Day day : days) {

        aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
        aShopLine += day.getAbbrevEnglish();
        for (int ii = 1; ii <= 3; ii++) {
            aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
        }
    }

    txtLines.add(aShopLine);

    System.out.println("Reading facilities xml file... ");
    FacilitiesReaderMatsimV1 facilities_reader = new FacilitiesReaderMatsimV1(scenario);
    facilities_reader.readFile(config.facilities().getInputFile());
    System.out.println("Reading facilities xml file...done.");

    Iterator<? extends ActivityFacility> facilityIterator = shopsOf2005.getFacilities().values().iterator();

    while (facilityIterator.hasNext()) {

        ActivityFacilityImpl facility = (ActivityFacilityImpl) facilityIterator.next();
        facilityId = facility.getId().toString();
        System.out.println(facilityId);

        try {
            shopId = new ShopId(facility.getId().toString());
        } catch (ArrayIndexOutOfBoundsException e) {
            continue;
        }

        // name, coordinates etc. (fixed length)
        aShopLine = shopId.getRetailer() + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getBusinessRegion()
                + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getShopType()
                + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getShopDescription()
                + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getStreet() + ShopsOf2005ToFacilities.FIELD_DELIM
                + shopId.getPostcode() + ShopsOf2005ToFacilities.FIELD_DELIM + shopId.getCity()
                + ShopsOf2005ToFacilities.FIELD_DELIM + (int) facility.getCoord().getY()
                + ShopsOf2005ToFacilities.FIELD_DELIM + (int) facility.getCoord().getX();
        ;

        ActivityOptionImpl shopping = (ActivityOptionImpl) facility.getActivityOptions()
                .get(ACTIVITY_TYPE_SHOP);
        if (shopping != null) {

            // open times (variable length)

            Set<OpeningTime> dailyOpentime = shopping.getOpeningTimes();

            if (dailyOpentime != null) {

                // what crappy code is that...but I had to get finished :-)
                opentime = (OpeningTimeImpl) ((TreeSet) dailyOpentime).last();
                aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                aShopLine += Time.writeTime(opentime.getStartTime());
                aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                aShopLine += Time.writeTime(opentime.getEndTime());
                if (dailyOpentime.size() == 2) {
                    opentime = (OpeningTimeImpl) ((TreeSet) dailyOpentime).first();
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                    aShopLine += Time.writeTime(opentime.getStartTime());
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                    aShopLine += Time.writeTime(opentime.getEndTime());
                } else if (dailyOpentime.size() == 1) {
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                    aShopLine += ShopsOf2005ToFacilities.FIELD_DELIM;
                }

            }

        }
        txtLines.add(aShopLine);

    }

    System.out.println("Writing txt file...");
    try {
        FileUtils.writeLines(new File((String) null /* filename not specified */), "UTF-8", txtLines);
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Writing txt file...done.");

}

From source file:org.bbaw.telota.ediarum.ReadRegister.java

/**
 * Der Konstruktor liest das Dokument der URL mit den benannten Knoten aus und konstruiert den Eintrag und die Id fr jeden Knoten.
 * @param indexURI Die URL zur Registerdatei
 * @param node Der X-Path-Ausdruck fr die Knoten der einzelnen Registereintrge
 * @param eintragExp Der Ausdruck um einen Registereintrag zu konstruieren. Er setzt sich aus Strings in "", Attributen beginnend mit @,
 *  Elementen mit / oder // und aus X-Path-Ausdrcken beginnend mit . zusammen. Die einzelnen Teile werden mit + verbunden.
 * @param idExp Der Ausdruck um die ID fr einen Registereintrag zu konstruieren. Er setzt sich wie eintragExp zusammen.
 * @throws AuthorOperationException//from   w ww.j ava  2s  . c  o m
 */
public ReadRegister(String indexURI, String node, String eintragExp, String idExp) {

    try {
        // Das neue Dokument wird vorbereitet.
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();

        // Wenn es sich um eine URL mit Authentifizierung handelt, ..
        InputStream is;
        if (indexURI.indexOf('@') > -1) {
            // .. werden die Verbindungsdaten gelesen ..
            String authString = indexURI.substring(indexURI.indexOf("://") + 3, indexURI.indexOf('@'));
            String webPage = indexURI.substring(0, indexURI.indexOf("://") + 3)
                    + indexURI.substring(indexURI.indexOf('@') + 1);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);

            // .. und eine Verbindung mit Login geffnet.
            URL url = new URL(webPage);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            is = urlConnection.getInputStream();
        } else {
            // Im anderen Fall wird direkt eine Verbindung geffnet.
            URL url = new URL(indexURI);
            URLConnection urlConnection = url.openConnection();
            is = urlConnection.getInputStream();
        }

        // Dann wird die Datei gelesen.
        InputSource inputSource = new InputSource(is);
        Document indexDoc = builder.parse(inputSource);
        // Die xPath-Routinen werden vorbereitet.
        XPath xpath = XPathFactory.newInstance().newXPath();
        // Das XPath-Query wird definiert.
        XPathExpression expr = xpath.compile(node);

        // Die Resultate werden ausgelesen..
        Object result = expr.evaluate(indexDoc, XPathConstants.NODESET);
        NodeList registerNodes = (NodeList) result;

        // .. dann werden fr die Eintrge und IDs entsprechend lange Arrays angelegt.
        eintrag = new String[registerNodes.getLength()];
        id = new String[registerNodes.getLength()];

        // Die Ausdrcke fr die Eintrge ..
        String[] eintragExpression = (eintragExp).split("[+]");
        for (int i = 0; i < eintragExpression.length; i++) {
            eintragExpression[i] = eintragExpression[i].trim();
        }
        // .. und IDs werden in einzelne Glieder geteilt. 
        String[] idExpression = (idExp).split("[+]");
        for (int i = 0; i < idExpression.length; i++) {
            idExpression[i] = idExpression[i].trim();
        }

        // Fr jeden Knoten ..
        for (int i = 0; i < registerNodes.getLength(); i++) {
            Element currentElement = (Element) registerNodes.item(i);
            // .. wird der Eintrag konstruiert.
            eintrag[i] = "";
            // Dazu werden die Glieder des entsprechenden Ausdrucks interpretiert.
            for (int j = 0; j < eintragExpression.length; j++) {
                try {
                    // Jedes Glied kann entweder als Attribut, ..
                    if (eintragExpression[j].startsWith("@")) {
                        String attributeName = eintragExpression[j].substring(1);
                        eintrag[i] += currentElement.getAttribute(attributeName);
                    }
                    // .. als String, ..
                    if (eintragExpression[j].startsWith("\"") && eintragExpression[j].endsWith("\"")) {
                        String stringexpression = eintragExpression[j].substring(1,
                                eintragExpression[j].length() - 1);
                        eintrag[i] += stringexpression;
                    }
                    // .. als spter zu verarbeitetende Variable, ..
                    if (eintragExpression[j].startsWith("$")) {
                        String stringexpression = eintragExpression[j];
                        eintrag[i] += stringexpression;
                    }
                    // **
                    // .. als nachkommendes Element ..
                    if (eintragExpression[j].startsWith("//")) {
                        // .. (was direkt gelesen werden kann und schnell geht, ..
                        String elementName = eintragExpression[j].substring(2);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            eintrag[i] += currentElement.getElementsByTagName(elementName).item(0)
                                    .getTextContent();
                        } else {
                            // .. oder welches ber eine X-Path-Abfrage gelesen werden kann und lange dauert), ..
                            XPathExpression queryExpr = xpath.compile("." + eintragExpression[j]);
                            NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                    XPathConstants.NODESET);
                            if (elementNodes.getLength() > 0
                                    && elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                                eintrag[i] += elementNodes.item(0).getTextContent();
                            }
                        }
                        // .. als direktes Kindelement (was schnell geht) ..
                    } else if (eintragExpression[j].startsWith("/")) {
                        String elementName = eintragExpression[j].substring(1);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            eintrag[i] += currentElement.getElementsByTagName(elementName).item(0)
                                    .getTextContent();
                        }
                    }
                    // .. oder als X-Path-Ausdruck (was sehr lange dauert) verstanden werden.
                    if (eintragExpression[j].startsWith(".")) {
                        XPathExpression queryExpr = xpath.compile(eintragExpression[j]);
                        NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                XPathConstants.NODESET);
                        if (elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                            eintrag[i] += elementNodes.item(0).getTextContent();
                        }
                    }
                } catch (ArrayIndexOutOfBoundsException e) {
                }
            }

            // Genauso wird die ID konstruiert.
            id[i] = "";
            // Dazu werden die Glieder des entsprechenden Ausdrucks interpretiert.
            for (int j = 0; j < idExpression.length; j++) {
                try {
                    // Jedes Glied kann entweder als Attribut, ..
                    if (idExpression[j].startsWith("@")) {
                        String attributeName = idExpression[j].substring(1);
                        id[i] += currentElement.getAttribute(attributeName);
                    }
                    // .. als String, ..
                    if (idExpression[j].startsWith("\"") && idExpression[j].endsWith("\"")) {
                        String stringexpression = idExpression[j].substring(1, idExpression[j].length() - 1);
                        id[i] += stringexpression;
                    }
                    // .. als spter zu verarbeitetende Variable, ..
                    if (idExpression[j].startsWith("$")) {
                        String stringexpression = idExpression[j];
                        id[i] += stringexpression;
                    }
                    // .. als nachkommendes Element ..
                    if (idExpression[j].startsWith("//")) {
                        // .. (was direkt gelesen werden kann und schnell geht, ..
                        String elementName = idExpression[j].substring(2);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            id[i] += currentElement.getElementsByTagName(elementName).item(0).getTextContent();
                        } else {
                            // .. oder welches ber eine X-Path-Abfrage gelesen werden kann und lange dauert), ..
                            XPathExpression queryExpr = xpath.compile("." + idExpression[j]);
                            NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                    XPathConstants.NODESET);
                            if (elementNodes.getLength() > 0
                                    && elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                                id[i] += elementNodes.item(0).getTextContent();
                            }
                        }
                        // .. als direktes Kindelement (was schnell geht) ..
                    } else if (idExpression[j].startsWith("/")) {
                        String elementName = idExpression[j].substring(1);
                        if (currentElement.getElementsByTagName(elementName).getLength() > 0) {
                            id[i] += currentElement.getElementsByTagName(elementName).item(0).getTextContent();
                        }
                    }
                    // .. oder als X-Path-Ausdruck (was sehr lange dauert) verstanden werden.
                    if (idExpression[j].startsWith(".")) {
                        XPathExpression queryExpr = xpath.compile(idExpression[j]);
                        NodeList elementNodes = (NodeList) queryExpr.evaluate(registerNodes.item(i),
                                XPathConstants.NODESET);
                        if (elementNodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
                            id[i] += elementNodes.item(0).getTextContent();
                        }
                    }
                } catch (ArrayIndexOutOfBoundsException e) {
                }
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (DOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:pl.betoncraft.betonquest.config.ConfigUpdater.java

@SuppressWarnings("unused")
private void update_from_v16() {
    try {//from   www .j  av  a2s.c o  m
        // move objectives from events.yml to objectives.yml
        Debug.info("Moving objectives to objectives.yml");
        for (ConfigPackage pack : Config.getPackages().values()) {
            String packName = pack.getName();
            Debug.info("  Package " + packName);
            ConfigAccessor events = pack.getEvents();
            ConfigAccessor objectives = pack.getObjectives();
            ConfigAccessor main = pack.getMain();
            for (String event : events.getConfig().getKeys(false)) {
                // extract label and build the new instruction
                int i = 0; // counts unnamed objectives
                String instruction = events.getConfig().getString(event);
                if (instruction.startsWith("objective ")) {
                    Debug.info("    Starting event " + event);
                    String[] parts = instruction.substring(10).split(" ");
                    StringBuilder string = new StringBuilder();
                    String label = null;
                    String conditions = "";
                    for (String part : parts) {
                        if (part.startsWith("label:")) {
                            label = part.substring(6);
                        } else if (part.startsWith("event_conditions:")) {
                            conditions = part;
                        } else if (parts[0].equalsIgnoreCase("delay") && part.startsWith("delay:")) {
                            string.append(part.substring(6));
                            string.append(' ');
                        } else {
                            string.append(part);
                            string.append(' ');
                        }
                    }
                    String newInstruction = string.toString().trim();
                    // if label is not present, skip this one
                    if (label == null) {
                        Debug.info("      There is no label, generating one");
                        label = "objective" + i;
                        i++;
                    }
                    Debug.info("      Saving the objective as " + label + ", instruction: " + newInstruction);
                    // save objective and generate label
                    objectives.getConfig().set(label, newInstruction);
                    events.getConfig().set(event, ("objective start " + label + " " + conditions).trim());
                } else if (instruction.startsWith("delete ")) {
                    // update delete events
                    Debug.info("    Delete event " + event);
                    events.getConfig().set(event, "objective " + instruction);
                }
            }
            // rename event_conditions to conditions
            for (String event : events.getConfig().getKeys(false)) {
                String instruction = events.getConfig().getString(event);
                events.getConfig().set(event, instruction.replace("event_conditions:", "conditions:"));
            }
            // update global locations
            String raw = main.getConfig().getString("global_locations");
            if (raw != null && !raw.equals("")) {
                StringBuilder string = new StringBuilder();
                String[] parts = raw.split(",");
                for (String event : parts) {
                    String inst = events.getConfig().getString(event);
                    if (inst == null) {
                        continue;
                    }
                    String[] instParts = inst.split(" ");
                    if (instParts.length > 2 && inst.startsWith("objective start ")) {
                        string.append(instParts[2] + ",");
                    }
                }
                main.getConfig().set("global_locations", string.substring(0, string.length() - 1));
            }
            events.saveConfig();
            objectives.saveConfig();
            main.saveConfig();
        }
        Debug.broadcast("Moved objectives to a separate file and renamed"
                + " 'event_conditions:' argument to 'conditions:'");
        Debug.info("Updating the database");
        Connection con = instance.getDB().getConnection();
        String prefix = Config.getString("config.mysql.prefix");
        // update database format
        Debug.info("Updating the database format");
        if (instance.isMySQLUsed()) {
            con.prepareStatement(
                    "ALTER TABLE " + prefix + "objectives ADD objective VARCHAR(512) NOT NULL AFTER playerID;")
                    .executeUpdate();
        } else {
            con.prepareStatement("BEGIN TRANSACTION").executeUpdate();
            con.prepareStatement("ALTER TABLE " + prefix + "objectives RENAME TO " + prefix + "objectives_old")
                    .executeUpdate();
            con.prepareStatement(
                    "CREATE TABLE IF NOT EXISTS " + prefix + "objectives (id INTEGER PRIMARY KEY AUTOINCREMENT,"
                            + " playerID VARCHAR(256) NOT NULL, objective VARCHAR(512)"
                            + " NOT NULL, instructions VARCHAR(2048) NOT NULL);")
                    .executeUpdate();
            con.prepareStatement("INSERT INTO " + prefix + "objectives"
                    + " SELECT id, playerID, 'null', instructions FROM " + prefix + "objectives_old")
                    .executeUpdate();
            con.prepareStatement("COMMIT").executeUpdate();
        }
        // update each entry
        Debug.info("Updating entries");
        ResultSet res = con.prepareStatement("SELECT * FROM " + prefix + "objectives").executeQuery();
        while (res.next()) {
            String oldInst = res.getString("instructions");
            Debug.info("  Loaded instruction: " + oldInst);
            String label = null;
            String[] parts = oldInst.split(" ");
            String newInst;
            for (String part : parts) {
                if (part.startsWith("label:")) {
                    label = part.substring(6);
                    break;
                }
            }
            if (label == null) {
                Debug.info("    The objective without label, removing");
                PreparedStatement stmt = con
                        .prepareStatement("DELETE FROM " + prefix + "objectives WHERE id = ?");
                stmt.setInt(1, res.getInt("id"));
                stmt.executeUpdate();
                continue;
            }
            // attack correct package in front of the label
            for (ConfigPackage pack : Config.getPackages().values()) {
                String packName = pack.getName();
                if (pack.getObjectives().getConfig().contains(label)) {
                    label = packName + "." + label;
                    break;
                }
            }
            try {
                switch (parts[0].toLowerCase()) {
                case "tame":
                case "block":
                case "smelt":
                case "craft":
                case "mobkill":
                    newInst = parts[2];
                    break;
                case "delay":
                    newInst = parts[1].substring(6);
                    break;
                case "npckill":
                case "mmobkill":
                    newInst = parts[2].substring(7);
                    break;
                default:
                    newInst = "";
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                Debug.info("    Could not read data from objective " + label + ", removing");
                PreparedStatement stmt = con
                        .prepareStatement("DELETE FROM " + prefix + "objectives WHERE id = ?");
                stmt.setInt(1, res.getInt("id"));
                stmt.executeUpdate();
                continue;
            }
            Debug.info("    Updating the " + label + " objective: '" + newInst + "'");
            PreparedStatement stmt = con.prepareStatement(
                    "UPDATE " + prefix + "objectives SET objective=?, instructions=? WHERE id = ?");
            stmt.setString(1, label);
            stmt.setString(2, newInst);
            stmt.setInt(3, res.getInt("id"));
            stmt.executeUpdate();
        }
        Debug.broadcast("Updated objective instruction strings in the database");
    } catch (Exception e) {
        e.printStackTrace();
        Debug.error(ERROR);
    }
    config.set("version", "v17");
    instance.saveConfig();
}