code
stringlengths
73
34.1k
label
stringclasses
1 value
public static ByteBuffer newDirectByteBuffer(long addr, int size, Object att) { dbbCC.setAccessible(true); Object b = null; try { b = dbbCC.newInstance(new Long(addr), new Integer(size), att); return ByteBuffer.class.cast(b); } catch(Exception e) { ...
java
public void releaseAll() { synchronized(this) { Object[] refSet = allocatedMemoryReferences.values().toArray(); if(refSet.length != 0) { logger.finer("Releasing allocated memory regions"); } for(Object ref : refSet) { release((Memor...
java
public static String md5sum(InputStream input) throws IOException { InputStream in = new BufferedInputStream(input); try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); DigestInputStream digestInputStream = new DigestInputStream(in, digest); ...
java
public void fill(long offset, long length, byte value) { unsafe.setMemory(address() + offset, length, value); }
java
public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) { int cursor = destOffset; for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) { int bbSize = bb.remaining(); if ((cursor + bbSize) > destArray.length) throw new ArrayIndexOutOfBo...
java
public void copyTo(long srcOffset, LBufferAPI dest, long destOffset, long size) { unsafe.copyMemory(address() + srcOffset, dest.address() + destOffset, size); }
java
public LBuffer slice(long from, long to) { if(from > to) throw new IllegalArgumentException(String.format("invalid range %,d to %,d", from, to)); long size = to - from; LBuffer b = new LBuffer(size); copyTo(from, b, 0, size); return b; }
java
public byte[] toArray() { if (size() > Integer.MAX_VALUE) throw new IllegalStateException("Cannot create byte array of more than 2GB"); int len = (int) size(); ByteBuffer bb = toDirectByteBuffer(0L, len); byte[] b = new byte[len]; // Copy data to the array bb...
java
public void writeTo(WritableByteChannel channel) throws IOException { for (ByteBuffer buffer : toDirectByteBuffers()) { channel.write(buffer); } }
java
public void writeTo(File file) throws IOException { FileChannel channel = new FileOutputStream(file).getChannel(); try { writeTo(channel); } finally { channel.close(); } }
java
public int readFrom(byte[] src, int srcOffset, long destOffset, int length) { int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length)); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src, srcOffset, readLen); return...
java
public int readFrom(ByteBuffer src, long destOffset) { if (src.remaining() + destOffset >= size()) throw new BufferOverflowException(); int readLen = src.remaining(); ByteBuffer b = toDirectByteBuffer(destOffset, readLen); b.position(0); b.put(src); return rea...
java
public static LBuffer loadFrom(File file) throws IOException { FileChannel fin = new FileInputStream(file).getChannel(); long fileSize = fin.size(); if (fileSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Cannot load from file more than 2GB: " + file); LBuffer b...
java
public ByteBuffer[] toDirectByteBuffers(long offset, long size) { long pos = offset; long blockSize = Integer.MAX_VALUE; long limit = offset + size; int numBuffers = (int) ((size + (blockSize - 1)) / blockSize); ByteBuffer[] result = new ByteBuffer[numBuffers]; int index ...
java
public String getWrappingHint(String fieldName) { if (isEmpty()) { return ""; } return String.format(" You can use this expression: %s(%s(%s))", formatMethod(wrappingMethodOwnerName, wrappingMethodName, ""), formatMethod(copyMethodOwnerName, copyMetho...
java
public static EffectiveAssignmentInsnFinder newInstance(final FieldNode targetVariable, final Collection<ControlFlowBlock> controlFlowBlocks) { return new EffectiveAssignmentInsnFinder(checkNotNull(targetVariable), checkNotNull(controlFlowBlocks)); }
java
public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() { final List<FieldNode> result = new ArrayList<FieldNode>(); for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) { final Initialisers setters = entry.getValue(); ...
java
protected final void verify() { collectInitialisers(); verifyCandidates(); verifyInitialisers(); collectPossibleInitialValues(); verifyPossibleInitialValues(); collectEffectiveAssignmentInstructions(); verifyEffectiveAssignmentInstructions(); collectAssign...
java
protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) { Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream() .collect(Collectors.toMap(r -> r.className, r -> r)); resultsMap.putAll(otherConfiguration.hardcodedResults()); hardcodedRes...
java
protected void mergeImmutableContainerTypesFrom(Configuration otherConfiguration) { Set<Dotted> union = Sets.union(hardcodedImmutableContainerClasses.build(), otherConfiguration.immutableContainerClasses()); hardcodedImmutableContainerClasses = ImmutableSet.<Dotted>builder().addAll(...
java
protected final void hardcodeValidCopyMethod(Class<?> fieldType, String fullyQualifiedMethodName, Class<?> argType) { if (argType==null || fieldType==null || fullyQualifiedMethodName==null) { throw new IllegalArgumentException("All parameters must be supplied - no nulls"); } Stri...
java
public static AliasFinder newInstance(final String variableName, final ControlFlowBlock controlFlowBlockToExamine) { checkArgument(!variableName.isEmpty()); return new AliasFinder(variableName, checkNotNull(controlFlowBlockToExamine)); }
java
private void generateCopyingPart(WrappingHint.Builder builder) { ImmutableCollection<CopyMethod> copyMethods = ImmutableMultimap.<String, CopyMethod>builder() .putAll(configuration.FIELD_TYPE_TO_COPY_METHODS) .putAll(userDefinedCopyMethods) .build() ...
java
private void generateWrappingPart(WrappingHint.Builder builder) { builder.setWrappingMethodOwnerName(configuration.UNMODIFIABLE_METHOD_OWNER) .setWrappingMethodName(configuration.FIELD_TYPE_TO_UNMODIFIABLE_METHOD.get(typeAssignedToField)); }
java
public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; if(paintBorder != null) paintBorder.setStrokeWidth(borderWidth); requestLayout(); invalidate(); }
java
public void setShadow(float radius, float dx, float dy, int color) { shadowRadius = radius; shadowDx = dx; shadowDy = dy; shadowColor = color; updateShadow(); }
java
public Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) // Don't do anything without a proper drawable return null; else if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable Log.i(TAG, "Bitmap drawable!"); return ((BitmapDrawable) drawable)....
java
public void updateBitmapShader() { if (image == null) return; shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); if(canvasSize != image.getWidth() || canvasSize != image.getHeight()) { Matrix matrix = new Matrix(); float scale = (float) canvasSize / (float) image.getWidth()...
java
public void refreshBitmapShader() { shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); }
java
private int calcItemWidth(RecyclerView rvCategories) { if (itemWidth == null || itemWidth == 0) { for (int i = 0; i < rvCategories.getChildCount(); i++) { itemWidth = rvCategories.getChildAt(i).getWidth(); if (itemWidth != 0) { break; ...
java
public final void setOrientation(int orientation) { mOrientation = orientation; mOrientationState = getOrientationStateFromParam(mOrientation); invalidate(); if (mOuterAdapter != null) { mOuterAdapter.setOrientation(mOrientation); } }
java
@SuppressWarnings("unused") public void selectItem(int position, boolean invokeListeners) { IOperationItem item = mOuterAdapter.getItem(position); IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition); int realPosition = mOuterAdapter.normalizePosition(position); /...
java
public IOrientationState getOrientationStateFromParam(int orientation) { switch (orientation) { case Orientation.ORIENTATION_HORIZONTAL_BOTTOM: return new OrientationStateHorizontalBottom(); case Orientation.ORIENTATION_HORIZONTAL_TOP: return new Orientati...
java
@Override public <T extends ViewGroup.MarginLayoutParams> T setSelectionMargin(int marginPx, T layoutParams) { return mSelectionGravityState.setSelectionMargin(marginPx, layoutParams); }
java
public int consume(Map<String, String> initialVars) { int result = 0; for (int i = 0; i < repeatNumber; i++) { result += super.consume(initialVars); } return result; }
java
public static void main(String[] args) { String modelFile = ""; String outputFile = ""; int numberOfRows = 0; try { modelFile = args[0]; outputFile = args[1]; numberOfRows = Integer.valueOf(args[2]); } catch (IndexOutOfBoundsException | NumberF...
java
public static Tuple2<Double, Double> getRandomGeographicalLocation() { return new Tuple2<>( (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100, (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100); }
java
public static Double getDistanceBetweenCoordinates(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { // sqrt( (x2-x1)^2 + (y2-y2)^2 ) Double xDiff = point1._1() - point2._1(); Double yDiff = point1._2() - point2._2(); return Math.sqrt(xDiff * xDiff + yDiff * yDiff); ...
java
public static Double getDistanceWithinThresholdOfCoordinates( Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { throw new NotImplementedError(); }
java
public static Boolean areCoordinatesWithinThreshold(Tuple2<Double, Double> point1, Tuple2<Double, Double> point2) { return getDistanceBetweenCoordinates(point1, point2) < COORDINATE_THRESHOLD; }
java
public static void main(String[] args) { //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal--> //MODEL USAGE EXAMPLE: <assign name="var_out_V1_2" expr="%ssn"/> <dg:transform name="EQ"/> Map<String, DataTransformer> transformers = new H...
java
public static UserStub getStubWithRandomParams(UserTypeVal userType) { // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles! // Oh the joys of type erasure. Tuple2<Double, Double> tuple = SocialNetworkUtilities.getRandomGeographicalLocation(); ...
java
public void writeOutput(DataPipe cr) { String[] nextLine = new String[cr.getDataMap().entrySet().size()]; int count = 0; for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { nextLine[count] = entry.getValue(); count++; } csvFile.writeNext...
java
public boolean isHoliday(String dateString) { boolean isHoliday = false; for (Holiday date : EquivalenceClassTransformer.HOLIDAYS) { if (convertToReadableDate(date.forYear(Integer.parseInt(dateString.substring(0, 4)))).equals(dateString)) { isHoliday = true; } ...
java
public String getNextDay(String dateString, boolean onlyBusinessDays) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(dateString).plusDays(1); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); if (onlyBusinessDays) { ...
java
public Date toDate(String dateString) { Date date = null; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { date = df.parse(dateString); } catch (ParseException ex) { System.out.println(ex.fillInStackTrace()); } return date; }
java
public String getRandomHoliday(String earliest, String latest) { String dateString = ""; DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime earlyDate = parser.parseDateTime(earliest); DateTime lateDate = parser.parseDateTime(latest); List<Holiday> holidays = new Linked...
java
public int numOccurrences(int year, int month, int day) { DateTimeFormatter parser = ISODateTimeFormat.date(); DateTime date = parser.parseDateTime(year + "-" + month + "-" + "01"); Calendar cal = Calendar.getInstance(); cal.setTime(date.toDate()); GregorianChronology calendar = ...
java
public String convertToReadableDate(Holiday holiday) { DateTimeFormatter parser = ISODateTimeFormat.date(); if (holiday.isInDateForm()) { String month = Integer.toString(holiday.getMonth()).length() < 2 ? "0" + holiday.getMonth() : Integer.toString(holiday.getMonth()); ...
java
public synchronized String requestBlock(String name) { if (blocks.isEmpty()) { return "exit"; } remainingBlocks.decrementAndGet(); return blocks.poll().createResponse(); }
java
public String makeReport(String name, String report) { long increment = Long.valueOf(report); long currentLineCount = globalLineCounter.addAndGet(increment); if (currentLineCount >= maxScenarios) { return "exit"; } else { return "ok"; } }
java
public void prepareStatus() { globalLineCounter = new AtomicLong(0); time = new AtomicLong(System.currentTimeMillis()); startTime = System.currentTimeMillis(); lastCount = 0; // Status thread regularly reports on what is happening Thread statusThread = new Thread() { ...
java
public void prepareServer() { try { server = new Server(0); jettyHandler = new AbstractHandler() { public void handle(String target, Request req, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletExcept...
java
public String getXmlFormatted(Map<String, String> dataMap) { StringBuilder sb = new StringBuilder(); for (String var : outTemplate) { sb.append(appendXmlStartTag(var)); sb.append(dataMap.get(var)); sb.append(appendXmlEndingTag(var)); } return sb...
java
private String appendXmlStartTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("<").append(value).append(">"); return sb.toString(); }
java
private String appendXmlEndingTag(String value) { StringBuilder sb = new StringBuilder(); sb.append("</").append(value).append(">"); return sb.toString(); }
java
private Map<String, String> fillInitialVariables() { Map<String, TransitionTarget> targets = model.getChildren(); Set<String> variables = new HashSet<>(); for (TransitionTarget target : targets.values()) { OnEntry entry = target.getOnEntry(); List<Action> actions = ...
java
public List<PossibleState> bfs(int min) throws ModelException { List<PossibleState> bootStrap = new LinkedList<>(); TransitionTarget initial = model.getInitialTarget(); PossibleState initialState = new PossibleState(initial, fillInitialVariables()); bootStrap.add(initialState); ...
java
public void process(SearchDistributor distributor) { List<PossibleState> bootStrap; try { bootStrap = bfs(bootStrapMin); } catch (ModelException e) { bootStrap = new LinkedList<>(); } List<Frontier> frontiers = new LinkedList<>(); for (Pos...
java
public void setModelByInputFileStream(InputStream inputFileStream) { try { this.model = SCXMLParser.parse(new InputSource(inputFileStream), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAXException | ModelException e) { ...
java
public void setModelByText(String model) { try { InputStream is = new ByteArrayInputStream(model.getBytes()); this.model = SCXMLParser.parse(new InputSource(is), null, customActionsFromTagExtensions()); this.setStateMachine(this.model); } catch (IOException | SAX...
java
public List<Set<String>> makeNWiseTuples(String[] variables, int nWise) { List<Set<String>> completeTuples = new ArrayList<>(); makeNWiseTuplesHelper(completeTuples, variables, 0, new HashSet<String>(), nWise); return completeTuples; }
java
public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) { List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise); List<Map<String, String>> testCases = new ArrayList<>(); for (Set<String> tuple : tuples) { tes...
java
public List<Map<String, String>> pipelinePossibleStates(NWiseAction action, List<Map<String, String>> possibleStateList) { String[] coVariables = action.getCoVariables().split(","); int n = Integer.valueOf(action.getN()); List<Map<String, String>> newPossibleStateList = new ArrayList<>(); ...
java
public void transform(DataPipe cr) { Map<String, String> map = cr.getDataMap(); for (String key : map.keySet()) { String value = map.get(key); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); ...
java
@Override public void processOutput(Map<String, String> resultsMap) { queue.add(resultsMap); if (queue.size() > 10000) { log.info("Queue size " + queue.size() + ", waiting"); try { Thread.sleep(500); } catch (InterruptedException ex) { ...
java
public void writeOutput(DataPipe cr) { try { context.write(NullWritable.get(), new Text(cr.getPipeDelimited(outTemplate))); } catch (Exception e) { throw new RuntimeException("Exception occurred while writing to Context", e); } }
java
public Map<String, String> decompose(Frontier frontier, String modelText) { if (!(frontier instanceof SCXMLFrontier)) { return null; } TransitionTarget target = ((SCXMLFrontier) frontier).getRoot().nextState; Map<String, String> variables = ((SCXMLFrontier) frontier).ge...
java
public static void printHelp(final Options options) { Collection<Option> c = options.getOptions(); System.out.println("Command line options are:"); int longestLongOption = 0; for (Option op : c) { if (op.getLongOpt().length() > longestLongOption) { longestLong...
java
public static void main(String[] args) { CmdLine cmd = new CmdLine(); Configuration conf = new Configuration(); int res = 0; try { res = ToolRunner.run(conf, cmd, args); } catch (Exception e) { System.err.println("Error while running MR job"); ...
java
public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) { return JavaConverters.asScalaIterableConverter(linkedList).asScala(); }
java
public static <T> T flattenOption(scala.Option<T> option) { if (option.isEmpty()) { return null; } else { return option.get(); } }
java
public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) { for (Map<String, String> possibleState : possibleStateList) { possibleState.put(action.getName(), action.getExpr()); } return possibleStateList; }
java
public JSONObject getJsonFormatted(Map<String, String> dataMap) { JSONObject oneRowJson = new JSONObject(); for (int i = 0; i < outTemplate.length; i++) { oneRowJson.put(outTemplate[i], dataMap.get(outTemplate[i])); } return oneRowJson; }
java
public Vector<Graph<UserStub>> generateAllNodeDataTypeGraphCombinationsOfMaxLength(int length) { Vector<Graph<UserStub>> graphs = super.generateAllNodeDataTypeGraphCombinationsOfMaxLength(length); if (WRITE_STRUCTURES_IN_PARALLEL) { // Left as an exercise to the student. thr...
java
public int consume(Map<String, String> initialVars) { this.dataPipe = new DataPipe(this); // Set initial variables for (Map.Entry<String, String> ent : initialVars.entrySet()) { dataPipe.getDataMap().put(ent.getKey(), ent.getValue()); } // Call transformers ...
java
public Future<String> sendRequest(final String path, final ReportingHandler reportingHandler) { return threadPool.submit(new Callable<String>() { @Override public String call() { String response = getResponse(path); if (reportingHandler != null) { ...
java
public void transform(DataPipe cr) { for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) { String value = entry.getValue(); if (value.equals("#{customplaceholder}")) { // Generate a random number int ran = rand.nextInt(); en...
java
public boolean isExit() { if (currentRow > finalRow) { //request new block of work String newBlock = this.sendRequestSync("this/request/block"); LineCountManager.LineCountBlock block = new LineCountManager.LineCountBlock(0, 0); if (newBlock.contains("exit")) { ...
java
@Override public View getDropDownView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.item_country, parent, false); viewHolder = new ViewHolder(); viewHolder...
java
@Override public View getView(int position, View convertView, ViewGroup parent) { Country country = getItem(position); if (convertView == null) { convertView = new ImageView(getContext()); } ((ImageView) convertView).setImageResource(getFlagResource(country)); ...
java
private int getFlagResource(Country country) { return getContext().getResources().getIdentifier("country_" + country.getIso().toLowerCase(), "drawable", getContext().getPackageName()); }
java
private static String getJsonFromRaw(Context context, int resource) { String json; try { InputStream inputStream = context.getResources().openRawResource(resource); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer...
java
public static CountryList getCountries(Context context) { if (mCountries != null) { return mCountries; } mCountries = new CountryList(); try { JSONArray countries = new JSONArray(getJsonFromRaw(context, R.raw.countries)); for (int i = 0; i < countries....
java
private void init(AttributeSet attrs) { inflate(getContext(), R.layout.intl_phone_input, this); /**+ * Country spinner */ mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country); mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext()); ...
java
public void hideKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0); }
java
public void setDefault() { try { TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); String phone = telephonyManager.getLine1Number(); if (phone != null && !phone.isEmpty()) { this.setNumber(phone); ...
java
public void setEmptyDefault(String iso) { if (iso == null || iso.isEmpty()) { iso = DEFAULT_COUNTRY; } int defaultIdx = mCountries.indexOfIso(iso); mSelectedCountry = mCountries.get(defaultIdx); mCountrySpinner.setSelection(defaultIdx); }
java
private void setHint() { if (mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry.getIso() != null) { Phonenumber.PhoneNumber phoneNumber = mPhoneUtil.getExampleNumberForType(mSelectedCountry.getIso(), PhoneNumberUtil.PhoneNumberType.MOBILE); if (phoneNumber != null) { ...
java
@SuppressWarnings("unused") public Phonenumber.PhoneNumber getPhoneNumber() { try { String iso = null; if (mSelectedCountry != null) { iso = mSelectedCountry.getIso(); } return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso); } c...
java
@SuppressWarnings("unused") public boolean isValid() { Phonenumber.PhoneNumber phoneNumber = getPhoneNumber(); return phoneNumber != null && mPhoneUtil.isValidNumber(phoneNumber); }
java
@SuppressWarnings("unused") public void setError(CharSequence error, Drawable icon) { mPhoneEdit.setError(error, icon); }
java
public void setOnKeyboardDone(final IntlPhoneInputListener listener) { mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DO...
java
private synchronized Client allocateClient(int targetPlayer, String description) throws IOException { Client result = openClients.get(targetPlayer); if (result == null) { // We need to open a new connection. final DeviceAnnouncement deviceAnnouncement = DeviceFinder.getInstance()...
java
private void closeClient(Client client) { logger.debug("Closing client {}", client); client.close(); openClients.remove(client.targetPlayer); useCounts.remove(client); timestamps.remove(client); }
java
private synchronized void freeClient(Client client) { int current = useCounts.get(client); if (current > 0) { timestamps.put(client, System.currentTimeMillis()); // Mark that it was used until now. useCounts.put(client, current - 1); if ((current == 1) && (idleLimit....
java
public <T> T invokeWithClientSession(int targetPlayer, ClientTask<T> task, String description) throws Exception { if (!isRunning()) { throw new IllegalStateException("ConnectionManager is not running, aborting " + description); } final Client client = allocateClient(targ...
java
@SuppressWarnings("WeakerAccess") public int getPlayerDBServerPort(int player) { ensureRunning(); Integer result = dbServerPorts.get(player); if (result == null) { return -1; } return result; }
java
private void requestPlayerDBServerPort(DeviceAnnouncement announcement) { Socket socket = null; try { InetSocketAddress address = new InetSocketAddress(announcement.getAddress(), DB_SERVER_QUERY_PORT); socket = new Socket(); socket.connect(address, socketTimeout.get()...
java
private byte[] receiveBytes(InputStream is) throws IOException { byte[] buffer = new byte[8192]; int len = (is.read(buffer)); if (len < 1) { throw new IOException("receiveBytes read " + len + " bytes."); } return Arrays.copyOf(buffer, len); }
java