Example usage for java.lang Long parseUnsignedLong

List of usage examples for java.lang Long parseUnsignedLong

Introduction

In this page you can find the example usage for java.lang Long parseUnsignedLong.

Prototype

public static long parseUnsignedLong(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as an unsigned decimal long .

Usage

From source file:sx.blah.discord.api.internal.DiscordVoiceWS.java

DiscordVoiceWS(IShard shard, VoiceUpdateResponse event) {
    this.shard = (ShardImpl) shard;
    this.endpoint = event.endpoint.replace(":80", "");
    this.token = event.token;
    this.guild = shard.getGuildByID(Long.parseUnsignedLong(event.guild_id));
}

From source file:epgtools.dumpepgfromts.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("tsfile").desc("ts")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit").desc(
            "??(???????100000000)")
            .hasArg().type(Long.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);//ww  w  . j  a  va 2s. c o m
    //        opts.addOption(PhysicalChannelNumberOption);
    opts.addOption(limitOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = 10000000L;
        } finally {
            limit = xl;
        }

        LOG.info("Starting application...");
        LOG.info("filename   : " + fileName);
        LOG.info("limit : " + limit);

        FileLoader fl = new FileLoader(new File(fileName), limit);
        fl.load();

        //???
        Set<Channel> ch = fl.getChannels();
        LOG.info("?? = " + ch.size());
        for (Channel c : ch) {
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
            LOG.info(c.getString());
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
        }

        //            ?
        Set<Programme> p = fl.getProgrammes();
        LOG.info(" = " + p.size());
        for (Programme pg : p) {
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
            LOG.info(pg.getString());
            LOG.info(
                    "***********************************************************************************************************************************************************************************************************");
        }

        System.gc();

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("?????", ex);
    }
}

From source file:dumpsection.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    Options opts = new Options();
    opts.addOption(fileNameOption);// w  ww .j a v  a 2 s  . c  om
    opts.addOption(limitOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        // handle interface option.
        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        final PROGRAM_ID pids = PROGRAM_ID.SDT_OR_BAT;

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids.getPids());
        } else {
            reader = new TsReader(new File(fileName), pids.getPids(), limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();

        for (Integer pid : ret.keySet()) {
            try (FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + "_SDT.txt")) {
                SectionReconstructor sr = new SectionReconstructor(ret.get(pid), pid);
                for (Section s : sr.getSections()) {
                    String text = Hex.encodeHexString(s.getData());
                    writer.write(text + "\n");
                }
                writer.flush();
            } catch (IOException ex) {
                LOG.fatal("", ex);
            }
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("?????", ex);
    }
}

From source file:dumptspacket.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;
    final Set<Integer> pids;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    final Option pidsOption = Option.builder("p").required().longOpt("pids")
            .desc("pid(?16?)").type(String.class).hasArgs().build();

    Options opts = new Options();
    opts.addOption(fileNameOption);/*from ww w.j a v a2 s  .c  o  m*/
    opts.addOption(limitOption);
    opts.addOption(pidsOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        // handle interface option.
        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        Set<Integer> x = new HashSet<>();
        List<String> ls = new ArrayList<>();
        ls.addAll(Arrays.asList(cl.getOptionValues(pidsOption.getOpt())));
        for (String s : ls) {
            try {
                x.add(Integer.parseUnsignedInt(s, 16));
            } catch (NumberFormatException e) {
                throw new ParseException(e.getMessage());
            }
        }
        pids = Collections.unmodifiableSet(x);

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);
        System.out.println("pids : " + dumpSet(pids));

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids);
        } else {
            reader = new TsReader(new File(fileName), pids, limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();
        try {
            for (Integer pid : ret.keySet()) {

                FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + ".txt");

                for (TsPacketParcel par : ret.get(pid)) {
                    String text = Hex.encodeHexString(par.getPacket().getData());
                    writer.write(text + "\n");

                }
                writer.flush();
                writer.close();
            }
        } catch (IOException ex) {
            LOG.fatal("", ex);
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("", ex);
    }
}

