List of usage examples for java.lang ArrayIndexOutOfBoundsException getMessage
public String getMessage()
From source file:net.pms.dlna.RootFolder.java
private void addWebFolder(File webConf) { if (webConf.exists()) { try {//from w ww.j a v a 2s . c o m LineNumberReader br = new LineNumberReader( new InputStreamReader(new FileInputStream(webConf), "UTF-8")); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() > 0 && !line.startsWith("#") && line.indexOf("=") > -1) { String key = line.substring(0, line.indexOf("=")); String value = line.substring(line.indexOf("=") + 1); String[] keys = parseFeedKey(key); try { if (keys[0].equals("imagefeed") || keys[0].equals("audiofeed") || keys[0].equals("videofeed") || keys[0].equals("audiostream") || keys[0].equals("videostream")) { String[] values = parseFeedValue(value); DLNAResource parent = null; if (keys[1] != null) { StringTokenizer st = new StringTokenizer(keys[1], ","); DLNAResource currentRoot = this; while (st.hasMoreTokens()) { String folder = st.nextToken(); parent = currentRoot.searchByName(folder); if (parent == null) { parent = new VirtualFolder(folder, ""); currentRoot.addChild(parent); } currentRoot = parent; } } if (parent == null) { parent = this; } if (keys[0].equals("imagefeed")) { parent.addChild(new ImagesFeed(values[0])); } else if (keys[0].equals("videofeed")) { parent.addChild(new VideosFeed(values[0])); } else if (keys[0].equals("audiofeed")) { parent.addChild(new AudiosFeed(values[0])); } else if (keys[0].equals("audiostream")) { parent.addChild(new WebAudioStream(values[0], values[1], values[2])); } else if (keys[0].equals("videostream")) { parent.addChild(new WebVideoStream(values[0], values[1], values[2])); } } } catch (ArrayIndexOutOfBoundsException e) { // catch exception here and go with parsing logger.info("Error at line " + br.getLineNumber() + " of WEB.conf: " + e.getMessage()); logger.debug(null, e); } } } br.close(); } catch (IOException e) { logger.info("Unexpected error in WEB.conf" + e.getMessage()); logger.debug(null, e); } } }
From source file:org.isatools.isacreator.spreadsheet.SpreadsheetFunctions.java
protected void removeColumn() { try {/*ww w.ja v a 2 s .c o m*/ if (spreadsheet.curColDelete != -1) { SpreadsheetModel model = (SpreadsheetModel) spreadsheet.getTable().getModel(); TableColumn col = spreadsheet.getTable().getColumnModel().getColumn(spreadsheet.curColDelete); spreadsheet.hiddenColumns.add(col.getHeaderValue().toString()); deleteColumn(model, col); removeDependentColumns(col); removeColumnFromDependencies(col); } } catch (ArrayIndexOutOfBoundsException e) { log.error("Problem encountered when removing a column " + e.getMessage()); } }
From source file:io.hops.hopsworks.api.jobs.JobService.java
/** * Get all the jobs in this project that have a running execution. The return * value is a JSON object, where each job * id is a key and the corresponding boolean indicates whether the job is * running or not.//from www . ja va 2 s .c om * <p/> * @param sc * @param req * @return */ @GET @Path("/running") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getConfigurationTemplate(@Context SecurityContext sc, @Context HttpServletRequest req) { List<Jobs> running = jobFacade.getRunningJobs(project); List<Jobs> allJobs = jobFacade.findForProject(project); JsonObjectBuilder builder = Json.createObjectBuilder(); for (Jobs desc : allJobs) { try { List<Execution> jobExecutions = exeFacade.findForJob(desc); if (jobExecutions != null && jobExecutions.isEmpty() == false) { Execution execution = jobExecutions.get(0); builder.add(desc.getId().toString(), Json.createObjectBuilder().add("running", false) .add("state", execution.getState().toString()) .add("finalStatus", execution.getFinalStatus().toString()) .add("progress", execution.getProgress()) .add("duration", execution.getExecutionDuration()) .add("submissiontime", execution.getSubmissionTime().toString())); } } catch (ArrayIndexOutOfBoundsException e) { LOGGER.log(Level.WARNING, "No execution was found: {0}", e.getMessage()); } } for (Jobs desc : running) { try { Execution execution = exeFacade.findForJob(desc).get(0); long executiontime = System.currentTimeMillis() - execution.getSubmissionTime().getTime(); //not given appId (not submited yet) if (execution.getAppId() == null && executiontime > 60000l * 5) { exeFacade.updateState(execution, JobState.INITIALIZATION_FAILED); exeFacade.updateFinalStatus(execution, JobFinalStatus.FAILED); continue; } String trackingUrl = appAttemptStateFacade.findTrackingUrlByAppId(execution.getAppId()); builder.add(desc.getId().toString(), Json.createObjectBuilder().add("running", true) .add("state", execution.getState().toString()) .add("finalStatus", execution.getFinalStatus().toString()) .add("progress", execution.getProgress()).add("duration", execution.getExecutionDuration()) .add("submissiontime", execution.getSubmissionTime().toString()).add("url", trackingUrl)); } catch (ArrayIndexOutOfBoundsException e) { LOGGER.log(Level.WARNING, "No execution was found: {0}", e.getMessage()); } } return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(builder.build()).build(); }
From source file:org.exoplatform.social.service.rest.PeopleRestService.java
private String substringActivity(ExoSocialActivity act) { String activity = ""; try {//from w w w . ja v a2s . co m if (act.getType() != null) { activity = act.getTitle().replaceAll("<br/>", " ").replaceAll("<br />", " ").replaceAll("<br>", " ") .replaceAll("</br>", " ").trim(); activity = StringEscapeUtils.unescapeHtml(activity); activity = activity.replaceAll("\"", "'"); if (activity.length() > MAX_CHAR && act.getType().equals(DEFAULT_ACTIVITY)) { String maxBody = activity.substring(0, MAX_CHAR); int tagEnterLocation = maxBody.indexOf('<', 0); if (tagEnterLocation != -1) { if (tagEnterLocation == 0) { if (maxBody.indexOf("<", tagEnterLocation) == 0) { int endtag = activity.indexOf(">", tagEnterLocation); int tagend = activity.indexOf("<", endtag); int tagend2 = activity.indexOf(">", tagend); String linktitle = activity.substring(endtag + 1, tagend); if (linktitle.length() > MAX_CHAR) { linktitle = linktitle.substring(0, MAX_CHAR); activity = activity.substring(0, endtag + 1) + linktitle + activity.substring(tagend, tagend2 + 1); } else { activity = activity.substring(0, tagend2 + 1) + SPACE_CHAR + activity.substring(tagend2 + 2, MAX_CHAR - linktitle.length()); } } activity = activity + "<span class='truncate_ellipsis'>" + THREE_DOTS + "</span>"; } else { int tagEndLocation = maxBody.indexOf("<", tagEnterLocation + 1); int tagLocationEnd = maxBody.indexOf("/>", tagEnterLocation); if ((tagEndLocation == -1 && tagLocationEnd == -1)) { String str1 = maxBody.substring(0, tagEnterLocation - 1); activity = str1 + "<span class='truncate_ellipsis'>" + THREE_DOTS + "</span>"; } if (tagEndLocation != -1) { if (tagEndLocation > MAX_CHAR - 3) { String charRest = activity.substring(0, tagEndLocation + 3); activity = charRest + "<span class='truncate_ellipsis'>" + THREE_DOTS + "</span>"; } else { if (tagEndLocation <= MAX_CHAR - 3) { activity = maxBody + "<span class='truncate_ellipsis'>" + THREE_DOTS + "</span>"; } } } if (tagLocationEnd != -1) { activity = maxBody + "<span class='truncate_ellipsis'>" + THREE_DOTS + "</span>"; } } } else { activity = maxBody + "<span class='truncate_ellipsis'>" + THREE_DOTS + "</span>"; } } if (act.getType().equals(DOC_ACTIVITY)) { try { if ((activity.split(">")[1].split("<")[0]).length() > MAX_DOC_CHAR) { String docName = activity.split(">")[1].split("<")[0].substring(0, MAX_DOC_CHAR) .concat(THREE_DOTS); String docUrl = activity.split(">")[0].split("=")[1].replace("\"", "'"); activity = "Shared a Document <a class='ColorLink' target='_blank' href=" + docUrl + "title='" + activity.split(">")[1].split("<")[0] + "'>" + docName + "</a>"; } } catch (ArrayIndexOutOfBoundsException e) { log.warn( "Error while recovering activity of type DOC_ACTIVITY [Url of shared Document Not found ]"); return ""; } } if (act.getType().equals(LINK_ACTIVITY)) { if (activity.indexOf("<", 0) != -1) { activity = activity.substring(activity.indexOf(">", 0) + 1, activity.indexOf("<", activity.indexOf(">", 0))); } if (activity.length() > MAX_CHAR) { activity = activity.substring(0, MAX_CHAR); } activity = "<a class='ColorLink' target='_blank' href='" + act.getUrl().replaceAll("\"", "'") + "'>" + activity + "</a>"; } } return activity; } catch (Exception e) { log.error( "Error while recovering user's last activity [WhoIsOnLine rendering phase] :" + e.getMessage(), e); return ""; } }
From source file:org.lockss.servlet.HashCUS.java
private boolean checkParams() { auid = getParameter(KEY_AUID);/*from w w w.j a va 2 s .c om*/ url = getParameter(KEY_URL); lower = getParameter(KEY_LOWER); upper = getParameter(KEY_UPPER); isRecord = (getParameter(KEY_RECORD) != null); alg = req.getParameter(KEY_ALG); if (StringUtil.isNullString(alg)) { alg = LcapMessage.getDefaultHashAlgorithm(); } String hTypeStr = getParameter(KEY_HASH_TYPE); if (StringUtil.isNullString(hTypeStr)) { hType = DEFAULT_HASH_TYPE; } else if (StringUtils.isNumeric(hTypeStr)) { try { int hTypeInt = Integer.parseInt(hTypeStr); hType = hashTypeCompat[hTypeInt]; if (hType == null) throw new ArrayIndexOutOfBoundsException(); } catch (ArrayIndexOutOfBoundsException e) { errMsg = "Unknown hash type: " + hTypeStr; return false; } catch (RuntimeException e) { errMsg = "Can't parse hash type: " + hTypeStr; return false; } } else { try { hType = HashType.valueOf(hTypeStr); } catch (IllegalArgumentException e) { errMsg = "Unknown hash type: " + hTypeStr; return false; } } String resTypeStr = getParameter(KEY_RESULT_TYPE); if (StringUtil.isNullString(resTypeStr)) { resType = DEFAULT_RESULT_TYPE; } else { try { resType = ResultType.valueOf(resTypeStr); } catch (IllegalArgumentException e) { errMsg = "Unknown result type: " + resTypeStr; return false; } } String resEncodingStr = getParameter(KEY_RESULT_ENCODING); if (StringUtil.isNullString(resEncodingStr)) { resEncoding = DEFAULT_RESULT_ENCODING; } else { try { resEncoding = ResultEncoding.valueOf(resEncodingStr); } catch (IllegalArgumentException e) { errMsg = "Unknown result encoding: " + resEncodingStr; return false; } } if (auid == null) { errMsg = "Select an AU"; return false; } au = pluginMgr.getAuFromId(auid); if (au == null) { errMsg = "No such AU. Select an AU"; return false; } if (url == null) { url = AuCachedUrlSetSpec.URL; // errMsg = "URL required"; // return false; } try { challenge = getB64Param(KEY_CHALLENGE); } catch (IllegalArgumentException e) { errMsg = "Challenge: Illegal Base64 string: " + e.getMessage(); return false; } try { verifier = getB64Param(KEY_VERIFIER); } catch (IllegalArgumentException e) { errMsg = "Verifier: Illegal Base64 string: " + e.getMessage(); return false; } PollSpec ps; try { switch (hType) { case V1File: if (upper != null || (lower != null && !lower.equals(PollSpec.SINGLE_NODE_LWRBOUND))) { errMsg = "Upper/Lower ignored"; } ps = new PollSpec(auid, url, PollSpec.SINGLE_NODE_LWRBOUND, null, Poll.V1_CONTENT_POLL); break; case V3Tree: ps = new PollSpec(auid, url, lower, upper, Poll.V3_POLL); break; case V3File: ps = new PollSpec(auid, url, PollSpec.SINGLE_NODE_LWRBOUND, null, Poll.V3_POLL); break; default: ps = new PollSpec(auid, url, lower, upper, Poll.V1_CONTENT_POLL); } } catch (Exception e) { errMsg = "Error making PollSpec: " + e.toString(); log.debug("Making Pollspec", e); return false; } log.debug("" + ps); cus = ps.getCachedUrlSet(); if (cus == null) { errMsg = "No such CUS: " + ps; return false; } log.debug("" + cus); return true; }
From source file:com.sababado.network.AsyncServiceCallTask.java
@Override protected Bundle doInBackground(Void... args) { mRunning = true;//from w w w. j a va 2s .c o m log(LOG_TYPE_DEBUG, "****in AsyncServiceCallTask do in Background"); int attempts = 0; if (!UtilNetwork.isNetworkAvailable(mContext)) { Bundle responseBundle = new Bundle(); responseBundle.putString(EXTRA_ERR_MSG, "Sorry, there is limited or no connectivity. Please try again later."); responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_NO_NETWORK); return responseBundle; } //get names and values String[] paramNames = mService.getAllParamNames(); String[] paramValues = mService.getAllParamValues(); //build parameter list String paramString = ""; if (paramNames != null && paramNames.length > 0) { try { //this assumes there is a 1 to 1 number of names and values List<NameValuePair> nvPairs = new LinkedList<NameValuePair>(); for (int i = 0; i < paramNames.length; i++) { nvPairs.add(new BasicNameValuePair(paramNames[i], paramValues[i])); } paramString = URLEncodedUtils.format(nvPairs, "utf-8"); } catch (ArrayIndexOutOfBoundsException e) { String message = "Failed paring param names and values (Index out of bounds). Make sure the there are the same number of param names and values."; log(LOG_TYPE_ERROR, message); throw new ArrayIndexOutOfBoundsException(message); } } String url = mService.getUrl(); //format the url string if (paramString.length() > 0) { //format url to have parameters only if there are parameters to add. if (!url.endsWith("?")) url += "?"; url += paramString; } log(LOG_TYPE_DEBUG, "Url: " + url); HttpResponse response = null; //while under the maximum number of attempts... while (attempts < MAX_ATTEMPTS) { try { log(LOG_TYPE_DEBUG, (attempts + 1) + "/" + MAX_ATTEMPTS + ": Creating Http Client"); //create the HttpClient HttpClient client = new DefaultHttpClient(); //set the request switch (mService.getCallType()) { case Service.CALL_TYPE_GET: log(LOG_TYPE_DEBUG, "Making GET Call"); HttpGet getRequest = new HttpGet(url); response = client.execute(getRequest); break; case Service.CALL_TYPE_POST: log(LOG_TYPE_DEBUG, "Making POST Call"); HttpPost postRequest = new HttpPost(url); response = client.execute(postRequest); break; case Service.CALL_TYPE_PUT: log(LOG_TYPE_DEBUG, "Making PUT Call"); HttpPut putRequest = new HttpPut(url); response = client.execute(putRequest); break; case Service.CALL_TYPE_DELETE: log(LOG_TYPE_DEBUG, "Making DELETE Call"); HttpDelete deleteRequest = new HttpDelete(url); response = client.execute(deleteRequest); break; default: throw new RuntimeException( "Invalid Call type, please see Service.CALL_TYPE_* for possible types."); } } catch (IOException e) { attempts++; publishProgress("IOException: Retrying, attempt " + (attempts + 1), e.getMessage()); } if (response != null) break; } //check if exceeded max number of attempts if (attempts == MAX_ATTEMPTS) { //max number of attempts exceeded, error Bundle responseBundle = new Bundle(); //responseBundle.putString(EXTRA_ERR_MSG, "Failed "+MAX_ATTEMPTS+" attempts, please retry later."); responseBundle.putString(EXTRA_ERR_MSG, "Could not connect to the server, please try again later"); responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_MAX_ATTEMPTS_REACHED); return responseBundle; } return parseResponse(response); }
From source file:vc.fq.FanfouExporter.ExportTread.java
/** * *///from www . j a v a2s.co m public void run() { String username = Main.txtUsr.getText(); String password = Main.txtPwd.getText(); String userID = Main.txtFriID.getText(); filepath = Main.txtFilePath.getText(); exportPic = Main.chkbxPic.isSelected(); if (filepath.charAt(filepath.length() - 1) == '/' || filepath.charAt(filepath.length() - 1) == '\\') { filepath = filepath.substring(0, filepath.length() - 1); } DateFormat df = new SimpleDateFormat("yyyyMMdd"); if (Main.rdbtnUsrTL.isSelected()) { content = 1; filename = df.format(new Date()) + "_" + username + "_tl"; } else if (Main.rdbtnMention.isSelected()) { content = 2; filename = df.format(new Date()) + "_" + username + "_mention"; } else if (Main.rdbtnDM.isSelected()) { content = 3; filename = df.format(new Date()) + "_" + username + "_dm"; } else if (Main.rdbtnFriTL.isSelected()) { content = 4; filename = df.format(new Date()) + "_" + userID + "_tl"; } else //? { content = 5; filename = df.format(new Date()) + "_" + username + "_fav"; } if (Main.rdbtnCSV.isSelected()) { format = 1; extention = ".csv"; } else if (Main.rdbtnXML.isSelected()) { format = 2; extention = ".xml"; } else if (Main.rdbtnHTML.isSelected()) { format = 3; extention = ".html"; } else { format = 4; extention = ".txt"; } setLog("\r\n?" + filepath + "\\" + filename + extention); if (exportPic) { setLog("" + filepath + "\\" + filename + "_pic "); } setLog("\r\n??..."); /* XAuth?,?Access_Token?Access_Token_Secret */ String strxauth = XAuth(username, password); if (strxauth == null) { Main.isStart = false; Main.btnStart.setText(""); return; } try { String[] tokenarr = strxauth.split("&"); String[] tokenarr2 = tokenarr[0].split("="); oauth_token = tokenarr2[1]; tokenarr2 = tokenarr[1].split("="); oauth_token_secret = tokenarr2[1]; setLog("??\r\n"); } catch (ArrayIndexOutOfBoundsException e) { setLog("?Access_Token\r\n?"); Main.isStart = false; Main.btnStart.setText(""); return; } filepath = filepath.replace("\\", "/"); File dirFile = new File(filepath); boolean mkdir; if (!dirFile.exists() && !dirFile.isDirectory()) { int option = JOptionPane.showConfirmDialog(null, "?,??", "?", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { mkdir = dirFile.mkdirs(); if (mkdir == false) { setLog(""); Main.isStart = false; Main.btnStart.setText(""); return; } setLog("?"); } else { setLog("?"); Main.isStart = false; Main.btnStart.setText(""); return; } } /* */ if (exportPic) { picpath = filepath + "/" + filename + "_pic"; dirFile = new File(picpath); if (!dirFile.exists() && !dirFile.isDirectory()) { mkdir = dirFile.mkdirs(); if (mkdir == false) { setLog(""); Main.isStart = false; Main.btnStart.setText(""); return; } setLog("?"); } } /* */ if (format != 3) //?html? { try { if (format == 1) //.csv outstream = new PrintWriter(new OutputStreamWriter( new FileOutputStream(filepath + "/" + filename + extention), "gb2312")); else outstream = new PrintWriter(new OutputStreamWriter( new FileOutputStream(filepath + "/" + filename + extention), "UTF-8")); } catch (FileNotFoundException e) { setLog(e.getMessage()); Main.isStart = false; Main.btnStart.setText(""); return; } catch (UnsupportedEncodingException e) { setLog(e.getMessage()); Main.isStart = false; Main.btnStart.setText(""); return; } } if (format == 1) { outstream.println( ",?,?id,??,?,id,,,??,?"); } else if (format == 2) { outstream.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); outstream.println("<statuses>"); } HttpURLConnection connection; int page = 1; while (true) { try { setLog("5s," + String.valueOf(num + 1) + "??"); Thread.sleep(5000); //?5s } catch (InterruptedException e) { setLog("?\r\n" + String.valueOf(num) + "??"); exitTread(); return; } if (content == 1) //?? { connection = timeline(page); } else if (content == 2) //?? { connection = mention(page); } else if (content == 3) //? { connection = timeline(page); } else if (content == 4) //??? { connection = timeline(page, userID); } else //? { connection = favorites(page); } if (errtime >= 5) { setLog("\r\n" + String.valueOf(num) + "??"); exitTread(); return; } String line; try { if (connection.getResponseCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); line = reader.readLine(); } else if (connection.getResponseCode() == 403) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String log = ""; line = reader.readLine(); while (line != null) { log = log + "\r\n" + line; line = reader.readLine(); } setLog(log); setLog("??TA?"); exitTread(); return; } else if (connection.getResponseCode() == 404) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String log = ""; line = reader.readLine(); while (line != null) { log = log + "\r\n" + line; line = reader.readLine(); } setLog(log); setLog(""); exitTread(); return; } else { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String log = ""; line = reader.readLine(); while (line != null) { log = log + "\r\n" + line; line = reader.readLine(); } errtime++; setLog(":\r\n" + log + "\r\n" + errtime + "?"); continue; } } catch (SocketTimeoutException e) { errtime++; setLog(":\r\n" + e.getMessage() + "\r\n" + errtime + "?"); continue; } catch (IOException e) { errtime++; setLog(":\r\n" + e.getMessage() + "\r\n" + errtime + "?"); continue; } writeFile(line, format, page); page++; } //while(true) }
From source file:org.exist.storage.index.BFile.java
protected void redoStoreOverflow(OverflowStoreLoggable loggable) { try {//from w w w. ja va2 s . c o m SinglePage page = getSinglePageForRedo(loggable, loggable.pageNum); if (page != null && requiresRedo(loggable, page)) { final BFilePageHeader ph = page.getPageHeader(); try { System.arraycopy(loggable.data, 0, page.getData(), 0, loggable.size); } catch (final ArrayIndexOutOfBoundsException e) { LOG.warn(loggable.data.length + "; " + page.getData().length + "; " + ph.getDataLength() + "; " + loggable.size); throw e; } ph.setDataLength(loggable.size); ph.setNextInChain(0); ph.setLsn(loggable.getLsn()); page.setDirty(true); dataCache.add(page); if (loggable.prevPage != Page.NO_PAGE) { page = getSinglePage(loggable.prevPage); SanityCheck.ASSERT(page != null, "Previous page is null"); page.getPageHeader().setNextInChain(loggable.pageNum); page.setDirty(true); dataCache.add(page); } } } catch (final IOException e) { LOG.warn("An IOException occurred during redo: " + e.getMessage(), e); } }
From source file:org.exist.storage.dom.DOMFile.java
/** * Split a data page at the position indicated by the rec parameter. * //from www . ja v a 2 s.c o m * The portion of the page starting at rec.offset is moved into a new page. * Every moved record is marked as relocated and a link is stored into the * original page to point to the new record position. * * @param doc * @param rec */ private RecordPos splitDataPage(Txn transaction, DocumentImpl doc, final RecordPos rec) { if (currentDocument != null) { currentDocument.getMetadata().incSplitCount(); } //Check if a split is really required. A split is not required if //all records following the split point are already links to other pages. //In this case, the new record is just appended to a new page linked to the old one. boolean requireSplit = false; for (int pos = rec.offset; pos < rec.getPage().len;) { final short tupleID = ByteConversion.byteToShort(rec.getPage().data, pos); pos += LENGTH_TID; if (!ItemId.isLink(tupleID)) { requireSplit = true; break; } pos += LENGTH_FORWARD_LOCATION; } if (!requireSplit) { LOG.debug("page: " + rec.getPage().getPageNum() + ": no split required." + " Next page:" + rec.getPage().getPageHeader().getNextDataPage() + " Previous page:" + rec.getPage().getPageHeader().getPreviousDataPage()); rec.offset = rec.getPage().len; return rec; } final DOMFilePageHeader pageHeader = rec.getPage().getPageHeader(); //Copy the old data up to the split point into a new array final int oldDataLen = pageHeader.getDataLength(); final byte[] oldData = rec.getPage().data; if (isTransactional && transaction != null) { final Loggable loggable = new SplitPageLoggable(transaction, rec.getPage().getPageNum(), rec.offset, oldData, oldDataLen); writeToLog(loggable, rec.getPage().page); } rec.getPage().data = new byte[fileHeader.getWorkSize()]; System.arraycopy(oldData, 0, rec.getPage().data, 0, rec.offset); //The old rec.page now contains a copy of the data up to the split point rec.getPage().len = rec.offset; pageHeader.setDataLength(rec.getPage().len); rec.getPage().setDirty(true); //Create a first split page DOMPage firstSplitPage = new DOMPage(); if (isTransactional && transaction != null) { final Loggable loggable = new CreatePageLoggable(transaction, rec.getPage().getPageNum(), firstSplitPage.getPageNum(), Page.NO_PAGE, pageHeader.getCurrentTupleID()); writeToLog(loggable, firstSplitPage.page); } DOMPage nextSplitPage = firstSplitPage; nextSplitPage.getPageHeader().setNextTupleID(pageHeader.getCurrentTupleID()); long backLink; short splitRecordCount = 0; LOG.debug("Splitting " + rec.getPage().getPageNum() + " at " + rec.offset + ": New page: " + nextSplitPage.getPageNum() + "; Next page: " + pageHeader.getNextDataPage()); //Start copying records from rec.offset to the new split pages for (int pos = rec.offset; pos < oldDataLen; splitRecordCount++) { //Read the current id final short tupleID = ByteConversion.byteToShort(oldData, pos); pos += LENGTH_TID; //This is already a link, so we just copy it if (ItemId.isLink(tupleID)) { /* No room in the old page, append a new one */ if (rec.getPage().len + LENGTH_TID + LENGTH_FORWARD_LOCATION > fileHeader.getWorkSize()) { final DOMPage newPage = new DOMPage(); final DOMFilePageHeader newPageHeader = newPage.getPageHeader(); if (isTransactional && transaction != null) { Loggable loggable = new CreatePageLoggable(transaction, rec.getPage().getPageNum(), newPage.getPageNum(), pageHeader.getNextDataPage(), pageHeader.getCurrentTupleID()); writeToLog(loggable, firstSplitPage.page); loggable = new UpdateHeaderLoggable(transaction, pageHeader.getPreviousDataPage(), rec.getPage().getPageNum(), newPage.getPageNum(), pageHeader.getPreviousDataPage(), pageHeader.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } newPageHeader.setNextTupleID(pageHeader.getCurrentTupleID()); newPageHeader.setPrevDataPage(rec.getPage().getPageNum()); newPageHeader.setNextDataPage(pageHeader.getNextDataPage()); LOG.debug("Appending page after split: " + newPage.getPageNum()); pageHeader.setNextDataPage(newPage.getPageNum()); pageHeader.setDataLength(rec.getPage().len); pageHeader.setRecordCount(countRecordsInPage(rec.getPage())); rec.getPage().cleanUp(); rec.getPage().setDirty(true); dataCache.add(rec.getPage()); //Switch record to new page... rec.setPage(newPage); rec.getPage().len = 0; dataCache.add(newPage); } if (isTransactional && transaction != null) { final long oldLink = ByteConversion.byteToLong(oldData, pos); final Loggable loggable = new AddLinkLoggable(transaction, rec.getPage().getPageNum(), ItemId.getId(tupleID), oldLink); writeToLog(loggable, rec.getPage().page); } ByteConversion.shortToByte(tupleID, rec.getPage().data, rec.getPage().len); rec.getPage().len += LENGTH_TID; System.arraycopy(oldData, pos, rec.getPage().data, rec.getPage().len, LENGTH_FORWARD_LOCATION); rec.getPage().len += LENGTH_FORWARD_LOCATION; pos += LENGTH_FORWARD_LOCATION; continue; } //Read data length final short vlen = ByteConversion.byteToShort(oldData, pos); pos += LENGTH_DATA_LENGTH; //If this is an overflow page, the real data length is always //LENGTH_LINK byte for the page number of the overflow page final short realLen = (vlen == OVERFLOW ? LENGTH_OVERFLOW_LOCATION : vlen); //Check if we have room in the current split page if (nextSplitPage.len + LENGTH_TID + LENGTH_DATA_LENGTH + LENGTH_ORIGINAL_LOCATION + realLen > fileHeader.getWorkSize()) { //Not enough room in the split page: append a new page final DOMPage newPage = new DOMPage(); final DOMFilePageHeader newPageHeader = newPage.getPageHeader(); if (isTransactional && transaction != null) { Loggable loggable = new CreatePageLoggable(transaction, nextSplitPage.getPageNum(), newPage.getPageNum(), Page.NO_PAGE, pageHeader.getCurrentTupleID()); writeToLog(loggable, firstSplitPage.page); loggable = new UpdateHeaderLoggable(transaction, nextSplitPage.getPageHeader().getPreviousDataPage(), nextSplitPage.getPageNum(), newPage.getPageNum(), nextSplitPage.getPageHeader().getPreviousDataPage(), nextSplitPage.getPageHeader().getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } newPageHeader.setNextTupleID(pageHeader.getCurrentTupleID()); newPageHeader.setPrevDataPage(nextSplitPage.getPageNum()); //No next page ? Well... we might want to enforce the value -pb LOG.debug("Creating new split page: " + newPage.getPageNum()); nextSplitPage.getPageHeader().setNextDataPage(newPage.getPageNum()); nextSplitPage.getPageHeader().setDataLength(nextSplitPage.len); nextSplitPage.getPageHeader().setRecordCount(splitRecordCount); nextSplitPage.cleanUp(); nextSplitPage.setDirty(true); dataCache.add(nextSplitPage); dataCache.add(newPage); nextSplitPage = newPage; splitRecordCount = 0; } /* * If the record has already been relocated, * read the original storage address and update the link there. */ if (ItemId.isRelocated(tupleID)) { backLink = ByteConversion.byteToLong(oldData, pos); pos += LENGTH_ORIGINAL_LOCATION; final RecordPos originalRecordPos = findRecord(backLink, false); final long oldLink = ByteConversion.byteToLong(originalRecordPos.getPage().data, originalRecordPos.offset); final long forwardLink = StorageAddress.createPointer((int) nextSplitPage.getPageNum(), ItemId.getId(tupleID)); if (isTransactional && transaction != null) { final Loggable loggable = new UpdateLinkLoggable(transaction, originalRecordPos.getPage().getPageNum(), originalRecordPos.offset, forwardLink, oldLink); writeToLog(loggable, originalRecordPos.getPage().page); } ByteConversion.longToByte(forwardLink, originalRecordPos.getPage().data, originalRecordPos.offset); originalRecordPos.getPage().setDirty(true); dataCache.add(originalRecordPos.getPage()); } else { backLink = StorageAddress.createPointer((int) rec.getPage().getPageNum(), ItemId.getId(tupleID)); } /* * Save the record to the split page: */ if (isTransactional && transaction != null) { //What does this "log" mean really ? Original ? -pb final byte[] logData = new byte[realLen]; System.arraycopy(oldData, pos, logData, 0, realLen); final Loggable loggable = new AddMovedValueLoggable(transaction, nextSplitPage.getPageNum(), tupleID, logData, backLink); writeToLog(loggable, nextSplitPage.page); } //Set the relocated flag and save the item id ByteConversion.shortToByte(ItemId.setIsRelocated(tupleID), nextSplitPage.data, nextSplitPage.len); nextSplitPage.len += LENGTH_TID; //Save length field ByteConversion.shortToByte(vlen, nextSplitPage.data, nextSplitPage.len); nextSplitPage.len += LENGTH_DATA_LENGTH; //Save link to the original page ByteConversion.longToByte(backLink, nextSplitPage.data, nextSplitPage.len); nextSplitPage.len += LENGTH_ORIGINAL_LOCATION; //Now save the data try { System.arraycopy(oldData, pos, nextSplitPage.data, nextSplitPage.len, realLen); } catch (final ArrayIndexOutOfBoundsException e) { SanityCheck.TRACE("pos = " + pos + "; len = " + nextSplitPage.len + "; currentLen = " + realLen + "; tupleID = " + tupleID + "; page = " + rec.getPage().getPageNum()); throw e; } nextSplitPage.len += realLen; pos += realLen; // save a link pointer in the original page if the record has not // been relocated before. if (!ItemId.isRelocated(tupleID)) { // the link doesn't fit into the old page. Append a new page if (rec.getPage().len + LENGTH_TID + LENGTH_FORWARD_LOCATION > fileHeader.getWorkSize()) { final DOMPage newPage = new DOMPage(); final DOMFilePageHeader newPageHeader = newPage.getPageHeader(); if (isTransactional && transaction != null) { Loggable loggable = new CreatePageLoggable(transaction, rec.getPage().getPageNum(), newPage.getPageNum(), pageHeader.getNextDataPage(), pageHeader.getCurrentTupleID()); writeToLog(loggable, firstSplitPage.page); loggable = new UpdateHeaderLoggable(transaction, pageHeader.getPreviousDataPage(), rec.getPage().getPageNum(), newPage.getPageNum(), pageHeader.getPreviousDataPage(), pageHeader.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } newPageHeader.setNextTupleID(pageHeader.getCurrentTupleID()); newPageHeader.setPrevDataPage(rec.getPage().getPageNum()); newPageHeader.setNextDataPage(pageHeader.getNextDataPage()); LOG.debug("Creating new page after split: " + newPage.getPageNum()); pageHeader.setNextDataPage(newPage.getPageNum()); pageHeader.setDataLength(rec.getPage().len); pageHeader.setRecordCount(countRecordsInPage(rec.getPage())); rec.getPage().cleanUp(); rec.getPage().setDirty(true); dataCache.add(rec.getPage()); //switch record to new page... rec.setPage(newPage); rec.getPage().len = 0; dataCache.add(newPage); } final long forwardLink = StorageAddress.createPointer((int) nextSplitPage.getPageNum(), ItemId.getId(tupleID)); if (isTransactional && transaction != null) { final Loggable loggable = new AddLinkLoggable(transaction, rec.getPage().getPageNum(), tupleID, forwardLink); writeToLog(loggable, rec.getPage().page); } ByteConversion.shortToByte(ItemId.setIsLink(tupleID), rec.getPage().data, rec.getPage().len); rec.getPage().len += LENGTH_TID; ByteConversion.longToByte(forwardLink, rec.getPage().data, rec.getPage().len); rec.getPage().len += LENGTH_FORWARD_LOCATION; } } //End of for loop: finished copying data //Link the split pages to the original page if (nextSplitPage.len == 0) { LOG.warn("Page " + nextSplitPage.getPageNum() + " is empty. Remove it"); //If nothing has been copied to the last split page, remove it if (nextSplitPage == firstSplitPage) { firstSplitPage = null; } try { unlinkPages(nextSplitPage.page); } catch (final IOException e) { LOG.warn("Failed to remove empty split page: " + e.getMessage(), e); } nextSplitPage.setDirty(true); dataCache.remove(nextSplitPage); nextSplitPage = null; } else { if (isTransactional && transaction != null) { final Loggable loggable = new UpdateHeaderLoggable(transaction, nextSplitPage.getPageHeader().getPreviousDataPage(), nextSplitPage.getPageNum(), pageHeader.getNextDataPage(), nextSplitPage.getPageHeader().getPreviousDataPage(), nextSplitPage.getPageHeader().getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } nextSplitPage.getPageHeader().setDataLength(nextSplitPage.len); nextSplitPage.getPageHeader().setNextDataPage(pageHeader.getNextDataPage()); nextSplitPage.getPageHeader().setRecordCount(splitRecordCount); nextSplitPage.cleanUp(); nextSplitPage.setDirty(true); dataCache.add(nextSplitPage); if (isTransactional && transaction != null) { final DOMFilePageHeader fisrtPageHeader = firstSplitPage.getPageHeader(); final Loggable loggable = new UpdateHeaderLoggable(transaction, rec.getPage().getPageNum(), firstSplitPage.getPageNum(), fisrtPageHeader.getNextDataPage(), fisrtPageHeader.getPreviousDataPage(), fisrtPageHeader.getNextDataPage()); writeToLog(loggable, nextSplitPage.page); } firstSplitPage.getPageHeader().setPrevDataPage(rec.getPage().getPageNum()); if (nextSplitPage != firstSplitPage) { firstSplitPage.setDirty(true); dataCache.add(firstSplitPage); } } final long nextPageNum = pageHeader.getNextDataPage(); if (Page.NO_PAGE != nextPageNum) { final DOMPage nextPage = getDOMPage(nextPageNum); if (isTransactional && transaction != null) { final Loggable loggable = new UpdateHeaderLoggable(transaction, nextSplitPage.getPageNum(), nextPage.getPageNum(), Page.NO_PAGE, nextPage.getPageHeader().getPreviousDataPage(), nextPage.getPageHeader().getNextDataPage()); writeToLog(loggable, nextPage.page); } nextPage.getPageHeader().setPrevDataPage(nextSplitPage.getPageNum()); nextPage.setDirty(true); dataCache.add(nextPage); } rec.setPage(getDOMPage(rec.getPage().getPageNum())); if (firstSplitPage != null) { if (isTransactional && transaction != null) { final Loggable loggable = new UpdateHeaderLoggable(transaction, pageHeader.getPreviousDataPage(), rec.getPage().getPageNum(), firstSplitPage.getPageNum(), pageHeader.getPreviousDataPage(), pageHeader.getNextDataPage()); writeToLog(loggable, rec.getPage().page); } pageHeader.setNextDataPage(firstSplitPage.getPageNum()); } pageHeader.setDataLength(rec.getPage().len); pageHeader.setRecordCount(countRecordsInPage(rec.getPage())); rec.getPage().cleanUp(); rec.offset = rec.getPage().len; return rec; }