Example usage for com.google.common.net InetAddresses forString

List of usage examples for com.google.common.net InetAddresses forString

Introduction

In this page you can find the example usage for com.google.common.net InetAddresses forString.

Prototype

public static InetAddress forString(String ipString) 

Source Link

Document

Returns the InetAddress having the given string representation.

Usage

From source file:google.registry.flows.TlsCredentials.java

static InetAddress parseInetAddress(String asciiAddr) {
    try {/*ww  w  . j  a va2s.c  o  m*/
        return InetAddresses.forString(HostAndPort.fromString(asciiAddr).getHostText());
    } catch (IllegalArgumentException e) {
        return null;
    }
}

From source file:pro.foundev.ingest.Loader.java

public void create(long recordsToCreate) {

    Faker faker = new Faker();
    Cluster cluster = Cluster.builder().addContactPoint(contactHost).build();
    Session session = cluster.newSession();
    new SchemaCreation(session).createSchema();
    PreparedStatement st = session.prepare("INSERT INTO " + getKeyspace() + "." + getTable()
            + " (id, origin_state, " + "ip_address, urls) values ( ?, ?, ?, ?)");
    long tickInterval = recordsToCreate / 100;
    int ticksCompleted = 0;
    for (long i = 0; i < recordsToCreate; i++) {
        List<ResultSetFuture> futures = new ArrayList<>();
        InetAddress fakeIp = InetAddresses.forString(createIpAddress());
        String fakeState = faker.address().stateAbbr();
        List<String> urls = new ArrayList<>();
        int seed = random.nextInt(10000);
        for (int j = 0; j < seed; j++) {
            urls.add(faker.internet().url());
        }/*  www .j  a  v a 2s  .co  m*/
        BoundStatement bs = st.bind(i, fakeState, fakeIp, urls);
        //      setLong(0, i).
        //        setString(1, fakeState).
        //        setInet(2, fakeIp ).
        //        setList(3, urls);
        //
        futures.add(session.executeAsync(bs));
        if (i % 100 == 0) {
            for (ResultSetFuture future : futures) {
                try {
                    future.getUninterruptibly(2, TimeUnit.SECONDS);
                } catch (TimeoutException e) {
                    logger.warning(e.getMessage());
                    logger.warning("retrying");
                }
            }
        }
        if (i != 0 && i % tickInterval == 0) {
            ticksCompleted++;
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < ticksCompleted; j++) {
                builder.append("=");
            }
            long ticksLeft = 100 - ticksCompleted;
            if (ticksLeft < 0) {
                throw new RuntimeException("ticks left is " + ticksLeft + " and I is " + i);
            }
            for (int j = 0; j < ticksLeft; j++) {
                builder.append(" ");
            }

            System.out.println("[" + builder.toString() + "]\r");
        }
    }
}

From source file:at.alladin.rmbt.controlServer.LogResource.java

@Post("json")
public String request(final String entity) {
    addAllowOrigin();/*from w ww.  j a  v a2 s .  co  m*/
    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    final InetAddress clientAddress = InetAddresses.forString(clientIpRaw);

    System.out.println(MessageFormat.format(labels.getString("NEW_LOG_REQ"), clientIpRaw));

    if (entity != null && !entity.isEmpty()) {
        try {
            request = new JSONObject(entity);

            UUID uuid = null;

            final String uuidString = request.optString("uuid", "");

            if (uuidString.length() != 0) {
                uuid = UUID.fromString(uuidString);
            }

            final Platform platform = Platform.valueOf(request.getString("plattform").toUpperCase(Locale.US));
            final String logFileName = request.getString("logfile");

            final File logPath = new File(LOG_PATH, platform.name().toLowerCase(Locale.US));
            final File logFile = new File(logPath, logFileName);

            final boolean appendClientInfo = !logFile.exists();

            try (PrintWriter out = new PrintWriter(
                    new BufferedWriter(new FileWriter(logFile, logFile.exists())))) {
                final String content = request.getString("content");
                request.remove("content");

                if (appendClientInfo) {
                    out.println("client IP: " + clientAddress.toString());
                    out.println("\n#############################################\n");
                    out.println(request.toString(3));
                    out.println("\n#############################################\n");
                }
                out.println(content);
            }

            final JSONObject fileTimes = request.optJSONObject("file_times");
            if (fileTimes != null) {
                try {
                    final Long created = fileTimes.getLong("created");
                    final Long lastAccess = fileTimes.getLong("last_access");
                    final Long lastModified = fileTimes.getLong("last_modified");
                    BasicFileAttributeView attributes = Files.getFileAttributeView(
                            Paths.get(logFile.getAbsolutePath()), BasicFileAttributeView.class);
                    FileTime lastModifiedTime = FileTime
                            .fromMillis(TimeUnit.MILLISECONDS.convert(lastModified, TimeUnit.SECONDS));
                    FileTime lastAccessTime = FileTime
                            .fromMillis(TimeUnit.MILLISECONDS.convert(lastAccess, TimeUnit.SECONDS));
                    FileTime createdTime = FileTime
                            .fromMillis(TimeUnit.MILLISECONDS.convert(created, TimeUnit.SECONDS));
                    attributes.setTimes(lastModifiedTime, lastAccessTime, createdTime);
                } catch (Exception e) {

                }

                //                   final Long lastModified = fileTimes.getLong("last_modified");
                //                   logFile.setLastModified(TimeUnit.MILLISECONDS.convert(lastModified, TimeUnit.SECONDS));
            }

            answer.put("status", "OK");
        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSON Data " + e.toString());
        } catch (final Exception e) {
            errorList.addError("ERROR_LOG_WRITE");
            System.out.println("Error writing Log " + e.toString());
        }
    } else {
        errorList.addErrorString("Expected request is missing.");
    }

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();

    return answerString;
}