From source file:epgtools.dumpchannellistfromts.Main.java

public void start(String[] args) throws ParseException {
    final String fileName;
    final Long limit;

    final Option directoryNameOption = Option.builder("d").required().longOpt("directoryname")
            .desc("??").hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    final Option destFileNameOption = Option.builder("f").required().longOpt("destname")
            .desc("???").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(directoryNameOption);
    opts.addOption(limitOption);/*from w  w w . j  a v  a2s . c o m*/
    opts.addOption(destFileNameOption);
    CommandLineParser parser = new DefaultParser();

    HelpFormatter help = new HelpFormatter();
    CommandLine cl;
    try {
        cl = parser.parse(opts, args);
    } catch (ParseException ex) {
        LOG.fatal("??????", ex);
        help.printHelp("My Java Application", opts);
        throw ex;
    }

    final File dirName = new File(cl.getOptionValue(directoryNameOption.getOpt()));
    if (!dirName.isDirectory()) {
        throw new IllegalArgumentException(
                "??????????? = "
                        + dirName.getAbsolutePath());
    }
    LOG.info("?? = " + dirName.getAbsolutePath());

    Long xl = null;
    try {
        if (cl.hasOption(limitOption.getOpt())) {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        }
    } catch (NumberFormatException e) {
        LOG.error(e);
        throw new IllegalArgumentException("????????");
    } finally {
        limit = xl;
        LOG.info("?? = " + limit);
    }

    final File destFile = new File(cl.getOptionValue(destFileNameOption.getOpt()));
    LOG.info("??? = " + destFile.getAbsolutePath());

    List<File> files = new TsFileSeeker(dirName).seek();

    LOG.info("?? = " + files.size());

    final PhysicalChannelNumberRecordBuilder bu = new PhysicalChannelNumberRecordBuilder();
    final Set<PhysicalChannelNumberRecord> records = Collections.synchronizedSet(new TreeSet<>());
    //NIT?
    for (File f : files) {
        SectionLoader loader = new SectionLoader(f, limit, RESERVED_PROGRAM_ID.NIT.getPids());
        try {
            Map<Integer, List<Section>> pids_sections = loader.load();
            for (Integer k : pids_sections.keySet()) {
                for (Section s : pids_sections.get(k)) {
                    if (s.checkCRC() != Section.CRC_STATUS.NO_CRC_ERROR) {
                        throw new IllegalArgumentException(
                                "CRC?? = " + Hex.encodeHexString(s.getData()));
                    } else if (s.getTable_id_const() != TABLE_ID.NIT_THIS_NETWORK) {
                        throw new IllegalArgumentException(
                                "?NIT????? = "
                                        + Hex.encodeHexString(s.getData()));
                    } else {
                        NetworkInformationTableBody nitbody = (NetworkInformationTableBody) s.getSectionBody();
                        bu.setNetworkId(nitbody.getNetwork_id());
                        for (Descriptor d1 : nitbody.getDescriptors_loop().getDescriptors_loopList()) {
                            if (d1.getDescriptor_tag_const() == DESCRIPTOR_TAG.NETWORK_NAME_DESCRIPTOR) {
                                final NetworkNameDescriptor nnd = (NetworkNameDescriptor) d1;
                                bu.setNetworkName(nnd.getChar_String());
                            }
                        }
                        for (TransportStreamLoop tsLoop : nitbody.getTransport_streams_loop()) {
                            bu.setTransportStreamId(tsLoop.getTransport_stream_id());
                            bu.setOriginalNetworkId(tsLoop.getOriginal_network_id());
                            for (Descriptor desc : tsLoop.getDescriptors_loop().getDescriptors_loopList()) {
                                if (desc.getDescriptor_tag_const() == DESCRIPTOR_TAG.SERVICE_LIST_DESCRIPTOR) {
                                    ServiceListDescriptor sd = (ServiceListDescriptor) desc;
                                    List<Service> svList = sd.getServiceList();
                                    for (Service service : svList) {
                                        if (service.getService_type_Enum() == SERVICE_TYPE.DIGITAL_TV_SERVICE) {
                                            bu.setServiceId(service.getService_id());

                                            if (bu.getOriginalNetworkId() < 0x10) {
                                                //BS
                                                bu.setPhysicalChannelNumber(bu.getServiceId());
                                            } else {
                                                //          
                                                bu.setPhysicalChannelNumber(
                                                        Integer.valueOf(this.getNameWithoutExtension(f)));
                                            }

                                            records.add(bu.build());
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            LOG.info("????? = " + f.getAbsolutePath(), ex);
        }
    }

    //        for (PhysicalChannelNumberRecord rec : records) {
    //            LOG.info(rec);
    //        }
    //        
    //???????
    List<PhysicalChannelNumberRecord> nl = new ArrayList<>();
    nl.addAll(records);
    CsvManager csvManager = CsvManagerFactory.newCsvManager();
    LOG.info(destFile.getAbsolutePath());
    try {
        csvManager.save(nl, PhysicalChannelNumberRecord.class).to(destFile, "UTF-8");
    } catch (IOException ex) {
        LOG.fatal("???????? = " + destFile.getAbsolutePath(), ex);
    }

}

From source file:sx.blah.discord.api.internal.DiscordVoiceWS.java

@Override
public void onWebSocketText(String message) {
    try {//w w  w.  jav a2s  .c o m
        JsonNode json = DiscordUtils.MAPPER.readTree(message);
        VoiceOps op = VoiceOps.get(json.get("op").asInt());
        JsonNode d = json.has("d") && !json.get("d").isNull() ? json.get("d") : null;

        switch (op) {
        case READY:
            try {
                VoiceReadyResponse ready = DiscordUtils.MAPPER.treeToValue(d, VoiceReadyResponse.class);
                voiceSocket.setup(endpoint, ready.port, ready.ssrc);
                beginHeartbeat(ready.heartbeat_interval);
            } catch (IOException e) {
                Discord4J.LOGGER.error(LogMarkers.VOICE_WEBSOCKET,
                        "Encountered error handling voice ready payload: ", e);
            }
            break;
        case SESSION_DESCRIPTION:
            VoiceDescriptionResponse description = DiscordUtils.MAPPER.treeToValue(d,
                    VoiceDescriptionResponse.class);
            voiceSocket.setSecret(description.secret_key);
            voiceSocket.begin();
            break;
        case SPEAKING:
            VoiceSpeakingResponse response = DiscordUtils.MAPPER.treeToValue(d, VoiceSpeakingResponse.class);
            IUser user = getGuild().getUserByID(Long.parseUnsignedLong(response.user_id));
            users.put(response.ssrc, user);
            guild.getClient().getDispatcher().dispatch(new UserSpeakingEvent(
                    user.getVoiceStateForGuild(guild).getChannel(), user, response.ssrc, response.speaking));
            break;
        case UNKNOWN:
            Discord4J.LOGGER.debug(LogMarkers.VOICE_WEBSOCKET, "Received unknown voice opcode, {}", message);
            break;
        }
    } catch (IOException e) {
        Discord4J.LOGGER.error(LogMarkers.WEBSOCKET, "JSON Parsing exception!", e);
    }
}

From source file:com.joyent.manta.http.ApacheHttpHeaderUtils.java

/**
 * In order to be sure we're continuing to download the same object we need to extract the {@code ETag} and {@code
 * Content-Range} headers from the response. Either header missing is an error. Additionally, when the {@code
 * Content-Range} header is present the specified range should be equal to the response's {@code Content-Length}.
 * If the {@code Content-Range} header is missing and {@code allowContentRangeInference} is true, we may infer the
 * response code was 200 and construct a representative {@code Content-Range} from byte offset 0 to
 * {@code Content-Length - 1}.// ww w . ja  v a 2  s  .  c o  m
 *
 * @param response the response to check for headers
 * @param allowContentRangeInference whether or not we can derive a {@link HttpRange.Response} from the
 * {@code Content-Length} header instead of only using it for verification.
 * @return the request headers we're concerned with validating
 * @throws ProtocolException when the headers are malformed, unparseable, or the {@code
 * Content-Range} and {@code Content-Length} are mismatched
 */
static Pair<String, HttpRange.Response> extractDownloadResponseFingerprint(final HttpResponse response,
        final boolean allowContentRangeInference) throws ProtocolException {

    final String etag = extractSingleHeaderValue(response, ETAG, true);

    final long contentLength;
    try {
        final String rawContentLength = extractSingleHeaderValue(response, CONTENT_LENGTH, true);
        // since we're passing required=true an ProtocolException would be thrown and
        // @SuppressWarnings("ConstantConditions") is too blunt a hammer and would apply to the whole method, so...
        // noinspection ConstantConditions
        contentLength = Long.parseUnsignedLong(rawContentLength);
    } catch (final NumberFormatException e) {
        throw new ProtocolException(
                String.format("Failed to parse Content-Length response, matching headers: %s",
                        Arrays.deepToString(response.getHeaders(CONTENT_LENGTH))));
    }

    final String rawContentRange = extractSingleHeaderValue(response, CONTENT_RANGE, false);

    if (StringUtils.isBlank(rawContentRange)) {
        if (!allowContentRangeInference) {
            throw new ProtocolException("Content-Range header required but missing.");
        }

        // the entire object is being requested
        return new ImmutablePair<>(etag, new HttpRange.Response(0, contentLength - 1, contentLength));
    }

    final HttpRange.Response contentRange = parseContentRange(rawContentRange);

    // Manta follows the spec and sends the Content-Length of the range, which we should ensure matches
    if (contentRange.contentLength() != contentLength) {
        throw new ProtocolException(String.format(
                "Content-Range start-to-end size and Content-Length mismatch: expected [%d], got [%d]",
                contentRange.contentLength(), contentLength));
    }

    return new ImmutablePair<>(etag, contentRange);
}

From source file:com.joyent.manta.http.HttpRange.java

/**
 * Deserialize a request range.//from w  ww.j  a  v a 2  s  .  co m
 *
 * @param requestRange the string representation of the range
 * @return a {@link BoundedRequest} range
 * @throws ProtocolException if the range could not be parsed
 */
static Request parseRequestRange(final String requestRange) throws ProtocolException {
    notNull(requestRange, "Request Range must not be null");

    final boolean boundedMatch = requestRange.matches(REGEX_BOUNDED_REQUEST_RANGE);
    final boolean unboundedMatch = requestRange.matches(REGEX_UNBOUNDED_REQUEST_RANGE);
    if (!boundedMatch && !unboundedMatch) {
        throw new ProtocolException(String.format(FMT_ERROR_MATCHING_REQUEST_RANGE, requestRange));
    }

    final String[] bounds = StringUtils.split(StringUtils.removeStart(requestRange, "bytes="), "-");
    if (boundedMatch) {
        if (bounds.length != PART_COUNT_BOUNDED_RANGE) {
            throw new ProtocolException(String.format(FMT_ERROR_MATCHING_REQUEST_RANGE, requestRange));
        }

        return new BoundedRequest(Long.parseUnsignedLong(bounds[0]), Long.parseUnsignedLong(bounds[1]));
    }

    if (unboundedMatch && bounds.length != PART_COUNT_UNBOUNDED_RANGE) {
        throw new ProtocolException(String.format(FMT_ERROR_MATCHING_REQUEST_RANGE, requestRange));
    }

    return new UnboundedRequest(Long.parseUnsignedLong(bounds[0]));
}