List of usage examples for java.util Scanner next
public String next()
From source file:gtu._work.ui.JSFMakerUI.java
void resetPasteClipboardHtmlToJtable() { String content = ClipboardUtil.getInstance().getContents(); Pattern tdStartPattern = Pattern.compile("<[tT][dDhH][^>]*>"); Pattern tdEndPattern = Pattern.compile("</[tT][dDhH]>"); Pattern innerPattern_HasTag = Pattern.compile("<[\\w:]+\\s[^>]*value=\"([^\"]*)\"[^>]*>", Pattern.MULTILINE);// w ww . j a v a 2 s .com Matcher innerMatcher = null; Scanner scan = new Scanner(content); Scanner tdScan = null; String currentContent = null; String tdContent = null; StringBuilder sb = new StringBuilder(); scan.useDelimiter("<tr>"); for (; scan.hasNext();) { boolean anyMatcher = false; tdScan = new Scanner(scan.next()); tdScan.useDelimiter(tdStartPattern); while (tdScan.hasNext()) { tdScan.useDelimiter(tdEndPattern); if (tdScan.hasNext()) { tdContent = tdScan.next().replaceAll(tdStartPattern.pattern(), ""); { innerMatcher = innerPattern_HasTag.matcher(tdContent.toString()); if (innerMatcher.find()) { currentContent = StringUtils.defaultIfEmpty(innerMatcher.group(1), " "); // System.out.format("1[%s]\n", currentContent); sb.append(currentContent + "\t"); continue; } currentContent = tdContent.toString().replaceAll("<[\\w:=,.#;/'?\"\\s\\{\\}\\(\\)\\[\\]]+>", ""); currentContent = currentContent.replaceAll("[\\s\t\n]", ""); currentContent = StringUtils.defaultIfEmpty(currentContent, " "); // System.out.format("2[%s]\n", currentContent); sb.append(currentContent + "\t"); anyMatcher = true; } } tdScan.useDelimiter(tdStartPattern); } if (anyMatcher) { sb.append("\n"); } } scan.close(); ClipboardUtil.getInstance().setContents(sb); System.out.println("####################################"); System.out.println(sb); System.out.println("####################################"); }
From source file:org.kuali.kfs.sys.context.CheckModularization.java
protected boolean testOptionalModuleOjbConfiguration(ModuleGroup moduleGroup, StringBuffer errorMessage) throws FileNotFoundException { boolean testSucceeded = true; for (String referencedNamespaceCode : OPTIONAL_NAMESPACE_CODES_TO_SPRING_FILE_SUFFIX.keySet()) { if (!(moduleGroup.namespaceCode.equals(referencedNamespaceCode) || moduleGroup.optionalModuleDependencyNamespaceCodes.contains(referencedNamespaceCode))) { if (OJB_FILES_BY_MODULE.get(moduleGroup.namespaceCode).isEmpty()) continue; String firstDatabaseRepositoryFilePath = OJB_FILES_BY_MODULE.get(moduleGroup.namespaceCode) .iterator().next();/*from w w w . j ava 2 s . c o m*/ // the first database repository file path is typically the file that comes shipped with KFS. If institutions override it, this unit test will not test them Scanner scanner = new Scanner(new File("work/src/" + firstDatabaseRepositoryFilePath)); int count = 0; while (scanner.hasNext()) { String token = scanner.next(); String firstPackagePrefix = PACKAGE_PREFIXES_BY_MODULE.get(referencedNamespaceCode).iterator() .next(); // A module may be responsible for many packages, but the first one should be the KFS built-in package that is *not* the module's integration package if (token.contains(firstPackagePrefix)) { count++; } } if (count > 0) { if (testSucceeded) { testSucceeded = false; errorMessage.append("\n").append(moduleGroup.namespaceCode).append(": "); } else { errorMessage.append(", "); } errorMessage.append(count).append(" references to ").append(referencedNamespaceCode); } } } return testSucceeded; }
From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java
private HashMap<String, String> parseEpub(File file) throws IOException, TMFVisibleException { LOG.debug("[parseEpub] - BEGIN"); ZipFile fi = new ZipFile(file); for (Enumeration e = fi.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.getName().endsWith("ncx")) { InputStream tocMaybeDirty = fi.getInputStream(entry); Scanner scanner = new Scanner(tocMaybeDirty, "UTF-8").useDelimiter("\\A"); String theString = scanner.hasNext() ? scanner.next() : ""; tocMaybeDirty.close();//w ww . j ava 2s . co m scanner.close(); String res = theString.replaceAll(">[\\s]*?<", "><"); InputStream toc = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8)); try { DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = dBuilder.parse(toc); toc.close(); if (doc.hasChildNodes()) { findNavMap(doc.getChildNodes()); } } catch (Exception ex) { LOG.error("Unable to navigate the TOC"); } removeEmptyTOC(epub); //search anchors in links and split Set set = epub.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); if (me.getValue().toString().contains("#")) { String[] parts = me.getValue().toString().split("#"); String anchor = parts[1]; epub.put(me.getKey().toString(), anchor); } } } if (entry.getName().endsWith("opf")) { //manage files because order is important InputStream content = fi.getInputStream(entry); Scanner scanner = new Scanner(content, "UTF-8").useDelimiter("\\A"); String contentString = scanner.hasNext() ? scanner.next() : ""; content.close(); scanner.close(); String filenameRegex = "href=\"(.*.htm(|l))\".*media-type=\"application/xhtml"; Pattern pattern = Pattern.compile(filenameRegex); Matcher matcher = pattern.matcher(contentString); Integer count = 0; while (matcher.find()) { files.put(count, matcher.group(1)); count++; } } if (entry.getName().endsWith("html") || entry.getName().endsWith("htm") || entry.getName().endsWith("xhtml")) { InputStream htmlFile = fi.getInputStream(entry); Scanner scanner = new Scanner(htmlFile, "UTF-8").useDelimiter("\\A"); String htmlString = scanner.hasNext() ? scanner.next() : ""; String regex1 = htmlString.replaceAll("^[^_]*?<body>", ""); //remove head String regex2 = regex1.replaceAll("</body>.*$", ""); //remove tail String htmlCleaned = regex2.replaceAll("<a.*?/>", ""); //anchor with one tag String[] bits = entry.getName().split("/"); String fileName = bits[bits.length - 1]; htmls.put(fileName, htmlCleaned); } } fi.close(); Integer i; for (i = 0; i < files.size(); i++) { stringBuilder.append("<p id=\"" + files.get(i) + "\"></p>"); // "anchor" also the heads of each files stringBuilder.append(htmls.get(files.get(i))); } String htmlAll = stringBuilder.toString(); /* We have all needed files, start to split For each link -> made a chunk Start from the bottom */ Metadata metadata = new Metadata(); Parser parser = new HtmlParser(); ListIterator<Map.Entry<String, String>> iter = new ArrayList<>(epub.entrySet()).listIterator(epub.size()); while (iter.hasPrevious()) { Map.Entry<String, String> me = iter.previous(); try { ContentHandler contenthandler = new BodyContentHandler(10 * htmlAll.length()); Scanner sc = new Scanner(htmlAll); sc.useDelimiter("id=\"" + me.getValue().toString() + "\">"); htmlAll = sc.next(); InputStream stream = new ByteArrayInputStream(sc.next().getBytes(StandardCharsets.UTF_8)); parser.parse(stream, contenthandler, metadata, new ParseContext()); String chapterText = contenthandler.toString().toLowerCase().replaceAll("\\d+.*", ""); String chapterTextWithoutNo = chapterText.replaceAll("\\d+.*", ""); // Remove the Project Gutenberg meta information from the text String chapterTextCleaned = chapterTextWithoutNo.split("end of the project gutenberg ebook")[0]; epub.put(me.getKey().toString(), chapterTextCleaned); } catch (Exception ex) { LOG.error("Unable to parse content for index: " + me.getKey() + ", this chapter will be deleted"); removeChapter(epub, me.getKey().toString()); } } /* I remove the Project Gutenberg license chapter from the Map, because it is useless for the classification and it generates a Lucene Exception in case of the Italian language (the license text is always in English). You can use this method in order to remove each chapter that is useless for classifying your Epub document. */ removeChapter(epub, "A Word from Project Gutenberg"); removeEmptyItems(epub); //If the Epub file has a bad structure, I try to use the basic Epub extractor of Tika. if (epub.size() == 0) { LOG.info("The Epub file has a bad structure. Try to use the Tika extractor"); epub.put("All text", autoParseAll(file)); } removeEmptyItems(epub); if (epub.size() == 0) { LOG.error("Unable to extract text from this Epub"); throw new TMFVisibleException("Unable to extract any text from this Epub."); } removeDownloadedFile(TEMPORARY_PATH); LOG.debug("[parseEpub] - END"); return epub; }
From source file:org.mifos.sdk.client.internal.RestClientService.java
/** * Retrieves a client image.//from w w w . ja va 2 s. c om * @param clientId the client ID * @param maxWidth Optional: the maximum width of the image * @param maxHeight Optional: the maximum height of the image * @return a {@link ClientImage} with the image and the type if found, null otherwise * @throws MifosXConnectException * @throws MifosXResourceException */ public ClientImage findImage(Long clientId, Long maxWidth, Long maxHeight) throws MifosXConnectException, MifosXResourceException { Preconditions.checkNotNull(clientId); final RestAdapter adapter = new RestAdapter.Builder().setClient(new OkClient(new OkHttpClient())) .setEndpoint(this.connectionProperties.getUrl()).setConverter(new Converter() { @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { try { Scanner s = new Scanner(body.in()).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } catch (IOException e) { } return null; } @Override public TypedOutput toBody(Object object) { return null; } }).build(); final RetrofitClientService clientService = adapter.create(RetrofitClientService.class); ClientImage clientImage = null; try { final String responseString = clientService.findImage(this.authenticationKey, this.connectionProperties.getTenant(), clientId, maxWidth, maxHeight); final byte[] responseBinaryData = Base64.decodeBase64(responseString.split(",")[1]); try { final ByteArrayInputStream inputStream = new ByteArrayInputStream(responseBinaryData); final BufferedImage image = ImageIO.read(inputStream); ClientImage.Type type = null; if (responseString.startsWith("data:image/png")) { type = ClientImage.Type.PNG; } else if (responseString.startsWith("data:image/jpeg")) { type = ClientImage.Type.JPEG; } else if (responseString.startsWith("data:image/gif")) { type = ClientImage.Type.GIF; } clientImage = ClientImage.image(image).type(type).build(); } catch (IOException e) { throw new IllegalStateException(e); } } catch (RetrofitError error) { if (error.getKind() == RetrofitError.Kind.NETWORK) { throw new MifosXConnectException(ErrorCode.NOT_CONNECTED); } else if (error.getKind() == RetrofitError.Kind.CONVERSION || error.getResponse().getStatus() == 401) { throw new MifosXConnectException(ErrorCode.INVALID_AUTHENTICATION_TOKEN); } else if (error.getResponse().getStatus() == 404) { throw new MifosXResourceException(ErrorCode.CLIENT_IMAGE_NOT_FOUND); } else if (error.getResponse().getStatus() == 403) { final String message = ServerResponseUtil.parseResponse(error.getResponse()); throw new MifosXResourceException(message); } else { throw new MifosXConnectException(ErrorCode.UNKNOWN); } } return clientImage; }
From source file:io.stallion.users.UserAdder.java
public void execute(CommandOptionsBase options, String action) throws Exception { Log.info("Settings: siteName {0} email password {1}", Settings.instance().getSiteName(), Settings.instance().getEmail().getPassword()); Scanner scanner = new Scanner(System.in); Console console = System.console(); if (empty(action)) { //System.out.print("Create new user or edit existing? (new/edit): "); //String newEdit = scanner.next(); System.out.print("Create new user or edit existing? (new/edit): "); //String newEdit = console.readLine("Create new user or edit existing? (new/edit): "); action = scanner.nextLine();/* ww w .j a v a2 s . c o m*/ } User user = null; if ("new".equals(action)) { user = new User(); user.setPredefined(true); } else if ("edit".equals(action)) { System.out.print("Enter the email, username, or ID of the user you wish to edit:"); String idMaybe = scanner.next(); if (StringUtils.isNumeric(idMaybe)) { user = (User) UserController.instance().forId(Long.parseLong(idMaybe)); } if (user == null) { user = (User) UserController.instance().forUniqueKey("email", idMaybe); } if (user == null) { user = (User) UserController.instance().forUniqueKey("username", idMaybe); } if (user == null) { System.out.print("Could not find user for key: " + idMaybe); System.exit(1); } } else { System.out.print("Invalid choice. Choose either 'new' or 'edit'"); System.exit(1); } System.out.print("User's given name: "); String givenName = scanner.nextLine(); if (!empty(givenName)) { user.setGivenName(givenName); } System.out.print("User's family name: "); String familyName = scanner.nextLine(); if (!empty(familyName)) { user.setFamilyName(familyName); user.setDisplayName(user.getGivenName() + " " + user.getFamilyName()); } System.out.print("User's email: "); String email = scanner.nextLine(); if (!empty(email)) { user.setEmail(email); user.setUsername(user.getEmail()); } System.out.print("Enter password: "); String password = ""; if (console != null) { password = new String(console.readPassword()); } else { password = new String(scanner.nextLine()); } //System.out.printf("password: \"%s\"\n", password); if (empty(password) && empty(user.getBcryptedPassword())) { throw new UsageException("You must set a password!"); } else if (!empty(password)) { String hashed = BCrypt.hashpw(password, BCrypt.gensalt()); user.setBcryptedPassword(hashed); } if (empty(user.getSecret())) { user.setSecret(RandomStringUtils.randomAlphanumeric(18)); } if (empty(user.getEncryptionSecret())) { user.setEncryptionSecret(RandomStringUtils.randomAlphanumeric(36)); } user.setPredefined(true); user.setRole(Role.ADMIN); user.setId(Context.dal().getTickets().nextId()); user.setFilePath(GeneralUtils.slugify(user.getEmail() + "---" + user.getId().toString()) + ".json"); UserController.instance().save(user); System.out.print("User saved with email " + user.getEmail() + " and id " + user.getId()); }
From source file:org.springfield.lou.servlet.LouServlet.java
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.addHeader("Access-Control-Allow-Origin", alloworigin); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "Content-Type,Range,If-None-Match,Accept-Ranges"); response.addHeader("Access-Control-Expose-Headers", "Content-Range"); //read the data from the put request //System.out.println("PUT REQ="+request.getRequestURI()); String mt = request.getContentType(); if (mt.equals("application/data")) { handleFileUpload(request);//from ww w . j a va2s. co m return; } InputStream inst = request.getInputStream(); String data; // reads the data from inputstring to a normal string. java.util.Scanner s = new java.util.Scanner(inst).useDelimiter("\\A"); data = (s.hasNext()) ? s.next() : null; if (data == null) { return; } //System.out.println("DATA="+data); Map<String, String[]> params = request.getParameterMap(); // lets find the correct nlication Html5ApplicationInterface app = null; String url = request.getRequestURI(); int pos = url.indexOf("/domain/"); if (pos != -1) { String tappname = url.substring(pos); app = ApplicationManager.instance().getApplication(tappname); } if (data.indexOf("put(") == 0) { // System.out.println("DO PUT WAS CALLED"); app.putData(data); return; } if (data.indexOf("stop(") == 0) { //System.out.println("RECIEVED STOP FROP CLIENT"); String screenid = data.substring(5, data.length() - 1); app.removeScreen(screenid, null); return; } //build an org.w3c.dom.Document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(data)); Document doc = builder.parse(is); //get the the user information from the xml Element root = (Element) doc.getElementsByTagName("fsxml").item(0); Element screenxml = (Element) root.getElementsByTagName("screen").item(0); String screenId = screenxml.getElementsByTagName("screenId").item(0).getTextContent(); // does this screen already have a id ? //System.out.println("SCREENID="+screenId); if (!screenId.equals("-1") && app.getScreen(screenId) != null) { // ok so we should find it and its attached app Screen screen = app.getScreen(screenId); screen.setSeen(); screen.setParameters(params); //System.out.println("OLD SCREEN = "+screen.getId()); response.setContentType("text/xml; charset=UTF-8"); OutputStream out = response.getOutputStream(); //PrintWriter out = response.getWriter(); String msg = screen.getMsg(); if (msg == null) { // bad bad bad try { synchronized (screen) { //screen.wait(); screen.wait(2 * 1000); // turned into 'highspeed' for testing so 2 seconds instead of 60, also means eddie.js change } } catch (InterruptedException e) { // System.out.println("got interrupt.. getting data"); } msg = screen.getMsg(); //System.out.println("MSG="+msg); if (msg == null) { // simulated a drop connection //System.out.println("SIM DROP"); msg = "set(synctime)=" + new Date().toString(); out.write(msg.getBytes()); out.flush(); out.close(); return; } } long starttime = new Date().getTime(); //System.out.println("data2="+msg); out.write(msg.getBytes()); out.flush(); out.close(); long endtime = new Date().getTime(); PerformanceManager.addNetworkCallTime(endtime - starttime); } else { //System.out.println("lost flow why ? screenId="+screenId+" "+app.getScreen(screenId)); if (!screenId.equals("-1")) { System.out.println("Sending stop"); response.setContentType("text/xml; charset=UTF-8"); OutputStream out = response.getOutputStream(); //PrintWriter out = response.getWriter(); out.write(XMLHelper.createScreenIdFSXML("-1", false).getBytes()); out.flush(); out.close(); } else { //System.out.println("PARAMS="+params); Capabilities caps = getCapabilities(root); // extend this with Location info caps.addCapability("ipnumber", request.getRemoteAddr()); caps.addCapability("servername", request.getServerName()); String ref = request.getHeader("Referer"); //System.out.println("REF="+ref); if (ref != null) { caps.addCapability("referer", ref); } else { caps.addCapability("referer", ""); } Screen screen = app.getNewScreen(caps, params); //System.out.println("PARAMSET="+params); screen.setParameters(params); // see if we need to override the location //String ploc = screen.getParameter("location"); //if (ploc!=null) screen.getLocation().setId(ploc); response.setContentType("text/xml; charset=UTF-8"); OutputStream out = response.getOutputStream(); out.write(XMLHelper.createScreenIdFSXML(screen.getId(), true).getBytes()); out.flush(); out.close(); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return; }
From source file:org.fao.geonet.kernel.csw.services.GetRecords.java
/** * Retrieves the values of attribute typeNames. If typeNames contains csw:BriefRecord or csw:SummaryRecord, an * exception is thrown.//from ww w. j ava2s . co m * * @param query the query * @return list of typenames, or null if not found * @throws InvalidParameterValueEx if a typename is illegal */ private Set<String> getTypeNames(Element query) throws InvalidParameterValueEx { Set<String> typeNames = null; String typeNames$ = query.getAttributeValue("typeNames"); if (typeNames$ != null) { Scanner commaSeparatedScanner = new Scanner(typeNames$).useDelimiter(","); while (commaSeparatedScanner.hasNext()) { String typeName = commaSeparatedScanner.next().trim(); // These two are explicitly not allowed as search targets in CSW 2.0.2, so we throw an exception if the // client asks for them if (typeName.equals("csw:BriefRecord") || typeName.equals("csw:SummaryRecord")) { throw new InvalidParameterValueEx("typeName", typeName); } if (typeNames == null) { typeNames = new HashSet<String>(); } typeNames.add(typeName); } } // TODO in if(isDebugEnabled) condition. Jeeves LOG doesn't provide that useful function though. if (typeNames != null) { for (String typeName : typeNames) { if (Log.isDebugEnabled(Geonet.CSW)) Log.debug(Geonet.CSW, "TypeName: " + typeName); } } else { if (Log.isDebugEnabled(Geonet.CSW)) Log.debug(Geonet.CSW, "No TypeNames found in request"); } // TODO end if(isDebugEnabled) return typeNames; }
From source file:com.zilotti.hostsjuggler.view.ActiveHostsFileWindow.java
private void highlightActiveHostsFile(File hostsFile) throws IOException, ParseException { BufferedReader br = null;/* w w w.j av a2 s.c o m*/ try { /* Converts the file to text */ // StringReader fileReader = new StringReader(getLinuxHostsFile()); // For testing br = new BufferedReader(new FileReader(hostsFile)); /* Character counter */ int charCounter = 0; /* Line counter */ int lineCounter = 1; /* Line */ String line = null; while ((line = br.readLine()) != null) { line += "\n"; activeHostsFileStyledText.append(line); /* * Remark line */ if (line.startsWith(REM_LINE_CHAR)) { int prevCharCounter = charCounter; charCounter += line.length(); formatRemark(prevCharCounter, charCounter); if (log.isTraceEnabled()) { log.trace("line ='" + line + "'"); //log.trace("remark='"+ getWindowsHostsFile().substring(prevCharCounter, charCounter) +"' ("+ prevCharCounter +","+ charCounter +")"); } } else if (StringUtils.isBlank(line)) // Empty line { charCounter += line.length(); } else // Expects a host line { int localCharCounter = charCounter; charCounter += line.length(); Scanner scanner = new Scanner(line); scanner.useDelimiter(Pattern.compile("(\\s)")); /* Output of the parsing code */ String ipAddress = null; /* Verifies the number of tokens. At least two must exist (IP address and one name) */ if (scanner.hasNext()) { /* The first token must be an IP address */ { ipAddress = scanner.next(); if (!NetworkUtils.isIpAddress(ipAddress)) throw new ParseException("IP address expected. Token found: " + ipAddress, lineCounter); int prevCharCounter = localCharCounter; localCharCounter += ipAddress.length() + 1; // Sums 1 because of the lost space formatIpAddress(prevCharCounter, localCharCounter); } /* The remaining tokens are the host names associated to the IP address */ { while (scanner.hasNext()) { String hostName = scanner.next(); if (StringUtils.isWhitespace(hostName) || StringUtils.isBlank(hostName)) { localCharCounter++; } else if (NetworkUtils.isHostName(hostName)) { int prevCharCounter = localCharCounter; localCharCounter += hostName.length() + 1; // 1 to compensate the space lost // if(log.isTraceEnabled()) // log.trace("hostName='"+ getWindowsHostsFile().substring(prevCharCounter, localCharCounter) +"' ("+ prevCharCounter +","+ localCharCounter +")"); formatHostName(prevCharCounter, localCharCounter); } else throw new ParseException("Host name expected at token " + localCharCounter + ". Found: " + hostName, lineCounter); } } } else throw new ParseException("At least 2 tokens are expected from a host line.", lineCounter); } lineCounter++; } } finally { if (br != null) br.close(); } }
From source file:com.tesora.dve.tools.CLIBuilder.java
protected String scan(Scanner scanner, String exists) throws PEException { if (hasRequiredArg(scanner, exists)) { return scanner.next(); }/* ww w.j a va 2 s .co m*/ return null; }
From source file:org.orekit.files.sp3.SP3Parser.java
/** Parses a header line from the SP3 file (line number 1 - 22). * @param lineNumber the current line number * @param line the line as read from the SP3 file * @param pi the current {@link ParseInfo} object * @throws OrekitException if a non-supported construct is found *//*ww w . j a v a2s .c om*/ private void parseHeaderLine(final int lineNumber, final String line, final ParseInfo pi) throws OrekitException { final SP3File file = pi.file; Scanner scanner = null; try { scanner = new Scanner(line).useDelimiter("\\s+").useLocale(Locale.US); // CHECKSTYLE: stop FallThrough check switch (lineNumber) { // version, epoch, data used and agency information case 1: { scanner.skip("#"); final String v = scanner.next(); final char version = v.substring(0, 1).toLowerCase().charAt(0); if (version != 'a' && version != 'b' && version != 'c') { throw new OrekitException(OrekitMessages.SP3_UNSUPPORTED_VERSION, version); } pi.hasVelocityEntries = "V".equals(v.substring(1, 2)); final int year = Integer.parseInt(v.substring(2)); final int month = scanner.nextInt(); final int day = scanner.nextInt(); final int hour = scanner.nextInt(); final int minute = scanner.nextInt(); final double second = scanner.nextDouble(); final AbsoluteDate epoch = new AbsoluteDate(year, month, day, hour, minute, second, TimeScalesFactory.getGPS()); file.setEpoch(epoch); final int numEpochs = scanner.nextInt(); file.setNumberOfEpochs(numEpochs); // data used indicator file.setDataUsed(scanner.next()); file.setCoordinateSystem(scanner.next()); file.setOrbitType(SP3OrbitType.valueOf(scanner.next())); file.setAgency(scanner.next()); break; } // additional date/time references in gps/julian day notation case 2: { scanner.skip("##"); // gps week file.setGpsWeek(scanner.nextInt()); // seconds of week file.setSecondsOfWeek(scanner.nextDouble()); // epoch interval file.setEpochInterval(scanner.nextDouble()); // julian day file.setJulianDay(scanner.nextInt()); // day fraction file.setDayFraction(scanner.nextDouble()); break; } // line 3 contains the number of satellites case 3: pi.maxSatellites = Integer.parseInt(line.substring(4, 6).trim()); // fall-through intended - the line contains already the first entries // the following 4 lines contain additional satellite ids case 4: case 5: case 6: case 7: { final int lineLength = line.length(); int count = file.getSatelliteCount(); int startIdx = 9; while (count++ < pi.maxSatellites && (startIdx + 3) <= lineLength) { final String satId = line.substring(startIdx, startIdx + 3).trim(); file.addSatellite(satId); startIdx += 3; } break; } // the following 5 lines contain general accuracy information for each satellite case 8: case 9: case 10: case 11: case 12: { final int lineLength = line.length(); int satIdx = (lineNumber - 8) * 17; int startIdx = 9; while (satIdx < pi.maxSatellites && (startIdx + 3) <= lineLength) { final SatelliteInformation satInfo = file.getSatellite(satIdx++); final int exponent = Integer.parseInt(line.substring(startIdx, startIdx + 3).trim()); // the accuracy is calculated as 2**exp (in m) -> can be safely // converted to an integer as there will be no fraction satInfo.setAccuracy((int) Math.pow(2d, exponent)); startIdx += 3; } break; } case 13: { file.setType(getFileType(line.substring(3, 5).trim())); // now identify the time system in use final String tsStr = line.substring(9, 12).trim(); final TimeSystem ts = TimeSystem.GPS; if (!tsStr.equalsIgnoreCase("ccc")) { TimeSystem.valueOf(tsStr); } file.setTimeSystem(ts); switch (ts) { case GPS: pi.timeScale = TimeScalesFactory.getGPS(); break; case GAL: pi.timeScale = TimeScalesFactory.getGST(); break; case GLO: case QZS: throw new OrekitException(OrekitMessages.SP3_UNSUPPORTED_TIMESYSTEM, ts.name()); case TAI: pi.timeScale = TimeScalesFactory.getTAI(); break; case UTC: pi.timeScale = TimeScalesFactory.getUTC(); break; default: pi.timeScale = TimeScalesFactory.getGPS(); break; } break; } case 14: // ignore additional custom fields break; // load base numbers for the standard deviations of // position/velocity/clock components case 15: { // String base = line.substring(3, 13).trim(); // if (!base.equals("0.0000000")) { // // (mm or 10**-4 mm/sec) // pi.posVelBase = Double.valueOf(base); // } // base = line.substring(14, 26).trim(); // if (!base.equals("0.000000000")) { // // (psec or 10**-4 psec/sec) // pi.clockBase = Double.valueOf(base); // } break; } case 16: case 17: case 18: // ignore additional custom parameters break; case 19: case 20: case 21: case 22: // ignore comment lines break; default: // ignore -> method should only be called up to line 22 break; } // CHECKSTYLE: resume FallThrough check } finally { if (scanner != null) { scanner.close(); } } }