From source file:org.squiddev.cctweaks.lua.lib.socket.AddressMatcher.java

public AddressMatcher(String[] matches) {
    boolean active = false;
    for (String host : matches) {
        try {//from   ww w  .j a va2s. c o m
            Matcher matcher = cidrPattern.matcher(host);
            if (matcher.matches()) {
                String address = matcher.group(1), prefix = matcher.group(2);

                int addr = InetAddresses.coerceToInteger(InetAddresses.forString(address));
                int mask = 0xFFFFFFFF << (32 - Integer.parseInt(prefix));
                int min = addr & mask;
                int max = addr | ~mask;

                active = true;
                ranges.add(new HostRange(min, max));
            } else {
                active = true;
                hosts.add(host);
                addresses.add(InetAddress.getByName(host));
            }
        } catch (Exception e) {
            Logger.error("Error adding " + host + " to blacklist/whitelist", e);
        }
    }

    this.active = active;
}

From source file:com.wealdtech.jersey.filters.RequestHintFilter.java

@Override
public ContainerRequest filter(final ContainerRequest request) {
    final RequestHint.Builder builder = RequestHint.builder();

    builder.userAgent(request.getHeaderValue("User-Agent"));

    final String geoPosition = request.getHeaderValue("Geo-Position");
    if (geoPosition != null) {
        // We only care about items prior to the space (if there is one)
        final Iterator<String> geoItems;
        if (geoPosition.indexOf(' ') != -1) {
            geoItems = Splitter.on(";").split(Splitter.on(" ").split(geoPosition).iterator().next()).iterator();
        } else {/*from  w  w  w. j  a v  a 2  s.c  o m*/
            geoItems = Splitter.on(";").split(geoPosition).iterator();
        }

        if (geoItems.hasNext()) {
            final String lat = geoItems.next();
            builder.latitude(Float.valueOf(lat));
        }
        if (geoItems.hasNext()) {
            final String lng = geoItems.next();
            builder.longitude(Float.valueOf(lng));
        }
        if (geoItems.hasNext()) {
            final String alt = geoItems.next();
            builder.altitude(Float.valueOf(alt));
        }
    }

    try {
        builder.address(InetAddresses.forString(req.getRemoteAddr()));
    } catch (final IllegalArgumentException ignored) {
        LOG.debug("Remote IP address {} could not be parsed", req.getRemoteAddr());
    }

    // Store our completed hint for access by resources
    this.req.setAttribute("com.wealdtech.requesthint", builder.build());

    return request;
}

From source file:pl.coffeepower.blog.messagebus.aeron.AeronSubscriber.java

@Inject
private AeronSubscriber(@NonNull Aeron aeron, @NonNull IdleStrategy idleStrategy,
        @NonNull Configuration configuration, @NonNull Disruptor<BytesEventFactory.BytesEvent> disruptor) {
    Preconditions.checkArgument(//  w w w .ja  va 2s.c  o m
            InetAddresses.forString(configuration.getMulticastAddress()).getAddress()[3] % 2 != 0,
            "Lowest byte in multicast address has to be odd");
    String channel = "aeron:udp?endpoint=" + configuration.getMulticastAddress() + ":"
            + configuration.getMulticastPort() + "|interface=" + configuration.getBindAddress();
    this.aeron = aeron;
    this.subscription = this.aeron.addSubscription(channel, configuration.getTopicId());
    this.idleStrategy = idleStrategy;
    this.disruptor = disruptor;
    this.disruptor.handleEventsWith((event, sequence, endOfBatch) -> {
        Preconditions.checkNotNull(handler);
        handler.received(event.getBuffer(), event.getCurrentLength());
    });
    this.ringBuffer = this.disruptor.start();
    this.opened.set(true);
    this.executor = Executors
            .newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("subscriber-thread").build());
    this.executor.execute(() -> {
        byte[] bytes = new byte[AeronConst.BUFFER_SIZE];
        while (opened.get()) {
            this.idleStrategy.idle(this.subscription.poll((buffer, offset, length, header) -> {
                Preconditions.checkState(opened.get(), "Already closed");
                buffer.getBytes(offset, bytes, 0, length);
                ringBuffer.publishEvent((event, sequence) -> event.copyToBuffer(bytes, length));
            }, 1));
        }
    });
    this.executor.shutdown();
    log.info("Created Subscriber: channel={}, streamId={}", channel, configuration.getTopicId());
}

From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.arp.ArpUtils.java

public static byte[] ipToBytes(Ipv4Address ip) {
    return InetAddresses.forString(ip.getValue()).getAddress();
}

From source file:org.apache.directory.server.dhcp.service.store.SimpleStoreLeaseManager.java

@SuppressWarnings("PMD.AvoidUsingHardCodedIP")
public SimpleStoreLeaseManager() {
    subnets.add(new DhcpConfigSubnet(NetworkAddress.forString("192.168.168.0/24"),
            InetAddresses.forString("192.168.168.159"), InetAddresses.forString("192.168.168.179")));
}

From source file:org.opendaylight.lispflowmapping.lisp.serializer.address.Ipv6Serializer.java

@Override
protected void serializeData(ByteBuffer buffer, LispAddress lispAddress) {
    Ipv6 address = (Ipv6) lispAddress.getAddress();
    buffer.put(InetAddresses.forString(address.getIpv6().getValue()).getAddress());
}

From source file:org.bitcoinj.core.MasternodeAddress.java

public static MasternodeAddress localhost(NetworkParameters params) {
    return new MasternodeAddress(InetAddresses.forString("127.0.0.1"), params.getPort());
}