file_id
int64 1
180k
| content
stringlengths 13
357k
| repo
stringlengths 6
109
| path
stringlengths 6
1.15k
|
---|---|---|---|
179,871 | package com.kodilla.patterns2.adapter.bookclasiffier;
import com.kodilla.patterns2.adapter.bookclasifier.MedianAdapter;
import com.kodilla.patterns2.adapter.bookclasifier.librarya.Book;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MedianAdapterTestSuite {
@Test
void publicationYearMedianAdapterTest(){
//Given
MedianAdapter medianAdapter = new MedianAdapter();
Set<Book> books = new HashSet<>();
books.add(new Book("Kugune Maruyama", "Overlord 1 The undead King", 2012, "Overlord1"));
books.add(new Book("Terry Pratchet", "Shepheard Crown", 2015, "Discworld42"));
books.add(new Book("J. K. Rowling", "Harry Potter and the philosopher Stone", 1997, "HarryPotter1"));
books.add(new Book("Aneta Jadowska", "Dynia i Jemioła. Nietypowe historie świąteczne", 2019, "JadOp3"));
//When
double median = medianAdapter.publicationYearMedian(books);
//Then
assertEquals(2015, median, 0);
}
}
| Bauaser-kun/kodilla-course | kodilla-patterns2/src/test/java/com/kodilla/patterns2/adapter/bookclasiffier/MedianAdapterTestSuite.java |
179,878 | public class Porucznik extends Stopnie
{
public int Stopien() {return 4;}
public Porucznik(String N) {this.Nazwa = N; }
}
| 0sk4r/Uwr | Programowanie_obiektowe/lista05/src/Porucznik.java |
179,879 | package com.company;
class Porucznik implements Stopien
{
private int val = 18;
public int get_stopien()
{
return this.val;
}
public int compareTo(Stopien Porownanie)
{
return Integer.compare(Porownanie.get_stopien(), this.get_stopien());
}
} | Ematerasu/Materialy_IIUWr | Programowanie obiektowe/Lista05/Zadanie1/Porucznik.java |
179,881 | public class Podporucznik extends Army {
public Float getRank(){
return new Float(3.0);
}
@Override
public String toString() {
return "Pulkownik";
}
} | DaDudek/Uwr | Programowanie Obiektowe/Lista5/Zadanie1/Podporucznik.java |
179,883 | import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args)
{
ArrayList<Stopnie> Wojsko = new ArrayList<Stopnie>();
Wojsko.add(new Szeregowy("Szeregowy 1"));
Wojsko.add(new Porucznik("Porucznik 2"));
Wojsko.add(new Kapral("Kapral 3"));
Wojsko.add(new Sierzant("Sierzant 4"));
Collections.sort(Wojsko);
for(Stopnie zolnierz : Wojsko) System.out.println(zolnierz);
}
}
| 0sk4r/Uwr | Programowanie_obiektowe/lista05/src/Main.java |
179,885 | package com.company;
//Szeregowy->kapral->sierzant->porucznik
//1->3->6->18 jezeli wszystkie stopnie po kolei numerowac
public class Main {
public static void main(String[] args)
{
StopnieWojskowe test = new StopnieWojskowe();
test.Dodaj(new Szeregowy());
test.Dodaj(new Sierzant());
test.Dodaj(new Porucznik());
test.Dodaj(new Kapral());
test.Wypisz();
test.Dodaj(new Sierzant());
System.out.println("\n");
System.out.println(test.Pobierz());
System.out.println("\n");
test.Dodaj(new Porucznik());
test.Wypisz();
System.out.println(test.zbior_rang.get(0).get_stopien());
}
}
| Ematerasu/Materialy_IIUWr | Programowanie obiektowe/Lista05/Zadanie1/Main.java |
179,891 | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.concurrency;
/*
* Written by Martin Buchholz with assistance from members of JCP
* JSR-166 Expert Group and released to the public domain, as
* explained at http://creativecommons.org/publicdomain/zero/1.0/
*/
/** Shared implementation code for java.util.concurrent. */
final class Helpers {
/** Optimized form of: key + "=" + val */
static String mapEntryToString(Object key, Object val) {
final String k, v;
final int klen, vlen;
final char[] chars =
new char[(klen = (k = objectToString(key)).length()) +
(vlen = (v = objectToString(val)).length()) + 1];
k.getChars(0, klen, chars, 0);
chars[klen] = '=';
v.getChars(0, vlen, chars, klen + 1);
return new String(chars);
}
private static String objectToString(Object x) {
// Extreme compatibility with StringBuilder.append(null)
String s;
return (x == null || (s = x.toString()) == null) ? "null" : s;
}
}
| JetBrains/intellij-community | platform/util/concurrency/src/com/intellij/concurrency/Helpers.java |
179,893 | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.util;
/**
* Helper for decoding HTML Strings by replacing character
* entity references with the referred character.
*
* @author Juergen Hoeller
* @author Martin Kersten
* @since 1.2.1
*/
class HtmlCharacterEntityDecoder {
private static final int MAX_REFERENCE_SIZE = 10;
private final HtmlCharacterEntityReferences characterEntityReferences;
private final String originalMessage;
private final StringBuilder decodedMessage;
private int currentPosition = 0;
private int nextPotentialReferencePosition = -1;
private int nextSemicolonPosition = -2;
public HtmlCharacterEntityDecoder(HtmlCharacterEntityReferences characterEntityReferences, String original) {
this.characterEntityReferences = characterEntityReferences;
this.originalMessage = original;
this.decodedMessage = new StringBuilder(original.length());
}
public String decode() {
while (this.currentPosition < this.originalMessage.length()) {
findNextPotentialReference(this.currentPosition);
copyCharactersTillPotentialReference();
processPossibleReference();
}
return this.decodedMessage.toString();
}
private void findNextPotentialReference(int startPosition) {
this.nextPotentialReferencePosition = Math.max(startPosition, this.nextSemicolonPosition - MAX_REFERENCE_SIZE);
do {
this.nextPotentialReferencePosition =
this.originalMessage.indexOf('&', this.nextPotentialReferencePosition);
if (this.nextSemicolonPosition != -1 &&
this.nextSemicolonPosition < this.nextPotentialReferencePosition) {
this.nextSemicolonPosition = this.originalMessage.indexOf(';', this.nextPotentialReferencePosition + 1);
}
if (this.nextPotentialReferencePosition == -1) {
break;
}
if (this.nextSemicolonPosition == -1) {
this.nextPotentialReferencePosition = -1;
break;
}
if (this.nextSemicolonPosition - this.nextPotentialReferencePosition < MAX_REFERENCE_SIZE) {
break;
}
this.nextPotentialReferencePosition = this.nextPotentialReferencePosition + 1;
}
while (this.nextPotentialReferencePosition != -1);
}
private void copyCharactersTillPotentialReference() {
if (this.nextPotentialReferencePosition != this.currentPosition) {
int skipUntilIndex = (this.nextPotentialReferencePosition != -1 ?
this.nextPotentialReferencePosition : this.originalMessage.length());
if (skipUntilIndex - this.currentPosition > 3) {
this.decodedMessage.append(this.originalMessage, this.currentPosition, skipUntilIndex);
this.currentPosition = skipUntilIndex;
}
else {
while (this.currentPosition < skipUntilIndex) {
this.decodedMessage.append(this.originalMessage.charAt(this.currentPosition++));
}
}
}
}
private void processPossibleReference() {
if (this.nextPotentialReferencePosition != -1) {
boolean isNumberedReference = (this.originalMessage.charAt(this.currentPosition + 1) == '#');
boolean wasProcessable = isNumberedReference ? processNumberedReference() : processNamedReference();
if (wasProcessable) {
this.currentPosition = this.nextSemicolonPosition + 1;
}
else {
char currentChar = this.originalMessage.charAt(this.currentPosition);
this.decodedMessage.append(currentChar);
this.currentPosition++;
}
}
}
private boolean processNumberedReference() {
char referenceChar = this.originalMessage.charAt(this.nextPotentialReferencePosition + 2);
boolean isHexNumberedReference = (referenceChar == 'x' || referenceChar == 'X');
try {
int value = (!isHexNumberedReference ?
Integer.parseInt(getReferenceSubstring(2)) :
Integer.parseInt(getReferenceSubstring(3), 16));
this.decodedMessage.append((char) value);
return true;
}
catch (NumberFormatException ex) {
return false;
}
}
private boolean processNamedReference() {
String referenceName = getReferenceSubstring(1);
char mappedCharacter = this.characterEntityReferences.convertToCharacter(referenceName);
if (mappedCharacter != HtmlCharacterEntityReferences.CHAR_NULL) {
this.decodedMessage.append(mappedCharacter);
return true;
}
return false;
}
private String getReferenceSubstring(int referenceOffset) {
return this.originalMessage.substring(
this.nextPotentialReferencePosition + referenceOffset, this.nextSemicolonPosition);
}
}
| spring-projects/spring-framework | spring-web/src/main/java/org/springframework/web/util/HtmlCharacterEntityDecoder.java |
179,894 | /*
* Copyright 2014 Martin Steiger
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna.platform;
import com.sun.jna.FromNativeContext;
import com.sun.jna.ToNativeContext;
import com.sun.jna.TypeConverter;
/**
* A {@link TypeConverter} that maps an integer enum value to
* an actual Java enum.
* @param <T> the enum type
* @author Martin Steiger
*/
public class EnumConverter<T extends Enum<T>> implements TypeConverter {
private final Class<T> clazz;
/**
* @param clazz the enum class
*/
public EnumConverter(Class<T> clazz)
{
this.clazz = clazz;
}
@Override
public T fromNative(Object input, FromNativeContext context) {
Integer i = (Integer) input;
T[] vals = clazz.getEnumConstants();
return vals[i];
}
@Override
public Integer toNative(Object input, ToNativeContext context) {
T t = clazz.cast(input);
return Integer.valueOf(t.ordinal());
}
@Override
public Class<Integer> nativeType() {
return Integer.class;
}
}
| java-native-access/jna | contrib/platform/src/com/sun/jna/platform/EnumConverter.java |
179,896 | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models;
/**
* @author <a href="mailto:external.Martin.Idel@bosch.io">Martin Idel</a>
* @version $Revision: 1 $
*/
public abstract class UserModelDefaultMethods implements UserModel {
@Override
public String getFirstName() {
return getFirstAttribute(FIRST_NAME);
}
@Override
public void setFirstName(String firstName) {
setSingleAttribute(FIRST_NAME, firstName);
}
@Override
public String getLastName() {
return getFirstAttribute(LAST_NAME);
}
@Override
public void setLastName(String lastName) {
setSingleAttribute(LAST_NAME, lastName);
}
@Override
public String getEmail() {
return getFirstAttribute(EMAIL);
}
@Override
public void setEmail(String email) {
email = email == null || email.trim().isEmpty() ? null : email.toLowerCase();
setSingleAttribute(EMAIL, email);
}
@Override
public String toString() {
return getClass().getName() + "@" + getId();
}
}
| keycloak/keycloak | server-spi-private/src/main/java/org/keycloak/models/UserModelDefaultMethods.java |
179,898 | package com.twitter.search.common.encoding.features;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
/**
* A smart integer normalizer that converts an integer of a known range to a small integer up to
* 8 bits long. This normalizer generates a boundary value array in the constructor as the buckets
* for different values.
* <p/>
* The normalized value has a nice properties:
* 1) it maintains the order of original value: if a > b, then normalize(a) > normalize(b).
* 2) the value 0 is always normalized to byte 0.
* 3) the normalized values are (almost) evenly distributed on the log scale
* 4) no waste in code space, all possible values representable by normalized bits are used,
* each corresponding to a different value.
*/
public class SmartIntegerNormalizer extends ByteNormalizer {
// The max value we want to support in this normalizer. If the input is larger than this value,
// it's normalized as if it's the maxValue.
private final int maxValue;
// Number of bits used for normalized value, the largest normalized value
// would be (1 << numBits) - 1.
private final int numBits;
// The inclusive lower bounds of all buckets. A normalized value k corresponds to original values
// in the inclusive-exclusive range
// [ boundaryValues[k], boundaryValues[k+1] )
private final int[] boundaryValues;
// The length of the boundaryValues array, or the number of buckets.
private final int length;
/**
* Construct a normalizer.
*
* @param maxValue max value it supports, must be larger than minValue. Anything larger than this
* would be treated as maxValue.
* @param numBits number of bits you want to use for this normalization, between 1 and 8.
* higher resolution for the lower numbers.
*/
public SmartIntegerNormalizer(int maxValue, int numBits) {
Preconditions.checkArgument(maxValue > 0);
Preconditions.checkArgument(numBits > 0 && numBits <= 8);
this.maxValue = maxValue;
this.numBits = numBits;
this.length = 1 << numBits;
this.boundaryValues = new int[length];
int index;
for (index = length - 1; index >= 0; --index) {
// values are evenly distributed on the log scale
int boundary = (int) Math.pow(maxValue, (double) index / length);
// we have more byte slots left than we have possible boundary values (buckets),
// just give consecutive boundary values to all remaining slots, starting from 0.
if (boundary <= index) {
break;
}
boundaryValues[index] = boundary;
}
if (index >= 0) {
for (int i = 1; i <= index; ++i) {
boundaryValues[i] = i;
}
}
boundaryValues[0] = 0; // the first one is always 0.
}
@Override
public byte normalize(double val) {
int intVal = (int) (val > maxValue ? maxValue : val);
return intToUnsignedByte(binarySearch(intVal, boundaryValues));
}
/**
* Return the lower bound of the bucket represent by norm. This simply returns the boundary
* value indexed by current norm.
*/
@Override
public double unnormLowerBound(byte norm) {
return boundaryValues[unsignedByteToInt(norm)];
}
/**
* Return the upper bound of the bucket represent by norm. This returns the next boundary value
* minus 1. If norm represents the last bucket, it returns the maxValue.
*/
@Override
public double unnormUpperBound(byte norm) {
// if it's already the last possible normalized value, just return the corresponding last
// boundary value.
int intNorm = unsignedByteToInt(norm);
if (intNorm == length - 1) {
return maxValue;
}
return boundaryValues[intNorm + 1] - 1;
}
/**
* Do a binary search on array and find the index of the item that's no bigger than value.
*/
private static int binarySearch(int value, int[] array) {
// corner cases
if (value <= array[0]) {
return 0;
} else if (value >= array[array.length - 1]) {
return array.length - 1;
}
int left = 0;
int right = array.length - 1;
int pivot = (left + right) >> 1;
do {
int midVal = array[pivot];
if (value == midVal) {
break;
} else if (value > midVal) {
left = pivot;
} else {
right = pivot;
}
pivot = (left + right) >> 1;
} while (pivot != left);
return pivot;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(String.format(
"Smart Integer Normalizer (numBits = %d, max = %d)\n",
this.numBits, this.maxValue));
for (int i = 0; i < this.length; i++) {
sb.append(String.format(
"[%2d] boundary = %6d, range [ %6d, %6d ), norm: %4d | %4d | %4d %s\n",
i, boundaryValues[i],
(int) unnormLowerBound(intToUnsignedByte(i)),
(int) unnormUpperBound(intToUnsignedByte(i)),
unsignedByteToInt(normalize(boundaryValues[i] - 1)),
unsignedByteToInt(normalize(boundaryValues[i])),
unsignedByteToInt(normalize(boundaryValues[i] + 1)),
i == boundaryValues[i] ? "*" : ""));
}
return sb.toString();
}
@VisibleForTesting
int[] getBoundaryValues() {
return boundaryValues;
}
}
| twitter/the-algorithm | src/java/com/twitter/search/common/encoding/features/SmartIntegerNormalizer.java |
179,899 | package io.quarkus.arc.impl;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
/**
*
* @author Martin Kouba
*/
public class LazyValue<T> {
private final Supplier<T> supplier;
private final Lock lock = new ReentrantLock();
private transient volatile T value;
public LazyValue(Supplier<T> supplier) {
this.supplier = supplier;
}
public T get() {
T valueCopy = value;
if (valueCopy != null) {
return valueCopy;
}
lock.lock();
try {
if (value == null) {
value = supplier.get();
}
return value;
} finally {
lock.unlock();
}
}
public T getIfPresent() {
return value;
}
public void clear() {
lock.lock();
value = null;
lock.unlock();
}
public boolean isSet() {
return value != null;
}
}
| quarkusio/quarkus | independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/LazyValue.java |
179,901 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.spi.diff;
import java.io.IOException;
import java.io.Reader;
//import org.openide.util.Lookup;
import org.netbeans.api.diff.Difference;
/**
* This class represents a provider of diff algorithm. The implementing class
* should calculate differences between two sources.
* <p>The registered Diff Providers can be obtained via {@link org.openide.util.Lookup}
* (e.g. you can get the default diff provider by
* <code>Lookup.getDefault().lookup(DiffProvider.class)</code>)
*
* @author Martin Entlicher
*/
public abstract class DiffProvider extends Object {
/*
public static DiffProvider getDefault() {
return (DiffProvider) Lookup.getDefault().lookup(DiffProvider.class);
}
*/
/**
* Create the differences of the content two streams.
* @param r1 the first source
* @param r2 the second source to be compared with the first one.
* @return the list of differences found, instances of {@link Difference};
* or <code>null</code> when some error occured.
* @throws IOException when the reading from input streams fails.
*/
public abstract Difference[] computeDiff(Reader r1, Reader r2) throws IOException;
}
| apache/netbeans | ide/diff/src/org/netbeans/spi/diff/DiffProvider.java |
179,902 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.engine.migration;
/**
* @author martin.grofcik
*/
public class Script {
protected String script;
protected String language;
public Script() {
}
public Script(String language, String script) {
this.script = script;
this.language = language;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
| flowable/flowable-engine | modules/flowable-engine/src/main/java/org/flowable/engine/migration/Script.java |
179,904 | //ConsoleOutHandler.java
//-------------------------------------
//part of YACY
//(C) by Michael Peter Christen; mc@yacy.net
//first published on http://www.anomic.de
//Frankfurt, Germany, 2004
//
//This file is contributed by Martin Thelian
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package net.yacy.kelondro.logging;
import java.io.BufferedOutputStream;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
public final class ConsoleOutHandler extends StreamHandler {
private static int c = 0;
public ConsoleOutHandler() {
setLevel(Level.FINEST);
setFormatter(new SimpleFormatter());
setOutputStream(new BufferedOutputStream(System.out));
}
@Override
public final synchronized void publish(final LogRecord record) {
super.publish(record);
if (c++ % 10 == 0) flush(); // not so many flushes, makes too much IO
}
@Override
public final synchronized void close() {
flush();
}
}
| yacy/yacy_search_server | source/net/yacy/kelondro/logging/ConsoleOutHandler.java |
179,905 | /*
Copyright 2008-2011 Gephi
Authors : Martin Škurla
Website : http://www.gephi.org
This file is part of Gephi.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2011 Gephi Consortium. All rights reserved.
The contents of this file are subject to the terms of either the GNU
General Public License Version 3 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://gephi.org/about/legal/license-notice/
or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
specific language governing permissions and limitations under the
License. When distributing the software, include this License Header
Notice in each file and include the License files at
/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 3, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 3] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 3 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 3 code and therefore, elected the GPL
Version 3 license, then the option applies only if the new code is
made subject to such option by the copyright holder.
Contributor(s):
Portions Copyrighted 2011 Gephi Consortium.
*/
package org.gephi.tools.spi;
/**
* @author Martin Škurla
*/
public class UnselectToolException extends RuntimeException {
}
| gephi/gephi | modules/ToolsAPI/src/main/java/org/gephi/tools/spi/UnselectToolException.java |
179,906 | /*
Quick Connect History Database
Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at
http://mozilla.org/MPL/2.0/.
*/
package com.freerdp.freerdpcore.services;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class HistoryDB extends SQLiteOpenHelper
{
public static final String QUICK_CONNECT_TABLE_NAME = "quick_connect_history";
public static final String QUICK_CONNECT_TABLE_COL_ITEM = "item";
public static final String QUICK_CONNECT_TABLE_COL_TIMESTAMP = "timestamp";
private static final int DB_VERSION = 1;
private static final String DB_NAME = "history.db";
public HistoryDB(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
@Override public void onCreate(SQLiteDatabase db)
{
String sqlQuickConnectHistory = "CREATE TABLE " + QUICK_CONNECT_TABLE_NAME + " (" +
QUICK_CONNECT_TABLE_COL_ITEM + " TEXT PRIMARY KEY, " +
QUICK_CONNECT_TABLE_COL_TIMESTAMP + " INTEGER"
+ ");";
db.execSQL(sqlQuickConnectHistory);
}
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
}
| FreeRDP/FreeRDP | client/Android/Studio/freeRDPCore/src/main/java/com/freerdp/freerdpcore/services/HistoryDB.java |
179,908 | package fj.data;
import fj.F;
import fj.Unit;
import fj.function.Try0;
import java.io.IOException;
/**
* IO monad for processing files
*
* @author Martin Grotzke
*
* @param <A> the type of the result produced by the IO
*/
@FunctionalInterface
public interface IO<A> extends Try0<A, IOException> {
A run() throws IOException;
default A f() throws IOException {
return run();
}
default SafeIO<Validation<IOException, A>> safe() {
return IOFunctions.toSafeValidation(this);
}
default <B> IO<B> map(F<A, B> f) {
return IOFunctions.map(this, f);
}
default <B> IO<B> bind(F<A, IO<B>> f) {
return IOFunctions.bind(this, f);
}
default <B> IO<B> append(IO<B> iob) {
return IOFunctions.append(this, iob);
}
public static IO<LazyString> getContents() {
return () -> IOFunctions.getContents().run();
}
public static IO<Unit> interact(F<LazyString, LazyString> f) {
return () -> IOFunctions.interact(f).run();
}
}
| functionaljava/functionaljava | core/src/main/java/fj/data/IO.java |
179,909 | /**
* The purpose of this utility is to allow ruby-processing users to use an alternative
* to processing.org color their sketches (to cope with ruby FixNumber vs java int)
* Copyright (C) 2015-16 Martin Prout. This tool is free software; you can
* redistribute it and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* Obtain a copy of the license at http://www.gnu.org/licenses/lgpl-2.1.html
*/
package monkstone;
/**
*
* @author Martin Prout
*/
public class ColorUtil {
/**
* Returns hex long as a positive int unless greater than Integer.MAX_VALUE
* else return the complement as a negative integer or something like that
*/
static final int hexLong(long hexlong) {
long SPLIT = Integer.MAX_VALUE + 1;
if (hexlong < SPLIT) {
return (int) hexlong;
} else {
return (int) (hexlong - SPLIT * 2L);
}
}
static public int colorString(String hexstring) {
return java.awt.Color.decode(hexstring).getRGB();
}
static public float colorLong(double hex) {
return (float) hex;
}
static public int colorLong(long hexlong){
return hexLong(hexlong);
}
static public float colorDouble(double hex){
return (float)hex;
}
}
| jashkenas/ruby-processing | src/monkstone/ColorUtil.java |
179,910 | /*
* $Id: TSAClient.java 3959 2009-06-09 08:31:05Z blowagie $
*
* Copyright 2009 Martin Brunecky
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999-2005 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2009 by Martin Brunecky. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* https://github.com/LibrePDF/OpenPDF
*/
package com.lowagie.text.pdf;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
/**
* Time Stamp Authority client (caller) interface.
* <p>
* Interface used by the PdfPKCS7 digital signature builder to call Time Stamp Authority providing RFC 3161 compliant
* time stamp token.
*
* @author Martin Brunecky, 07/17/2007
* @since 2.1.6
*/
public interface TSAClient {
/**
* Get the time stamp token size estimate. Implementation must return value large enough to accomodate the entire
* token returned by getTimeStampToken() _prior_ to actual getTimeStampToken() call.
*
* @return an estimate of the token size
*/
int getTokenSizeEstimate();
/**
* Gets the MessageDigest to digest the data imprint
*
* @return the digest algorithm name
* @throws GeneralSecurityException a security problem
*/
MessageDigest getMessageDigest() throws GeneralSecurityException;
/**
* Get RFC 3161 timeStampToken. Method may return null indicating that timestamp should be skipped.
*
* @param caller PdfPKCS7 - calling PdfPKCS7 instance (in case caller needs it)
* @param imprint byte[] - data imprint to be time-stamped
* @return byte[] - encoded, TSA signed data of the timeStampToken
* @throws Exception - TSA request failed
*/
byte[] getTimeStampToken(PdfPKCS7 caller, byte[] imprint) throws Exception;
} | LibrePDF/OpenPDF | openpdf/src/main/java/com/lowagie/text/pdf/TSAClient.java |
179,911 | package com.tagtraum.perf.gcviewer.ctrl.impl;
import com.tagtraum.perf.gcviewer.ctrl.GCModelLoader;
import com.tagtraum.perf.gcviewer.imp.DataReaderException;
import com.tagtraum.perf.gcviewer.imp.MonitoredBufferedInputStream;
import com.tagtraum.perf.gcviewer.model.GCModel;
import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Base class for {@link GCModelLoader}s
*
* @author martin.geldmacher (refactored)
*/
public abstract class AbstractGCModelLoaderImpl extends SwingWorker<GCModel, Object> implements GCModelLoader {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == MonitoredBufferedInputStream.PROGRESS) {
setProgress((int) evt.getNewValue());
}
}
protected void done() {
Logger logger = getGcResource().getLogger();
try {
getGcResource().setModel(get());
// TODO delete
getGcResource().getModel().printDetailedInformation();
}
catch (InterruptedException e) {
logger.log(Level.FINE, "model get() interrupted", e);
}
catch (ExecutionException | RuntimeException e) {
if (logger.isLoggable(Level.WARNING))
logger.log(Level.WARNING, "Failed to create GCModel from " + getGcResource().getResourceName(), e);
}
}
@Override
protected GCModel doInBackground() throws Exception {
setProgress(0);
final GCModel result;
try {
result = loadGcModel();
}
catch (DataReaderException | RuntimeException e) {
Logger logger = getGcResource().getLogger();
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Failed to load GCModel from " + getGcResource().getResourceName(), e);
}
throw e;
}
return result;
}
protected abstract GCModel loadGcModel() throws DataReaderException;
}
| chewiebug/GCViewer | src/main/java/com/tagtraum/perf/gcviewer/ctrl/impl/AbstractGCModelLoaderImpl.java |
179,912 | /*******************************************************************************
* Copyright (c) 2014 Martin Marinov.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Martin Marinov - initial API and implementation
******************************************************************************/
package martin.tempest.sources;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JLabel;
import javax.swing.JTextField;
import martin.tempest.core.TSDRLibrary;
import martin.tempest.core.exceptions.TSDRLibraryNotCompatible;
/**
* This class allows {@link TSDRLibrary} to use various devices as SDR frontend inputs. Note that all of these are backed up
* by native dynamic libraries so it can be platform dependent.
*
* This class attempts to provide a flexible way of managing plugins for multiple OSes and architectues.
*
* @author Martin Marinov
*
*/
public class TSDRSource {
/**
* This is the official TSDRSource register. All available sources are to be registered here.
*/
private final static TSDRSource[] SOURCES = new TSDRSource[] {
new TSDRFileSource(),
new TSDRMiricsSource(),
new TSDRUHDSource(),
new TSDRExtIOSource(),
};
/** The native name of the dynamic library. It should not contain prefixes or extensions.
* For example a library could be called "abc", so libname would be "abc". When the library
* needs to be loaded, the system will make sure it loads abs.dll on Windows or libabs.so on Linux.
* An exception to this rule is if the libname contains full absolute path to the dll and {@link #absolute} is set to true. */
public final String libname;
/**
* If true, {@link #libname} will have the full path to the file that is the native library that this source represents
*/
public final boolean absolute;
/**
* A user friendly description of the library. Use this for displaying in GUI.
*/
public final String descr;
private TSDRSourceParamChangedListener callback = null;
private String params = "";
/**
* Return all of the available built-in TSDRSources.
* @return a list of all available TSDRSources. Some of them might be incompatible with the current user's system, but this will raise the appropriate exception
*/
public static TSDRSource[] getAvailableSources() {
return SOURCES;
}
/**
* Create a {@link TSDRSource} on the fly. This represents a native library that {@link TSDRLibrary} will load
* so that it can access the input of various SDR devices. The library supplied must be compatible with {@link TSDRLibrary},
* otherwise it won't be loaded.
* @param desc a user friendly description
* @param libname let's assume your library is called "abc". If you supply absolute equals to false, then setting libname to "abc" will mean
* the system will look for "abc.dll" on Windows or "libabc.so" on Linux, etc in the LD_LIBRARY_PATH or the java.library.path. This is the best way
* to be platform independent. If, however, your library is not in any of these folders, you can supply the absolute path, for example "D:\abc.dll" here and set absolute to true.
* NOTE however that if any dependent libraries are not in the LD_LIBRARY_PATH, this native library will fail to load no matter whether you have set absolute to true or false.
* @param absolute look at information about libname
*/
public TSDRSource(final String desc, final String libname, final boolean absolute) {
this.descr = desc;
this.libname = libname;
this.absolute = absolute;
}
/**
* This function can be called by the plugin itself when it's ready to be loaded/reloaded. Call it only if your application does not have a GUI or really need to force
* usage of a certain parameter.
* @param params
*/
public void setParams(final String params) {
this.params = params;
if (callback != null) callback.onParametersChanged(this);
}
/**
* Get the most current parameters
* @return
*/
public String getParams() {
return params;
}
@Override
public String toString() {
return descr;
}
/**
* The functions tries to find the absolute path to the native library that implements this source.
* It will also look into paths that are supplied with java.library.path
* @return a full path to the library or just {@link #libname}
*/
public String getAbsolutePathToLibrary() {
if (absolute) return libname;
try {
return TSDRLibrary.extractLibrary(libname).getAbsolutePath();
} catch (TSDRLibraryNotCompatible e) {
String fullname;
try {
fullname = TSDRLibrary.getNativeLibraryFullName(libname);
// if the library is not in the jar, try looking for it somewhere else
final File direct = new File(fullname);
if (direct.exists()) return direct.getAbsolutePath();
final String[] paths = System.getProperty("java.library.path").split(File.pathSeparator);
for (final String path : paths) {
final File temp = new File(path+File.separator+fullname);
if (temp.exists()) return temp.getAbsolutePath();
}
} catch (TSDRLibraryNotCompatible e1) {}
}
return libname;
}
/**
* Register a callback that will get notified as soon as the parameters are changed. The caller
* may want to reload the plugin in the {@link TSDRLibrary} so that the changes would take place.
* @param callback
*/
public void setOnParameterChangedCallback(final TSDRSourceParamChangedListener callback) {
this.callback = callback;
}
/**
* This should be called when the plugin is to be loaded. It will set the plugin parameters correctly according to user's desire so that once the parameters are set,
* it can be loaded to {@link TSDRLibrary}. In order to get a notification when the plugin is ready to be loaded to TSDRLibrary, register your callback with {@link #setOnParameterChangedCallback(TSDRSourceParamChangedListener)}
* @param cont the container that will receive the components
* @param defaultprefs the suggested parameters for this plugin. The plugin will decide what the exact value would be.
*/
public boolean populateGUI(final Container cont, final String defaultprefs, final ActionListenerRegistrator okbutton) {
if (cont == null) setParams(defaultprefs);
final JLabel description = new JLabel("Type in the parameters:");
cont.add(description);
description.setBounds(12, 12, 400-12, 24);
final JTextField params = new JTextField(defaultprefs);
cont.add(params);
params.setBounds(12, 12+32, 400-12, 24);
okbutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setParams(params.getText());
}
});
return true;
}
/**
* Interface that allows for events to be generated when a new parameter is applied to the plugin.
* The plugin will need to be reloaded so that they take place.
*
* @author Martin Marinov
*
*/
public static interface TSDRSourceParamChangedListener {
/**
* Everytime a source changes its parameters, this function will be called.
* A good suggestion would be to call {@link TSDRLibrary#loadPlugin}
* @param source the {@link TSDRSource} that was changed
*/
void onParametersChanged(final TSDRSource source);
}
public static interface ActionListenerRegistrator {
public void addActionListener(ActionListener l);
}
}
| rtlsdrblog/TempestSDR | JavaGUI/src/martin/tempest/sources/TSDRSource.java |
179,913 | /*
* This class is adopted from Htmlunit with the following copyright:
*
* Copyright (c) 2002-2012 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ZAP: Based on work by Gargoyle Software and adopted from Htmlunit (as stated above).
*/
package org.zaproxy.zap.spider;
/**
* The UrlResolve handles the process of resolving a relative URL against a base URL (context).
*
* @deprecated (2.12.0) See the spider add-on in zap-extensions instead.
*/
@Deprecated
public final class URLResolver {
/** Private constructor to avoid initialization of object. */
private URLResolver() {}
/**
* Resolves a given relative URL against a base URL. See <a
* href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a> Section 4 for more details.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
public static String resolveUrl(final String baseUrl, final String relativeUrl) {
// Parameter check
if (baseUrl == null) {
throw new IllegalArgumentException("Base URL must not be null");
}
if (relativeUrl == null) {
throw new IllegalArgumentException("Relative URL must not be null");
}
final Url url = resolveUrl(parseUrl(baseUrl.trim()), relativeUrl.trim());
return url.toString();
}
/**
* Returns the index within the specified string of the first occurrence of the specified search
* character.
*
* @param s the string to search
* @param searchChar the character to search for
* @param beginIndex the index at which to start the search
* @param endIndex the index at which to stop the search
* @return the index of the first occurrence of the character in the string or <tt>-1</tt>
*/
private static int indexOf(
final String s, final char searchChar, final int beginIndex, final int endIndex) {
for (int i = beginIndex; i < endIndex; i++) {
if (s.charAt(i) == searchChar) {
return i;
}
}
return -1;
}
/**
* Parses a given specification using the algorithm depicted in <a
* href="https://tools.ietf.org/html/rfc1808#section-2.4">RFC1808 - Section 2.4</a>:
*
* <blockquote>
*
* <h3>Section 2.4: Parsing a URL</h3>
*
* An accepted method for parsing URLs is useful to clarify the generic-RL syntax of Section 2.2
* and to describe the algorithm for resolving relative URLs presented in Section 4. This
* section describes the parsing rules for breaking down a URL (relative or absolute) into the
* component parts described in Section 2.1. The rules assume that the URL has already been
* separated from any surrounding text and copied to a "parse string". The rules are listed in
* the order in which they would be applied by the parser.
*
* </blockquote>
*
* @param spec The specification to parse.
* @return the parsed specification.
*/
private static Url parseUrl(final String spec) {
final Url url = new Url();
int startIndex = 0;
int endIndex = spec.length();
// Section 2.4.1: Parsing the Fragment Identifier
//
// If the parse string contains a crosshatch "#" character, then the
// substring after the first (left-most) crosshatch "#" and up to the
// end of the parse string is the <fragment> identifier. If the
// crosshatch is the last character, or no crosshatch is present, then
// the fragment identifier is empty. The matched substring, including
// the crosshatch character, is removed from the parse string before
// continuing.
//
// Note that the fragment identifier is not considered part of the URL.
// However, since it is often attached to the URL, parsers must be able
// to recognize and set aside fragment identifiers as part of the
// process.
final int crosshatchIndex = indexOf(spec, '#', startIndex, endIndex);
if (crosshatchIndex >= 0) {
url.fragment_ = spec.substring(crosshatchIndex + 1, endIndex);
endIndex = crosshatchIndex;
}
// Section 2.4.2: Parsing the Scheme
//
// If the parse string contains a colon ":" after the first character
// and before any characters not allowed as part of a scheme name (i.e.,
// any not an alphanumeric, plus "+", period ".", or hyphen "-"), the
// <scheme> of the URL is the substring of characters up to but not
// including the first colon. These characters and the colon are then
// removed from the parse string before continuing.
final int colonIndex = indexOf(spec, ':', startIndex, endIndex);
if (colonIndex > 0) {
final String scheme = spec.substring(startIndex, colonIndex);
if (isValidScheme(scheme)) {
url.scheme_ = scheme;
startIndex = colonIndex + 1;
}
}
// Section 2.4.3: Parsing the Network Location/Login
//
// If the parse string begins with a double-slash "//", then the
// substring of characters after the double-slash and up to, but not
// including, the next slash "/" character is the network location/login
// (<net_loc>) of the URL. If no trailing slash "/" is present, the
// entire remaining parse string is assigned to <net_loc>. The double-
// slash and <net_loc> are removed from the parse string before
// continuing.
//
// Note: We also accept a question mark "?" or a semicolon ";" character as
// delimiters for the network location/login (<net_loc>) of the URL.
final int locationStartIndex;
int locationEndIndex;
if (spec.startsWith("//", startIndex)) {
locationStartIndex = startIndex + 2;
locationEndIndex = indexOf(spec, '/', locationStartIndex, endIndex);
if (locationEndIndex >= 0) {
startIndex = locationEndIndex;
}
} else {
locationStartIndex = -1;
locationEndIndex = -1;
}
// Section 2.4.4: Parsing the Query Information
//
// If the parse string contains a question mark "?" character, then the
// substring after the first (left-most) question mark "?" and up to the
// end of the parse string is the <query> information. If the question
// mark is the last character, or no question mark is present, then the
// query information is empty. The matched substring, including the
// question mark character, is removed from the parse string before
// continuing.
final int questionMarkIndex = indexOf(spec, '?', startIndex, endIndex);
if (questionMarkIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the question mark "?" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = questionMarkIndex;
startIndex = questionMarkIndex;
}
url.query_ = spec.substring(questionMarkIndex + 1, endIndex);
endIndex = questionMarkIndex;
}
// Section 2.4.5: Parsing the Parameters
//
// If the parse string contains a semicolon ";" character, then the
// substring after the first (left-most) semicolon ";" and up to the end
// of the parse string is the parameters (<params>). If the semicolon
// is the last character, or no semicolon is present, then <params> is
// empty. The matched substring, including the semicolon character, is
// removed from the parse string before continuing.
final int semicolonIndex = indexOf(spec, ';', startIndex, endIndex);
if (semicolonIndex >= 0) {
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The substring of characters after the double-slash and up to, but not
// including, the semicolon ";" character is the network location/login
// (<net_loc>) of the URL.
locationEndIndex = semicolonIndex;
startIndex = semicolonIndex;
}
url.parameters_ = spec.substring(semicolonIndex + 1, endIndex);
endIndex = semicolonIndex;
}
// Section 2.4.6: Parsing the Path
//
// After the above steps, all that is left of the parse string is the URL <path> and the
// slash "/" that may precede it. Even though the initial slash is not part of the URL path,
// the parser must remember whether or not it was present so that later processes can
// differentiate between relative and absolute paths. Often this is done by simply storing
// the preceding slash along with the path.
if ((locationStartIndex >= 0) && (locationEndIndex < 0)) {
// The entire remaining parse string is assigned to the network location/login
// (<net_loc>) of the URL.
locationEndIndex = endIndex;
} else if (startIndex < endIndex) {
url.path_ = spec.substring(startIndex, endIndex);
}
// Set the network location/login (<net_loc>) of the URL.
if ((locationStartIndex >= 0) && (locationEndIndex >= 0)) {
url.location_ = spec.substring(locationStartIndex, locationEndIndex);
}
return url;
}
/**
* Checks if it is a valid scheme.
*
* @param scheme the scheme
* @return true, if is a valid scheme name
*/
private static boolean isValidScheme(final String scheme) {
final int length = scheme.length();
if (length <= 0) {
return false;
}
char c = scheme.charAt(0);
if (!Character.isLetter(c)) {
return false;
}
for (int i = 1; i < length; i++) {
c = scheme.charAt(i);
if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' && c != '-') {
return false;
}
}
return true;
}
/**
* Resolves a given relative URL against a base URL using the algorithm depicted in <a
* href="http://www.faqs.org/rfcs/rfc1808.html">RFC1808</a>:
*
* <p>Section 4: Resolving Relative URLs
*
* <p>This section describes an example algorithm for resolving URLs within a context in which
* the URLs may be relative, such that the result is always a URL in absolute form. Although
* this algorithm cannot guarantee that the resulting URL will equal that intended by the
* original author, it does guarantee that any valid URL (relative or absolute) can be
* consistently transformed to an absolute form given a valid base URL.
*
* @param baseUrl The base URL in which to resolve the specification.
* @param relativeUrl The relative URL to resolve against the base URL.
* @return the resolved specification.
*/
private static Url resolveUrl(final Url baseUrl, final String relativeUrl) {
final Url url = parseUrl(relativeUrl);
// Step 1: The base URL is established according to the rules of
// Section 3. If the base URL is the empty string (unknown),
// the embedded URL is interpreted as an absolute URL and
// we are done.
if (baseUrl == null) {
return url;
}
// Step 2: Both the base and embedded URLs are parsed into their component parts as
// described in Section 2.4.
// a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL) and we are done.
if (relativeUrl.length() == 0) {
return new Url(baseUrl);
}
// b) If the embedded URL starts with a scheme name, it is interpreted as an absolute URL
// and we are done.
if (url.scheme_ != null) {
return url;
}
// c) Otherwise, the embedded URL inherits the scheme of the base URL.
url.scheme_ = baseUrl.scheme_;
// Step 3: If the embedded URL's <net_loc> is non-empty, we skip to Step 7. Otherwise, the
// embedded URL inherits the <net_loc> (if any) of the base URL.
if (url.location_ != null) {
return url;
}
url.location_ = baseUrl.location_;
// Step 4: If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if ((url.path_ != null) && ((url.path_.length() > 0) && ('/' == url.path_.charAt(0)))) {
url.path_ = removeLeadingSlashPoints(url.path_);
return url;
}
// Step 5: If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path,
// and
if (url.path_ == null) {
url.path_ = baseUrl.path_;
// a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (url.parameters_ != null) {
return url;
}
url.parameters_ = baseUrl.parameters_;
// b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (url.query_ != null) {
return url;
}
url.query_ = baseUrl.query_;
return url;
}
// Step 6: The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place.
final String basePath = baseUrl.path_;
String path = "";
if (basePath != null) {
final int lastSlashIndex = basePath.lastIndexOf('/');
if (lastSlashIndex >= 0) {
path = basePath.substring(0, lastSlashIndex + 1);
}
} else {
path = "/";
}
path = path.concat(url.path_);
// The following operations are then applied, in order, to the new path:
// a) All occurrences of "./", where "." is a complete path segment, are removed.
int pathSegmentIndex;
while ((pathSegmentIndex = path.indexOf("/./")) >= 0) {
path =
path.substring(0, pathSegmentIndex + 1)
.concat(path.substring(pathSegmentIndex + 3));
}
// b) If the path ends with "." as a complete path segment, that "." is removed.
if (path.endsWith("/.")) {
path = path.substring(0, path.length() - 1);
}
// c) All occurrences of "<segment>/../", where <segment> is a complete path segment not
// equal to "..", are removed. Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration, until no matching pattern
// remains.
while ((pathSegmentIndex = path.indexOf("/../")) > 0) {
final String pathSegment = path.substring(0, pathSegmentIndex);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex < 0) {
continue;
}
if (!"..".equals(pathSegment.substring(slashIndex))) {
path =
path.substring(0, slashIndex + 1)
.concat(path.substring(pathSegmentIndex + 4));
}
}
// d) If the path ends with "<segment>/..", where <segment> is a complete path segment not
// equal to "..", that "<segment>/.." is removed.
if (path.endsWith("/..")) {
final String pathSegment = path.substring(0, path.length() - 3);
final int slashIndex = pathSegment.lastIndexOf('/');
if (slashIndex >= 0) {
path = path.substring(0, slashIndex + 1);
}
}
path = removeLeadingSlashPoints(path);
url.path_ = path;
// Step 7: The resulting URL components, including any inherited from
// the base URL, are recombined to give the absolute form of
// the embedded URL.
return url;
}
/**
* "/.." at the beginning should be removed as browsers do (not in RFC).
*
* @param path the path
* @return the cleaned string defining the path.
*/
private static String removeLeadingSlashPoints(String path) {
while (path.startsWith("/..")) {
path = path.substring(3);
}
return path;
}
/**
* Class <tt>Url</tt> represents a Uniform Resource Locator.
*
* @author Martin Tamme
*/
private static class Url {
/** The scheme_. */
private String scheme_;
/** The location_. */
private String location_;
/** The path_. */
private String path_;
/** The parameters_. */
private String parameters_;
/** The query_. */
private String query_;
/** The fragment_. */
private String fragment_;
/** Creates an <tt>Url</tt> object. */
public Url() {}
/**
* Creates an <tt>Url</tt> object from the specified <tt>Url</tt> object.
*
* @param url an <tt>Url</tt> object.
*/
public Url(final Url url) {
scheme_ = url.scheme_;
location_ = url.location_;
path_ = url.path_;
parameters_ = url.parameters_;
query_ = url.query_;
fragment_ = url.fragment_;
}
/**
* Returns a string representation of the <tt>Url</tt> object.
*
* @return a string representation of the <tt>Url</tt> object.
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
if (scheme_ != null) {
sb.append(scheme_);
sb.append(':');
}
if (location_ != null) {
sb.append("//");
sb.append(location_);
}
if (path_ != null) {
sb.append(path_);
}
if (parameters_ != null) {
sb.append(';');
sb.append(parameters_);
}
if (query_ != null) {
sb.append('?');
sb.append(query_);
}
if (fragment_ != null) {
sb.append('#');
sb.append(fragment_);
}
return sb.toString();
}
}
}
| zaproxy/zaproxy | zap/src/main/java/org/zaproxy/zap/spider/URLResolver.java |
179,914 | package monkstone.vecmath;
/**
*
* @author Martin Prout
*/
public interface JRender {
/**
*
* @param x
* @param y
*/
public void vertex(double x, double y);
/**
*
* @param x
* @param y
*/
public void curveVertex(double x, double y);
/**
*
* @param x
* @param y
* @param z
*/
public void vertex(double x, double y, double z);
/**
*
* @param x
* @param y
* @param z
* @param u
* @param v
*/
public void vertex(double x, double y, double z, double u, double v);
/**
*
* @param x
* @param y
* @param z
*/
public void curveVertex(double x, double y, double z);
/**
*
* @param x
* @param y
* @param z
*/
public void normal(double x, double y, double z);
}
| jashkenas/ruby-processing | src/monkstone/vecmath/JRender.java |
179,915 | /*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 Dennis Sheirer
* *
* * This program is free software: you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * This program is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>
* * *****************************************************************************
*
*
*/
package org.jdesktop.swingx;
import org.jdesktop.swingx.mapviewer.TileFactoryInfo;
/**
* Uses OpenStreetMap
* @author Martin Dummer
*/
public class OSMTileFactoryInfo extends TileFactoryInfo
{
private static final int max = 19;
/**
* Default constructor
*/
public OSMTileFactoryInfo()
{
super("OpenStreetMap",
1, max - 2, max,
256, true, true, // tile size is 256 and x/y orientation is normal
"https://tile.openstreetmap.org",
"x", "y", "z"); // 5/15/10.png
}
@Override
public String getTileUrl(int x, int y, int zoom)
{
zoom = max - zoom;
String url = this.baseURL + "/" + zoom + "/" + x + "/" + y + ".png";
return url;
}
}
| DSheirer/sdrtrunk | src/main/java/org/jdesktop/swingx/OSMTileFactoryInfo.java |
179,916 | package com.dexvis.javafx.scene.control;
import javafx.event.Event;
import javafx.event.EventTarget;
import javafx.event.EventType;
/**
*
* A custom event to house events for the JsonGuiPane.
*
* @author Patrick Martin
*
*/
public class JsonGuiEvent extends Event
{
public static final EventType<JsonGuiEvent> ROOT_EVENT = new EventType<>(
Event.ANY, "ROOT_EVENT");
public static final EventType<JsonGuiEvent> CHANGE_EVENT = new EventType<>(
ROOT_EVENT, "CHANGE ");
private JsonGuiEventPayload payload = null;
private static final long serialVersionUID = 1L;
public JsonGuiEvent(Object source, EventTarget target,
EventType<JsonGuiEvent> eventType)
{
super(source, target, eventType);
payload = (JsonGuiEventPayload) source;
}
public JsonGuiEventPayload getPayload()
{
return payload;
}
}
| PatMartin/Dex | src/com/dexvis/javafx/scene/control/JsonGuiEvent.java |
179,917 | package com.dexvis.dex.wf;
/**
*
* This class provides information about the nature of a task.
*
* @author Patrick E. Martin
*
*/
public class DexTaskMetaData
{
private boolean taskRequiresInitialization = false;
private boolean taskIsComposite = false;
// Be pessimistic, must be explicitly set to be eligible to run within a non
// JavaFX Application thread.
private boolean taskExecutionUpdatesUI = true;
private boolean taskInitializationUpdatesUI = true;
private boolean taskIsHeadless = false;
private boolean taskIsDatasource = false;
private boolean taskIsInternal = false;
// There is an opportunity here for describing task which can be
// run in parallel. Think about the metaphor with types for more
// sophisticated scheduling models.
//
// taskCanRunInParallel
// taskCanRunInParallelWithinExtendedBasicBlock
//
// taskType = parallel | serial
public DexTaskMetaData()
{
}
public static DexTaskMetaData metaData()
{
return new DexTaskMetaData();
}
public boolean getTaskRequiresInitialization()
{
return taskRequiresInitialization;
}
public void setTaskRequiresInitialization(boolean taskRequiresInitialization)
{
this.taskRequiresInitialization = taskRequiresInitialization;
}
public boolean getTaskIsComposite()
{
return taskIsComposite;
}
public void setTaskIsComposite(boolean taskIsComposite)
{
this.taskIsComposite = taskIsComposite;
}
public boolean getTaskExecutionUpdatesUI()
{
return taskExecutionUpdatesUI;
}
public void setTaskExecutionUpdatesUI(boolean taskExecutionUpdatesUI)
{
this.taskExecutionUpdatesUI = taskExecutionUpdatesUI;
}
public boolean getTaskInitializationUpdatesUI()
{
return taskInitializationUpdatesUI;
}
public void setTaskInitializationUpdatesUI(boolean taskInitializationUpdatesUI)
{
this.taskInitializationUpdatesUI = taskInitializationUpdatesUI;
}
public boolean getTaskIsHeadless()
{
return taskIsHeadless;
}
public void setTaskIsHeadless(boolean taskIsHeadless)
{
this.taskIsHeadless = taskIsHeadless;
}
public boolean getTaskIsDatasource()
{
return taskIsDatasource;
}
public void setTaskIsDatasource(boolean taskIsDatasource)
{
this.taskIsDatasource = taskIsDatasource;
}
public boolean getTaskIsInternal()
{
return taskIsInternal;
}
public void setTaskIsInternal(boolean taskIsInternal)
{
this.taskIsInternal = taskIsInternal;
}
}
| PatMartin/Dex | src/com/dexvis/dex/wf/DexTaskMetaData.java |
179,918 | // SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-FileCopyrightText: Copyright (C) 2010 The Android Open Source Project
// SPDX-License-Identifier: BSD-3-Clause AND Apache-2.0
package com.kitware.JavaVTK;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import java.io.File;
public class JavaVTKActivity extends Activity
{
JavaVTKView mView;
@Override protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
mView = new JavaVTKView(getApplication());
this.setContentView(mView);
}
@Override protected void onPause()
{
super.onPause();
this.mView.onPause();
}
@Override protected void onResume()
{
super.onResume();
this.mView.onResume();
}
}
| Kitware/VTK | Examples/Android/JavaVTK/src/com/kitware/JavaVTK/JavaVTKActivity.java |
179,919 | /*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.map;
import org.jdesktop.swingx.painter.Painter;
import java.awt.*;
/**
* Paints a selection rectangle
* @author Martin Steiger
*/
public class SelectionPainter implements Painter<Object>
{
private Color fillColor = new Color(128, 192, 255, 128);
private Color frameColor = new Color(0, 0, 255, 128);
private SelectionAdapter adapter;
/**
* @param adapter the selection adapter
*/
public SelectionPainter(SelectionAdapter adapter)
{
this.adapter = adapter;
}
@Override
public void paint(Graphics2D g, Object t, int width, int height)
{
Rectangle rc = adapter.getRectangle();
if (rc != null)
{
g.setColor(frameColor);
g.draw(rc);
g.setColor(fillColor);
g.fill(rc);
}
}
}
| DSheirer/sdrtrunk | src/main/java/io/github/dsheirer/map/SelectionPainter.java |
179,920 | package com.dexvis.exception;
/**
*
* This class holds an element not found exception. This is used to indicate
* that the element being referenced in the hashtable, property file, or
* whatever, wasn't found.
*
* @author Patrick E. Martin
* @version 1.0
*
*/
public class InvalidArgumentException extends ContainerException
{
/**
*
*/
private static final long serialVersionUID = -4636569787500850826L;
public InvalidArgumentException(String errorMessage)
{
super(errorMessage);
}
public InvalidArgumentException(String errorMessage, Exception ex)
{
super(errorMessage, ex);
}
public InvalidArgumentException(Exception ex)
{
super(ex);
}
}
| PatMartin/Dex | src/com/dexvis/exception/InvalidArgumentException.java |
179,921 | package com.dexvis.exception;
/**
*
* This class holds an element not found exception. This is used to indicate
* that the element being referenced in the hashtable, property file, or
* whatever, wasn't found.
*
* @author Patrick E. Martin
* @version 1.0
*
*/
public class ElementNotFoundException extends ContainerException
{
// generated
private static final long serialVersionUID = 6069060137605160516L;
public ElementNotFoundException(String errorMessage)
{
super(errorMessage);
}
public ElementNotFoundException(String errorMessage, Exception ex)
{
super(errorMessage, ex);
}
public ElementNotFoundException(Exception ex)
{
super(ex);
}
}
| PatMartin/Dex | src/com/dexvis/exception/ElementNotFoundException.java |
179,922 | package org.archive.bdb;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.SerializationException;
import sun.reflect.ReflectionFactory;
/**
* Extensions to Kryo to let classes control their own registration, suggest
* other classes to register together, and use the same (Sun-JVM-only) trick
* for deserializing classes without no-arg constructors.
*
* newInstance technique and constructor caching inspired by the
* KryoReflectionFactorySupport class of Martin Grotzke's kryo-serializers
* project. <a href="https://github.com/magro/kryo-serializers">https://github.com/magro/kryo-serializers</a>
*
* TODO: more comments!
*
* @author gojomo
*/
@SuppressWarnings("unchecked")
public class AutoKryo extends Kryo {
protected ArrayList<Class<?>> registeredClasses = new ArrayList<Class<?>>();
@Override
protected void handleUnregisteredClass(@SuppressWarnings("rawtypes") Class type) {
System.err.println("UNREGISTERED FOR KRYO "+type+" in "+registeredClasses.get(0));
super.handleUnregisteredClass(type);
}
public void autoregister(Class<?> type) {
if (registeredClasses.contains(type)) {
return;
}
registeredClasses.add(type);
try {
invokeStatic(
"autoregisterTo",
type,
new Class[]{ ((Class<?>)AutoKryo.class), },
new Object[] { this, });
} catch (Exception e) {
register(type);
}
}
protected static final ReflectionFactory REFLECTION_FACTORY = ReflectionFactory.getReflectionFactory();
protected static final Object[] INITARGS = new Object[0];
protected static final Map<Class<?>, Constructor<?>> CONSTRUCTOR_CACHE = new ConcurrentHashMap<Class<?>, Constructor<?>>();
@Override
public <T> T newInstance(Class<T> type) {
SerializationException ex = null;
try {
return super.newInstance(type);
} catch (SerializationException se) {
ex = se;
}
try {
Constructor<?> constructor = CONSTRUCTOR_CACHE.get(type);
if(constructor == null) {
constructor = REFLECTION_FACTORY.newConstructorForSerialization(
type, Object.class.getDeclaredConstructor( new Class[0] ) );
constructor.setAccessible( true );
CONSTRUCTOR_CACHE.put(type, constructor);
}
Object inst = constructor.newInstance( INITARGS );
return (T) inst;
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
throw ex;
}
protected Object invokeStatic(String method, Class<?> clazz, Class<?>[] types, Object[] args) throws Exception {
return clazz.getMethod(method, types).invoke(null, args);
}
}
| internetarchive/heritrix3 | commons/src/main/java/org/archive/bdb/AutoKryo.java |
179,923 | /* Copyright (c) 2008-2023, Nathan Sweet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
package com.esotericsoftware.kryo.serializers;
import static com.esotericsoftware.kryo.Kryo.*;
import static com.esotericsoftware.kryo.util.Util.*;
import static java.lang.Long.numberOfLeadingZeros;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.KryoSerializable;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.Date;
import java.util.EnumSet;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
/** Contains many serializer classes that are provided by {@link Kryo#addDefaultSerializer(Class, Class) default}.
* @author Nathan Sweet */
public class DefaultSerializers {
public static class VoidSerializer extends ImmutableSerializer {
public void write (Kryo kryo, Output output, Object object) {
}
public Object read (Kryo kryo, Input input, Class type) {
return null;
}
}
public static class BooleanSerializer extends ImmutableSerializer<Boolean> {
public void write (Kryo kryo, Output output, Boolean object) {
output.writeBoolean(object);
}
public Boolean read (Kryo kryo, Input input, Class<? extends Boolean> type) {
return input.readBoolean();
}
}
public static class ByteSerializer extends ImmutableSerializer<Byte> {
public void write (Kryo kryo, Output output, Byte object) {
output.writeByte(object);
}
public Byte read (Kryo kryo, Input input, Class<? extends Byte> type) {
return input.readByte();
}
}
public static class CharSerializer extends ImmutableSerializer<Character> {
public void write (Kryo kryo, Output output, Character object) {
output.writeChar(object);
}
public Character read (Kryo kryo, Input input, Class<? extends Character> type) {
return input.readChar();
}
}
public static class ShortSerializer extends ImmutableSerializer<Short> {
public void write (Kryo kryo, Output output, Short object) {
output.writeShort(object);
}
public Short read (Kryo kryo, Input input, Class<? extends Short> type) {
return input.readShort();
}
}
public static class IntSerializer extends ImmutableSerializer<Integer> {
public void write (Kryo kryo, Output output, Integer object) {
output.writeInt(object, false);
}
public Integer read (Kryo kryo, Input input, Class<? extends Integer> type) {
return input.readInt(false);
}
}
public static class LongSerializer extends ImmutableSerializer<Long> {
public void write (Kryo kryo, Output output, Long object) {
output.writeVarLong(object, false);
}
public Long read (Kryo kryo, Input input, Class<? extends Long> type) {
return input.readVarLong(false);
}
}
public static class FloatSerializer extends ImmutableSerializer<Float> {
public void write (Kryo kryo, Output output, Float object) {
output.writeFloat(object);
}
public Float read (Kryo kryo, Input input, Class<? extends Float> type) {
return input.readFloat();
}
}
public static class DoubleSerializer extends ImmutableSerializer<Double> {
public void write (Kryo kryo, Output output, Double object) {
output.writeDouble(object);
}
public Double read (Kryo kryo, Input input, Class<? extends Double> type) {
return input.readDouble();
}
}
/** @see Output#writeString(String) */
public static class StringSerializer extends ImmutableSerializer<String> {
{
setAcceptsNull(true);
}
public void write (Kryo kryo, Output output, String object) {
output.writeString(object);
}
public String read (Kryo kryo, Input input, Class<? extends String> type) {
return input.readString();
}
}
/** Serializer for {@link BigInteger} and any subclass.
* @author Tumi <serverperformance@gmail.com> (enhacements) */
public static class BigIntegerSerializer extends ImmutableSerializer<BigInteger> {
{
setAcceptsNull(true);
}
public void write (Kryo kryo, Output output, BigInteger object) {
if (object == null) {
output.writeByte(NULL);
return;
}
// fast-path optimizations for BigInteger.ZERO constant
if (object == BigInteger.ZERO) {
output.writeByte(2);
output.writeByte(0);
return;
}
// default behaviour
byte[] bytes = object.toByteArray();
output.writeVarInt(bytes.length + 1, true);
output.writeBytes(bytes);
}
public BigInteger read (Kryo kryo, Input input, Class<? extends BigInteger> type) {
int length = input.readVarInt(true);
if (length == NULL) return null;
byte[] bytes = input.readBytes(length - 1);
if (type != BigInteger.class && type != null) {
// Use reflection for subclasses.
return newBigIntegerSubclass(type, bytes);
}
if (length == 2) {
// Fast-path optimizations for BigInteger constants.
switch (bytes[0]) {
case 0:
return BigInteger.ZERO;
case 1:
return BigInteger.ONE;
case 10:
return BigInteger.TEN;
}
}
return new BigInteger(bytes);
}
private static BigInteger newBigIntegerSubclass(Class<? extends BigInteger> type, byte[] bytes) {
try {
Constructor<? extends BigInteger> constructor = type.getConstructor(byte[].class);
if (!constructor.isAccessible()) {
try {
constructor.setAccessible(true);
} catch (SecurityException ignored) {
}
}
return constructor.newInstance(bytes);
} catch (Exception ex) {
throw new KryoException(ex);
}
}
}
/** Serializer for {@link BigDecimal} and any subclass.
* @author Tumi <serverperformance@gmail.com> (enhacements) */
public static class BigDecimalSerializer extends ImmutableSerializer<BigDecimal> {
{
setAcceptsNull(true);
}
public void write (Kryo kryo, Output output, BigDecimal object) {
if (object == null) {
output.writeByte(NULL);
return;
}
if (object == BigDecimal.ZERO) {
output.writeVarInt(2, true);
output.writeByte((byte) 0);
output.writeInt(0, false);
return;
}
if (object == BigDecimal.ONE) {
output.writeVarInt(2, true);
output.writeByte((byte) 1);
output.writeInt(0, false);
return;
}
BigInteger unscaledBig = null; // avoid getting it from BigDecimal, as non-inflated BigDecimal will have to create it
boolean compactForm = object.precision() < 19; // less than nineteen decimal digits for sure fits in a long
if (!compactForm) {
unscaledBig = object.unscaledValue(); // get and remember for possible use in non-compact form
compactForm = unscaledBig.bitLength() <= 63; // check exactly if unscaled value will fit in a long
}
if (!compactForm) {
byte[] bytes = unscaledBig.toByteArray();
output.writeVarInt(bytes.length + 1, true);
output.writeBytes(bytes);
} else {
long unscaledLong = object.scaleByPowerOfTen(object.scale()).longValue(); // best way to get unscaled long value without creating unscaled BigInteger on the way
writeUnscaledLong(output, unscaledLong);
}
output.writeInt(object.scale(), false);
}
// compatible with writing unscaled value represented as BigInteger's bytes
private static void writeUnscaledLong (Output output, long unscaledLong) {
int insignificantBits = unscaledLong >= 0
? numberOfLeadingZeros(unscaledLong)
: numberOfLeadingZeros(~unscaledLong);
int significantBits = (64 - insignificantBits) + 1; // one more bit is for the sign
int length = (significantBits + (8 - 1)) >> 3; // how many bytes are needed (rounded up)
output.writeByte(length + 1);
output.writeLong(unscaledLong, length);
}
public BigDecimal read (Kryo kryo, Input input, Class<? extends BigDecimal> type) {
BigInteger unscaledBig = null;
long unscaledLong = 0;
int length = input.readVarInt(true);
if (length == NULL) return null;
length--;
if (length > 8) {
byte[] bytes = input.readBytes(length);
unscaledBig = new BigInteger(bytes);
} else {
unscaledLong = input.readLong(length);
}
int scale = input.readInt(false);
if (type != BigDecimal.class && type != null) {
// For subclasses, use reflection
return newBigDecimalSubclass(type, unscaledBig != null ? unscaledBig : BigInteger.valueOf(unscaledLong), scale);
} else {
// For BigDecimal, if possible use factory methods to avoid instantiating BigInteger
if (unscaledBig != null) {
return new BigDecimal(unscaledBig, scale);
} else {
if (scale == 0) {
if (unscaledLong == 0) return BigDecimal.ZERO;
if (unscaledLong == 1) return BigDecimal.ONE;
}
return BigDecimal.valueOf(unscaledLong, scale);
}
}
}
private static BigDecimal newBigDecimalSubclass(Class<? extends BigDecimal> type, BigInteger unscaledValue, int scale) {
try {
Constructor<? extends BigDecimal> constructor = type.getConstructor(BigInteger.class, int.class);
if (!constructor.isAccessible()) {
try {
constructor.setAccessible(true);
} catch (SecurityException ignored) {
}
}
return constructor.newInstance(unscaledValue, scale);
} catch (Exception ex) {
throw new KryoException(ex);
}
}
}
public static class ClassSerializer extends ImmutableSerializer<Class> {
{
setAcceptsNull(true);
}
public void write (Kryo kryo, Output output, Class type) {
kryo.writeClass(output, type);
if (type != null && (type.isPrimitive() || isWrapperClass(type))) output.writeBoolean(type.isPrimitive());
}
public Class read (Kryo kryo, Input input, Class<? extends Class> ignored) {
Registration registration = kryo.readClass(input);
if (registration == null) return null;
Class type = registration.getType();
if (!type.isPrimitive() || input.readBoolean()) return type;
return getWrapperClass(type);
}
}
/** Serializer for {@link Date}, {@link java.sql.Date}, {@link Time}, {@link Timestamp} and any other subclass.
* @author Tumi <serverperformance@gmail.com> */
public static class DateSerializer extends Serializer<Date> {
private Date create (Kryo kryo, Class<? extends Date> type, long time) throws KryoException {
if (type == Date.class || type == null) {
return new Date(time);
}
if (type == Timestamp.class) {
return new Timestamp(time);
}
if (type == java.sql.Date.class) {
return new java.sql.Date(time);
}
if (type == Time.class) {
return new Time(time);
}
// other cases, reflection
try {
// Try to avoid invoking the no-args constructor
// (which is expected to initialize the instance with the current time)
Constructor<? extends Date> constructor = type.getConstructor(long.class);
if (!constructor.isAccessible()) {
try {
constructor.setAccessible(true);
} catch (SecurityException ignored) {
}
}
return constructor.newInstance(time);
} catch (Exception ex) {
// default strategy
Date d = kryo.newInstance(type);
d.setTime(time);
return d;
}
}
public void write (Kryo kryo, Output output, Date object) {
output.writeVarLong(object.getTime(), true);
}
public Date read (Kryo kryo, Input input, Class<? extends Date> type) {
return create(kryo, type, input.readVarLong(true));
}
public Date copy (Kryo kryo, Date original) {
return create(kryo, original.getClass(), original.getTime());
}
}
/** Serializer for {@link Timestamp} which preserves the nanoseconds field. */
public static class TimestampSerializer extends Serializer<Timestamp> {
public void write (Kryo kryo, Output output, Timestamp object) {
output.writeVarLong(integralTimeComponent(object), true);
output.writeVarInt(object.getNanos(), true);
}
public Timestamp read (Kryo kryo, Input input, Class<? extends Timestamp> type) {
return create(input.readVarLong(true), input.readVarInt(true));
}
public Timestamp copy (Kryo kryo, Timestamp original) {
return create(integralTimeComponent(original), original.getNanos());
}
private long integralTimeComponent (Timestamp object) {
return object.getTime() - (object.getNanos() / 1_000_000);
}
private Timestamp create (long time, int nanos) {
Timestamp t = new Timestamp(time);
t.setNanos(nanos);
return t;
}
}
public static class EnumSerializer extends ImmutableSerializer<Enum> {
{
setAcceptsNull(true);
}
private Object[] enumConstants;
public EnumSerializer (Class<? extends Enum> type) {
enumConstants = type.getEnumConstants();
// We allow the serialization of the (abstract!) Enum.class (instead of an actual "user" enum),
// which also creates an EnumSerializer instance during Kryo.writeClass with the following trace:
// ClassSerializer.write -> Kryo.writeClass -> DefaultClassResolver.writeClass
// -> Kryo.getDefaultSerializer -> ReflectionSerializerFactory.makeSerializer(kryo, EnumSerializer, Enum.class)
// This EnumSerializer instance is expected to be never called for write/read.
if (enumConstants == null && !Enum.class.equals(type))
throw new IllegalArgumentException("The type must be an enum: " + type);
}
public void write (Kryo kryo, Output output, Enum object) {
if (object == null) {
output.writeVarInt(NULL, true);
return;
}
output.writeVarInt(object.ordinal() + 1, true);
}
public Enum read (Kryo kryo, Input input, Class<? extends Enum> type) {
int ordinal = input.readVarInt(true);
if (ordinal == NULL) return null;
ordinal--;
if (ordinal < 0 || ordinal > enumConstants.length - 1)
throw new KryoException("Invalid ordinal for enum \"" + type.getName() + "\": " + ordinal);
Object constant = enumConstants[ordinal];
return (Enum)constant;
}
}
public static class EnumSetSerializer extends Serializer<EnumSet> {
public void write (Kryo kryo, Output output, EnumSet object) {
Serializer serializer;
if (object.isEmpty()) {
EnumSet tmp = EnumSet.complementOf(object);
if (tmp.isEmpty()) throw new KryoException("An EnumSet must have a defined Enum to be serialized.");
serializer = kryo.writeClass(output, tmp.iterator().next().getClass()).getSerializer();
} else {
serializer = kryo.writeClass(output, object.iterator().next().getClass()).getSerializer();
}
output.writeVarInt(object.size(), true);
for (Object element : object)
serializer.write(kryo, output, element);
}
public EnumSet read (Kryo kryo, Input input, Class<? extends EnumSet> type) {
Registration registration = kryo.readClass(input);
EnumSet object = EnumSet.noneOf(registration.getType());
Serializer serializer = registration.getSerializer();
int length = input.readVarInt(true);
for (int i = 0; i < length; i++)
object.add(serializer.read(kryo, input, null));
return object;
}
public EnumSet copy (Kryo kryo, EnumSet original) {
return EnumSet.copyOf(original);
}
}
/** @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class CurrencySerializer extends ImmutableSerializer<Currency> {
{
setAcceptsNull(true);
}
public void write (Kryo kryo, Output output, Currency object) {
output.writeString(object == null ? null : object.getCurrencyCode());
}
public Currency read (Kryo kryo, Input input, Class<? extends Currency> type) {
String currencyCode = input.readString();
if (currencyCode == null) return null;
return Currency.getInstance(currencyCode);
}
}
/** @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class StringBufferSerializer extends Serializer<StringBuffer> {
{
setAcceptsNull(true);
}
public void write (Kryo kryo, Output output, StringBuffer object) {
output.writeString(object == null ? null : object.toString());
}
public StringBuffer read (Kryo kryo, Input input, Class<? extends StringBuffer> type) {
String value = input.readString();
if (value == null) return null;
return new StringBuffer(value);
}
public StringBuffer copy (Kryo kryo, StringBuffer original) {
return new StringBuffer(original);
}
}
/** @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class StringBuilderSerializer extends Serializer<StringBuilder> {
{
setAcceptsNull(true);
}
public void write (Kryo kryo, Output output, StringBuilder object) {
output.writeString(object == null ? null : object.toString());
}
public StringBuilder read (Kryo kryo, Input input, Class<? extends StringBuilder> type) {
return input.readStringBuilder();
}
public StringBuilder copy (Kryo kryo, StringBuilder original) {
return new StringBuilder(original);
}
}
public static class KryoSerializableSerializer extends Serializer<KryoSerializable> {
public void write (Kryo kryo, Output output, KryoSerializable object) {
object.write(kryo, output);
}
public KryoSerializable read (Kryo kryo, Input input, Class<? extends KryoSerializable> type) {
KryoSerializable object = kryo.newInstance(type);
kryo.reference(object);
object.read(kryo, input);
return object;
}
}
/** Serializer for lists created via {@link Collections#emptyList()} or that were just assigned the
* {@link Collections#EMPTY_LIST}.
* @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class CollectionsEmptyListSerializer extends ImmutableSerializer<Collection> {
public void write (Kryo kryo, Output output, Collection object) {
}
public Collection read (Kryo kryo, Input input, Class<? extends Collection> type) {
return Collections.EMPTY_LIST;
}
}
/** Serializer for maps created via {@link Collections#emptyMap()} or that were just assigned the
* {@link Collections#EMPTY_MAP}.
* @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class CollectionsEmptyMapSerializer extends ImmutableSerializer<Map> {
public void write (Kryo kryo, Output output, Map object) {
}
public Map read (Kryo kryo, Input input, Class<? extends Map> type) {
return Collections.EMPTY_MAP;
}
}
/** Serializer for sets created via {@link Collections#emptySet()} or that were just assigned the
* {@link Collections#EMPTY_SET}.
* @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class CollectionsEmptySetSerializer extends ImmutableSerializer<Set> {
public void write (Kryo kryo, Output output, Set object) {
}
public Set read (Kryo kryo, Input input, Class<? extends Set> type) {
return Collections.EMPTY_SET;
}
}
/** Serializer for lists created via {@link Collections#singletonList(Object)}.
* @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class CollectionsSingletonListSerializer extends Serializer<List> {
public void write (Kryo kryo, Output output, List object) {
kryo.writeClassAndObject(output, object.get(0));
}
public List read (Kryo kryo, Input input, Class<? extends List> type) {
return Collections.singletonList(kryo.readClassAndObject(input));
}
public List copy (Kryo kryo, List original) {
return Collections.singletonList(kryo.copy(original.get(0)));
}
}
/** Serializer for maps created via {@link Collections#singletonMap(Object, Object)}.
* @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class CollectionsSingletonMapSerializer extends Serializer<Map> {
public void write (Kryo kryo, Output output, Map object) {
Entry entry = (Entry)object.entrySet().iterator().next();
kryo.writeClassAndObject(output, entry.getKey());
kryo.writeClassAndObject(output, entry.getValue());
}
public Map read (Kryo kryo, Input input, Class<? extends Map> type) {
Object key = kryo.readClassAndObject(input);
Object value = kryo.readClassAndObject(input);
return Collections.singletonMap(key, value);
}
public Map copy (Kryo kryo, Map original) {
Entry entry = (Entry)original.entrySet().iterator().next();
return Collections.singletonMap(kryo.copy(entry.getKey()), kryo.copy(entry.getValue()));
}
}
/** Serializer for sets created via {@link Collections#singleton(Object)}.
* @author <a href="mailto:martin.grotzke@javakaffee.de">Martin Grotzke</a> */
public static class CollectionsSingletonSetSerializer extends Serializer<Set> {
public void write (Kryo kryo, Output output, Set object) {
kryo.writeClassAndObject(output, object.iterator().next());
}
public Set read (Kryo kryo, Input input, Class<? extends Set> type) {
return Collections.singleton(kryo.readClassAndObject(input));
}
public Set copy (Kryo kryo, Set original) {
return Collections.singleton(kryo.copy(original.iterator().next()));
}
}
/** Serializer for {@link TimeZone}. Assumes the timezones are immutable.
* @author Tumi <serverperformance@gmail.com> */
public static class TimeZoneSerializer extends ImmutableSerializer<TimeZone> {
public void write (Kryo kryo, Output output, TimeZone object) {
output.writeString(object.getID());
}
public TimeZone read (Kryo kryo, Input input, Class<? extends TimeZone> type) {
return TimeZone.getTimeZone(input.readString());
}
}
/** Serializer for {@link GregorianCalendar}, java.util.JapaneseImperialCalendar, and sun.util.BuddhistCalendar.
* @author Tumi <serverperformance@gmail.com> */
public static class CalendarSerializer extends Serializer<Calendar> {
// The default value of gregorianCutover.
private static final long DEFAULT_GREGORIAN_CUTOVER = -12219292800000L;
TimeZoneSerializer timeZoneSerializer = new TimeZoneSerializer();
public void write (Kryo kryo, Output output, Calendar object) {
timeZoneSerializer.write(kryo, output, object.getTimeZone()); // can't be null
output.writeVarLong(object.getTimeInMillis(), true);
output.writeBoolean(object.isLenient());
output.writeInt(object.getFirstDayOfWeek(), true);
output.writeInt(object.getMinimalDaysInFirstWeek(), true);
if (object instanceof GregorianCalendar)
output.writeVarLong(((GregorianCalendar)object).getGregorianChange().getTime(), false);
else
output.writeVarLong(DEFAULT_GREGORIAN_CUTOVER, false);
}
public Calendar read (Kryo kryo, Input input, Class<? extends Calendar> type) {
Calendar result = Calendar.getInstance(timeZoneSerializer.read(kryo, input, TimeZone.class));
result.setTimeInMillis(input.readVarLong(true));
result.setLenient(input.readBoolean());
result.setFirstDayOfWeek(input.readInt(true));
result.setMinimalDaysInFirstWeek(input.readInt(true));
long gregorianChange = input.readVarLong(false);
if (gregorianChange != DEFAULT_GREGORIAN_CUTOVER)
if (result instanceof GregorianCalendar) ((GregorianCalendar)result).setGregorianChange(new Date(gregorianChange));
return result;
}
public Calendar copy (Kryo kryo, Calendar original) {
return (Calendar)original.clone();
}
}
/** Serializer for {@link TreeMap} and any subclass.
* @author Tumi <serverperformance@gmail.com> (enhacements) */
public static class TreeMapSerializer extends MapSerializer<TreeMap> {
protected void writeHeader (Kryo kryo, Output output, TreeMap treeSet) {
kryo.writeClassAndObject(output, treeSet.comparator());
}
protected TreeMap create (Kryo kryo, Input input, Class<? extends TreeMap> type, int size) {
return createTreeMap(type, (Comparator)kryo.readClassAndObject(input));
}
protected TreeMap createCopy (Kryo kryo, TreeMap original) {
return createTreeMap(original.getClass(), original.comparator());
}
private TreeMap createTreeMap (Class<? extends TreeMap> type, Comparator comparator) {
if (type == TreeMap.class || type == null) return new TreeMap(comparator);
// Use reflection for subclasses.
try {
Constructor constructor = type.getConstructor(Comparator.class);
if (!constructor.isAccessible()) {
try {
constructor.setAccessible(true);
} catch (SecurityException ignored) {
}
}
return (TreeMap)constructor.newInstance(comparator);
} catch (Exception ex) {
throw new KryoException(ex);
}
}
}
/** Serializer for {@link ConcurrentSkipListMap} and any subclass.
* @author Mr14huashao <mr11huashao@gmail.com> (enhacements) */
public static class ConcurrentSkipListMapSerializer extends MapSerializer<ConcurrentSkipListMap> {
@Override
protected void writeHeader (Kryo kryo, Output output, ConcurrentSkipListMap concurrentSkipListMap) {
kryo.writeClassAndObject(output, concurrentSkipListMap.comparator());
}
@Override
protected ConcurrentSkipListMap create (Kryo kryo, Input input, Class<? extends ConcurrentSkipListMap> type,
int size) {
return createConcurrentSkipListMap(type, (Comparator)kryo.readClassAndObject(input));
}
@Override
protected ConcurrentSkipListMap createCopy (Kryo kryo, ConcurrentSkipListMap original) {
return createConcurrentSkipListMap(original.getClass(), original.comparator());
}
private ConcurrentSkipListMap createConcurrentSkipListMap (Class<? extends ConcurrentSkipListMap> type,
Comparator comparator) {
if (type == ConcurrentSkipListMap.class || type == null) {
return new ConcurrentSkipListMap(comparator);
}
// Use reflection for subclasses.
try {
Constructor constructor = type.getConstructor(Comparator.class);
if (!constructor.isAccessible()) {
try {
constructor.setAccessible(true);
} catch (SecurityException ignored) {
}
}
return (ConcurrentSkipListMap)constructor.newInstance(comparator);
} catch (Exception ex) {
throw new KryoException(ex);
}
}
}
/** Serializer for {@link TreeMap} and any subclass.
* @author Tumi <serverperformance@gmail.com> (enhacements) */
public static class TreeSetSerializer extends CollectionSerializer<TreeSet> {
protected void writeHeader (Kryo kryo, Output output, TreeSet treeSet) {
kryo.writeClassAndObject(output, treeSet.comparator());
}
protected TreeSet create (Kryo kryo, Input input, Class<? extends TreeSet> type, int size) {
return createTreeSet(type, (Comparator)kryo.readClassAndObject(input));
}
protected TreeSet createCopy (Kryo kryo, TreeSet original) {
return createTreeSet(original.getClass(), original.comparator());
}
private TreeSet createTreeSet (Class<? extends Collection> type, Comparator comparator) {
if (type == TreeSet.class || type == null) return new TreeSet(comparator);
// Use reflection for subclasses.
try {
Constructor constructor = type.getConstructor(Comparator.class);
if (!constructor.isAccessible()) {
try {
constructor.setAccessible(true);
} catch (SecurityException ignored) {
}
}
return (TreeSet)constructor.newInstance(comparator);
} catch (Exception ex) {
throw new KryoException(ex);
}
}
}
/** Serializer for {@link PriorityQueue} and any subclass.
* @author Nathan Sweet */
public static class PriorityQueueSerializer extends CollectionSerializer<PriorityQueue> {
protected void writeHeader (Kryo kryo, Output output, PriorityQueue queue) {
kryo.writeClassAndObject(output, queue.comparator());
}
protected PriorityQueue create (Kryo kryo, Input input, Class<? extends PriorityQueue> type, int size) {
return createPriorityQueue(type, size, (Comparator)kryo.readClassAndObject(input));
}
protected PriorityQueue createCopy (Kryo kryo, PriorityQueue original) {
return createPriorityQueue(original.getClass(), original.size(), original.comparator());
}
private PriorityQueue createPriorityQueue (Class<? extends Collection> type, int size, Comparator comparator) {
final int initialCapacity = Math.max(size, 1);
if (type == PriorityQueue.class || type == null) return new PriorityQueue(initialCapacity, comparator);
// Use reflection for subclasses.
try {
Constructor constructor = type.getConstructor(int.class, Comparator.class);
if (!constructor.isAccessible()) {
try {
constructor.setAccessible(true);
} catch (SecurityException ignored) {
}
}
return (PriorityQueue)constructor.newInstance(initialCapacity, comparator);
} catch (Exception ex) {
throw new KryoException(ex);
}
}
}
/** Serializer for {@link Locale} (immutables).
* @author Tumi <serverperformance@gmail.com> */
public static class LocaleSerializer extends ImmutableSerializer<Locale> {
// Missing constants in j.u.Locale for common locale
public static final Locale SPANISH = new Locale("es", "", "");
public static final Locale SPAIN = new Locale("es", "ES", "");
protected Locale create (String language, String country, String variant) {
// Fast-path for default locale in this system (may not be in the Locale constants list)
Locale defaultLocale = Locale.getDefault();
if (isSameLocale(defaultLocale, language, country, variant)) return defaultLocale;
// Fast-paths for constants declared in java.util.Locale :
// 1. "US" locale (typical forced default in many applications)
if (defaultLocale != Locale.US && isSameLocale(Locale.US, language, country, variant)) return Locale.US;
// 2. Language-only constant locales
if (isSameLocale(Locale.ENGLISH, language, country, variant)) return Locale.ENGLISH;
if (isSameLocale(Locale.GERMAN, language, country, variant)) return Locale.GERMAN;
if (isSameLocale(SPANISH, language, country, variant)) return SPANISH;
if (isSameLocale(Locale.FRENCH, language, country, variant)) return Locale.FRENCH;
if (isSameLocale(Locale.ITALIAN, language, country, variant)) return Locale.ITALIAN;
if (isSameLocale(Locale.JAPANESE, language, country, variant)) return Locale.JAPANESE;
if (isSameLocale(Locale.KOREAN, language, country, variant)) return Locale.KOREAN;
if (isSameLocale(Locale.SIMPLIFIED_CHINESE, language, country, variant)) return Locale.SIMPLIFIED_CHINESE;
if (isSameLocale(Locale.CHINESE, language, country, variant)) return Locale.CHINESE;
if (isSameLocale(Locale.TRADITIONAL_CHINESE, language, country, variant)) return Locale.TRADITIONAL_CHINESE;
// 2. Language with Country constant locales
if (isSameLocale(Locale.UK, language, country, variant)) return Locale.UK;
if (isSameLocale(Locale.GERMANY, language, country, variant)) return Locale.GERMANY;
if (isSameLocale(SPAIN, language, country, variant)) return SPAIN;
if (isSameLocale(Locale.FRANCE, language, country, variant)) return Locale.FRANCE;
if (isSameLocale(Locale.ITALY, language, country, variant)) return Locale.ITALY;
if (isSameLocale(Locale.JAPAN, language, country, variant)) return Locale.JAPAN;
if (isSameLocale(Locale.KOREA, language, country, variant)) return Locale.KOREA;
// if (isSameLocale(Locale.CHINA, language, country, variant)) // CHINA==SIMPLIFIED_CHINESE, see Locale.java
// return Locale.CHINA;
// if (isSameLocale(Locale.PRC, language, country, variant)) // PRC==SIMPLIFIED_CHINESE, see Locale.java
// return Locale.PRC;
// if (isSameLocale(Locale.TAIWAN, language, country, variant)) // TAIWAN==SIMPLIFIED_CHINESE, see Locale.java
// return Locale.TAIWAN;
if (isSameLocale(Locale.CANADA, language, country, variant)) return Locale.CANADA;
if (isSameLocale(Locale.CANADA_FRENCH, language, country, variant)) return Locale.CANADA_FRENCH;
return new Locale(language, country, variant);
}
public void write (Kryo kryo, Output output, Locale l) {
output.writeAscii(l.getLanguage());
output.writeAscii(l.getCountry());
output.writeString(l.getVariant());
}
public Locale read (Kryo kryo, Input input, Class<? extends Locale> type) {
String language = input.readString();
String country = input.readString();
String variant = input.readString();
return create(language, country, variant);
}
protected static boolean isSameLocale (Locale locale, String language, String country, String variant) {
return (locale.getLanguage().equals(language) && locale.getCountry().equals(country)
&& locale.getVariant().equals(variant));
}
}
/** Serializer for {@link Charset}. */
public static class CharsetSerializer extends ImmutableSerializer<Charset> {
public void write (Kryo kryo, Output output, Charset object) {
output.writeString(object.name());
}
public Charset read (Kryo kryo, Input input, Class<? extends Charset> type) {
return Charset.forName(input.readString());
}
}
/** Serializer for {@link URL}. */
public static class URLSerializer extends ImmutableSerializer<URL> {
public void write (Kryo kryo, Output output, URL object) {
output.writeString(object.toExternalForm());
}
public URL read (Kryo kryo, Input input, Class<? extends URL> type) {
try {
return new java.net.URL(input.readString());
} catch (MalformedURLException ex) {
throw new KryoException(ex);
}
}
}
/** Serializer for {@link Arrays#asList(Object...)}. */
public static class ArraysAsListSerializer extends CollectionSerializer<List> {
protected List create (Kryo kryo, Input input, Class type, int size) {
return new ArrayList(size);
}
public List read (Kryo kryo, Input input, Class type) {
List list = super.read(kryo, input, type);
if (list == null) return null;
return Arrays.asList(list.toArray());
}
public List copy (Kryo kryo, List original) {
Object[] copyArr = new Object[original.size()];
List<Object> copy = Arrays.asList(copyArr);
kryo.reference(copy);
for (int i = 0; i < original.size(); i++) {
copyArr[i] = kryo.copy(original.get(i));
}
return copy;
}
}
/** Serializer for {@link BitSet} */
public static class BitSetSerializer extends Serializer<BitSet> {
public void write (Kryo kryo, Output output, BitSet set) {
long[] values = set.toLongArray();
output.writeVarInt(values.length, true);
output.writeLongs(values, 0, values.length);
}
public BitSet read (Kryo kryo, Input input, Class type) {
int length = input.readVarInt(true);
long[] values = input.readLongs(length);
return BitSet.valueOf(values);
}
public BitSet copy (Kryo kryo, BitSet original) {
return BitSet.valueOf(original.toLongArray());
}
}
/** Serializer for {@link Pattern} */
public static class PatternSerializer extends ImmutableSerializer<Pattern> {
public void write (final Kryo kryo, final Output output, final Pattern pattern) {
output.writeString(pattern.pattern());
output.writeInt(pattern.flags(), true);
}
public Pattern read (final Kryo kryo, final Input input, final Class<? extends Pattern> patternClass) {
String regex = input.readString();
int flags = input.readInt(true);
return Pattern.compile(regex, flags);
}
}
/** Serializer for {@link URI} */
public static class URISerializer extends ImmutableSerializer<java.net.URI> {
public void write (Kryo kryo, Output output, URI uri) {
output.writeString(uri.toString());
}
public URI read (Kryo kryo, Input input, Class<? extends URI> uriClass) {
try {
return new URI(input.readString());
} catch (URISyntaxException ex) {
throw new KryoException(ex);
}
}
}
/** Serializer for {@link UUID} */
public static class UUIDSerializer extends ImmutableSerializer<UUID> {
public void write (Kryo kryo, Output output, UUID uuid) {
output.writeLong(uuid.getMostSignificantBits());
output.writeLong(uuid.getLeastSignificantBits());
}
public UUID read (final Kryo kryo, final Input input, final Class<? extends UUID> uuidClass) {
return new UUID(input.readLong(), input.readLong());
}
}
/** Serializer for {@link AtomicBoolean} */
public static class AtomicBooleanSerializer extends Serializer<AtomicBoolean> {
public void write (Kryo kryo, Output output, AtomicBoolean object) {
output.writeBoolean(object.get());
}
public AtomicBoolean read (Kryo kryo, Input input, Class<? extends AtomicBoolean> type) {
return new AtomicBoolean(input.readBoolean());
}
public AtomicBoolean copy (Kryo kryo, AtomicBoolean original) {
return new AtomicBoolean(original.get());
}
}
/** Serializer for {@link AtomicInteger} */
public static class AtomicIntegerSerializer extends Serializer<AtomicInteger> {
public void write (Kryo kryo, Output output, AtomicInteger object) {
output.writeInt(object.get());
}
public AtomicInteger read (Kryo kryo, Input input, Class<? extends AtomicInteger> type) {
return new AtomicInteger(input.readInt());
}
public AtomicInteger copy (Kryo kryo, AtomicInteger original) {
return new AtomicInteger(original.get());
}
}
/** Serializer for {@link AtomicLong} */
public static class AtomicLongSerializer extends Serializer<AtomicLong> {
public void write (Kryo kryo, Output output, AtomicLong object) {
output.writeLong(object.get());
}
public AtomicLong read (Kryo kryo, Input input, Class<? extends AtomicLong> type) {
return new AtomicLong(input.readLong());
}
public AtomicLong copy (Kryo kryo, AtomicLong original) {
return new AtomicLong(original.get());
}
}
/** Serializer for {@link AtomicReference} */
public static class AtomicReferenceSerializer extends Serializer<AtomicReference> {
public void write (Kryo kryo, Output output, AtomicReference object) {
kryo.writeClassAndObject(output, object.get());
}
public AtomicReference read (Kryo kryo, Input input, Class<? extends AtomicReference> type) {
final Object value = kryo.readClassAndObject(input);
return new AtomicReference(value);
}
public AtomicReference copy (Kryo kryo, AtomicReference original) {
return new AtomicReference<>(kryo.copy(original.get()));
}
}
}
| EsotericSoftware/kryo | src/com/esotericsoftware/kryo/serializers/DefaultSerializers.java |
179,924 | /*
* Copyright (c) 2014 Martin Prout
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package monkstone.arcball;
/**
*
* @author Martin Prout
*/
public enum Constrain {
/**
* Used to constrain arc-ball rotation about X axis
*/
XAXIS(0),
/**
* Used to constrain arc-ball rotation about Y axis
*/
YAXIS(1),
/**
* Used to constrain arc-ball rotation about Z axis
*/
ZAXIS(2),
/**
* Used for default no constrain arc-ball about any axis
*/
FREE(-1);
private final int index;
Constrain(int idx) {
this.index = idx;
}
/**
* Numeric value of constrained axis
* @return index int
*/
public int index() {
return index;
}
}
| jashkenas/ruby-processing | src/monkstone/arcball/Constrain.java |
179,925 | package monkstone.vecmath;
import processing.core.PApplet;
/**
*
* @author Martin Prout
*/
public class AppRender implements JRender {
final PApplet app;
/**
*
* @param app
*/
public AppRender(final PApplet app) {
this.app = app;
}
/**
*
* @param x
* @param y
*/
@Override
public void vertex(double x, double y) {
app.vertex((float) x, (float) y);
}
/**
*
* @param x
* @param y
*/
@Override
public void curveVertex(double x, double y) {
app.curveVertex((float) x, (float) y);
}
/**
*
* @param x
* @param y
* @param z
*/
@Override
public void vertex(double x, double y, double z) {
app.vertex((float) x, (float) y, (float) z);
}
/**
*
* @param x
* @param y
* @param z
*/
@Override
public void normal(double x, double y, double z) {
app.normal((float) x, (float) y, (float) z);
}
/**
*
* @param x
* @param y
* @param z
* @param u
* @param v
*/
@Override
public void vertex(double x, double y, double z, double u, double v) {
app.vertex((float) x, (float) y, (float) z, (float) u, (float) v);
}
/**
*
* @param x
* @param y
* @param z
*/
@Override
public void curveVertex(double x, double y, double z) {
app.curveVertex((float) x, (float) y, (float) z);
}
}
| jashkenas/ruby-processing | src/monkstone/vecmath/AppRender.java |
179,926 | package org.pac4j.oidc.util;
import org.pac4j.core.context.CallContext;
import org.pac4j.oidc.client.OidcClient;
import java.util.Optional;
/**
* ValueRetriever retrieves a given value from the {@link org.pac4j.core.context.WebContext}. It can
* either read the value from the session store or use some method to regenerate
* the value. This is used to validate values such as the {@link com.nimbusds.oauth2.sdk.id.State}, for
* CSRF mitigation or the {@link com.nimbusds.oauth2.sdk.pkce.CodeVerifier} for PKCE.
*
* @author Martin Hansen
* @author Emond Papegaaij
* @since 4.0.3
*/
@FunctionalInterface
public interface ValueRetriever {
/**
* <p>retrieve.</p>
*
* @param ctx a {@link CallContext} object
* @param key a {@link String} object
* @param client a {@link OidcClient} object
* @return a {@link Optional} object
*/
Optional<Object> retrieve(CallContext ctx, String key, OidcClient client);
}
| pac4j/pac4j | pac4j-oidc/src/main/java/org/pac4j/oidc/util/ValueRetriever.java |
179,927 | /*
* Copyright (C) 2015-16 Martin Prout
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package monkstone.arcball;
/**
*
* @author Martin Prout
*/
public final class Jvector {
static final double EPSILON = 9.999999747378752E-5f;
/**
*
*/
public double x;
/**
*
*/
public double y;
/**
*
*/
public double z;
/**
*
* @param x
* @param y
* @param z
*/
public Jvector(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
*
*/
public Jvector() {
this(0.0f, 0.0f, 0.0f);
}
/**
*
* @param vect
*/
public Jvector(Jvector vect) {
this(vect.x, vect.y, vect.z);
}
/**
*
* @param other
* @return subtracted vector
*/
public Jvector sub(Jvector other) {
return new Jvector(this.x - other.x, this.y - other.y, this.z - other.z);
}
/**
*
* @param scalar
* @return subtracted vector
*/
public Jvector mult(double scalar) {
return new Jvector(this.x * scalar, this.y * scalar, this.z * scalar);
}
/**
*
* @return magnitude float
*/
public double mag() {
return Math.sqrt(x * x + y * y + z * z);
}
/**
* The usual normalize
*
* @return this Jvector
*/
public Jvector normalize() {
double mag = Math.sqrt(x * x + y * y + z * z);
this.x /= mag;
this.y /= mag;
this.z /= mag;
return this;
}
/**
*
* @param other
* @return new dot product
*/
public double dot(Jvector other) {
return x * other.x + y * other.y + z * other.z;
}
/**
*
* @param other
* @return new cross product
*/
public Jvector cross(Jvector other) {
double xc = y * other.z - z * other.y;
double yc = z * other.x - x * other.z;
double zc = x * other.y - y * other.x;
return new Jvector(xc, yc, zc);
}
/**
*
* @param other
* @return boolean
*/
public boolean equals(Jvector other) {
if (other instanceof Jvector) {
if (Math.abs(this.x - other.x) > EPSILON) {
return false;
}
if (Math.abs(this.y - other.y) > EPSILON) {
return false;
}
return (Math.abs(this.z - other.z) > EPSILON);
}
return false;
}
/**
*
* @param obj
* @return boolean
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Jvector other = (Jvector) obj;
if (Double.doubleToLongBits(this.x) != Double.doubleToLongBits(other.x)) {
return false;
}
if (Double.doubleToLongBits(this.y) != Double.doubleToLongBits(other.y)) {
return false;
}
return (Double.doubleToLongBits(this.z) != Double.doubleToLongBits(other.z));
}
/**
*
* @return has int
*/
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32));
hash = 97 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32));
hash = 97 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32));
return hash;
}
}
| jashkenas/ruby-processing | src/monkstone/arcball/Jvector.java |
179,928 | // Copyright 2014 nilangshah - offered under the terms of the MIT License
package kilim.concurrent;
//"Inspired directly by Martin's work --> https://github.com/mjpt777/examples"
import kilim.MailboxSPSC;
import kilim.Pausable;
import kilim.Task;
public class SPSCQueue<T> {
protected T[] buffer;
public final VolatileLongCell tail = new VolatileLongCell(0L);
public final VolatileLongCell head = new VolatileLongCell(0L);
protected final int mask;
public static class PaddedLong {
public volatile long p11, p21, p31, p41, p51, p61;
public long value = 0;
public volatile long p1, p2, p3, p4, p5, p6;
}
protected final PaddedLong tailCache = new PaddedLong();
protected final PaddedLong headCache = new PaddedLong();
@SuppressWarnings("unchecked")
public SPSCQueue(int initialSize) {
if (initialSize < 1)
throw new IllegalArgumentException("initialSize: " + initialSize
+ " cannot be less then 1");
initialSize = findNextPositivePowerOfTwo(initialSize); // Convert
// mailbox size
// to power of 2
buffer = (T[]) new Object[initialSize];
mask = initialSize - 1;
}
public static int findNextPositivePowerOfTwo(final int value) {
return 1 << (32 - Integer.numberOfLeadingZeros(value - 1));
}
public T poll() {
T msg = null;
final long currentHead = head.get();
boolean flag = false;
if (currentHead >= tailCache.value) {
tailCache.value = tail.get();
if (currentHead >= tailCache.value) {
return null;
}
}
if (!flag) {
final int index = (int) currentHead & mask;
msg = buffer[index];
buffer[index] = null;
head.lazySet(currentHead + 1);
}
return msg;
}
public boolean offer(T msg) {
if (msg == null) {
throw new NullPointerException("Null is not a valid element");
}
final long currentTail = tail.get();
final long wrapPoint = currentTail - buffer.length;
if (headCache.value <= wrapPoint) {
headCache.value = head.get();
if (headCache.value <= wrapPoint) {
return false;
}
}
buffer[(int) currentTail & mask] = msg;
tail.lazySet(currentTail + 1);
return true;
}
public void putMailbox(T[] buf,MailboxSPSC mb) throws Pausable {
long currentTail = tail.get();
int n = buf.length;
for (int i = 0; i < n; i++) {
if (buf[i] == null) {
throw new NullPointerException("Null is not a valid element");
}
}
int count = 0;
Task t = Task.getCurrentTask();
boolean available = false;
int m = buffer.length;
while (n != count) {
long wrapPoint = currentTail - m;
while (headCache.value <= wrapPoint) {
headCache.value = head.get();
if (headCache.value <= wrapPoint) {
if (available) {
// we have put atleast one new message so we should wake
// up if someone is waiting for message
tail.lazySet(currentTail);
}
mb.subscribe(available,t,true);
available = false;
}
}
buffer[(int) (currentTail++) & mask] = buf[count++];
available = true;
}
tail.lazySet(currentTail);
mb.subscribe(true,t,false);
}
public boolean fillnb(T[] msg) {
int n = msg.length;
long currentHead = head.get();
if ((currentHead + n) > tailCache.value) {
tailCache.value = tail.get();
}
n = (int) Math.min(tailCache.value - currentHead, n);
if (n == 0) {
return false;
}
int i = 0;
do {
final int index = (int) (currentHead++) & mask;
msg[i++] = buffer[index];
buffer[index] = null;
} while (0 != --n);
head.lazySet(currentHead);
return true;
}
public boolean isEmpty() {
headCache.value = head.get();
return (buffer[(int) headCache.value & mask]==null);
}
public boolean hasSpace() {
tailCache.value = tail.get();
return (buffer[(int) tailCache.value & mask] == null);
}
public int size() {
return (int) (tail.get() - head.get());
}
}
| kilim/kilim | src/kilim/concurrent/SPSCQueue.java |
179,929 | /*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package org.jdesktop.swingx.mapviewer;
/**
* Notified when the status of a tile has changed
* @author Martin Steiger
*/
public interface TileListener
{
/**
* Notification when a tile is loaded
* @param tile the tile
*/
public void tileLoaded(Tile tile);
}
| DSheirer/sdrtrunk | src/main/java/org/jdesktop/swingx/mapviewer/TileListener.java |
179,930 | /*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna.input;
/**
* This enum is a categorization of the various keys available on a normal computer keyboard that are usable
* (detectable) by a terminal environment. For ordinary numbers, letters and symbols, the enum value is <i>Character</i>
* but please keep in mind that newline and tab, usually represented by \n and \t, are considered their own separate
* values by this enum (<i>Enter</i> and <i>Tab</i>).
* <p>
* Previously (before Lanterna 3.0), this enum was embedded inside the Key class.
*
* @author Martin
*/
public enum KeyType {
/**
* This value corresponds to a regular character 'typed', usually alphanumeric or a symbol. The one special case
* here is the enter key which could be expected to be returned as a '\n' character but is actually returned as a
* separate {@code KeyType} (see below). Tab, backspace and some others works this way too.
*/
CHARACTER,
ESCAPE,
BACKSPACE,
ARROW_LEFT,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN,
INSERT,
DELETE,
HOME,
END,
PAGE_UP,
PAGE_DOWN,
TAB,
REVERSE_TAB,
ENTER,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
KEY_TYPE,
//"Virtual" KeyStroke types
/**
* This value is only internally within Lanterna to understand where the cursor currently is, it's not expected to
* be returned by the API to an input read call.
*/
CURSOR_LOCATION,
/**
* This type is not really a key stroke but actually a 'catch-all' for mouse related events. Please note that mouse
* event capturing must first be enabled and many terminals don't suppose this extension at all.
*/
MOUSE_EVENT,
/**
* This value is returned when you try to read input and the input stream has been closed.
*/
EOF,
;
}
| mabe02/lanterna | src/main/java/com/googlecode/lanterna/input/KeyType.java |
179,931 | package com.dexvis.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import com.dexvis.exception.MissingPropertyException;
/**
*
* This class offers convenience functions for retrieving properties.
*
* @author Patrick E. Martin
* @version 1.0
*
*/
public class PropertyUtil
{
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
public static String getString(Properties properties, String property)
throws MissingPropertyException
{
if (properties.containsKey(property))
{
return properties.getProperty(property);
}
throw new MissingPropertyException("Property: '" + property
+ "' has not been defined.");
}
public static String getString(Properties properties, String property,
String defaultValue)
{
if (properties.containsKey(property))
{
return properties.getProperty(property);
}
return defaultValue;
}
public boolean getBoolean(Properties properties, String property)
throws MissingPropertyException
{
if (properties.containsKey(property))
{
return properties.getProperty(property).equalsIgnoreCase("true");
}
throw new MissingPropertyException("Property: '" + property
+ "' has not been defined.");
}
public boolean getBoolean(Properties properties, String property,
boolean defaultValue)
{
if (properties.containsKey(property))
{
return properties.getProperty(property).equalsIgnoreCase("true");
}
return defaultValue;
}
public Integer getInteger(Properties properties, String property)
throws MissingPropertyException
{
if (properties.containsKey(property))
{
return new Integer(properties.getProperty(property));
}
throw new MissingPropertyException("Property: '" + property
+ "' has not been defined.");
}
public Integer getInteger(Properties properties, String property,
int defaultValue)
{
return getInteger(properties, property, new Integer(defaultValue));
}
public Integer getInteger(Properties properties, String property,
Integer defaultValue)
{
if (properties.containsKey(property))
{
return new Integer(properties.getProperty(property));
}
return defaultValue;
}
public Double getDouble(Properties properties, String property)
throws MissingPropertyException
{
if (properties.containsKey(property))
{
return new Double(properties.getProperty(property));
}
throw new MissingPropertyException("Property: '" + property
+ "' has not been defined.");
}
public Double getDouble(Properties properties, String property,
double defaultValue)
{
return getDouble(properties, property, new Double(defaultValue));
}
public Double getDouble(Properties properties, String property,
Double defaultValue)
{
if (properties.containsKey(property))
{
return new Double(properties.getProperty(property));
}
return defaultValue;
}
public Date getDate(Properties properties, String property)
throws MissingPropertyException, ParseException
{
if (properties.containsKey(property))
{
return dateFormat.parse(properties.getProperty(property));
}
throw new MissingPropertyException("Property: '" + property
+ "' has not been defined.");
}
public Date getDate(Properties properties, String property, Date defaultValue)
{
return getDate(properties, property, defaultValue);
}
}
| PatMartin/Dex | src/com/dexvis/util/PropertyUtil.java |
179,932 | /* This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package cc.mallet.classify;
import java.util.HashMap;
import java.util.TreeMap;
import cc.mallet.classify.Classification;
import cc.mallet.classify.Classifier;
import cc.mallet.pipe.Pipe;
import cc.mallet.types.Instance;
import cc.mallet.types.Label;
/**
* A Classifier that will return the most frequent class label based on a training set.
* The Classifier needs to be trained using the MostFrequentClassAssignmentTrainer.
*
* @see MostFrequentClassAssignmentTrainer
*
* @author Martin Wunderlich <a href="mailto:martin@wunderlich.com">martin@wunderlich.com</a>
*/
public class MostFrequentClassifier extends Classifier {
TreeMap<String, Integer> sortedLabelMap = new TreeMap<String, Integer>();
HashMap<String, Label> labels = new HashMap<String, Label>();
/**
*
*/
private static final long serialVersionUID = -2685212760735255652L;
public MostFrequentClassifier(Pipe instancePipe) {
this.instancePipe = instancePipe;
}
/**
* Classify an instance using the most frequent class label.
*
* @param Instance to be classified. Data field must be a FeatureVector.
* @return Classification containing the labeling of the instance.
*/
@Override
public Classification classify(Instance instance) {
String mostFrequentLabelStr = this.sortedLabelMap.firstEntry().getKey();
Label mostFrequentLabel = this.labels.get(mostFrequentLabelStr);
Classification mostFrequentClassification = new Classification(instance, this, mostFrequentLabel);
return mostFrequentClassification;
}
public void addTargetLabel(Label label) {
String labelEntry = (String) label.getEntry();
if(! this.labels.containsKey(labelEntry) ) {
this.sortedLabelMap.put(labelEntry, Integer.valueOf(1));
this.labels.put(labelEntry, label);
}
else {
Integer oldCount = this.sortedLabelMap.get(labelEntry);
Integer newCount = oldCount + 1;
this.sortedLabelMap.put(labelEntry, newCount);
this.labels.put(labelEntry, label);
}
}
}
| mimno/Mallet | src/cc/mallet/classify/MostFrequentClassifier.java |
179,934 | package com.dexvis.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.dexvis.exception.MissingOptionException;
/**
*
* This class offers a mechanism for reading arguments from the command line.
*
* @author Patrick E. Martin
* @version 1.0
*
*/
public class Options
{
private Map<String, String> defaultOptions;
private Properties options;
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
public Options(String args[])
{
this(args, new HashMap<String, String>());
}
public Options(String args[], Map<String, String> defaultOptions)
{
this.defaultOptions = defaultOptions;
this.options = new Properties();
String curOption = "UNDEFINED";
for (int i = 0; i < args.length; i++)
{
// It's an option specifier.
if (args[i].startsWith("-"))
{
curOption = args[i].substring(1).trim();
options.put(curOption, Boolean.TRUE.toString());
}
// It's an option, set it.
else
{
options.put(curOption, args[i]);
}
}
}
public String getString(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return options.getProperty(option);
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option);
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public String getString(String option, String defaultOption)
{
if (options.containsKey(option))
{
return options.getProperty(option);
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option);
}
return defaultOption;
}
public boolean getBoolean(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return options.getProperty(option).equalsIgnoreCase("true");
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option).equalsIgnoreCase("true");
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public boolean getBoolean(String option, boolean defaultOption)
{
if (options.containsKey(option))
{
return options.getProperty(option).equalsIgnoreCase("true");
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option).equalsIgnoreCase("true");
}
return defaultOption;
}
public Integer getInteger(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return new Integer(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Integer(defaultOptions.get(option));
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public Integer getInteger(String option, int defaultOption)
{
return getInteger(option, new Integer(defaultOption));
}
public Integer getInteger(String option, Integer defaultOption)
{
if (options.containsKey(option))
{
return new Integer(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Integer(defaultOptions.get(option));
}
return defaultOption;
}
public Double getDouble(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return new Double(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Double(defaultOptions.get(option));
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public Double getDouble(String option, double defaultOption)
{
return getDouble(option, new Double(defaultOption));
}
public Double getDouble(String option, Double defaultOption)
{
if (options.containsKey(option))
{
return new Double(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Double(defaultOptions.get(option));
}
return defaultOption;
}
public Date getDate(String option) throws MissingOptionException,
ParseException
{
if (options.containsKey(option))
{
return dateFormat.parse(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return dateFormat.parse(defaultOptions.get(option));
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public Date getDate(String option, Date defaultOption)
{
return getDate(option, defaultOption);
}
public Properties getProperties()
{
return options;
}
}
| PatMartin/Dex | src/com/dexvis/util/Options.java |
179,935 | /*
* Written by Doug Lea and Martin Buchholz with assistance from members of
* JCP JSR-166 Expert Group and released to the public domain, as explained
* at http://creativecommons.org/publicdomain/zero/1.0/
*/
package jsr166y;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;
/**
* An unbounded concurrent {@linkplain Deque deque} based on linked nodes.
* Concurrent insertion, removal, and access operations execute safely
* across multiple threads.
* A {@code ConcurrentLinkedDeque} is an appropriate choice when
* many threads will share access to a common collection.
* Like most other concurrent collection implementations, this class
* does not permit the use of {@code null} elements.
*
* <p>Iterators are <i>weakly consistent</i>, returning elements
* reflecting the state of the deque at some point at or since the
* creation of the iterator. They do <em>not</em> throw {@link
* java.util.ConcurrentModificationException
* ConcurrentModificationException}, and may proceed concurrently with
* other operations.
*
* <p>Beware that, unlike in most collections, the {@code size} method
* is <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these deques, determining the current number
* of elements requires a traversal of the elements, and so may report
* inaccurate results if this collection is modified during traversal.
* Additionally, the bulk operations {@code addAll},
* {@code removeAll}, {@code retainAll}, {@code containsAll},
* {@code equals}, and {@code toArray} are <em>not</em> guaranteed
* to be performed atomically. For example, an iterator operating
* concurrently with an {@code addAll} operation might view only some
* of the added elements.
*
* <p>This class and its iterator implement all of the <em>optional</em>
* methods of the {@link Deque} and {@link Iterator} interfaces.
*
* <p>Memory consistency effects: As with other concurrent collections,
* actions in a thread prior to placing an object into a
* {@code ConcurrentLinkedDeque}
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
* actions subsequent to the access or removal of that element from
* the {@code ConcurrentLinkedDeque} in another thread.
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.7
* @author Doug Lea
* @author Martin Buchholz
* @param <E> the type of elements held in this collection
*/
public class ConcurrentLinkedDeque<E>
extends AbstractCollection<E>
implements Deque<E>, java.io.Serializable {
/*
* This is an implementation of a concurrent lock-free deque
* supporting interior removes but not interior insertions, as
* required to support the entire Deque interface.
*
* We extend the techniques developed for ConcurrentLinkedQueue and
* LinkedTransferQueue (see the internal docs for those classes).
* Understanding the ConcurrentLinkedQueue implementation is a
* prerequisite for understanding the implementation of this class.
*
* The data structure is a symmetrical doubly-linked "GC-robust"
* linked list of nodes. We minimize the number of volatile writes
* using two techniques: advancing multiple hops with a single CAS
* and mixing volatile and non-volatile writes of the same memory
* locations.
*
* A node contains the expected E ("item") and links to predecessor
* ("prev") and successor ("next") nodes:
*
* class Node<E> { volatile Node<E> prev, next; volatile E item; }
*
* A node p is considered "live" if it contains a non-null item
* (p.item != null). When an item is CASed to null, the item is
* atomically logically deleted from the collection.
*
* At any time, there is precisely one "first" node with a null
* prev reference that terminates any chain of prev references
* starting at a live node. Similarly there is precisely one
* "last" node terminating any chain of next references starting at
* a live node. The "first" and "last" nodes may or may not be live.
* The "first" and "last" nodes are always mutually reachable.
*
* A new element is added atomically by CASing the null prev or
* next reference in the first or last node to a fresh node
* containing the element. The element's node atomically becomes
* "live" at that point.
*
* A node is considered "active" if it is a live node, or the
* first or last node. Active nodes cannot be unlinked.
*
* A "self-link" is a next or prev reference that is the same node:
* p.prev == p or p.next == p
* Self-links are used in the node unlinking process. Active nodes
* never have self-links.
*
* A node p is active if and only if:
*
* p.item != null ||
* (p.prev == null && p.next != p) ||
* (p.next == null && p.prev != p)
*
* The deque object has two node references, "head" and "tail".
* The head and tail are only approximations to the first and last
* nodes of the deque. The first node can always be found by
* following prev pointers from head; likewise for tail. However,
* it is permissible for head and tail to be referring to deleted
* nodes that have been unlinked and so may not be reachable from
* any live node.
*
* There are 3 stages of node deletion;
* "logical deletion", "unlinking", and "gc-unlinking".
*
* 1. "logical deletion" by CASing item to null atomically removes
* the element from the collection, and makes the containing node
* eligible for unlinking.
*
* 2. "unlinking" makes a deleted node unreachable from active
* nodes, and thus eventually reclaimable by GC. Unlinked nodes
* may remain reachable indefinitely from an iterator.
*
* Physical node unlinking is merely an optimization (albeit a
* critical one), and so can be performed at our convenience. At
* any time, the set of live nodes maintained by prev and next
* links are identical, that is, the live nodes found via next
* links from the first node is equal to the elements found via
* prev links from the last node. However, this is not true for
* nodes that have already been logically deleted - such nodes may
* be reachable in one direction only.
*
* 3. "gc-unlinking" takes unlinking further by making active
* nodes unreachable from deleted nodes, making it easier for the
* GC to reclaim future deleted nodes. This step makes the data
* structure "gc-robust", as first described in detail by Boehm
* (http://portal.acm.org/citation.cfm?doid=503272.503282).
*
* GC-unlinked nodes may remain reachable indefinitely from an
* iterator, but unlike unlinked nodes, are never reachable from
* head or tail.
*
* Making the data structure GC-robust will eliminate the risk of
* unbounded memory retention with conservative GCs and is likely
* to improve performance with generational GCs.
*
* When a node is dequeued at either end, e.g. via poll(), we would
* like to break any references from the node to active nodes. We
* develop further the use of self-links that was very effective in
* other concurrent collection classes. The idea is to replace
* prev and next pointers with special values that are interpreted
* to mean off-the-list-at-one-end. These are approximations, but
* good enough to preserve the properties we want in our
* traversals, e.g. we guarantee that a traversal will never visit
* the same element twice, but we don't guarantee whether a
* traversal that runs out of elements will be able to see more
* elements later after enqueues at that end. Doing gc-unlinking
* safely is particularly tricky, since any node can be in use
* indefinitely (for example by an iterator). We must ensure that
* the nodes pointed at by head/tail never get gc-unlinked, since
* head/tail are needed to get "back on track" by other nodes that
* are gc-unlinked. gc-unlinking accounts for much of the
* implementation complexity.
*
* Since neither unlinking nor gc-unlinking are necessary for
* correctness, there are many implementation choices regarding
* frequency (eagerness) of these operations. Since volatile
* reads are likely to be much cheaper than CASes, saving CASes by
* unlinking multiple adjacent nodes at a time may be a win.
* gc-unlinking can be performed rarely and still be effective,
* since it is most important that long chains of deleted nodes
* are occasionally broken.
*
* The actual representation we use is that p.next == p means to
* goto the first node (which in turn is reached by following prev
* pointers from head), and p.next == null && p.prev == p means
* that the iteration is at an end and that p is a (static final)
* dummy node, NEXT_TERMINATOR, and not the last active node.
* Finishing the iteration when encountering such a TERMINATOR is
* good enough for read-only traversals, so such traversals can use
* p.next == null as the termination condition. When we need to
* find the last (active) node, for enqueueing a new node, we need
* to check whether we have reached a TERMINATOR node; if so,
* restart traversal from tail.
*
* The implementation is completely directionally symmetrical,
* except that most public methods that iterate through the list
* follow next pointers ("forward" direction).
*
* We believe (without full proof) that all single-element deque
* operations (e.g., addFirst, peekLast, pollLast) are linearizable
* (see Herlihy and Shavit's book). However, some combinations of
* operations are known not to be linearizable. In particular,
* when an addFirst(A) is racing with pollFirst() removing B, it is
* possible for an observer iterating over the elements to observe
* A B C and subsequently observe A C, even though no interior
* removes are ever performed. Nevertheless, iterators behave
* reasonably, providing the "weakly consistent" guarantees.
*
* Empirically, microbenchmarks suggest that this class adds about
* 40% overhead relative to ConcurrentLinkedQueue, which feels as
* good as we can hope for.
*/
private static final long serialVersionUID = 876323262645176354L;
/**
* A node from which the first node on list (that is, the unique node p
* with p.prev == null && p.next != p) can be reached in O(1) time.
* Invariants:
* - the first node is always O(1) reachable from head via prev links
* - all live nodes are reachable from the first node via succ()
* - head != null
* - (tmp = head).next != tmp || tmp != head
* - head is never gc-unlinked (but may be unlinked)
* Non-invariants:
* - head.item may or may not be null
* - head may not be reachable from the first or last node, or from tail
*/
private transient volatile Node<E> head;
/**
* A node from which the last node on list (that is, the unique node p
* with p.next == null && p.prev != p) can be reached in O(1) time.
* Invariants:
* - the last node is always O(1) reachable from tail via next links
* - all live nodes are reachable from the last node via pred()
* - tail != null
* - tail is never gc-unlinked (but may be unlinked)
* Non-invariants:
* - tail.item may or may not be null
* - tail may not be reachable from the first or last node, or from head
*/
private transient volatile Node<E> tail;
private static final Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR;
@SuppressWarnings("unchecked")
Node<E> prevTerminator() {
return (Node<E>) PREV_TERMINATOR;
}
@SuppressWarnings("unchecked")
Node<E> nextTerminator() {
return (Node<E>) NEXT_TERMINATOR;
}
static final class Node<E> {
volatile Node<E> prev;
volatile E item;
volatile Node<E> next;
Node() { // default constructor for NEXT_TERMINATOR, PREV_TERMINATOR
}
/**
* Constructs a new node. Uses relaxed write because item can
* only be seen after publication via casNext or casPrev.
*/
Node(E item) {
UNSAFE.putObject(this, itemOffset, item);
}
boolean casItem(E cmp, E val) {
return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
}
void lazySetNext(Node<E> val) {
UNSAFE.putOrderedObject(this, nextOffset, val);
}
boolean casNext(Node<E> cmp, Node<E> val) {
return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
}
void lazySetPrev(Node<E> val) {
UNSAFE.putOrderedObject(this, prevOffset, val);
}
boolean casPrev(Node<E> cmp, Node<E> val) {
return UNSAFE.compareAndSwapObject(this, prevOffset, cmp, val);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long prevOffset;
private static final long itemOffset;
private static final long nextOffset;
static {
try {
UNSAFE = getUnsafe();
Class<?> k = Node.class;
prevOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("prev"));
itemOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("item"));
nextOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("next"));
} catch (Exception e) {
throw new Error(e);
}
}
}
/**
* Links e as first element.
*/
private void linkFirst(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);
restartFromHead:
for (;;)
for (Node<E> h = head, p = h, q;;) {
if ((q = p.prev) != null &&
(q = (p = q).prev) != null)
// Check for head updates every other hop.
// If p == q, we are sure to follow head instead.
p = (h != (h = head)) ? h : q;
else if (p.next == p) // PREV_TERMINATOR
continue restartFromHead;
else {
// p is first node
newNode.lazySetNext(p); // CAS piggyback
if (p.casPrev(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this deque,
// and for newNode to become "live".
if (p != h) // hop two nodes at a time
casHead(h, newNode); // Failure is OK.
return;
}
// Lost CAS race to another thread; re-read prev
}
}
}
/**
* Links e as last element.
*/
private void linkLast(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p.prev == p) // NEXT_TERMINATOR
continue restartFromTail;
else {
// p is last node
newNode.lazySetPrev(p); // CAS piggyback
if (p.casNext(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this deque,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time
casTail(t, newNode); // Failure is OK.
return;
}
// Lost CAS race to another thread; re-read next
}
}
}
private static final int HOPS = 2;
/**
* Unlinks non-null node x.
*/
void unlink(Node<E> x) {
// assert x != null;
// assert x.item == null;
// assert x != PREV_TERMINATOR;
// assert x != NEXT_TERMINATOR;
final Node<E> prev = x.prev;
final Node<E> next = x.next;
if (prev == null) {
unlinkFirst(x, next);
} else if (next == null) {
unlinkLast(x, prev);
} else {
// Unlink interior node.
//
// This is the common case, since a series of polls at the
// same end will be "interior" removes, except perhaps for
// the first one, since end nodes cannot be unlinked.
//
// At any time, all active nodes are mutually reachable by
// following a sequence of either next or prev pointers.
//
// Our strategy is to find the unique active predecessor
// and successor of x. Try to fix up their links so that
// they point to each other, leaving x unreachable from
// active nodes. If successful, and if x has no live
// predecessor/successor, we additionally try to gc-unlink,
// leaving active nodes unreachable from x, by rechecking
// that the status of predecessor and successor are
// unchanged and ensuring that x is not reachable from
// tail/head, before setting x's prev/next links to their
// logical approximate replacements, self/TERMINATOR.
Node<E> activePred, activeSucc;
boolean isFirst, isLast;
int hops = 1;
// Find active predecessor
for (Node<E> p = prev; ; ++hops) {
if (p.item != null) {
activePred = p;
isFirst = false;
break;
}
Node<E> q = p.prev;
if (q == null) {
if (p.next == p)
return;
activePred = p;
isFirst = true;
break;
}
else if (p == q)
return;
else
p = q;
}
// Find active successor
for (Node<E> p = next; ; ++hops) {
if (p.item != null) {
activeSucc = p;
isLast = false;
break;
}
Node<E> q = p.next;
if (q == null) {
if (p.prev == p)
return;
activeSucc = p;
isLast = true;
break;
}
else if (p == q)
return;
else
p = q;
}
// TODO: better HOP heuristics
if (hops < HOPS
// always squeeze out interior deleted nodes
&& (isFirst | isLast))
return;
// Squeeze out deleted nodes between activePred and
// activeSucc, including x.
skipDeletedSuccessors(activePred);
skipDeletedPredecessors(activeSucc);
// Try to gc-unlink, if possible
if ((isFirst | isLast) &&
// Recheck expected state of predecessor and successor
(activePred.next == activeSucc) &&
(activeSucc.prev == activePred) &&
(isFirst ? activePred.prev == null : activePred.item != null) &&
(isLast ? activeSucc.next == null : activeSucc.item != null)) {
updateHead(); // Ensure x is not reachable from head
updateTail(); // Ensure x is not reachable from tail
// Finally, actually gc-unlink
x.lazySetPrev(isFirst ? prevTerminator() : x);
x.lazySetNext(isLast ? nextTerminator() : x);
}
}
}
/**
* Unlinks non-null first node.
*/
private void unlinkFirst(Node<E> first, Node<E> next) {
// assert first != null;
// assert next != null;
// assert first.item == null;
for (Node<E> o = null, p = next, q;;) {
if (p.item != null || (q = p.next) == null) {
if (o != null && p.prev != p && first.casNext(next, p)) {
skipDeletedPredecessors(p);
if (first.prev == null &&
(p.next == null || p.item != null) &&
p.prev == first) {
updateHead(); // Ensure o is not reachable from head
updateTail(); // Ensure o is not reachable from tail
// Finally, actually gc-unlink
o.lazySetNext(o);
o.lazySetPrev(prevTerminator());
}
}
return;
}
else if (p == q)
return;
else {
o = p;
p = q;
}
}
}
/**
* Unlinks non-null last node.
*/
private void unlinkLast(Node<E> last, Node<E> prev) {
// assert last != null;
// assert prev != null;
// assert last.item == null;
for (Node<E> o = null, p = prev, q;;) {
if (p.item != null || (q = p.prev) == null) {
if (o != null && p.next != p && last.casPrev(prev, p)) {
skipDeletedSuccessors(p);
if (last.next == null &&
(p.prev == null || p.item != null) &&
p.next == last) {
updateHead(); // Ensure o is not reachable from head
updateTail(); // Ensure o is not reachable from tail
// Finally, actually gc-unlink
o.lazySetPrev(o);
o.lazySetNext(nextTerminator());
}
}
return;
}
else if (p == q)
return;
else {
o = p;
p = q;
}
}
}
/**
* Guarantees that any node which was unlinked before a call to
* this method will be unreachable from head after it returns.
* Does not guarantee to eliminate slack, only that head will
* point to a node that was active while this method was running.
*/
private final void updateHead() {
// Either head already points to an active node, or we keep
// trying to cas it to the first node until it does.
Node<E> h, p, q;
restartFromHead:
while ((h = head).item == null && (p = h.prev) != null) {
for (;;) {
if ((q = p.prev) == null ||
(q = (p = q).prev) == null) {
// It is possible that p is PREV_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
if (casHead(h, p))
return;
else
continue restartFromHead;
}
else if (h != head)
continue restartFromHead;
else
p = q;
}
}
}
/**
* Guarantees that any node which was unlinked before a call to
* this method will be unreachable from tail after it returns.
* Does not guarantee to eliminate slack, only that tail will
* point to a node that was active while this method was running.
*/
private final void updateTail() {
// Either tail already points to an active node, or we keep
// trying to cas it to the last node until it does.
Node<E> t, p, q;
restartFromTail:
while ((t = tail).item == null && (p = t.next) != null) {
for (;;) {
if ((q = p.next) == null ||
(q = (p = q).next) == null) {
// It is possible that p is NEXT_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
if (casTail(t, p))
return;
else
continue restartFromTail;
}
else if (t != tail)
continue restartFromTail;
else
p = q;
}
}
}
private void skipDeletedPredecessors(Node<E> x) {
whileActive:
do {
Node<E> prev = x.prev;
// assert prev != null;
// assert x != NEXT_TERMINATOR;
// assert x != PREV_TERMINATOR;
Node<E> p = prev;
findActive:
for (;;) {
if (p.item != null)
break findActive;
Node<E> q = p.prev;
if (q == null) {
if (p.next == p)
continue whileActive;
break findActive;
}
else if (p == q)
continue whileActive;
else
p = q;
}
// found active CAS target
if (prev == p || x.casPrev(prev, p))
return;
} while (x.item != null || x.next == null);
}
private void skipDeletedSuccessors(Node<E> x) {
whileActive:
do {
Node<E> next = x.next;
// assert next != null;
// assert x != NEXT_TERMINATOR;
// assert x != PREV_TERMINATOR;
Node<E> p = next;
findActive:
for (;;) {
if (p.item != null)
break findActive;
Node<E> q = p.next;
if (q == null) {
if (p.prev == p)
continue whileActive;
break findActive;
}
else if (p == q)
continue whileActive;
else
p = q;
}
// found active CAS target
if (next == p || x.casNext(next, p))
return;
} while (x.item != null || x.prev == null);
}
/**
* Returns the successor of p, or the first node if p.next has been
* linked to self, which will only be true if traversing with a
* stale pointer that is now off the list.
*/
final Node<E> succ(Node<E> p) {
// TODO: should we skip deleted nodes here?
Node<E> q = p.next;
return (p == q) ? first() : q;
}
/**
* Returns the predecessor of p, or the last node if p.prev has been
* linked to self, which will only be true if traversing with a
* stale pointer that is now off the list.
*/
final Node<E> pred(Node<E> p) {
Node<E> q = p.prev;
return (p == q) ? last() : q;
}
/**
* Returns the first node, the unique node p for which:
* p.prev == null && p.next != p
* The returned node may or may not be logically deleted.
* Guarantees that head is set to the returned node.
*/
Node<E> first() {
restartFromHead:
for (;;)
for (Node<E> h = head, p = h, q;;) {
if ((q = p.prev) != null &&
(q = (p = q).prev) != null)
// Check for head updates every other hop.
// If p == q, we are sure to follow head instead.
p = (h != (h = head)) ? h : q;
else if (p == h
// It is possible that p is PREV_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
|| casHead(h, p))
return p;
else
continue restartFromHead;
}
}
/**
* Returns the last node, the unique node p for which:
* p.next == null && p.prev != p
* The returned node may or may not be logically deleted.
* Guarantees that tail is set to the returned node.
*/
Node<E> last() {
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p == t
// It is possible that p is NEXT_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
|| casTail(t, p))
return p;
else
continue restartFromTail;
}
}
// Minor convenience utilities
/**
* Throws NullPointerException if argument is null.
*
* @param v the element
*/
private static void checkNotNull(Object v) {
if (v == null)
throw new NullPointerException();
}
/**
* Returns element unless it is null, in which case throws
* NoSuchElementException.
*
* @param v the element
* @return the element
*/
private E screenNullResult(E v) {
if (v == null)
throw new NoSuchElementException();
return v;
}
/**
* Creates an array list and fills it with elements of this list.
* Used by toArray.
*
* @return the arrayList
*/
private ArrayList<E> toArrayList() {
ArrayList<E> list = new ArrayList<E>();
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null)
list.add(item);
}
return list;
}
/**
* Constructs an empty deque.
*/
public ConcurrentLinkedDeque() {
head = tail = new Node<E>(null);
}
/**
* Constructs a deque initially containing the elements of
* the given collection, added in traversal order of the
* collection's iterator.
*
* @param c the collection of elements to initially contain
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public ConcurrentLinkedDeque(Collection<? extends E> c) {
// Copy c into a private chain of Nodes
Node<E> h = null, t = null;
for (E e : c) {
checkNotNull(e);
Node<E> newNode = new Node<E>(e);
if (h == null)
h = t = newNode;
else {
t.lazySetNext(newNode);
newNode.lazySetPrev(t);
t = newNode;
}
}
initHeadTail(h, t);
}
/**
* Initializes head and tail, ensuring invariants hold.
*/
private void initHeadTail(Node<E> h, Node<E> t) {
if (h == t) {
if (h == null)
h = t = new Node<E>(null);
else {
// Avoid edge case of a single Node with non-null item.
Node<E> newNode = new Node<E>(null);
t.lazySetNext(newNode);
newNode.lazySetPrev(t);
t = newNode;
}
}
head = h;
tail = t;
}
/**
* Inserts the specified element at the front of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException}.
*
* @throws NullPointerException if the specified element is null
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Inserts the specified element at the end of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException}.
*
* <p>This method is equivalent to {@link #add}.
*
* @throws NullPointerException if the specified element is null
*/
public void addLast(E e) {
linkLast(e);
}
/**
* Inserts the specified element at the front of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @throws NullPointerException if the specified element is null
*/
public boolean offerFirst(E e) {
linkFirst(e);
return true;
}
/**
* Inserts the specified element at the end of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* <p>This method is equivalent to {@link #add}.
*
* @return {@code true} (as specified by {@link Deque#offerLast})
* @throws NullPointerException if the specified element is null
*/
public boolean offerLast(E e) {
linkLast(e);
return true;
}
public E peekFirst() {
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null)
return item;
}
return null;
}
public E peekLast() {
for (Node<E> p = last(); p != null; p = pred(p)) {
E item = p.item;
if (item != null)
return item;
}
return null;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getFirst() {
return screenNullResult(peekFirst());
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getLast() {
return screenNullResult(peekLast());
}
public E pollFirst() {
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null && p.casItem(item, null)) {
unlink(p);
return item;
}
}
return null;
}
public E pollLast() {
for (Node<E> p = last(); p != null; p = pred(p)) {
E item = p.item;
if (item != null && p.casItem(item, null)) {
unlink(p);
return item;
}
}
return null;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeFirst() {
return screenNullResult(pollFirst());
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeLast() {
return screenNullResult(pollLast());
}
// *** Queue and stack methods ***
/**
* Inserts the specified element at the tail of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* @return {@code true} (as specified by {@link Queue#offer})
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
return offerLast(e);
}
/**
* Inserts the specified element at the tail of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException} or return {@code false}.
*
* @return {@code true} (as specified by {@link Collection#add})
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
return offerLast(e);
}
public E poll() { return pollFirst(); }
public E remove() { return removeFirst(); }
public E peek() { return peekFirst(); }
public E element() { return getFirst(); }
public void push(E e) { addFirst(e); }
public E pop() { return removeFirst(); }
/**
* Removes the first element {@code e} such that
* {@code o.equals(e)}, if such an element exists in this deque.
* If the deque does not contain the element, it is unchanged.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean removeFirstOccurrence(Object o) {
checkNotNull(o);
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null && o.equals(item) && p.casItem(item, null)) {
unlink(p);
return true;
}
}
return false;
}
/**
* Removes the last element {@code e} such that
* {@code o.equals(e)}, if such an element exists in this deque.
* If the deque does not contain the element, it is unchanged.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean removeLastOccurrence(Object o) {
checkNotNull(o);
for (Node<E> p = last(); p != null; p = pred(p)) {
E item = p.item;
if (item != null && o.equals(item) && p.casItem(item, null)) {
unlink(p);
return true;
}
}
return false;
}
/**
* Returns {@code true} if this deque contains at least one
* element {@code e} such that {@code o.equals(e)}.
*
* @param o element whose presence in this deque is to be tested
* @return {@code true} if this deque contains the specified element
*/
public boolean contains(Object o) {
if (o == null) return false;
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null && o.equals(item))
return true;
}
return false;
}
/**
* Returns {@code true} if this collection contains no elements.
*
* @return {@code true} if this collection contains no elements
*/
public boolean isEmpty() {
return peekFirst() == null;
}
/**
* Returns the number of elements in this deque. If this deque
* contains more than {@code Integer.MAX_VALUE} elements, it
* returns {@code Integer.MAX_VALUE}.
*
* <p>Beware that, unlike in most collections, this method is
* <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these deques, determining the current
* number of elements requires traversing them all to count them.
* Additionally, it is possible for the size to change during
* execution of this method, in which case the returned result
* will be inaccurate. Thus, this method is typically not very
* useful in concurrent applications.
*
* @return the number of elements in this deque
*/
public int size() {
int count = 0;
for (Node<E> p = first(); p != null; p = succ(p))
if (p.item != null)
// Collection.size() spec says to max out
if (++count == Integer.MAX_VALUE)
break;
return count;
}
/**
* Removes the first element {@code e} such that
* {@code o.equals(e)}, if such an element exists in this deque.
* If the deque does not contain the element, it is unchanged.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
/**
* Appends all of the elements in the specified collection to the end of
* this deque, in the order that they are returned by the specified
* collection's iterator. Attempts to {@code addAll} of a deque to
* itself result in {@code IllegalArgumentException}.
*
* @param c the elements to be inserted into this deque
* @return {@code true} if this deque changed as a result of the call
* @throws NullPointerException if the specified collection or any
* of its elements are null
* @throws IllegalArgumentException if the collection is this deque
*/
public boolean addAll(Collection<? extends E> c) {
if (c == this)
// As historically specified in AbstractQueue#addAll
throw new IllegalArgumentException();
// Copy c into a private chain of Nodes
Node<E> beginningOfTheEnd = null, last = null;
for (E e : c) {
checkNotNull(e);
Node<E> newNode = new Node<E>(e);
if (beginningOfTheEnd == null)
beginningOfTheEnd = last = newNode;
else {
last.lazySetNext(newNode);
newNode.lazySetPrev(last);
last = newNode;
}
}
if (beginningOfTheEnd == null)
return false;
// Atomically append the chain at the tail of this collection
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p.prev == p) // NEXT_TERMINATOR
continue restartFromTail;
else {
// p is last node
beginningOfTheEnd.lazySetPrev(p); // CAS piggyback
if (p.casNext(null, beginningOfTheEnd)) {
// Successful CAS is the linearization point
// for all elements to be added to this deque.
if (!casTail(t, last)) {
// Try a little harder to update tail,
// since we may be adding many elements.
t = tail;
if (last.next == null)
casTail(t, last);
}
return true;
}
// Lost CAS race to another thread; re-read next
}
}
}
/**
* Removes all of the elements from this deque.
*/
public void clear() {
while (pollFirst() != null)
;
}
/**
* Returns an array containing all of the elements in this deque, in
* proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this deque. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this deque
*/
public Object[] toArray() {
return toArrayList().toArray();
}
/**
* Returns an array containing all of the elements in this deque,
* in proper sequence (from first to last element); the runtime
* type of the returned array is that of the specified array. If
* the deque fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of
* the specified array and the size of this deque.
*
* <p>If this deque fits in the specified array with room to spare
* (i.e., the array has more elements than this deque), the element in
* the array immediately following the end of the deque is set to
* {@code null}.
*
* <p>Like the {@link #toArray()} method, this method acts as
* bridge between array-based and collection-based APIs. Further,
* this method allows precise control over the runtime type of the
* output array, and may, under certain circumstances, be used to
* save allocation costs.
*
* <p>Suppose {@code x} is a deque known to contain only strings.
* The following code can be used to dump the deque into a newly
* allocated array of {@code String}:
*
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the deque are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this deque
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this deque
* @throws NullPointerException if the specified array is null
*/
public <T> T[] toArray(T[] a) {
return toArrayList().toArray(a);
}
/**
* Returns an iterator over the elements in this deque in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
*
* <p>The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
* ConcurrentModificationException}, and guarantees to traverse
* elements as they existed upon construction of the iterator, and
* may (but is not guaranteed to) reflect any modifications
* subsequent to construction.
*
* @return an iterator over the elements in this deque in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* Returns an iterator over the elements in this deque in reverse
* sequential order. The elements will be returned in order from
* last (tail) to first (head).
*
* <p>The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
* ConcurrentModificationException}, and guarantees to traverse
* elements as they existed upon construction of the iterator, and
* may (but is not guaranteed to) reflect any modifications
* subsequent to construction.
*
* @return an iterator over the elements in this deque in reverse order
*/
public Iterator<E> descendingIterator() {
return new DescendingItr();
}
private abstract class AbstractItr implements Iterator<E> {
/**
* Next node to return item for.
*/
private Node<E> nextNode;
/**
* nextItem holds on to item fields because once we claim
* that an element exists in hasNext(), we must return it in
* the following next() call even if it was in the process of
* being removed when hasNext() was called.
*/
private E nextItem;
/**
* Node returned by most recent call to next. Needed by remove.
* Reset to null if this element is deleted by a call to remove.
*/
private Node<E> lastRet;
abstract Node<E> startNode();
abstract Node<E> nextNode(Node<E> p);
AbstractItr() {
advance();
}
/**
* Sets nextNode and nextItem to next valid node, or to null
* if no such.
*/
private void advance() {
lastRet = nextNode;
Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
for (;; p = nextNode(p)) {
if (p == null) {
// p might be active end or TERMINATOR node; both are OK
nextNode = null;
nextItem = null;
break;
}
E item = p.item;
if (item != null) {
nextNode = p;
nextItem = item;
break;
}
}
}
public boolean hasNext() {
return nextItem != null;
}
public E next() {
E item = nextItem;
if (item == null) throw new NoSuchElementException();
advance();
return item;
}
public void remove() {
Node<E> l = lastRet;
if (l == null) throw new IllegalStateException();
l.item = null;
unlink(l);
lastRet = null;
}
}
/** Forward iterator */
private class Itr extends AbstractItr {
Node<E> startNode() { return first(); }
Node<E> nextNode(Node<E> p) { return succ(p); }
}
/** Descending iterator */
private class DescendingItr extends AbstractItr {
Node<E> startNode() { return last(); }
Node<E> nextNode(Node<E> p) { return pred(p); }
}
/**
* Saves the state to a stream (that is, serializes it).
*
* @serialData All of the elements (each an {@code E}) in
* the proper order, followed by a null
* @param s the stream
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden stuff
s.defaultWriteObject();
// Write out all elements in the proper order.
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null)
s.writeObject(item);
}
// Use trailing null as sentinel
s.writeObject(null);
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
* @param s the stream
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in elements until trailing null sentinel found
Node<E> h = null, t = null;
Object item;
while ((item = s.readObject()) != null) {
@SuppressWarnings("unchecked")
Node<E> newNode = new Node<E>((E) item);
if (h == null)
h = t = newNode;
else {
t.lazySetNext(newNode);
newNode.lazySetPrev(t);
t = newNode;
}
}
initHeadTail(h, t);
}
private boolean casHead(Node<E> cmp, Node<E> val) {
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
}
private boolean casTail(Node<E> cmp, Node<E> val) {
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long headOffset;
private static final long tailOffset;
static {
PREV_TERMINATOR = new Node<Object>();
PREV_TERMINATOR.next = PREV_TERMINATOR;
NEXT_TERMINATOR = new Node<Object>();
NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
try {
UNSAFE = getUnsafe();
Class<?> k = ConcurrentLinkedDeque.class;
headOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("head"));
tailOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("tail"));
} catch (Exception e) {
throw new Error(e);
}
}
/**
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
* Replace with a simple call to Unsafe.getUnsafe when integrating
* into a jdk.
*
* @return a sun.misc.Unsafe
*/
static sun.misc.Unsafe getUnsafe() {
try {
return sun.misc.Unsafe.getUnsafe();
} catch (SecurityException se) {
try {
return java.security.AccessController.doPrivileged
(new java.security
.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
java.lang.reflect.Field f = sun.misc
.Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (sun.misc.Unsafe) f.get(null);
}});
} catch (java.security.PrivilegedActionException e) {
throw new RuntimeException("Could not initialize intrinsics",
e.getCause());
}
}
}
}
| h2oai/h2o-3 | h2o-core/src/main/java/jsr166y/ConcurrentLinkedDeque.java |
179,936 | /*
* The MIT License
*
* Copyright 2015 Coinmate.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.knowm.xchange.coinmate;
import org.knowm.xchange.BaseExchange;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.coinmate.service.CoinmateAccountService;
import org.knowm.xchange.coinmate.service.CoinmateMarketDataService;
import org.knowm.xchange.coinmate.service.CoinmateMetadataServiceRaw;
import org.knowm.xchange.coinmate.service.CoinmateTradeService;
import org.knowm.xchange.exceptions.ExchangeException;
import java.io.IOException;
/** @author Martin Stachon */
public class CoinmateExchange extends BaseExchange implements Exchange {
@Override
protected void initServices() {
this.marketDataService = new CoinmateMarketDataService(this);
this.accountService = new CoinmateAccountService(this);
this.tradeService = new CoinmateTradeService(this);
}
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {
ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass());
exchangeSpecification.setSslUri("https://coinmate.io");
exchangeSpecification.setHost("coinmate.io");
exchangeSpecification.setPort(80);
exchangeSpecification.setExchangeName("CoinMate");
exchangeSpecification.setExchangeDescription("Bitcoin trading made simple.");
return exchangeSpecification;
}
@Override
public void remoteInit() throws IOException, ExchangeException {
CoinmateMetadataServiceRaw metadataService = new CoinmateMetadataServiceRaw(this);
exchangeMetaData = metadataService.getMetadata();
}
}
| knowm/XChange | xchange-coinmate/src/main/java/org/knowm/xchange/coinmate/CoinmateExchange.java |
179,937 | /*
* Copyright (C) 2003 Sun Microsystems, Inc.
* Copyright (C) 2003-2010 Martin Koegler
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
package com.iiordanov.bVNC;
import android.util.Log;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
import java.net.Socket;
import java.security.SecureRandom;
import java.security.Security;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public abstract class TLSTunnelBase {
private static final String TAG = "TLSTunnelBase";
Socket sock;
public TLSTunnelBase(Socket sock_) {
sock = sock_;
}
protected void initContext(SSLContext sc) throws java.security.GeneralSecurityException {
sc.init(null, null, new SecureRandom());
}
public SSLSocket setup() throws Exception {
try {
SSLSocketFactory sslfactory;
SSLSocket sslsock;
Security.setProperty("jdk.tls.disabledAlgorithms",
"SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, NULL");
Security.removeProvider(BouncyCastleJsseProvider.PROVIDER_NAME);
Security.insertProviderAt(new BouncyCastleJsseProvider(), 1);
SSLContext sc = SSLContext.getInstance("TLS", BouncyCastleJsseProvider.PROVIDER_NAME);
Log.i(TAG, "Generating TLS context");
initContext(sc);
Log.i(TAG, "Doing TLS handshake");
sslfactory = sc.getSocketFactory();
sslsock = (SSLSocket) sslfactory.createSocket(sock,
sock.getInetAddress().
getHostName(),
sock.getPort(), true);
sslsock.setTcpNoDelay(true);
sslsock.setSoTimeout(Constants.SOCKET_CONN_TIMEOUT);
setParam(sslsock);
sslsock.setSoTimeout(0);
/* Not necessary - just ensures that we know what cipher
* suite we are using for the output of toString()
*/
sslsock.startHandshake();
Log.i(TAG, "TLS done");
return sslsock;
} catch (java.io.IOException e) {
throw new Exception("TLS handshake failed " + e.toString());
} catch (java.security.GeneralSecurityException e) {
throw new Exception("TLS handshake failed " + e.toString());
}
}
protected abstract void setParam(SSLSocket sock) throws Exception;
}
| iiordanov/remote-desktop-clients | bVNC/src/main/java/com/iiordanov/bVNC/TLSTunnelBase.java |
179,938 | package com.tagtraum.perf.gcviewer.model;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An (artificial) {@link GCResource} that represents a collection of actual {@link GCResource}s that are to be
* treated as one consecutive log.
*
* @author martin.geldmacher
*/
public class GcResourceSeries extends AbstractGcResource {
private static final Logger logger = Logger.getLogger(GcResourceSeries.class.getName());
private static final AtomicInteger COUNT = new AtomicInteger(0);
private final List<GCResource> resourcesInOrder;
public GcResourceSeries(List<GCResource> resourcesInOrder) {
super(buildName(resourcesInOrder), Logger.getLogger("GCResourceSeries".concat(Integer.toString(COUNT.incrementAndGet()))));
this.resourcesInOrder = resourcesInOrder;
setLogger(resourcesInOrder);
}
private void setLogger(List<GCResource> resourcesInOrder) {
// Contained GCResource should use the same logger
for (GCResource resource : resourcesInOrder) {
resource.setLogger(getLogger());
}
}
public List<GCResource> getResourcesInOrder() {
return resourcesInOrder;
}
@Override
public boolean hasUnderlyingResourceChanged() {
// Assumption: Once a logfile has been rotated, it doesn't change anymore.
// Only the last logfile can be active. Check if it has changed.
return getLastGcResource().hasUnderlyingResourceChanged();
}
@Override
public void setModel(GCModel model) {
for (GCResource resource : resourcesInOrder) {
resource.setModel(model);
}
super.setModel(model);
}
private GCResource getLastGcResource() {
return resourcesInOrder.get(resourcesInOrder.size() - 1);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GcResourceSeries that = (GcResourceSeries) o;
return resourcesInOrder.equals(that.resourcesInOrder);
}
@Override
public int hashCode() {
return resourcesInOrder.hashCode();
}
@Override
public String toString() {
return "GCResourceSeries [resourceName=" + getResourceName() + ", isReload=" + isReload() + ", logger=" + getLogger() + ", model=" + getModel() + "]";
}
protected static String buildName(List<GCResource> resourcesInOrder) {
if (resourcesInOrder == null || resourcesInOrder.isEmpty())
throw new IllegalArgumentException("At least one GCResource expected!");
try {
GCResource first = resourcesInOrder.get(0);
GCResource last = resourcesInOrder.get(resourcesInOrder.size() - 1);
return buildName(first.getResourceName(), last.getResourceName());
}
catch (Exception ex) {
logger.log(Level.WARNING, "Failed to build name for GCResources. Reason: " + ex.getMessage());
logger.log(Level.FINER, "Details: ", ex);
return resourcesInOrder.get(0).getResourceName();
}
}
protected static String buildName(String first, String last) {
if (first.equals(last))
return first;
String prefix = greatestCommonPrefix(first, last);
String firstSuffix = getSuffix(first, prefix);
String lastSuffix = getSuffix(last, prefix);
return prefix + firstSuffix + "-" + lastSuffix;
}
private static String getSuffix(String full, String prefix) {
int beginIndex = 0;
int indexOfPrefix = prefix.isEmpty() ? 0 : full.lastIndexOf(prefix);
if (indexOfPrefix >= 0)
beginIndex = indexOfPrefix + prefix.length();
String suffix = full.substring(beginIndex);
String number = suffix.replaceAll("\\D+", "");
if (number.isEmpty())
return suffix;
return number;
}
private static String greatestCommonPrefix(String a, String b) {
int minLength = Math.min(a.length(), b.length());
for (int i = 0; i < minLength; i++) {
if (a.charAt(i) != b.charAt(i)) {
return a.substring(0, i);
}
}
return a.substring(0, minLength);
}
}
| chewiebug/GCViewer | src/main/java/com/tagtraum/perf/gcviewer/model/GcResourceSeries.java |
179,939 | /*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
******************************************************************************/
package io.github.dsheirer.map;
import org.apache.commons.math3.util.FastMath;
import org.jdesktop.swingx.JXMapViewer;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
/**
* Creates a selection rectangle based on mouse input
* Also triggers repaint events in the viewer
* @author Martin Steiger
*/
public class SelectionAdapter extends MouseAdapter
{
private boolean dragging;
private JXMapViewer viewer;
private Point2D startPos = new Point2D.Double();
private Point2D endPos = new Point2D.Double();
/**
* @param viewer the jxmapviewer
*/
public SelectionAdapter(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mousePressed(MouseEvent e)
{
if (e.getButton() != MouseEvent.BUTTON3)
return;
startPos.setLocation(e.getX(), e.getY());
endPos.setLocation(e.getX(), e.getY());
dragging = true;
}
@Override
public void mouseDragged(MouseEvent e)
{
if (!dragging)
return;
endPos.setLocation(e.getX(), e.getY());
viewer.repaint();
}
@Override
public void mouseReleased(MouseEvent e)
{
if (!dragging)
return;
if (e.getButton() != MouseEvent.BUTTON3)
return;
viewer.repaint();
dragging = false;
}
/**
* @return the selection rectangle
*/
public Rectangle getRectangle()
{
if (dragging)
{
int x1 = (int) FastMath.min(startPos.getX(), endPos.getX());
int y1 = (int) FastMath.min(startPos.getY(), endPos.getY());
int x2 = (int) FastMath.max(startPos.getX(), endPos.getX());
int y2 = (int) FastMath.max(startPos.getY(), endPos.getY());
return new Rectangle(x1, y1, x2-x1, y2-y1);
}
return null;
}
}
| DSheirer/sdrtrunk | src/main/java/io/github/dsheirer/map/SelectionAdapter.java |
179,940 | package com.dexvis.dex;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TreeItem;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.tbee.javafx.scene.layout.MigPane;
import com.dexvis.dex.collections.HierarchicalMap;
import com.dexvis.dex.wf.DexJob;
import com.dexvis.dex.wf.DexJobScheduler;
import com.dexvis.dex.wf.DexTask;
import com.dexvis.dex.wf.SerialJob;
import com.dexvis.javafx.scene.control.DexFileChooser;
import com.dexvis.javafx.scene.control.DexOptions;
import com.dexvis.javafx.scene.control.DexTaskItem;
import com.dexvis.javafx.scene.control.DexTaskList;
import com.dexvis.javafx.scene.control.DexTaskTree;
import com.dexvis.javafx.scene.control.ModalDialog;
import com.dexvis.util.ClassPathUtil;
import com.dexvis.util.DateUtil;
import com.dexvis.util.SortedList;
import com.dexvis.util.ThreadUtil;
/**
*
* This is the main class for Dex.
*
* @author Patrick Martin
*
*/
public class Dex extends Application
{
public static Dex instance;
private static DexConfig config = DexConfig.newInstance();
// Thread factory for executing task serially.
private final static BasicThreadFactory serialThreadFactory = new BasicThreadFactory.Builder()
.namingPattern("Dex-Serial-Task-%d").daemon(true)
.priority(Thread.MAX_PRIORITY).build();
// Executor for executing task serially.
public static ExecutorService serialExecutor = Executors
.newSingleThreadExecutor(serialThreadFactory);
// Thread factory for concurrent task execution. Such task may not update the
// UI.
private final static BasicThreadFactory concurrentThreadFactory = new BasicThreadFactory.Builder()
.namingPattern("Dex-Concurrent-Task-%d").daemon(true)
.priority(Thread.MAX_PRIORITY).build();
// Executor for parallel task execution.
public static ExecutorService concurrentExecutor = Executors
.newFixedThreadPool(
Math.max(1, Runtime.getRuntime().availableProcessors() - 1),
concurrentThreadFactory);
// Service for task completion notification.
public static CompletionService<Object> CCS = new ExecutorCompletionService(
concurrentExecutor);
static
{
// Output this just to make sure the system properly identifies the
// available core.
System.out.println("Available Processors: "
+ Runtime.getRuntime().availableProcessors());
// Read in the portion of the config file which deals with dates.
// This allows the user to extend Dex's capabilities in the area
// of date-format recognition when encountering exotic time/date
// formats in the while.
try
{
List<Object> dateFormats = config.getObjectList("dateFormats");
for (Object obj : dateFormats)
{
Map<String, String> spec = (Map<String, String>) obj;
String name = spec.get("name");
String pattern = spec.get("pattern");
String format = spec.get("format");
System.out.println("Adding date format: name='" + name + "', pattern='"
+ pattern + "', format='" + format + "'");
DateUtil.addFormat(pattern, format);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
System.out.println("DEX-CONFIG: '" + config + "'");
}
// GUI component housing our project name. Defaults to UnsavedProject.dex
private StringProperty curProjectStringProp = new SimpleStringProperty(
"UnsavedProject.dex");
// The list of task to be executed.
private DexTaskList taskList = null;
// Pane containing our available tasks.
private MigPane palettePane = new MigPane("insets 1", "[grow]", "[grow][]");
// The workflow tasks pane.
private MigPane workflowPane = new MigPane("insets 1", "[grow]", "[grow]");
// Main stage.
private Stage stage = null;
// Holds our current project.
private DexProject project = null;
// Main scene.
private Scene scene;
// Allows us to load projects from disk.
private DexFileChooser projectChooser = new DexFileChooser("project",
"Load Project", "Save Project", "DEX", "dex");
// Handles task selection within the palette by displaying the help screen for
// that task within the workflow pane.
ChangeListener<Object> taskChange = (ov, objOld, objNew) -> {
if (objNew == null)
{
return;
}
DexTaskItem item = ((TreeItem<DexTaskItem>) objNew).getValue();
if (item != null && item.getTask() != null && item.getTask().get() != null)
{
workflowPane.getChildren().clear();
Node helpNode = item.getTask().get().getHelp();
workflowPane.add(helpNode, "grow");
}
};
// Handles task selection within the workflow by displaying their config
// and/or output.
ChangeListener<Object> activeTaskChange = (ov, objOld, objNew) -> {
// System.out.println("*** Active Task Change: " + objNew);
// Defensive coding, ensure something is selected.
if (objNew == null)
{
return;
}
// Get the number of selected task.
int numSelected = taskList.getSelectionModel().getSelectedIndices().size();
// Determine when to wrap to the next row.
int wrapNum = (int) Math.ceil(Math.sqrt(numSelected));
// Main container for displayed task.
MigPane taskContainer = new MigPane("", "[grow]", "[grow]");
// Clear out the old workflow view.
workflowPane.getChildren().clear();
// System.out.println("WRAPPING: " + numSelected + "->" + wrapNum);
int itemNum = 0;
for (DexTaskItem item : taskList.getSelectionModel().getSelectedItems())
{
if (item != null)
{
itemNum++;
Node configNode = item.getTask().get().getConfig();
// If the last, grow as much as we can.
if (itemNum == taskList.getSelectionModel().getSelectedItems().size())
{
taskContainer.add(configNode, "growx,growy,span");
}
// If on a row border, grow and span.
else if (itemNum % wrapNum == 0)
{
taskContainer.add(configNode, "growx,growy,span");
}
else
{
taskContainer.add(configNode, "growx,growy");
}
}
}
workflowPane.add(taskContainer, "grow,span");
};
private void init(Stage stage)
{
try
{
instance = this;
this.stage = stage;
stage.setTitle("Data Explorer");
MigPane rootLayout = new MigPane("", "[grow]", "[][grow]");
MigPane topMenuPane = new MigPane("", "[][][grow]", "[]");
MenuBar menubar = new MenuBar();
menubar.setId("dex-main-menubar");
Menu fileMenu = new Menu("File");
MenuItem newMenuItem = new MenuItem("New Project");
MenuItem openMenuItem = new MenuItem("Open Project");
MenuItem appendMenuItem = new MenuItem("Append Project");
MenuItem prependMenuItem = new MenuItem("Prepend Project");
MenuItem saveMenuItem = new MenuItem("Save Project");
MenuItem exitMenuItem = new MenuItem("Exit");
Menu optionsMenu = new Menu("Options");
MenuItem generalOptionsMenuItem = new MenuItem("General Options");
generalOptionsMenuItem.setOnAction(action -> options(action));
generalOptionsMenuItem.setOnAction(action -> options(action));
MenuItem reloadStylesheetsMenuItem = new MenuItem("Reload Stylesheets");
reloadStylesheetsMenuItem.setOnAction(action -> reloadStylesheets());
optionsMenu.getItems().addAll(generalOptionsMenuItem,
reloadStylesheetsMenuItem);
newMenuItem.setOnAction(action -> newProject(action));
openMenuItem.setOnAction(action -> open(action));
appendMenuItem.setOnAction(action -> append(action));
prependMenuItem.setOnAction(action -> prepend(action));
saveMenuItem.setOnAction(action -> save(action));
exitMenuItem.setOnAction(action -> exit(action));
fileMenu.getItems().addAll(newMenuItem, openMenuItem, appendMenuItem,
prependMenuItem, saveMenuItem, exitMenuItem);
Menu helpMenu = new Menu("Help");
MenuItem aboutMenuItem = new MenuItem("About Data Explorer");
aboutMenuItem.setOnAction(action -> about(action));
MenuItem userGuideMenuItem = new MenuItem("User Guide");
userGuideMenuItem.setOnAction(action -> userguide(action));
helpMenu.getItems().addAll(aboutMenuItem, userGuideMenuItem);
menubar.getMenus().addAll(fileMenu, optionsMenu, helpMenu);
// Text infoLabel = TextUtil.DropShadow("Info:");
Label curFileLabel = new Label("Filename:");
curFileLabel.setId("dex-curfile-label");
Text curFileText = new Text();
curFileText.textProperty().bind(curProjectStringProp);
topMenuPane.add(menubar);
topMenuPane.add(curFileLabel);
topMenuPane.add(curFileText, "span");
// topMenuPane.add(getTaskManager(), "span");
// /////////////////////////////////////////////////////////////////////
// Workflow
// /////////////////////////////////////////////////////////////////////
taskList = new DexTaskList();
taskList.setStage(stage);
taskList.getSelectionModel().selectedItemProperty()
.addListener(activeTaskChange);
DexTaskTree taskTree = new DexTaskTree(getTasks());
taskTree.getSelectionModel().selectedItemProperty()
.addListener(taskChange);
taskTree.setOnMouseClicked(event -> onMouseClick(event));
// Button initWfButton = new Button("Initialize");
Button executeWfButton = new Button("Execute");
// initWfButton.setOnAction(action -> initializeWorkflow(action));
executeWfButton.setOnAction(action -> executeWorkflow(action));
workflowPane.setStyle("-fx-background-color: grey;");
Button enableAllButton = new Button("Enable All");
enableAllButton.setOnAction(action -> taskList.enableAll());
Button disableAllButton = new Button("Disable All");
disableAllButton.setOnAction(action -> taskList.disableAll());
MigPane taskPane = new MigPane("", "[grow][grow]", "[grow][]");
taskPane.add(taskList, "grow, span");
taskPane.add(enableAllButton, "growx");
taskPane.add(disableAllButton, "growx, span");
SplitPane paletteAndWFSplitPane = new SplitPane();
paletteAndWFSplitPane.setOrientation(Orientation.HORIZONTAL);
paletteAndWFSplitPane.getItems().addAll(taskTree, taskPane);
paletteAndWFSplitPane.setDividerPositions(.50f);
palettePane.add(paletteAndWFSplitPane, "grow, span");
palettePane.add(executeWfButton, "growx, span");
SplitPane wfAndDisplaySplitPane = new SplitPane();
wfAndDisplaySplitPane.setOrientation(Orientation.HORIZONTAL);
wfAndDisplaySplitPane.getItems().addAll(palettePane, workflowPane);
wfAndDisplaySplitPane.setDividerPositions(0.25f);
rootLayout.add(topMenuPane, "growx,span");
rootLayout.add(wfAndDisplaySplitPane, "grow");
rootLayout.setOnKeyPressed(action -> keyPress(action));
rootLayout.getStyleClass().add("root");
scene = new Scene(rootLayout, 1600, 900);
// AquaFx.style();
scene.getStylesheets().add("Dex.css");
// scene.getStylesheets().add("/win7glass.css");
stage.setScene(scene);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void exit(ActionEvent evt)
{
System.exit(0);
}
public void newProject(ActionEvent evt)
{
curProjectStringProp.set("UnsavedProject.dex");
taskList.getItems().clear();
}
// TODO: Make sure we clear out everything else we care about too.
public void open(ActionEvent evt)
{
try
{
File projectFile = projectChooser.load(evt);
if (projectFile != null)
{
project = DexProject.readProject(stage, projectFile);
clearOldProject();
taskList.setItems(FXCollections.observableArrayList(project
.getTaskItems()));
curProjectStringProp.set(projectFile.toString());
}
}
catch(Exception ex)
{
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
ModalDialog dialog = new ModalDialog(stage, "Open Status", sw.toString(),
"Ok");
ex.printStackTrace();
}
}
private void clearOldProject()
{
// Clear the task list.
taskList.getItems().clear();
// Reset the project name.
curProjectStringProp.set("UnnamedProject.dex");
// Clear the copy buffer?
// taskList.clearCopyTasks();
}
public void append(ActionEvent evt)
{
try
{
File projectFile = projectChooser.load(evt);
if (projectFile != null)
{
DexProject project = DexProject.readProject(stage, projectFile);
taskList.getItems().addAll(project.getTaskItems());
}
}
catch(Exception ex)
{
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
ModalDialog dialog = new ModalDialog(stage, "Open Status", sw.toString(),
"Ok");
ex.printStackTrace();
}
}
public void prepend(ActionEvent evt)
{
try
{
File projectFile = projectChooser.load(evt);
if (projectFile != null)
{
DexProject project = DexProject.readProject(stage, projectFile);
taskList.getItems().addAll(0, project.getTaskItems());
}
}
catch(Exception ex)
{
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
ModalDialog dialog = new ModalDialog(stage, "Open Status", sw.toString(),
"Ok");
ex.printStackTrace();
}
}
public void save(ActionEvent evt)
{
try
{
File saveFile = projectChooser.save(evt);
if (saveFile != null)
{
DexProject project = new DexProject();
for (DexTaskItem task : taskList.getItems())
{
project.addDataFilter(task);
}
project.writeProject(saveFile);
curProjectStringProp.set(saveFile.toString());
}
}
catch(Exception ex)
{
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
ModalDialog dialog = new ModalDialog(stage, "Save Status", sw.toString(),
"Ok");
ex.printStackTrace();
}
}
public void keyPress(KeyEvent keyEvent)
{
// System.out.println("EVENT: " + evt);
if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.S)
{
System.out.println("Saving: '" + curProjectStringProp.get() + "'");
try
{
File saveFile = new File(curProjectStringProp.get());
if (saveFile != null)
{
DexProject project = new DexProject();
for (DexTaskItem task : taskList.getItems())
{
project.addDataFilter(task);
}
project.writeProject(saveFile);
}
}
catch(Exception ex)
{
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
ModalDialog dialog = new ModalDialog(stage, "Save Status",
sw.toString(), "Ok");
ex.printStackTrace();
}
}
// Control-O : Open project
else if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.O)
{
System.out.println("Opening: '" + curProjectStringProp.get() + "'");
open(new ActionEvent());
}
// Run:
else if (keyEvent.isControlDown() && keyEvent.getCode() == KeyCode.R)
{
executeWorkflow(new ActionEvent());
}
}
public static Dex getInstance()
{
return Dex.instance;
}
public static void reportException(Stage stage, Exception ex)
{
ThreadUtil.runAndWait(() -> {
System.err.println("=========================");
ex.printStackTrace();
if (ex != null)
{
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
ModalDialog dialog = new ModalDialog(stage, "Execution Status", sw
.toString(), "Ok");
}
});
}
public static void updateUI()
{
try
{
// actual work to update UI:
FutureTask<Void> updateUITask = new FutureTask(() -> {
}, null);
// submit for execution on FX Application Thread:
Platform.runLater(updateUITask);
// block until work complete:
updateUITask.get();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public static void killAllSerialTasks()
{
ExecutorService oldExecutorService = serialExecutor;
oldExecutorService.shutdownNow();
// Executor for parallel task execution.
serialExecutor = Executors.newSingleThreadExecutor(serialThreadFactory);
}
public void executeWorkflow(ActionEvent evt)
{
System.out.println("Execute Workflow: ");
DexJobScheduler scheduler = new DexJobScheduler();
DexJob job = new SerialJob(taskList.getItems());
try
{
job.setStage(stage);
}
catch(Exception ex)
{
// Harmless, no progress bar.
}
try
{
scheduler.execute(job);
}
catch(Exception ex)
{
reportException(stage, ex);
}
}
public void onMouseClick(MouseEvent evt)
{
// System.out.println("Mouse Click Detected: " + evt.getClickCount());
if (evt.getClickCount() > 1)
{
DexTaskTree source = (DexTaskTree) evt.getSource();
if (source != null && source.getSelectionModel() != null
&& source.getSelectionModel().getSelectedItem() != null)
{
DexTaskItem item = source.getSelectionModel().getSelectedItem()
.getValue();
DexTask task = item.getTask().get();
try
{
if (task != null)
{
DexTask newTask = task.getClass().newInstance();
newTask.setStage(stage);
DexTaskItem newItem = new DexTaskItem(item);
taskList.getItems().add(newItem);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
else
{
try
{
Thread.sleep(300);
}
catch(InterruptedException iEx)
{
}
}
evt.consume();
}
// Find task classes which:
//
// 1) Have the pattern "task" in the name.
// 2) Are assignment compatible with the DexTask interface.
// 3) Are not abstract or an interface.
final static Predicate<String> isDexTask = (final String className) -> {
if (className == null || className.indexOf("task") <= 0)
{
return false;
}
try
{
Class clazz = Class.forName(className);
boolean matches = clazz != null && DexTask.class.isAssignableFrom(clazz)
&& !Modifier.isAbstract(clazz.getModifiers())
&& !Modifier.isInterface(clazz.getModifiers());
// System.out.println("Class " + className + ": " + matches);
return matches;
}
catch(Exception ex)
{
return false;
}
};
private Map<String, Object> getTasks()
{
Map<String, Object> taskMap = new HierarchicalMap<String, Object>();
List<DexTask> subList;
try
{
System.out.println("*** Searching for Dex Task inside your classpath...");
List<String> classNameList = ClassPathUtil.getClasses().stream()
// Remove the .class suffix
.map(path -> path.substring(0, path.length() - 6)).filter(isDexTask)
.collect(Collectors.toList());
for (String taskName : classNameList)
{
System.out.println("Found Task: '" + taskName + "'");
try
{
DexTask task = (DexTask) Class.forName(taskName).newInstance();
// System.out.println("-- TASK: " + task);
task.setStage(stage);
String category = task.getCategory();
if (taskMap.containsKey(category))
{
subList = (List<DexTask>) taskMap.get(category);
}
else
{
System.out.println(" ** NEW CATEGORY: '" + category + "'");
subList = new SortedList<DexTask>();
taskMap.put(task.getCategory(), subList);
}
subList.add(task);
}
catch(Exception ex)
{
// Abstract classes which can't be instantiated.
if (!taskName.equals("com.dexvis.dex.task.base.WebTask")
&& !taskName.equals("com.dexvis.dex.wf.DexTask"))
{
ex.printStackTrace();
}
}
}
}
catch(Exception ex)
{
// REM: Handle abstract classes.
// Report and skip for now.
ex.printStackTrace();
}
return taskMap;
}
public void about(ActionEvent evt)
{
try
{
Stage helpStage = new Stage();
MigPane rootLayout = new MigPane("", "[grow]", "[grow]");
WebView wv = new WebView();
WebEngine we = wv.getEngine();
String PAGE = "https://patmartin.gitbooks.io/dex-docs/content/about.html";
we.load(PAGE);
rootLayout.add(wv, "grow");
Scene helpScene = new Scene(rootLayout, 800, 600);
helpStage.setScene(helpScene);
helpStage.show();
}
catch(Exception ex)
{
// ex.printStackTrace();
}
}
public void options(ActionEvent evt)
{
try
{
DexOptions options = DexOptions.readOptions();
options.initialize(stage, this);
}
catch(Exception ex)
{
DexOptions options = new DexOptions();
options.initialize(stage, this);
// ex.printStackTrace();
}
}
public void reloadStylesheets()
{
try
{
System.out.println("Reloading stylesheet: Dex.css");
// scene.getStylesheets().clear();
scene.getStylesheets().add("Dex.css");
}
catch(Exception ex)
{
// ex.printStackTrace();
}
}
public void userguide(ActionEvent evt)
{
try
{
Stage helpStage = new Stage();
MigPane rootLayout = new MigPane("", "[grow]", "[grow]");
WebView wv = new WebView();
WebEngine we = wv.getEngine();
String PAGE = "https://patmartin.gitbooks.io/dex-docs/content/index.html";
// File helpFile = new File(PAGE);
// URL helpURL = helpFile.toURL();
we.load(PAGE);
rootLayout.add(wv, "grow");
Scene helpScene = new Scene(rootLayout, 800, 600);
helpStage.setScene(helpScene);
helpStage.show();
}
catch(Exception ex)
{
// ex.printStackTrace();
}
}
// Might be nice.
public Node getTaskManager()
{
return new Button("Cancel");
}
@Override
public void start(Stage stage) throws Exception
{
init(stage);
stage.sizeToScene();
stage.show();
}
public static void main(String[] args)
{
// ProxySelector.setDefault(ProxySelector.getDefault());
Platform.setImplicitExit(false);
launch(args);
}
}
| PatMartin/Dex | src/com/dexvis/dex/Dex.java |
179,941 | package com.dexvis.util;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonStructure;
import javax.json.JsonValue;
import com.dexvis.datastruct.NVP;
/**
*
* A rather meager class containing JSON utilities.
*
* @author Patrick Martin
*
*/
public class JsonUtil
{
public static Object pathToObject(String jsonPath) throws IOException
{
return fileToObject(new File(jsonPath));
}
public static Object fileToObject(File jsonFile) throws IOException
{
return stringToObject(StreamUtil.readFile(jsonFile));
}
/**
*
* Given a string containing valid JSON, return it's Java object
* representation.
*
* @param jsonStr
* The JSON string to parse.
*
* @return The java object equivalent to the JSON string.
*
*/
public static Object stringToObject(String jsonStr)
{
try
{
System.out.println("PARSING-JSON: '" + jsonStr);
JsonReader reader = Json.createReader(new StringReader(jsonStr));
JsonStructure jsonStruct = reader.read();
return parseJsonValue(jsonStruct);
}
catch(Exception ex)
{
ex.printStackTrace();
Object empty[] = new Object[0];
return empty;
}
}
public static List<NVP> parseNVPList(String rootName, String jsonStr)
{
ArrayList<NVP> nvpList = new ArrayList<NVP>();
if (jsonStr != null)
{
Object jsonObj = stringToObject(jsonStr);
parseNVPList(rootName, nvpList, jsonObj);
}
return nvpList;
}
private static void parseNVPList(String name, List<NVP> nvpList,
Object jsonObj)
{
if (name == null || name.trim().length() <= 0 || jsonObj == null)
{
return;
}
if (jsonObj instanceof Map)
{
Map<String, Object> map = (Map<String, Object>) jsonObj;
for (Object key : map.keySet())
{
parseNVPList(name + "." + key, nvpList, map.get(key));
}
}
else if (jsonObj instanceof List)
{
List<Object> list = (List<Object>) jsonObj;
for (Object obj : list)
{
parseNVPList(name, nvpList, obj);
}
}
// Primitives
else
{
nvpList.add(new NVP(name, jsonObj.toString()));
}
}
public static List<Map<String, String>> parseTabular(String jsonStr)
{
if (jsonStr != null)
{
return parseTabular(stringToObject(jsonStr));
}
return null;
}
private static List<Map<String, String>> parseTabular(Object jsonObj)
{
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
if (jsonObj == null)
{
return null;
}
if (jsonObj instanceof List)
{
List<Object> objList = (List<Object>) jsonObj;
for (Object obj : objList)
{
if (obj instanceof Map) {
Map jsonObjMap = (Map) obj;
if (jsonObjMap != null) {
Map<String, String> objMap = new LinkedHashMap<String, String>();
for (Object key : jsonObjMap.keySet()) {
String keyStr = key.toString();
Object val = jsonObjMap.get(key);
String valStr = (val == null) ? "" : val.toString();
objMap.put(keyStr, valStr);
}
list.add(objMap);
}
}
}
}
return list;
}
/**
*
* Given a JSON Value, return it's Java object representation.
*
* @param value
* The JSON value to convert.
*
* @return The Java object value of the converted JSON.
*
*/
public static Object parseJsonValue(JsonValue value)
{
if (value == null)
{
return null;
}
switch (value.getValueType())
{
case ARRAY:
return parseJsonArray((JsonArray) value);
case OBJECT:
return parseJsonObject((JsonObject) value);
case STRING:
return ((JsonString) value).getString();
case NUMBER:
String num = ((JsonNumber) value).toString();
try
{
return Integer.parseInt(num);
}
catch(Exception ex)
{
try
{
return Double.parseDouble(num);
}
catch(Exception iEx)
{
iEx.printStackTrace();
return num;
}
}
case TRUE:
return true;
case FALSE:
return false;
case NULL:
return null;
}
return null;
}
/**
*
* Given a JsonArray, convert it to a list of objects.
*
* @param array
* The JsonArray to convert.
*
* @return A list of objects.
*
*/
public static List<Object> parseJsonArray(JsonArray array)
{
List<Object> objects = new ArrayList<Object>();
if (array == null)
{
return objects;
}
for (JsonValue value : array)
{
objects.add(parseJsonValue(value));
}
return objects;
}
/**
*
* Given a JsonObject, return it's equivalent as a Map.
*
* @param obj
* The JSON object to convert.
* @return An equivalent representation expressed as a Map<String, Object.
*/
public static Map<String, Object> parseJsonObject(JsonObject obj)
{
Map<String, Object> objMap = new HashMap<String, Object>();
if (obj == null)
{
return objMap;
}
for (String key : obj.keySet())
{
objMap.put(key, parseJsonValue(obj.get(key)));
}
return objMap;
}
public static void main(String args[])
{
System.out.println(stringToObject("[ {\"foo\": \"bar\"} ]"));
}
}
| PatMartin/Dex | src/com/dexvis/util/JsonUtil.java |
179,942 | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.locale;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CountryUtil {
public static List<Country> getAllSepaEuroCountries() {
List<Country> list = new ArrayList<>();
String[] codes = {"AT", "BE", "CY", "DE", "EE", "FI", "FR", "GR", "IE",
"IT", "LV", "LT", "LU", "MC", "MT", "NL", "PT", "SK", "SI", "ES", "AD", "SM", "VA"};
populateCountryListByCodes(list, codes);
list.sort((a, b) -> a.name.compareTo(b.name));
return list;
}
public static List<Country> getAllRevolutCountries() {
List<Country> list = new ArrayList<>();
String[] codes = {"AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR",
"DE", "GR", "HU", "IS", "IE", "IT", "LV", "LI", "LT", "LU", "MT", "NL",
"NO", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "GB",
"AU", "CA", "SG", "CH", "US"};
populateCountryListByCodes(list, codes);
list.sort((a, b) -> a.name.compareTo(b.name));
return list;
}
public static List<Country> getAllAmazonGiftCardCountries() {
List<Country> list = new ArrayList<>();
String[] codes = {"AU", "CA", "FR", "DE", "IT", "NL", "ES", "GB", "IN", "JP",
"SA", "SE", "SG", "TR", "US"};
populateCountryListByCodes(list, codes);
list.sort(Comparator.comparing(a -> a.name));
return list;
}
public static List<Country> getAllSepaInstantEuroCountries() {
return getAllSepaEuroCountries();
}
private static void populateCountryListByCodes(List<Country> list, String[] codes) {
for (String code : codes) {
Locale locale = new Locale(LanguageUtil.getDefaultLanguage(), code, "");
final String countryCode = locale.getCountry();
String regionCode = getRegionCode(countryCode);
final Region region = new Region(regionCode, getRegionName(regionCode));
Country country = new Country(countryCode, locale.getDisplayCountry(), region);
if (countryCode.equals("XK"))
country = new Country(countryCode, getNameByCode(countryCode), region);
list.add(country);
}
}
public static boolean containsAllSepaEuroCountries(List<String> countryCodesToCompare) {
List<String> countryCodesBase = getAllSepaEuroCountries().stream().map(c -> c.code).collect(Collectors.toList());
return countryCodesToCompare.containsAll(countryCodesBase) && countryCodesBase.containsAll(countryCodesToCompare);
}
public static boolean containsAllSepaInstantEuroCountries(List<String> countryCodesToCompare) {
return containsAllSepaEuroCountries(countryCodesToCompare);
}
public static List<Country> getAllSepaNonEuroCountries() {
List<Country> list = new ArrayList<>();
String[] codes = {"BG", "HR", "CZ", "DK", "GB", "HU", "PL", "RO",
"SE", "IS", "NO", "LI", "CH", "JE", "GI"};
populateCountryListByCodes(list, codes);
list.sort((a, b) -> a.name.compareTo(b.name));
return list;
}
public static List<Country> getAllSepaInstantNonEuroCountries() {
return getAllSepaNonEuroCountries();
}
public static List<Country> getAllSepaCountries() {
List<Country> list = new ArrayList<>();
list.addAll(getAllSepaEuroCountries());
list.addAll(getAllSepaNonEuroCountries());
return list;
}
public static List<Country> getAllSepaInstantCountries() {
return getAllSepaCountries();
}
public static Country getDefaultCountry() {
String regionCode = getRegionCode(getLocale().getCountry());
final Region region = new Region(regionCode, getRegionName(regionCode));
return new Country(getLocale().getCountry(), getLocale().getDisplayCountry(), region);
}
public static Optional<Country> findCountryByCode(String countryCode) {
return getAllCountries().stream().filter(e -> e.code.equals(countryCode)).findAny();
}
public static String getNameByCode(String countryCode) {
if (countryCode.equals("XK"))
return "Republic of Kosovo";
else
return new Locale(LanguageUtil.getDefaultLanguage(), countryCode).getDisplayCountry();
}
public static String getNameAndCode(String countryCode) {
if (countryCode.isEmpty())
return "";
return getNameByCode(countryCode) + " (" + countryCode + ")";
}
public static String getCodesString(List<String> countryCodes) {
return countryCodes.stream().collect(Collectors.joining(", "));
}
public static String getNamesByCodesString(List<String> countryCodes) {
return getNamesByCodes(countryCodes).stream().collect(Collectors.joining(",\n"));
}
public static List<Region> getAllRegions() {
final List<Region> allRegions = new ArrayList<>();
String regionCode = "AM";
Region region = new Region(regionCode, getRegionName(regionCode));
allRegions.add(region);
regionCode = "AF";
region = new Region(regionCode, getRegionName(regionCode));
allRegions.add(region);
regionCode = "EU";
region = new Region(regionCode, getRegionName(regionCode));
allRegions.add(region);
regionCode = "AS";
region = new Region(regionCode, getRegionName(regionCode));
allRegions.add(region);
regionCode = "OC";
region = new Region(regionCode, getRegionName(regionCode));
allRegions.add(region);
return allRegions;
}
public static List<Country> getAllCountriesForRegion(Region selectedRegion) {
return Lists.newArrayList(Collections2.filter(getAllCountries(), country ->
selectedRegion != null && country != null && selectedRegion.equals(country.region)));
}
public static List<Country> getAllCountries() {
final Set<Country> allCountries = new HashSet<>();
for (final Locale locale : getAllCountryLocales()) {
String regionCode = getRegionCode(locale.getCountry());
final Region region = new Region(regionCode, getRegionName(regionCode));
Country country = new Country(locale.getCountry(), locale.getDisplayCountry(), region);
if (locale.getCountry().equals("XK"))
country = new Country(locale.getCountry(), "Republic of Kosovo", region);
allCountries.add(country);
}
allCountries.add(new Country("GE", "Georgia", new Region("AS", getRegionName("AS"))));
allCountries.add(new Country("BW", "Botswana", new Region("AF", getRegionName("AF"))));
allCountries.add(new Country("IR", "Iran", new Region("AS", getRegionName("AS"))));
final List<Country> allCountriesList = new ArrayList<>(allCountries);
allCountriesList.sort((locale1, locale2) -> locale1.name.compareTo(locale2.name));
return allCountriesList;
}
private static List<Locale> getAllCountryLocales() {
List<Locale> allLocales = LocaleUtil.getAllLocales();
// Filter duplicate locale entries
Set<Locale> allLocalesAsSet = allLocales.stream().filter(locale -> !locale.getCountry().isEmpty())
.collect(Collectors.toSet());
List<Locale> allCountryLocales = new ArrayList<>();
allCountryLocales.addAll(allLocalesAsSet);
allCountryLocales.sort((locale1, locale2) -> locale1.getDisplayCountry().compareTo(locale2.getDisplayCountry()));
return allCountryLocales;
}
private static List<String> getNamesByCodes(List<String> countryCodes) {
return countryCodes.stream().map(CountryUtil::getNameByCode).collect(Collectors.toList());
}
private static String getRegionName(final String regionCode) {
return regionCodeToNameMap.get(regionCode);
}
private static final Map<String, String> regionCodeToNameMap = new HashMap<>();
// Key is: ISO 3166 code, value is region code as defined in regionCodeToNameMap
private static final Map<String, String> regionByCountryCodeMap = new HashMap<>();
static {
regionCodeToNameMap.put("AM", "Americas");
regionCodeToNameMap.put("AF", "Africa");
regionCodeToNameMap.put("EU", "Europe");
regionCodeToNameMap.put("AS", "Asia");
regionCodeToNameMap.put("OC", "Oceania");
// Data extracted from https://restcountries.eu/rest/v2/all?fields=name;region;subregion;alpha2Code;languages
regionByCountryCodeMap.put("AF", "AS"); // name=Afghanistan / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("AX", "EU"); // name=Åland Islands / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("AL", "EU"); // name=Albania / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("DZ", "AF"); // name=Algeria / region=Africa / subregion=Northern Africa
regionByCountryCodeMap.put("AS", "OC"); // name=American Samoa / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("AD", "EU"); // name=Andorra / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("AO", "AF"); // name=Angola / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("AI", "AM"); // name=Anguilla / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("AG", "AM"); // name=Antigua and Barbuda / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("AR", "AM"); // name=Argentina / region=Americas / subregion=South America
regionByCountryCodeMap.put("AM", "AS"); // name=Armenia / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("AW", "AM"); // name=Aruba / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("AU", "OC"); // name=Australia / region=Oceania / subregion=Australia and New Zealand
regionByCountryCodeMap.put("AT", "EU"); // name=Austria / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("AZ", "AS"); // name=Azerbaijan / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("BS", "AM"); // name=Bahamas / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("BH", "AS"); // name=Bahrain / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("BD", "AS"); // name=Bangladesh / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("BB", "AM"); // name=Barbados / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("BY", "EU"); // name=Belarus / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("BE", "EU"); // name=Belgium / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("BZ", "AM"); // name=Belize / region=Americas / subregion=Central America
regionByCountryCodeMap.put("BJ", "AF"); // name=Benin / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("BM", "AM"); // name=Bermuda / region=Americas / subregion=Northern America
regionByCountryCodeMap.put("BT", "AS"); // name=Bhutan / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("BO", "AM"); // name=Bolivia (Plurinational State of) / region=Americas / subregion=South America
regionByCountryCodeMap.put("BQ", "AM"); // name=Bonaire, Sint Eustatius and Saba / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("BA", "EU"); // name=Bosnia and Herzegovina / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("BW", "AF"); // name=Botswana / region=Africa / subregion=Southern Africa
regionByCountryCodeMap.put("BR", "AM"); // name=Brazil / region=Americas / subregion=South America
regionByCountryCodeMap.put("IO", "AF"); // name=British Indian Ocean Territory / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("UM", "AM"); // name=United States Minor Outlying Islands / region=Americas / subregion=Northern America
regionByCountryCodeMap.put("VG", "AM"); // name=Virgin Islands (British) / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("VI", "AM"); // name=Virgin Islands (U.S.) / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("BN", "AS"); // name=Brunei Darussalam / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("BG", "EU"); // name=Bulgaria / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("BF", "AF"); // name=Burkina Faso / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("BI", "AF"); // name=Burundi / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("KH", "AS"); // name=Cambodia / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("CM", "AF"); // name=Cameroon / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("CA", "AM"); // name=Canada / region=Americas / subregion=Northern America
regionByCountryCodeMap.put("CV", "AF"); // name=Cabo Verde / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("KY", "AM"); // name=Cayman Islands / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("CF", "AF"); // name=Central African Republic / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("TD", "AF"); // name=Chad / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("CL", "AM"); // name=Chile / region=Americas / subregion=South America
regionByCountryCodeMap.put("CN", "AS"); // name=China / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("CX", "OC"); // name=Christmas Island / region=Oceania / subregion=Australia and New Zealand
regionByCountryCodeMap.put("CC", "OC"); // name=Cocos (Keeling) Islands / region=Oceania / subregion=Australia and New Zealand
regionByCountryCodeMap.put("CO", "AM"); // name=Colombia / region=Americas / subregion=South America
regionByCountryCodeMap.put("KM", "AF"); // name=Comoros / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("CG", "AF"); // name=Congo / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("CD", "AF"); // name=Congo (Democratic Republic of the) / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("CK", "OC"); // name=Cook Islands / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("CR", "AM"); // name=Costa Rica / region=Americas / subregion=Central America
regionByCountryCodeMap.put("HR", "EU"); // name=Croatia / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("CU", "AM"); // name=Cuba / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("CW", "AM"); // name=Curaçao / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("CY", "EU"); // name=Cyprus / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("CZ", "EU"); // name=Czech Republic / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("DK", "EU"); // name=Denmark / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("DJ", "AF"); // name=Djibouti / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("DM", "AM"); // name=Dominica / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("DO", "AM"); // name=Dominican Republic / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("EC", "AM"); // name=Ecuador / region=Americas / subregion=South America
regionByCountryCodeMap.put("EG", "AF"); // name=Egypt / region=Africa / subregion=Northern Africa
regionByCountryCodeMap.put("SV", "AM"); // name=El Salvador / region=Americas / subregion=Central America
regionByCountryCodeMap.put("GQ", "AF"); // name=Equatorial Guinea / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("ER", "AF"); // name=Eritrea / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("EE", "EU"); // name=Estonia / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("ET", "AF"); // name=Ethiopia / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("FK", "AM"); // name=Falkland Islands (Malvinas) / region=Americas / subregion=South America
regionByCountryCodeMap.put("FO", "EU"); // name=Faroe Islands / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("FJ", "OC"); // name=Fiji / region=Oceania / subregion=Melanesia
regionByCountryCodeMap.put("FI", "EU"); // name=Finland / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("FR", "EU"); // name=France / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("GF", "AM"); // name=French Guiana / region=Americas / subregion=South America
regionByCountryCodeMap.put("PF", "OC"); // name=French Polynesia / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("TF", "AF"); // name=French Southern Territories / region=Africa / subregion=Southern Africa
regionByCountryCodeMap.put("GA", "AF"); // name=Gabon / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("GM", "AF"); // name=Gambia / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("GE", "AS"); // name=Georgia / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("DE", "EU"); // name=Germany / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("GH", "AF"); // name=Ghana / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("GI", "EU"); // name=Gibraltar / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("GR", "EU"); // name=Greece / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("GL", "AM"); // name=Greenland / region=Americas / subregion=Northern America
regionByCountryCodeMap.put("GD", "AM"); // name=Grenada / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("GP", "AM"); // name=Guadeloupe / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("GU", "OC"); // name=Guam / region=Oceania / subregion=Micronesia
regionByCountryCodeMap.put("GT", "AM"); // name=Guatemala / region=Americas / subregion=Central America
regionByCountryCodeMap.put("GG", "EU"); // name=Guernsey / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("GN", "AF"); // name=Guinea / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("GW", "AF"); // name=Guinea-Bissau / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("GY", "AM"); // name=Guyana / region=Americas / subregion=South America
regionByCountryCodeMap.put("HT", "AM"); // name=Haiti / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("VA", "EU"); // name=Holy See / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("HN", "AM"); // name=Honduras / region=Americas / subregion=Central America
regionByCountryCodeMap.put("HK", "AS"); // name=Hong Kong / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("HU", "EU"); // name=Hungary / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("IS", "EU"); // name=Iceland / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("IN", "AS"); // name=India / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("ID", "AS"); // name=Indonesia / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("CI", "AF"); // name=Côte d'Ivoire / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("IR", "AS"); // name=Iran (Islamic Republic of) / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("IQ", "AS"); // name=Iraq / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("IE", "EU"); // name=Ireland / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("IM", "EU"); // name=Isle of Man / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("IL", "AS"); // name=Israel / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("IT", "EU"); // name=Italy / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("JM", "AM"); // name=Jamaica / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("JP", "AS"); // name=Japan / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("JE", "EU"); // name=Jersey / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("JO", "AS"); // name=Jordan / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("KZ", "AS"); // name=Kazakhstan / region=Asia / subregion=Central Asia
regionByCountryCodeMap.put("KE", "AF"); // name=Kenya / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("KI", "OC"); // name=Kiribati / region=Oceania / subregion=Micronesia
regionByCountryCodeMap.put("KW", "AS"); // name=Kuwait / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("KG", "AS"); // name=Kyrgyzstan / region=Asia / subregion=Central Asia
regionByCountryCodeMap.put("LA", "AS"); // name=Lao People's Democratic Republic / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("LV", "EU"); // name=Latvia / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("LB", "AS"); // name=Lebanon / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("LS", "AF"); // name=Lesotho / region=Africa / subregion=Southern Africa
regionByCountryCodeMap.put("LR", "AF"); // name=Liberia / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("LY", "AF"); // name=Libya / region=Africa / subregion=Northern Africa
regionByCountryCodeMap.put("LI", "EU"); // name=Liechtenstein / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("LT", "EU"); // name=Lithuania / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("LU", "EU"); // name=Luxembourg / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("MO", "AS"); // name=Macao / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("MK", "EU"); // name=Macedonia (the former Yugoslav Republic of) / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("MG", "AF"); // name=Madagascar / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("MW", "AF"); // name=Malawi / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("MY", "AS"); // name=Malaysia / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("MV", "AS"); // name=Maldives / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("ML", "AF"); // name=Mali / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("MT", "EU"); // name=Malta / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("MH", "OC"); // name=Marshall Islands / region=Oceania / subregion=Micronesia
regionByCountryCodeMap.put("MQ", "AM"); // name=Martinique / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("MR", "AF"); // name=Mauritania / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("MU", "AF"); // name=Mauritius / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("YT", "AF"); // name=Mayotte / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("MX", "AM"); // name=Mexico / region=Americas / subregion=Central America
regionByCountryCodeMap.put("FM", "OC"); // name=Micronesia (Federated States of) / region=Oceania / subregion=Micronesia
regionByCountryCodeMap.put("MD", "EU"); // name=Moldova (Republic of) / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("MC", "EU"); // name=Monaco / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("MN", "AS"); // name=Mongolia / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("ME", "EU"); // name=Montenegro / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("MS", "AM"); // name=Montserrat / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("MA", "AF"); // name=Morocco / region=Africa / subregion=Northern Africa
regionByCountryCodeMap.put("MZ", "AF"); // name=Mozambique / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("MM", "AS"); // name=Myanmar / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("NA", "AF"); // name=Namibia / region=Africa / subregion=Southern Africa
regionByCountryCodeMap.put("NR", "OC"); // name=Nauru / region=Oceania / subregion=Micronesia
regionByCountryCodeMap.put("NP", "AS"); // name=Nepal / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("NL", "EU"); // name=Netherlands / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("NC", "OC"); // name=New Caledonia / region=Oceania / subregion=Melanesia
regionByCountryCodeMap.put("NZ", "OC"); // name=New Zealand / region=Oceania / subregion=Australia and New Zealand
regionByCountryCodeMap.put("NI", "AM"); // name=Nicaragua / region=Americas / subregion=Central America
regionByCountryCodeMap.put("NE", "AF"); // name=Niger / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("NG", "AF"); // name=Nigeria / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("NU", "OC"); // name=Niue / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("NF", "OC"); // name=Norfolk Island / region=Oceania / subregion=Australia and New Zealand
regionByCountryCodeMap.put("KP", "AS"); // name=Korea (Democratic People's Republic of) / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("MP", "OC"); // name=Northern Mariana Islands / region=Oceania / subregion=Micronesia
regionByCountryCodeMap.put("NO", "EU"); // name=Norway / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("OM", "AS"); // name=Oman / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("PK", "AS"); // name=Pakistan / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("PW", "OC"); // name=Palau / region=Oceania / subregion=Micronesia
regionByCountryCodeMap.put("PS", "AS"); // name=Palestine, State of / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("PA", "AM"); // name=Panama / region=Americas / subregion=Central America
regionByCountryCodeMap.put("PG", "OC"); // name=Papua New Guinea / region=Oceania / subregion=Melanesia
regionByCountryCodeMap.put("PY", "AM"); // name=Paraguay / region=Americas / subregion=South America
regionByCountryCodeMap.put("PE", "AM"); // name=Peru / region=Americas / subregion=South America
regionByCountryCodeMap.put("PH", "AS"); // name=Philippines / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("PN", "OC"); // name=Pitcairn / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("PL", "EU"); // name=Poland / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("PT", "EU"); // name=Portugal / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("PR", "AM"); // name=Puerto Rico / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("QA", "AS"); // name=Qatar / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("XK", "EU"); // name=Republic of Kosovo / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("RE", "AF"); // name=Réunion / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("RO", "EU"); // name=Romania / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("RU", "EU"); // name=Russian Federation / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("RW", "AF"); // name=Rwanda / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("BL", "AM"); // name=Saint Barthélemy / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("SH", "AF"); // name=Saint Helena, Ascension and Tristan da Cunha / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("KN", "AM"); // name=Saint Kitts and Nevis / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("LC", "AM"); // name=Saint Lucia / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("MF", "AM"); // name=Saint Martin (French part) / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("PM", "AM"); // name=Saint Pierre and Miquelon / region=Americas / subregion=Northern America
regionByCountryCodeMap.put("VC", "AM"); // name=Saint Vincent and the Grenadines / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("WS", "OC"); // name=Samoa / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("SM", "EU"); // name=San Marino / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("ST", "AF"); // name=Sao Tome and Principe / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("SA", "AS"); // name=Saudi Arabia / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("SN", "AF"); // name=Senegal / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("RS", "EU"); // name=Serbia / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("SC", "AF"); // name=Seychelles / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("SL", "AF"); // name=Sierra Leone / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("SG", "AS"); // name=Singapore / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("SX", "AM"); // name=Sint Maarten (Dutch part) / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("SK", "EU"); // name=Slovakia / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("SI", "EU"); // name=Slovenia / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("SB", "OC"); // name=Solomon Islands / region=Oceania / subregion=Melanesia
regionByCountryCodeMap.put("SO", "AF"); // name=Somalia / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("ZA", "AF"); // name=South Africa / region=Africa / subregion=Southern Africa
regionByCountryCodeMap.put("GS", "AM"); // name=South Georgia and the South Sandwich Islands / region=Americas / subregion=South America
regionByCountryCodeMap.put("KR", "AS"); // name=Korea (Republic of) / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("SS", "AF"); // name=South Sudan / region=Africa / subregion=Middle Africa
regionByCountryCodeMap.put("ES", "EU"); // name=Spain / region=Europe / subregion=Southern Europe
regionByCountryCodeMap.put("LK", "AS"); // name=Sri Lanka / region=Asia / subregion=Southern Asia
regionByCountryCodeMap.put("SD", "AF"); // name=Sudan / region=Africa / subregion=Northern Africa
regionByCountryCodeMap.put("SR", "AM"); // name=Suriname / region=Americas / subregion=South America
regionByCountryCodeMap.put("SJ", "EU"); // name=Svalbard and Jan Mayen / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("SZ", "AF"); // name=Swaziland / region=Africa / subregion=Southern Africa
regionByCountryCodeMap.put("SE", "EU"); // name=Sweden / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("CH", "EU"); // name=Switzerland / region=Europe / subregion=Western Europe
regionByCountryCodeMap.put("SY", "AS"); // name=Syrian Arab Republic / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("TW", "AS"); // name=Taiwan / region=Asia / subregion=Eastern Asia
regionByCountryCodeMap.put("TJ", "AS"); // name=Tajikistan / region=Asia / subregion=Central Asia
regionByCountryCodeMap.put("TZ", "AF"); // name=Tanzania, United Republic of / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("TH", "AS"); // name=Thailand / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("TL", "AS"); // name=Timor-Leste / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("TG", "AF"); // name=Togo / region=Africa / subregion=Western Africa
regionByCountryCodeMap.put("TK", "OC"); // name=Tokelau / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("TO", "OC"); // name=Tonga / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("TT", "AM"); // name=Trinidad and Tobago / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("TN", "AF"); // name=Tunisia / region=Africa / subregion=Northern Africa
regionByCountryCodeMap.put("TR", "AS"); // name=Turkey / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("TM", "AS"); // name=Turkmenistan / region=Asia / subregion=Central Asia
regionByCountryCodeMap.put("TC", "AM"); // name=Turks and Caicos Islands / region=Americas / subregion=Caribbean
regionByCountryCodeMap.put("TV", "OC"); // name=Tuvalu / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("UG", "AF"); // name=Uganda / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("UA", "EU"); // name=Ukraine / region=Europe / subregion=Eastern Europe
regionByCountryCodeMap.put("AE", "AS"); // name=United Arab Emirates / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("GB", "EU"); // name=United Kingdom of Great Britain and Northern Ireland / region=Europe / subregion=Northern Europe
regionByCountryCodeMap.put("US", "AM"); // name=United States of America / region=Americas / subregion=Northern America
regionByCountryCodeMap.put("UY", "AM"); // name=Uruguay / region=Americas / subregion=South America
regionByCountryCodeMap.put("UZ", "AS"); // name=Uzbekistan / region=Asia / subregion=Central Asia
regionByCountryCodeMap.put("VU", "OC"); // name=Vanuatu / region=Oceania / subregion=Melanesia
regionByCountryCodeMap.put("VE", "AM"); // name=Venezuela (Bolivarian Republic of) / region=Americas / subregion=South America
regionByCountryCodeMap.put("VN", "AS"); // name=Viet Nam / region=Asia / subregion=South-Eastern Asia
regionByCountryCodeMap.put("WF", "OC"); // name=Wallis and Futuna / region=Oceania / subregion=Polynesia
regionByCountryCodeMap.put("EH", "AF"); // name=Western Sahara / region=Africa / subregion=Northern Africa
regionByCountryCodeMap.put("YE", "AS"); // name=Yemen / region=Asia / subregion=Western Asia
regionByCountryCodeMap.put("ZM", "AF"); // name=Zambia / region=Africa / subregion=Eastern Africa
regionByCountryCodeMap.put("ZW", "AF"); // name=Zimbabwe / region=Africa / subregion=Eastern Africa
}
public static String getRegionCode(String countryCode) {
if (regionByCountryCodeMap.containsKey(countryCode))
return regionByCountryCodeMap.get(countryCode);
else
return "Undefined";
}
public static String getDefaultCountryCode() {
// might be set later in pref or config, so not use Preferences.getDefaultLocale() anywhere in the code
return getLocale().getCountry();
}
private static Locale getLocale() {
return GlobalSettings.getLocale();
}
}
| bisq-network/bisq | core/src/main/java/bisq/core/locale/CountryUtil.java |
179,943 | /*
* Copyright (C) 2015 Naman Dwivedi
*
* Licensed under the GNU General Public License v3
*
* This is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*/
package com.naman14.timber.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.view.View;
import android.widget.ImageView;
import com.naman14.timber.R;
import com.naman14.timber.dataloaders.AlbumLoader;
import com.naman14.timber.lastfmapi.LastFmClient;
import com.naman14.timber.lastfmapi.callbacks.AlbumInfoListener;
import com.naman14.timber.lastfmapi.models.AlbumQuery;
import com.naman14.timber.lastfmapi.models.LastfmAlbum;
import com.naman14.timber.models.Album;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public class ImageUtils {
private static final DisplayImageOptions lastfmDisplayImageOptions =
new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnFail(R.drawable.ic_empty_music2)
.build();
private static final DisplayImageOptions diskDisplayImageOptions =
new DisplayImageOptions.Builder()
.cacheInMemory(true)
.build();
public static void loadAlbumArtIntoView(final long albumId, final ImageView view) {
loadAlbumArtIntoView(albumId, view, new SimpleImageLoadingListener());
}
public static void loadAlbumArtIntoView(final long albumId, final ImageView view,
final ImageLoadingListener listener) {
if (PreferencesUtility.getInstance(view.getContext()).alwaysLoadAlbumImagesFromLastfm()) {
loadAlbumArtFromLastfm(albumId, view, listener);
} else {
loadAlbumArtFromDiskWithLastfmFallback(albumId, view, listener);
}
}
private static void loadAlbumArtFromDiskWithLastfmFallback(final long albumId, ImageView view,
final ImageLoadingListener listener) {
ImageLoader.getInstance()
.displayImage(TimberUtils.getAlbumArtUri(albumId).toString(),
view,
diskDisplayImageOptions,
new SimpleImageLoadingListener() {
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
loadAlbumArtFromLastfm(albumId, (ImageView) view, listener);
listener.onLoadingFailed(imageUri, view, failReason);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
listener.onLoadingComplete(imageUri, view, loadedImage);
}
});
}
private static void loadAlbumArtFromLastfm(long albumId, final ImageView albumArt, final ImageLoadingListener listener) {
Album album = AlbumLoader.getAlbum(albumArt.getContext(), albumId);
LastFmClient.getInstance(albumArt.getContext())
.getAlbumInfo(new AlbumQuery(album.title, album.artistName),
new AlbumInfoListener() {
@Override
public void albumInfoSuccess(final LastfmAlbum album) {
if (album != null) {
ImageLoader.getInstance()
.displayImage(album.mArtwork.get(4).mUrl,
albumArt,
lastfmDisplayImageOptions, new SimpleImageLoadingListener(){
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
listener.onLoadingComplete(imageUri, view, loadedImage);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
listener.onLoadingFailed(imageUri, view, failReason);
}
});
}
}
@Override
public void albumInfoFailed() { }
});
}
public static Drawable createBlurredImageFromBitmap(Bitmap bitmap, Context context, int inSampleSize) {
RenderScript rs = RenderScript.create(context);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
Bitmap blurTemplate = BitmapFactory.decodeStream(bis, null, options);
final Allocation input = Allocation.createFromBitmap(rs, blurTemplate);
final Allocation output = Allocation.createTyped(rs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(8f);
script.setInput(input);
script.forEach(output);
output.copyTo(blurTemplate);
return new BitmapDrawable(context.getResources(), blurTemplate);
}
}
| naman14/Timber | app/src/main/java/com/naman14/timber/utils/ImageUtils.java |
179,944 | package play.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Represents a set of character entity references defined by the
* HTML 4.0 standard.
*
* <p>A complete description of the HTML 4.0 character set can be found
* at http://www.w3.org/TR/html4/charset.html.
*
* @author Juergen Hoeller
* @author Martin Kersten
* @since 1.2.1
*/
public class HTML {
/*
* Shared instance of pre-parsed HTML character entity references.
*/
private static final HtmlCharacterEntityReferences characterEntityReferences = new HtmlCharacterEntityReferences();
/**
* Turn special characters into HTML character references. Handles complete character set defined in HTML 4.01
* recommendation.
* <p>
* Escapes all special characters to their corresponding entity reference (e.g. <code><</code>).
* <p>
* Reference: <a href="http://www.w3.org/TR/html4/sgml/entities.html"> http://www.w3.org/TR/html4/sgml/entities.html
* </a>
*
* @param input
* the (unescaped) input string
* @return the escaped string
*/
public static String htmlEscape(String input) {
if (input == null) {
return null;
}
StringBuilder escaped = new StringBuilder(input.length() * 2);
for (int i = 0; i < input.length(); i++) {
char character = input.charAt(i);
String reference = characterEntityReferences.convertToReference(character);
if (reference != null) {
escaped.append(reference);
} else {
escaped.append(character);
}
}
return escaped.toString();
}
public static class HtmlCharacterEntityReferences {
static final char REFERENCE_START = '&';
static final String DECIMAL_REFERENCE_START = "&#";
static final String HEX_REFERENCE_START = "&#x";
static final char REFERENCE_END = ';';
static final char CHAR_NULL = (char) -1;
private static final String PROPERTIES_FILE = "htmlentities.properties";
private final String[] characterToEntityReferenceMap = new String[3000];
private final Map<String, Character> entityReferenceToCharacterMap = new HashMap<>(252);
/**
* Returns a new set of character entity references reflecting the HTML 4.0 character set.
*/
public HtmlCharacterEntityReferences() {
Properties entityReferences = new Properties();
// Load reference definition file.
InputStream is = HtmlCharacterEntityReferences.class.getResourceAsStream(PROPERTIES_FILE);
if (is == null) {
throw new IllegalStateException("Cannot find reference definition file [htmlentities.properties] as class path resource");
}
try {
try {
entityReferences.load(is);
} finally {
is.close();
}
} catch (IOException ex) {
throw new IllegalStateException(
"Failed to parse reference definition file [HtmlCharacterEntityReferences.properties]: " + ex.getMessage());
}
// Parse reference definition propertes.
Enumeration<?> keys = entityReferences.propertyNames();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
int referredChar = Integer.parseInt(key);
int index = (referredChar < 1000 ? referredChar : referredChar - 7000);
String reference = entityReferences.getProperty(key);
this.characterToEntityReferenceMap[index] = REFERENCE_START + reference + REFERENCE_END;
this.entityReferenceToCharacterMap.put(reference, (char) referredChar);
}
}
/**
* Return the number of supported entity references.
*
* @return Number of supported entity references
*/
public int getSupportedReferenceCount() {
return this.entityReferenceToCharacterMap.size();
}
/**
* Return true if the given character is mapped to a supported entity reference.
*
* @param character
* The given character
* @return true if the given character is mapped to a supported entity reference
*/
public boolean isMappedToReference(char character) {
return (convertToReference(character) != null);
}
/**
* Return the reference mapped to the given character or <code>null</code>.
*
* @param character
* The given character
* @return The reference mapped to the given character or <code>null</code>
*/
public String convertToReference(char character) {
if (character < 1000 || (character >= 8000 && character < 10000)) {
int index = (character < 1000 ? character : character - 7000);
String entityReference = this.characterToEntityReferenceMap[index];
if (entityReference != null) {
return entityReference;
}
}
return null;
}
/**
* Return the char mapped to the given entityReference or -1.
*
* @param entityReference
* The given entityReference
* @return The char mapped to the given entityReference or -1.
*/
public char convertToCharacter(String entityReference) {
Character referredCharacter = this.entityReferenceToCharacterMap.get(entityReference);
if (referredCharacter != null) {
return referredCharacter.charValue();
}
return CHAR_NULL;
}
}
}
| playframework/play1 | framework/src/play/utils/HTML.java |
179,945 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
/**
* This extension adds support for synchronizing corresponding presentation requests across multiple swapchains using the <em>present barrier</em>.
*
* <dl>
* <dt><b>Name String</b></dt>
* <dd>{@code VK_NV_present_barrier}</dd>
* <dt><b>Extension Type</b></dt>
* <dd>Device extension</dd>
* <dt><b>Registered Extension Number</b></dt>
* <dd>293</dd>
* <dt><b>Revision</b></dt>
* <dd>1</dd>
* <dt><b>Extension and Version Dependencies</b></dt>
* <dd>{@link KHRGetPhysicalDeviceProperties2 VK_KHR_get_physical_device_properties2} or <a href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#versions-1.1">Version 1.1</a> and {@link KHRSurface VK_KHR_surface} and {@link KHRGetSurfaceCapabilities2 VK_KHR_get_surface_capabilities2} and {@link KHRSwapchain VK_KHR_swapchain}</dd>
* <dt><b>Contact</b></dt>
* <dd><ul>
* <li>Liya Li <a href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_NV_present_barrier]%20@liyli%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_NV_present_barrier%20extension*">liyli</a></li>
* </ul></dd>
* </dl>
*
* <h5>Other Extension Metadata</h5>
*
* <dl>
* <dt><b>Last Modified Date</b></dt>
* <dd>2022-05-16</dd>
* <dt><b>Contributors</b></dt>
* <dd><ul>
* <li>Liya Li, Nvidia</li>
* <li>Martin Schwarzer, Nvidia</li>
* <li>Andy Wolf, Nvidia</li>
* <li>Ian Williams, Nvidia</li>
* <li>Ben Morris, Nvidia</li>
* <li>James Jones, Nvidia</li>
* <li>Jeff Juliano, Nvidia</li>
* </ul></dd>
* </dl>
*/
public final class NVPresentBarrier {
/** The extension specification version. */
public static final int VK_NV_PRESENT_BARRIER_SPEC_VERSION = 1;
/** The extension name. */
public static final String VK_NV_PRESENT_BARRIER_EXTENSION_NAME = "VK_NV_present_barrier";
/**
* Extends {@code VkStructureType}.
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_BARRIER_FEATURES_NV STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_BARRIER_FEATURES_NV}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_PRESENT_BARRIER_NV STRUCTURE_TYPE_SURFACE_CAPABILITIES_PRESENT_BARRIER_NV}</li>
* <li>{@link #VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_BARRIER_CREATE_INFO_NV STRUCTURE_TYPE_SWAPCHAIN_PRESENT_BARRIER_CREATE_INFO_NV}</li>
* </ul>
*/
public static final int
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_BARRIER_FEATURES_NV = 1000292000,
VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_PRESENT_BARRIER_NV = 1000292001,
VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_BARRIER_CREATE_INFO_NV = 1000292002;
private NVPresentBarrier() {}
} | LWJGL/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/NVPresentBarrier.java |
179,946 | /**
* The purpose of this library is to allow users to use ArcBall in processing
* sketches Copyright (C) 2014 Martin Prout This library is free software; you
* can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Obtain a copy of the license at http://www.gnu.org/licenses/lgpl-2.1.html
*/
/*
* CREDITS...Initially I found this arcball in a sketch by Ariel Malka,
* only later did I find the Tom Carden processing tutorial example, so take your pick
*
* 1) Ariel Malka - June 23, 2003 http://www.chronotext.org
*
* 2) Simon Greenwold? 2003 (as reported 2006 by Tom Carden http://wiki.processing.org/w/Arcball)
*
* 3) Arcball concept invented by Ken Shoemake, published in his 1985 SIGGRAPH paper "Animating rotations with quaternion curves".
*
* 4) Somewhat modified by Martin Prout to support callbacks from processing sketch
**/
package monkstone.arcball;
import java.util.Objects;
import processing.core.PApplet;
import processing.event.KeyEvent;
import processing.event.MouseEvent;
/**
* Supports the Arcball and MouseWheel zoom manipulation of objects in
* processing
*
* @author Martin Prout
*/
public class Arcball {
private double center_x;
private double center_y;
private double radius;
private Jvector v_down;
private Jvector v_drag;
private Quaternion q_now;
private Quaternion q_down;
private Quaternion q_drag;
private Jvector[] axisSet;
private Constrain axis;
private boolean isActive = false;
private PApplet parent;
private double zoom = 1.0f;
private WheelHandler zoomWheelHandler;
private boolean camera = false;
float DEPTH = (float) (1 / (2 * Math.tan(Math.PI / 6)));
/**
*
* @param parent PApplet
* @param center_x double x coordinate of arcball center
* @param center_y double y coordinate of arcball center
* @param radius double radius of arcball
*/
public Arcball(PApplet parent, double center_x, double center_y, double radius) {
this.zoomWheelHandler = new WheelHandler() {
@Override
public void handleWheel(int delta) {
zoom += delta * 0.05;
}
};
this.parent = parent;
this.center_x = center_x;
this.center_y = center_y;
this.radius = radius;
this.v_down = new Jvector();
this.v_drag = new Jvector();
this.q_now = new Quaternion();
this.q_down = new Quaternion();
this.q_drag = new Quaternion();
this.axisSet = new Jvector[]{new Jvector(1.0f, 0.0f, 0.0f), new Jvector(0.0f, 1.0f, 0.0f), new Jvector(0.0f, 0.0f, 1.0f)};
this.axis = Constrain.FREE; // no constraints...
}
/**
* Default centered arcball and half width or half height whichever smaller
*
* @param parent
*
*/
public Arcball(PApplet parent) {
// this(parent, parent.width / 2.0f, parent.height / 2.0f, Math.min(parent.width, parent.height) * 0.5f);
this(parent, 0f, 0f, Math.min(parent.width, parent.height) * 0.8f);
parent.camera(parent.width / 2.0f, parent.height / 2.0f, (parent.height * DEPTH), 0, 0, 0, 0, 1.0f, 0);
camera = true;
this.axis = Constrain.FREE; // no constraints...
}
/**
* mouse event to register
*
* @param e
*/
public void mouseEvent(MouseEvent e) {
int x = e.getX();
int y = e.getY();
switch (e.getAction()) {
case (MouseEvent.PRESS):
v_down = mouse2sphere(x, y);
q_down.set(q_now);
q_drag.reset();
break;
case (MouseEvent.DRAG):
v_drag = mouse2sphere(x, y);
q_drag.set(v_down.dot(v_drag), v_down.cross(v_drag));
break;
case (MouseEvent.WHEEL):
if (zoomWheelHandler != null) {
zoomWheelHandler.handleWheel(e.getCount());
}
break;
default:
}
}
/**
* key event to register
*
* @param e
*/
public void keyEvent(processing.event.KeyEvent e) {
if (e.getAction() != KeyEvent.PRESS) {
} else {
switch (e.getKey()) {
case 'x':
constrain(Constrain.XAXIS);
break;
case 'y':
constrain(Constrain.YAXIS);
break;
case 'z':
constrain(Constrain.ZAXIS);
break;
}
}
if (e.getAction() == KeyEvent.RELEASE) {
constrain(Constrain.FREE);
}
}
/**
*
*/
public void pre() {
if (!camera) {
parent.translate((float) center_x, (float) center_y);
}
update();
}
/**
* May or may not be required for use in Web Applet it works so why worry as
* used by Jonathan Feinberg peasycam, and that works OK
*
* @param active
*/
public void setActive(boolean active) {
if (active != isActive) {
isActive = active;
if (active) {
this.parent.registerMethod("dispose", this);
this.parent.registerMethod("pre", this);
this.parent.registerMethod("mouseEvent", this);
this.parent.registerMethod("keyEvent", this);
} else {
this.parent.unregisterMethod("pre", this);
this.parent.unregisterMethod("mouseEvent", this);
this.parent.unregisterMethod("keyEvent", this);
}
}
}
/**
* Don't call this directly in sketch use reflection to call in eg in pre()
*/
private void update() {
q_now = Quaternion.mult(q_drag, q_down);
applyQuaternion2Matrix(q_now);
parent.scale((float) zoom);
}
/**
* Returns either the Jvector of mouse position mapped to a sphere or the
* constrained version (when constrained to one axis)
*
* @param x
* @param y
* @return mouse coordinate mapped to unit sphere
*/
public Jvector mouse2sphere(double x, double y) {
Jvector v = new Jvector((x - center_x) / radius, (y - center_y) / radius, 0);
double mag_sq = v.x * v.x + v.y * v.y;
if (mag_sq > 1.0) {
v.normalize();
} else {
v.z = Math.sqrt(1.0 - mag_sq);
}
if (axis != Constrain.FREE) {
v = constrainVector(v, axisSet[axis.index()]);
}
return v;
}
/**
* Returns the Jvector if the axis is constrained
*
* @param vector
* @param axis
* @return constrained vector
*/
public Jvector constrainVector(Jvector vector, Jvector axis) {
Jvector res = vector.sub(axis.mult(axis.dot(vector)));
return res.normalize(); // like Jvector res is changed
}
/**
* Constrain rotation to this axis
*
* @param axis
*/
public void constrain(Constrain axis) {
this.axis = axis;
}
/**
* Rotate the parent sketch according to the quaternion
*
* @param q
*/
public void applyQuaternion2Matrix(Quaternion q) {
// instead of transforming q into a matrix and applying it...
double[] aa = q.getValue();
parent.rotate((float) aa[0], (float) aa[1], (float) aa[2], (float) aa[3]);
}
/**
* A recommended inclusion for a processing library
*/
public void dispose() {
setActive(false);
}
/**
*
* @param obj
* @return java boolean
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Arcball other = (Arcball) obj;
if (Double.doubleToLongBits(this.center_x) != Double.doubleToLongBits(other.center_x)) {
return false;
}
if (Double.doubleToLongBits(this.center_y) != Double.doubleToLongBits(other.center_y)) {
return false;
}
if (Double.doubleToLongBits(this.radius) != Double.doubleToLongBits(other.radius)) {
return false;
}
return Objects.equals(this.parent, other.parent);
}
/**
*
* @return has code int
*/
@Override
public int hashCode() {
long hash = 3;
hash = 59 * hash + Double.doubleToLongBits(this.center_x);
hash = 59 * hash + Double.doubleToLongBits(this.center_y);
hash = 59 * hash + Double.doubleToLongBits(this.radius);
hash = 59 * hash + Objects.hashCode(this.parent);
return (int) hash;
}
}
| jashkenas/ruby-processing | src/monkstone/arcball/Arcball.java |
179,947 | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved.
* Portions Copyright (c) 2017, 2020, Chris Fraire <cfraire@me.com>.
*/
package org.opengrok.indexer.analysis.java;
import java.io.Reader;
import org.opengrok.indexer.analysis.AbstractAnalyzer;
import org.opengrok.indexer.analysis.AnalyzerFactory;
import org.opengrok.indexer.analysis.JFlexTokenizer;
import org.opengrok.indexer.analysis.JFlexXref;
import org.opengrok.indexer.analysis.plain.AbstractSourceCodeAnalyzer;
/**
*
* @author Martin Englund
*/
@SuppressWarnings("java:S110")
public class JavaAnalyzer extends AbstractSourceCodeAnalyzer {
/**
* Creates a new instance of JavaAnalyzer.
* @param factory defined instance for the analyzer
*/
protected JavaAnalyzer(AnalyzerFactory factory) {
super(factory, () -> new JFlexTokenizer(new JavaSymbolTokenizer(
AbstractAnalyzer.DUMMY_READER)));
}
/**
* @return {@code "Java"}
*/
@Override
public String getCtagsLang() {
return "Java";
}
/**
* Gets a version number to be used to tag processed documents so that
* re-analysis can be re-done later if a stored version number is different
* from the current implementation.
* @return 20180208_00
*/
@Override
protected int getSpecializedVersionNo() {
return 20180208_00; // Edit comment above too!
}
/**
* Creates a wrapped {@link JavaXref} instance.
* @param reader the data to produce xref for
* @return a defined instance
*/
@Override
protected JFlexXref newXref(Reader reader) {
return new JFlexXref(new JavaXref(reader));
}
@Override
protected boolean supportsScopes() {
return true;
}
}
| oracle/opengrok | opengrok-indexer/src/main/java/org/opengrok/indexer/analysis/java/JavaAnalyzer.java |
179,948 | /**
* The purpose of this tool is to allow ruby-processing users to use an alternative
* to processing.org map, lerp and norm methods in their sketches
* Copyright (C) 2015-16 Martin Prout. This tool is free software; you can
* redistribute it and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* Obtain a copy of the license at http://www.gnu.org/licenses/lgpl-2.1.html
*/
package monkstone;
import org.jruby.Ruby;
import org.jruby.RubyClass;
import org.jruby.RubyFloat;
import org.jruby.RubyModule;
import org.jruby.RubyObject;
import org.jruby.RubyRange;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
*
* @author MartinProut
*/
public class MathTool extends RubyObject {
private static final long serialVersionUID = 4427564758225746633L;
/**
*
* @param runtime
*/
public static void createMathTool(Ruby runtime) {
RubyModule processing = runtime.defineModule("Processing");
RubyModule module = processing.defineModuleUnder("MathTool");
module.defineAnnotatedMethods(MathTool.class);
}
/**
*
* @param context JRuby runtime
* @param recv self
* @param args array of RubyRange (must be be numeric)
* @return RubyFloat
*/
@JRubyMethod(name = "map1d", rest = true, module = true)
public static IRubyObject mapOneD(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
double value = (Double) args[0].toJava(Double.class);
RubyRange r1 = (RubyRange) args[1];
RubyRange r2 = (RubyRange) args[2];
double first1 = (Double) r1.first(context).toJava(Double.class);
double first2 = (Double) r2.first(context).toJava(Double.class);
double last1 = (Double) r1.last(context).toJava(Double.class);
double last2 = (Double) r2.last(context).toJava(Double.class);
return mapMt(context, value, first1, last1, first2, last2);
}
/**
*
* @param context JRuby runtime
* @param recv self
* @param args array of RubyRange (must be be numeric)
* @return RubyFloat
*/
@JRubyMethod(name = "constrained_map", rest = true, module = true)
public static IRubyObject constrainedMap(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
double value = (Double) args[0].toJava(Double.class);
RubyRange r1 = (RubyRange) args[1];
RubyRange r2 = (RubyRange) args[2];
double first1 = (Double) r1.first(context).toJava(Double.class);
double first2 = (Double) r2.first(context).toJava(Double.class);
double last1 = (Double) r1.last(context).toJava(Double.class);
double last2 = (Double) r2.last(context).toJava(Double.class);
double max = Math.max(first1, last1);
double min = Math.min(first1, last1);
if (value < min) {
value = min;
}
if (value > max) {
value = max;
}
return mapMt(context, value, first1, last1, first2, last2);
}
/**
*
* @param context JRuby runtime
* @param recv self
* @param args floats as in processing map function
* @return RubyFloat
*/
@JRubyMethod(name = {"p5map", "map"}, rest = true, module = true)
public static IRubyObject mapProcessing(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
double value = (Double) args[0].toJava(Double.class);
double first1 = (Double) args[1].toJava(Double.class);
double first2 = (Double) args[3].toJava(Double.class);
double last1 = (Double) args[2].toJava(Double.class);
double last2 = (Double) args[4].toJava(Double.class);
return mapMt(context, value, first1, last1, first2, last2);
}
/**
* A more correct version than processing.org version
* @param context
* @param recv
* @param args args[2] should be between 0 and 1.0 if not returns start or stop
* @return lerp value
*/
@JRubyMethod(name = "lerp", rest = true, module = true)
public static IRubyObject lerpP(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
double start = (Double) args[0].toJava(Double.class);
double stop = (Double) args[1].toJava(Double.class);
double amount = (Double) args[2].toJava(Double.class);
if (amount <= 0) return args[0];
if (amount >= 1.0) return args[1];
return context.getRuntime().newFloat((1 - amount) * start + (stop * amount));
}
/**
* Identical to p5map(value, low, high, 0, 1).
* Numbers outside of the range are not clamped to 0 and 1,
* because out-of-range values are often intentional and useful.
* @param context
* @param recv
* @param args
* @return norm value
*/
@JRubyMethod(name = "norm", rest = true, module = true)
public static IRubyObject normP(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
double value = (Double) args[0].toJava(Double.class);
double start = (Double) args[1].toJava(Double.class);
double stop = (Double) args[2].toJava(Double.class);
return mapMt(context, value, start, stop, 0, 1.0);
}
/**
* Identical to p5map(value, low, high, 0, 1) but 'clamped'.
* Numbers outside of the range are clamped to 0 and 1,
* @param context
* @param recv
* @param args
* @return strict normalized value ie 0..1.0
*/
@JRubyMethod(name = "norm_strict", rest = true, module = true)
public static IRubyObject norm_strict(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
Ruby ruby = context.runtime;
double value = (Double) args[0].toJava(Double.class);
double start = (Double) args[1].toJava(Double.class);
double stop = (Double) args[2].toJava(Double.class);
if (value <= start) {
return new RubyFloat(ruby, 0);
} else if (value >= stop) {
return new RubyFloat(ruby, 1.0);
} else {
return mapMt(context, value, start, stop, 0, 1.0);
}
}
static final RubyFloat mapMt(ThreadContext context, double value, double first1, double last1, double first2, double last2) {
double result = first2 + (last2 - first2) * ((value - first1) / (last1 - first1));
return context.getRuntime().newFloat(result);
}
/**
* Provides processing constrain method as a ruby module method
* @param context
* @param recv
* @param args
* @return original or limit values
*/
@JRubyMethod(name = "constrain", rest = true, module = true)
public static IRubyObject constrainValue(ThreadContext context, IRubyObject recv, IRubyObject[] args) {
RubyFloat value = args[0].convertToFloat();
RubyFloat start = args[1].convertToFloat();
RubyFloat stop = args[2].convertToFloat();
if (value.op_ge(context, start).isTrue() && value.op_le(context, stop).isTrue()) {
return args[0];
} else if (value.op_ge(context, start).isTrue()) {
return args[2];
} else {
return args[1];
}
}
/**
*
* @param runtime
* @param metaClass
*/
public MathTool(Ruby runtime, RubyClass metaClass) {
super(runtime, metaClass);
}
}
| jashkenas/ruby-processing | src/monkstone/MathTool.java |
179,949 | /*******************************************************************************
* Copyright (c) 2014 Martin Marinov.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Martin Marinov - initial API and implementation
******************************************************************************/
package martin.tempest.gui;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import javax.imageio.ImageIO;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.JTextField;
import javax.swing.DefaultComboBoxModel;
import martin.tempest.core.TSDRLibrary;
import martin.tempest.core.TSDRLibrary.PARAM;
import martin.tempest.core.TSDRLibrary.PARAM_DOUBLE;
import martin.tempest.core.TSDRLibrary.SYNC_DIRECTION;
import martin.tempest.core.exceptions.TSDRException;
import martin.tempest.core.exceptions.TSDRLoadPluginException;
import martin.tempest.gui.HoldButton.HoldListener;
import martin.tempest.gui.PlotVisualizer.TransformerAndCallback;
import martin.tempest.sources.TSDRSource;
import martin.tempest.sources.TSDRSource.ActionListenerRegistrator;
import martin.tempest.sources.TSDRSource.TSDRSourceParamChangedListener;
import javax.swing.JSlider;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.prefs.Preferences;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
public class Main implements TSDRLibrary.FrameReadyCallback, TSDRLibrary.IncomingValueCallback, TSDRSourceParamChangedListener, OnTSDRParamChangedCallback {
private final static String SNAPSHOT_FORMAT = "png";
private final static int OSD_TIME = 2000;
private final static int OSD_TIME_LONG = 5000;
private final static int AUTO_FRAMERATE_CONVERGANCE_ITERATIONS = 3;
private final static int FRAMERATE_SIGNIFICANT_FIGURES = 8;
private final static long FREQUENCY_STEP = 5000000;
private final static double FRAMERATE_MIN_CHANGE = 1.0/Math.pow(10, FRAMERATE_SIGNIFICANT_FIGURES);
private final static String FRAMERATE_FORMAT = "%."+FRAMERATE_SIGNIFICANT_FIGURES+"f";
private final Preferences prefs = Preferences.userNodeForPackage(this.getClass());
private final static String PREF_WIDTH = "width";
private final static String PREF_HEIGHT = "height";
private final static String PREF_FRAMERATE = "framerate";
private final static String PREF_COMMAND_PREFIX = "command";
private final static String PREF_FREQ = "frequency";
private final static String PREF_GAIN = "gain";
private final static String PREF_MOTIONBLUR = "motionblur";
private final static String PREF_HEIGHT_LOCK = "height_lock";
private final static String PREF_AREA_AROUND_MOUSE = "area_around_mouse";
private final static String PREF_HQ_REDNERING = "hq_rendering";
private final static String PREF_NEAREST_NEIGHBOUR = "near_neigh_rend";
private final static String PREF_LOW_PASS_BEFORE_SYNC = "lp_before_sync";
private final static String PREF_AUTOGAIN_AFTER_PROC = "auto_bf_proc";
private final SpinnerModel frequency_spinner_model = new SpinnerNumberModel(new Long(prefs.getLong(PREF_FREQ, 400000000)), new Long(0), new Long(2147483647), new Long(FREQUENCY_STEP));
private JFrame frmTempestSdr;
private JFrame fullscreenframe;
private JDialog deviceframe;
private JSpinner spWidth;
private JSpinner spHeight;
@SuppressWarnings("rawtypes")
private JComboBox cbVideoModes;
private JSpinner spFrequency;
private JLabel lblFrequency;
private JSlider slGain;
private JSlider slMotionBlur;
private JLabel lblGain;
private JButton btnStartStop;
private final TSDRLibrary mSdrlib;
private ImageVisualizer visualizer;
private PlotVisualizer line_plotter, frame_plotter;
private AutoScaleVisualizer autoScaleVisualizer;
//private SNRVisualizer snrLevelVisualizer; to enable snr start by uncommenting this
private Rectangle visualizer_bounds;
private double framerate = 25;
private JTextField txtFramerate;
private HoldButton btnLowerFramerate, btnHigherFramerate, btnUp, btnDown, btnLeft, btnRight;
private JPanel pnInputDeviceSettings;
private ParametersToggleButton tglbtnAutoPosition, tglbtnPllFramerate, tglbtnAutocorrPlots, tglbtnSuperBandwidth;
private JToggleButton tglbtnLockHeightAndFramerate;
private JToggleButton btnReset;
private JToggleButton tglbtnDmp;
private JToggleButton btnAutoResolution;
private JLabel lblFrames;
private JSpinner spAreaAroundMouse;
private JOptionPane optpaneDevices;
private final TSDRSource[] souces = TSDRSource.getAvailableSources();
private final JMenuItem[] souces_menues = new JMenuItem[souces.length];
private final VideoMode[] videomodes = VideoMode.getVideoModes();
private volatile boolean auto_resolution = false;
private Integer auto_resolution_fps_id = null;
private Integer auto_resolution_fps_offset = null;
private final HashMap<Long, Integer> auto_resolution_map = new HashMap<Long, Integer>();
private volatile boolean snapshot = false;
private volatile boolean height_change_from_auto = false;
private volatile boolean plot_change_from_auto = false;
private volatile boolean spinner_change_from_auto = false;
private boolean video_mode_change_manually_triggered = false;
private int image_width = 1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frmTempestSdr.setVisible(true);
} catch (Exception e) {
displayException(null, e);
}
}
});
}
private static void displayException(final Component panel, final Throwable t) {
final String msg = t.getMessage();
final String exceptionname = t.getClass().getSimpleName();
JOptionPane.showMessageDialog(panel, (msg == null) || (msg.trim().isEmpty()) ? "A "+exceptionname+" occured." : msg, exceptionname, JOptionPane.ERROR_MESSAGE);
t.printStackTrace();
}
/**
* Create the application.
* @throws TSDRException
*/
public Main() throws TSDRException {
mSdrlib = new TSDRLibrary();
mSdrlib.registerFrameReadyCallback(this);
mSdrlib.registerValueChangedCallback(this);
initialize();
}
/**
* Initialize the contents of the frame.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private void initialize() {
final int width_initial = prefs.getInt(PREF_WIDTH, 576);
final int height_initial = prefs.getInt(PREF_HEIGHT, 625);
final double framerate_initial = prefs.getDouble(PREF_FRAMERATE, framerate);
final int closest_videomode_id = VideoMode.findClosestVideoModeId(width_initial, height_initial, framerate_initial, videomodes);
final boolean heightlock_enabled = prefs.getBoolean(PREF_HEIGHT_LOCK, true);
frmTempestSdr = new JFrame();
frmTempestSdr.setFocusable(true);
frmTempestSdr.setFocusableWindowState(true);
frmTempestSdr.addKeyListener(keyhook);
frmTempestSdr.setResizable(false);
frmTempestSdr.setTitle("TempestSDR");
frmTempestSdr.setBounds(100, 100, 810, 632);
frmTempestSdr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTempestSdr.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
frmTempestSdr.requestFocus();
}
});
visualizer = new ImageVisualizer();
visualizer.setBounds(10, 33, 530, 346);
visualizer.addKeyListener(keyhook);
visualizer.setFocusable(true);
visualizer.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (fullscreenframe.isVisible()) {
fullscreenframe.remove(visualizer);
visualizer.setBounds(visualizer_bounds);
frmTempestSdr.getContentPane().add(visualizer);
fullscreenframe.setVisible(false);
frmTempestSdr.requestFocus();
} else {
visualizer_bounds = visualizer.getBounds();
frmTempestSdr.remove(visualizer);
fullscreenframe.getContentPane().add(visualizer);
fullscreenframe.setVisible(true);
visualizer.requestFocus();
}
} else
visualizer.requestFocus();
}
});
frmTempestSdr.getContentPane().setLayout(null);
frmTempestSdr.getContentPane().add(visualizer);
line_plotter = new PlotVisualizer(height_transformer);
line_plotter.setBounds(10, 498, 727, 95);
frmTempestSdr.getContentPane().add(line_plotter);
line_plotter.setSelectedValue(height_initial);
btnStartStop = new JButton("Start");
btnStartStop.setBounds(581, 33, 209, 25);
btnStartStop.setEnabled(false);
btnStartStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performStartStop();
}
});
frmTempestSdr.getContentPane().add(btnStartStop);
lblFrequency = new JLabel("Freq.:");
lblFrequency.setBounds(591, 358, 55, 16);
lblFrequency.setHorizontalAlignment(SwingConstants.RIGHT);
frmTempestSdr.getContentPane().add(lblFrequency);
spFrequency = new JSpinner();
spFrequency.setBounds(651, 356, 139, 22);
spFrequency.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
onCenterFreqChange();
}
});
spFrequency.setModel(frequency_spinner_model);
frmTempestSdr.getContentPane().add(spFrequency);
framerate = framerate_initial;
frame_plotter = new PlotVisualizer(fps_transofmer);
frame_plotter.setBounds(10, 391, 727, 95);
frmTempestSdr.getContentPane().add(frame_plotter);
frame_plotter.setSelectedValue(framerate);
menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 825, 21);
frmTempestSdr.getContentPane().add(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
for (int i = 0; i < souces.length; i++) {
final TSDRSource src = souces[i];
souces_menues[i] = new JMenuItem("Load "+src.toString());
souces_menues[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onPluginSelected(src);
}
});
mnFile.add(souces_menues[i]);
}
mnFile.addSeparator();
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mnFile.add(exit);
mnTweaks = new JMenu("Tweaks");
menuBar.add(mnTweaks);
mntmTakeSnapshot = new JMenuItem("Take snapshot");
mntmTakeSnapshot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
snapshot = true;
}
});
mnTweaks.add(mntmTakeSnapshot);
chckbxmntmNewCheckItem = new JCheckBoxMenuItem("Inverted colours");
chckbxmntmNewCheckItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mSdrlib.setInvertedColors(chckbxmntmNewCheckItem.isSelected());
}
});
mnTweaks.add(chckbxmntmNewCheckItem);
chckbxmntmHighQualityRendering = new JCheckBoxMenuItem("High quality rendering", prefs.getBoolean(PREF_HQ_REDNERING, false));
chckbxmntmHighQualityRendering.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final boolean enabled = chckbxmntmHighQualityRendering.isSelected();
visualizer.setRenderingQualityHigh(enabled);
prefs.putBoolean(PREF_HQ_REDNERING, enabled);
}
});
mnTweaks.add(chckbxmntmHighQualityRendering);
final JCheckBoxMenuItem chckbxmntmNearestNeighbourResampling = new JCheckBoxMenuItem("Nearest neighbour resampling", prefs.getBoolean(PREF_NEAREST_NEIGHBOUR, false));
chckbxmntmNearestNeighbourResampling.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
final boolean enabled = chckbxmntmNearestNeighbourResampling.isSelected();
mSdrlib.setParam(PARAM.NEAREST_NEIGHBOUR_RESAMPLING, enabled ? 1 : 0);
prefs.putBoolean(PREF_NEAREST_NEIGHBOUR, enabled);
} catch (TSDRException e1) {
onException(mSdrlib, e1);
}
}
});
mnTweaks.add(chckbxmntmNearestNeighbourResampling);
chckbxmntmLowpassBeforeSync = new JCheckBoxMenuItem("Lowpass before sync detection", prefs.getBoolean(PREF_LOW_PASS_BEFORE_SYNC, true));
chckbxmntmLowpassBeforeSync.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
final boolean enabled = chckbxmntmLowpassBeforeSync.isSelected();
mSdrlib.setParam(PARAM.LOW_PASS_BEFORE_SYNC, enabled ? 1 : 0);
prefs.putBoolean(PREF_LOW_PASS_BEFORE_SYNC, enabled);
} catch (TSDRException e1) {
onException(mSdrlib, e1);
}
}
});
mnTweaks.add(chckbxmntmLowpassBeforeSync);
chckbxmntmAutoCorrectAfterProc = new JCheckBoxMenuItem("Autogain after lowpass", prefs.getBoolean(PREF_AUTOGAIN_AFTER_PROC, false));
chckbxmntmAutoCorrectAfterProc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
final boolean enabled = chckbxmntmAutoCorrectAfterProc.isSelected();
mSdrlib.setParam(PARAM.AUTOGAIN_AFTER_PROCESSING, enabled ? 1 : 0);
prefs.putBoolean(PREF_AUTOGAIN_AFTER_PROC, enabled);
} catch (TSDRException e1) {
onException(mSdrlib, e1);
}
}
});
mnTweaks.add(chckbxmntmAutoCorrectAfterProc);
btnReset = new JToggleButton("RST");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
btnReset.setSelected(true);
mSdrlib.setParam(PARAM.AUTOCORR_PLOTS_RESET, 1);
} catch (TSDRException e1) {
displayException(frmTempestSdr, e1);
}
}
});
btnReset.setToolTipText("Reset the autocorrelation plots");
btnReset.setMargin(new Insets(0, 0, 0, 0));
btnReset.setBounds(749, 417, 41, 22);
frmTempestSdr.getContentPane().add(btnReset);
cbVideoModes = new JComboBox();
cbVideoModes.setBounds(581, 70, 209, 22);
frmTempestSdr.getContentPane().add(cbVideoModes);
cbVideoModes.setModel(new DefaultComboBoxModel(videomodes));
if (closest_videomode_id != -1 && closest_videomode_id < videomodes.length && closest_videomode_id >= 0) cbVideoModes.setSelectedIndex(closest_videomode_id);
JLabel lblWidth = new JLabel("Width:");
lblWidth.setBounds(581, 100, 65, 16);
frmTempestSdr.getContentPane().add(lblWidth);
lblWidth.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblHeight = new JLabel("Height:");
lblHeight.setBounds(581, 127, 65, 16);
frmTempestSdr.getContentPane().add(lblHeight);
lblHeight.setHorizontalAlignment(SwingConstants.RIGHT);
JLabel lblFramerate = new JLabel("FPS:");
lblFramerate.setBounds(581, 154, 65, 16);
frmTempestSdr.getContentPane().add(lblFramerate);
lblFramerate.setHorizontalAlignment(SwingConstants.RIGHT);
spWidth = new JSpinner();
spWidth.setBounds(651, 97, 102, 22);
frmTempestSdr.getContentPane().add(spWidth);
spWidth.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
if (spinner_change_from_auto) return;
onResolutionChange((Integer) spWidth.getValue(), (Integer) spHeight.getValue(), framerate);
}
});
spWidth.setModel(new SpinnerNumberModel(width_initial, 1, 10000, 1));
spHeight = new JSpinner();
spHeight.setBounds(651, 124, 102, 22);
frmTempestSdr.getContentPane().add(spHeight);
spHeight.addChangeListener(new ChangeListener() {
private Integer oldheight = null;
public void stateChanged(ChangeEvent arg0) {
if (spinner_change_from_auto) return;
final Integer width = (Integer) spWidth.getValue();
final Integer newheight = (Integer) spHeight.getValue();
if (oldheight != null && tglbtnLockHeightAndFramerate.isSelected() && !height_change_from_auto)
onResolutionChange(width, newheight, framerate * oldheight / (double) newheight);
else
onResolutionChange(width, newheight, framerate);
oldheight = newheight;
}
});
spHeight.setModel(new SpinnerNumberModel(height_initial, 1, 10000, 1));
tglbtnLockHeightAndFramerate = new JToggleButton("L");
tglbtnLockHeightAndFramerate.setBounds(765, 123, 25, 22);
frmTempestSdr.getContentPane().add(tglbtnLockHeightAndFramerate);
tglbtnLockHeightAndFramerate.setToolTipText("Link the framerate with the height");
tglbtnLockHeightAndFramerate.setSelected(heightlock_enabled);
tglbtnLockHeightAndFramerate.setMargin(new Insets(0, 0, 0, 0));
tglbtnPllFramerate = new ParametersToggleButton(PARAM.PLLFRAMERATE, "A", prefs, true);
tglbtnPllFramerate.setBounds(765, 151, 25, 22);
frmTempestSdr.getContentPane().add(tglbtnPllFramerate);
tglbtnPllFramerate.setToolTipText("Automatically adjust the FPS to keep the video stable");
tglbtnPllFramerate.setParaChangeCallback(this);
tglbtnPllFramerate.setMargin(new Insets(0, 0, 0, 0));
tglbtnAutocorrPlots = new ParametersToggleButton(PARAM.AUTOCORR_PLOTS_OFF, "OFF", prefs, false);
tglbtnAutocorrPlots.setBounds(749, 442, 41, 22);
frmTempestSdr.getContentPane().add(tglbtnAutocorrPlots);
tglbtnAutocorrPlots.setToolTipText("Turn off autocorrelation plots");
tglbtnAutocorrPlots.setParaChangeCallback(this);
tglbtnAutocorrPlots.setMargin(new Insets(0, 0, 0, 0));
txtFramerate = new JTextField();
txtFramerate.setBounds(651, 151, 102, 22);
frmTempestSdr.getContentPane().add(txtFramerate);
txtFramerate.setText(String.format(FRAMERATE_FORMAT, framerate_initial));
txtFramerate.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (spinner_change_from_auto) return;
onFrameRateTextChanged();
}
});
txtFramerate.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent evt) {
if (spinner_change_from_auto) return;
if(evt.getKeyCode() == KeyEvent.VK_ENTER)
onFrameRateTextChanged();
}
});
txtFramerate.setColumns(10);
btnHigherFramerate = new HoldButton(">");
btnHigherFramerate.setBounds(712, 174, 41, 25);
frmTempestSdr.getContentPane().add(btnHigherFramerate);
btnHigherFramerate.setMargin(new Insets(0, 0, 0, 0));
btnLowerFramerate = new HoldButton("<");
btnLowerFramerate.setBounds(651, 173, 41, 25);
frmTempestSdr.getContentPane().add(btnLowerFramerate);
btnLowerFramerate.setMargin(new Insets(0, 0, 0, 0));
btnUp = new HoldButton("Up");
btnUp.setBounds(652, 210, 70, 25);
frmTempestSdr.getContentPane().add(btnUp);
btnUp.setMargin(new Insets(0, 0, 0, 0));
btnLeft = new HoldButton("Left");
btnLeft.setBounds(581, 241, 65, 25);
frmTempestSdr.getContentPane().add(btnLeft);
btnLeft.setMargin(new Insets(0, 0, 0, 0));
tglbtnAutoPosition = new ParametersToggleButton(PARAM.AUTOSHIFT, "Auto", prefs, true);
tglbtnAutoPosition.setBounds(651, 240, 70, 26);
frmTempestSdr.getContentPane().add(tglbtnAutoPosition);
tglbtnAutoPosition.setToolTipText("Automatically try to center on the image");
tglbtnAutoPosition.setParaChangeCallback(this);
tglbtnAutoPosition.setMargin(new Insets(0, 0, 0, 0));
btnRight = new HoldButton("Right");
btnRight.setBounds(725, 241, 65, 25);
frmTempestSdr.getContentPane().add(btnRight);
btnRight.setMargin(new Insets(0, 0, 0, 0));
btnDown = new HoldButton("Down");
btnDown.setBounds(651, 271, 70, 25);
frmTempestSdr.getContentPane().add(btnDown);
btnDown.setMargin(new Insets(0, 0, 0, 0));
JLabel lblMotionBlur = new JLabel("Lpass:");
lblMotionBlur.setBounds(581, 308, 65, 16);
frmTempestSdr.getContentPane().add(lblMotionBlur);
lblMotionBlur.setHorizontalAlignment(SwingConstants.RIGHT);
lblGain = new JLabel("Gain:");
lblGain.setBounds(581, 328, 65, 16);
frmTempestSdr.getContentPane().add(lblGain);
lblGain.setHorizontalAlignment(SwingConstants.RIGHT);
slGain = new JSlider();
slGain.setBounds(652, 328, 138, 26);
frmTempestSdr.getContentPane().add(slGain);
slGain.setValue((int) (prefs.getFloat(PREF_GAIN, 0.5f) * (slGain.getMaximum() - slGain.getMinimum()) + slGain.getMinimum()));
slMotionBlur = new JSlider();
slMotionBlur.setBounds(652, 308, 139, 22);
frmTempestSdr.getContentPane().add(slMotionBlur);
slMotionBlur.setValue((int) (prefs.getFloat(PREF_MOTIONBLUR, 0.0f) * (slMotionBlur.getMaximum() - slMotionBlur.getMinimum()) + slMotionBlur.getMinimum()));
lblFrames = new JLabel("00");
lblFrames.setToolTipText("The number of runs of the autocorrelation averaging");
lblFrames.setHorizontalAlignment(SwingConstants.RIGHT);
lblFrames.setBounds(742, 390, 48, 15);
frmTempestSdr.getContentPane().add(lblFrames);
spAreaAroundMouse = new JSpinner();
spAreaAroundMouse.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent arg0) {
setAreaAroundMouse();
}
});
spAreaAroundMouse.setToolTipText("The area around the mouse in pixels used to picking the best value");
spAreaAroundMouse.setModel(new SpinnerNumberModel(new Integer(prefs.getInt(PREF_AREA_AROUND_MOUSE, 15)), new Integer(0), null, new Integer(1)));
spAreaAroundMouse.setBounds(749, 466, 41, 20);
frmTempestSdr.getContentPane().add(spAreaAroundMouse);
btnAutoResolution = new JToggleButton("AUT");
btnAutoResolution.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final boolean selected = btnAutoResolution.isSelected();
if (selected) {
auto_resolution_map.clear();
auto_resolution_fps_id = null;
auto_resolution_fps_offset = null;
}
auto_resolution = selected;
}
});
btnAutoResolution.setToolTipText("Automatically choose the best resolution and framerate from the available data");
btnAutoResolution.setMargin(new Insets(0, 0, 0, 0));
btnAutoResolution.setBounds(749, 571, 41, 22);
frmTempestSdr.getContentPane().add(btnAutoResolution);
tglbtnSuperBandwidth = new ParametersToggleButton(PARAM.SUPERRESOLUTION, "T", null, false);
tglbtnSuperBandwidth.setText("SB");
tglbtnSuperBandwidth.setToolTipText("Simulate bandwidth several times bigger than what the device can offer");
tglbtnSuperBandwidth.setMargin(new Insets(0, 0, 0, 0));
tglbtnSuperBandwidth.setBounds(765, 278, 25, 22);
tglbtnSuperBandwidth.setParaChangeCallback(this);
frmTempestSdr.getContentPane().add(tglbtnSuperBandwidth);
autoScaleVisualizer = new AutoScaleVisualizer();
autoScaleVisualizer.setBounds(540, 33, 25, 346);
frmTempestSdr.getContentPane().add(autoScaleVisualizer);
slMotionBlur.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
onMotionBlurLevelChanged();
}
});
slGain.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
onGainLevelChanged();
}
});
btnDown.addHoldListener(new HoldListener() {
public void onHold(final int clickssofar) {
onSync(SYNC_DIRECTION.DOWN, clickssofar);
}
});
btnRight.addHoldListener(new HoldListener() {
public void onHold(final int clickssofar) {
onSync(SYNC_DIRECTION.RIGHT, clickssofar);
}
});
tglbtnAutoPosition.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
onAutoPostionChanged();
}
});
btnLeft.addHoldListener(new HoldListener() {
public void onHold(final int clickssofar) {
onSync(SYNC_DIRECTION.LEFT, clickssofar);
}
});
btnUp.addHoldListener(new HoldListener() {
public void onHold(final int clickssofar) {
onSync(SYNC_DIRECTION.UP, clickssofar);
}
});
btnLowerFramerate.addHoldListener(new HoldListener() {
public void onHold(final int clickssofar) {
onFrameRateChanged(true, clickssofar);
}
});
btnHigherFramerate.addHoldListener(new HoldListener() {
public void onHold(final int clickssofar) {
onFrameRateChanged(false, clickssofar);
}
});
tglbtnAutocorrPlots.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
frame_plotter.reset();
line_plotter.reset();
}
});
tglbtnLockHeightAndFramerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
prefs.putBoolean(PREF_HEIGHT_LOCK, tglbtnLockHeightAndFramerate.isSelected());
}
});
cbVideoModes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final VideoMode selected = (VideoMode) cbVideoModes.getSelectedItem();
for (int i = 0; i < videomodes.length; i++)
if (videomodes[i].equals(selected)) {
onVideoModeSelected(i);
return;
}
}
});
frmTempestSdr.setFocusableWindowState(true);
frmTempestSdr.requestFocus();
onGainLevelChanged();
onMotionBlurLevelChanged();
// full screen frame
fullscreenframe = new JFrame("Video display");
fullscreenframe.setFocusable(true);
fullscreenframe.addKeyListener(keyhook);
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
fullscreenframe.setSize(xSize,ySize);
fullscreenframe.setUndecorated(true);
fullscreenframe.setLocation(0, 0);
pnInputDeviceSettings = new JPanel();
pnInputDeviceSettings.setBounds(10, 68, 551, 74);
pnInputDeviceSettings.setLayout(null);
optpaneDevices = new JOptionPane();
optpaneDevices.setMessage(pnInputDeviceSettings);
optpaneDevices.setMessageType(JOptionPane.PLAIN_MESSAGE);
optpaneDevices.setOptionType(JOptionPane.OK_CANCEL_OPTION);
// dialog frame
deviceframe = optpaneDevices.createDialog(frmTempestSdr, "");
deviceframe.setResizable(false);
deviceframe.getContentPane().add(optpaneDevices);
onAutoPostionChanged();
setAreaAroundMouse();
visualizer.setRenderingQualityHigh(chckbxmntmHighQualityRendering.isSelected());
//snrLevelVisualizer = new SNRVisualizer();
//snrLevelVisualizer.setBounds(10, 33, 25, 346);
//frmTempestSdr.getContentPane().add(snrLevelVisualizer);
tglbtnDmp = new JToggleButton("DMP");
tglbtnDmp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
tglbtnDmp.setSelected(true);
mSdrlib.setParam(PARAM.AUTOCORR_DUMP, 1);
} catch (TSDRException e1) {
displayException(frmTempestSdr, e1);
}
}
});
tglbtnDmp.setToolTipText("Dump the full instanteneous autocorrelation to file");
tglbtnDmp.setMargin(new Insets(0, 0, 0, 0));
tglbtnDmp.setBounds(749, 498, 41, 22);
frmTempestSdr.getContentPane().add(tglbtnDmp);
try {
mSdrlib.setParam(PARAM.NEAREST_NEIGHBOUR_RESAMPLING, chckbxmntmNearestNeighbourResampling.isSelected() ? 1 : 0);
mSdrlib.setParam(PARAM.LOW_PASS_BEFORE_SYNC, chckbxmntmLowpassBeforeSync.isSelected() ? 1 : 0);
mSdrlib.setParam(PARAM.AUTOGAIN_AFTER_PROCESSING, chckbxmntmAutoCorrectAfterProc.isSelected() ? 1 : 0);
} catch (TSDRException e1) {}
}
private void onVideoModeSelected(final int modeid) {
if (video_mode_change_manually_triggered) return;
onResolutionChange(modeid);
}
private void setAreaAroundMouse() {
try {
final int area_around_mouse = (Integer) spAreaAroundMouse.getValue();
line_plotter.setAreaAroundMouse(area_around_mouse);
frame_plotter.setAreaAroundMouse(area_around_mouse);
prefs.putInt(PREF_AREA_AROUND_MOUSE, area_around_mouse);
} catch (Throwable t) {};
}
private void performStartStop() {
if (mSdrlib.isRunning()) {
new Thread() {
@Override
public void run() {
try {
if (!mSdrlib.isRunning()) btnStartStop.setEnabled(false);
mSdrlib.stop();
} catch (TSDRException e) {
displayException(frmTempestSdr, e);
}
}
}.start();
} else {
try {
final Long newfreq = (Long) spFrequency.getValue();
if (newfreq != null && newfreq > 0)
mSdrlib.setBaseFreq(newfreq);
float gain = (slGain.getValue() - slGain.getMinimum()) / (float) (slGain.getMaximum() - slGain.getMinimum());
if (gain < 0.0f) gain = 0.0f; else if (gain > 1.0f) gain = 1.0f;
mSdrlib.setGain(gain);
} catch (TSDRException e) {
displayException(frmTempestSdr, e);
return;
}
try {
image_width = (Integer) spWidth.getValue();
mSdrlib.startAsync((Integer) spHeight.getValue(), framerate);
} catch (TSDRException e1) {
displayException(frmTempestSdr, e1);
btnStartStop.setText("Start");
return;
}
btnStartStop.setText("Stop");
setPluginMenuEnabled(false);
}
}
private void onSync(final SYNC_DIRECTION dir, final int repeatssofar) {
mSdrlib.sync(repeatssofar, dir);
}
private void onResolutionChange(int id, double refreshrate, int height) {
if (id < 0 || id >= videomodes.length) return;
final VideoMode mode = videomodes[id];
onResolutionChange(mode.width, height, refreshrate, id);
}
private void onResolutionChange(int id) {
if (id < 0 || id >= videomodes.length) return;
final VideoMode mode = videomodes[id];
onResolutionChange(mode.width, mode.height, mode.refreshrate, id);
}
private void onResolutionChange(final double fps, final int height, final String msg) {
final int modeid = VideoMode.findClosestVideoModeId(fps, height, videomodes);
if (modeid >= 0 && modeid < videomodes.length) {
onResolutionChange(modeid, fps, height);
visualizer.setOSD(String.format(msg, " "+videomodes[modeid]), OSD_TIME_LONG);
} else {
setFrameRate(fps);
}
}
private void onResolutionChange(int width, int height, double framerate) {
onResolutionChange(width, height, framerate, VideoMode.findClosestVideoModeId(width, height, framerate, videomodes));
}
private void onResolutionChange(int width, int height, double framerate, int closest_videomode_id) {
this.framerate = framerate;
plot_change_from_auto = true;
frame_plotter.setSelectedValue(framerate);
line_plotter.setSelectedValue(height);
spinner_change_from_auto = true;
final String frameratetext = String.format(FRAMERATE_FORMAT, framerate);
txtFramerate.setText(frameratetext);
try {
image_width = width;
mSdrlib.setResolution(height, framerate);
prefs.putDouble(PREF_FRAMERATE, framerate);
prefs.putInt(PREF_WIDTH, width);
spWidth.setValue(width);
prefs.putInt(PREF_HEIGHT, height);
spHeight.setValue(height);
video_mode_change_manually_triggered = true;
if (closest_videomode_id >= 0 && closest_videomode_id < videomodes.length) {
cbVideoModes.setSelectedIndex(closest_videomode_id);
cbVideoModes.repaint();
}
video_mode_change_manually_triggered = false;
} catch (TSDRException e) {
displayException(frmTempestSdr, e);
} finally {
plot_change_from_auto = false;
}
spinner_change_from_auto = false;
}
private void onCenterFreqChange() {
final Long newfreq = (Long) spFrequency.getValue();
if (newfreq == null || newfreq < 0) return;
try {
mSdrlib.setBaseFreq(newfreq);
visualizer.setOSD("Freq: "+newfreq+" Hz", OSD_TIME);
prefs.putLong(PREF_FREQ, newfreq);
} catch (TSDRException e) {
displayException(frmTempestSdr, e);
}
}
private void onGainLevelChanged() {
float gain = (slGain.getValue() - slGain.getMinimum()) / (float) (slGain.getMaximum() - slGain.getMinimum());
if (gain < 0.0f) gain = 0.0f; else if (gain > 1.0f) gain = 1.0f;
try {
mSdrlib.setGain(gain);
prefs.putFloat(PREF_GAIN, gain);
} catch (TSDRException e) {
displayException(frmTempestSdr, e);
}
}
private void onMotionBlurLevelChanged() {
float mblur = slMotionBlur.getValue() / 100.0f;
try {
mSdrlib.setMotionBlur(mblur);
prefs.putFloat(PREF_MOTIONBLUR, mblur);
} catch (TSDRException e) {
displayException(frmTempestSdr, e);
}
}
private void onFrameRateTextChanged() {
try {
final Double val = Double.parseDouble(txtFramerate.getText().trim());
if (val != null && val > 0) {
framerate = val;
frame_plotter.setSelectedValue(framerate);
}
} catch (NumberFormatException e) {}
setFrameRate(framerate);
}
private void setFramerateValButDoNotSyncWithLibrary(final double val) {
framerate = val;
frame_plotter.setSelectedValue(framerate);
final String frameratetext = String.format(FRAMERATE_FORMAT, framerate);
txtFramerate.setText(frameratetext);
prefs.putDouble(PREF_FRAMERATE, framerate);
}
private void setFrameRate(final double val) {
final int width = (Integer) spWidth.getValue();
final int height = (Integer) spHeight.getValue();
onResolutionChange(width, height, val);
final String frameratetext = String.format(FRAMERATE_FORMAT, framerate);
visualizer.setOSD("Framerate: "+frameratetext+" fps", OSD_TIME);
}
private void onKeyboardKeyPressed(final KeyEvent e) {
final int keycode = e.getKeyCode();
if (e.isShiftDown()) {
switch (keycode) {
case KeyEvent.VK_LEFT:
btnLeft.doHold();
visualizer.setOSD("Move: Left", OSD_TIME);
break;
case KeyEvent.VK_RIGHT:
btnRight.doHold();
visualizer.setOSD("Move: Right", OSD_TIME);
break;
case KeyEvent.VK_UP:
btnUp.doHold();
visualizer.setOSD("Move: Up", OSD_TIME);
break;
case KeyEvent.VK_DOWN:
btnDown.doHold();
visualizer.setOSD("Move: Down", OSD_TIME);
break;
}
} else {
switch (keycode) {
case KeyEvent.VK_RIGHT:
btnHigherFramerate.doHold();
break;
case KeyEvent.VK_LEFT:
btnLowerFramerate.doHold();
break;
case KeyEvent.VK_UP:
spFrequency.setValue(frequency_spinner_model.getNextValue());
break;
case KeyEvent.VK_DOWN:
spFrequency.setValue(frequency_spinner_model.getPreviousValue());
break;
}
}
}
private void onKeyboardKeyReleased(final KeyEvent e) {
final int keycode = e.getKeyCode();
if (e.isShiftDown()) {
switch (keycode) {
case KeyEvent.VK_LEFT:
btnLeft.doRelease();
btnHigherFramerate.doRelease();
break;
case KeyEvent.VK_RIGHT:
btnRight.doRelease();
btnLowerFramerate.doRelease();
break;
case KeyEvent.VK_UP:
btnUp.doRelease();
break;
case KeyEvent.VK_DOWN:
btnDown.doRelease();
break;
}
} else {
switch (keycode) {
case KeyEvent.VK_RIGHT:
btnLeft.doRelease();
btnHigherFramerate.doRelease();
break;
case KeyEvent.VK_LEFT:
btnRight.doRelease();
btnLowerFramerate.doRelease();
break;
}
}
}
private void onFrameRateChanged(boolean left, int clicksofar) {
double amount = clicksofar * clicksofar * FRAMERATE_MIN_CHANGE;
if (amount > 0.05) amount = 0.05;
if (left && framerate > amount)
framerate -= amount;
else if (!left)
framerate += amount;
setFrameRate(framerate);
}
private void onAutoPostionChanged() {
if (tglbtnAutoPosition.isSelected()) {
btnDown.setEnabled(false);
btnUp.setEnabled(false);
btnLeft.setEnabled(false);
btnRight.setEnabled(false);
} else {
btnDown.setEnabled(true);
btnUp.setEnabled(true);
btnLeft.setEnabled(true);
btnRight.setEnabled(true);
}
}
private void setPluginMenuEnabled(boolean value) {
for (int i = 0; i < souces_menues.length; i++)
souces_menues[i].setEnabled(value);
}
private int roundData(double height) {
return (int) Math.round(height);
}
private void onPluginSelected(final TSDRSource current) {
if (!mSdrlib.isRunning()) btnStartStop.setEnabled(false);
try {
mSdrlib.unloadPlugin();
} catch (TSDRException e) {};
pnInputDeviceSettings.removeAll();
pnInputDeviceSettings.revalidate();
pnInputDeviceSettings.repaint();
final String preferences = prefs.get(PREF_COMMAND_PREFIX+current, "");
current.setOnParameterChangedCallback(this);
final ActRegistrator reg = new ActRegistrator();
final boolean usesdialog = current.populateGUI(pnInputDeviceSettings, preferences, reg);
if (usesdialog) {
pnInputDeviceSettings.revalidate();
pnInputDeviceSettings.repaint();
deviceframe.setTitle("Load "+current);
deviceframe.setSize(570, 170);
deviceframe.setLocationByPlatform(true);
deviceframe.setVisible(true);
try {
if (((Integer)optpaneDevices.getValue()).intValue() == JOptionPane.OK_OPTION)
reg.action();
} catch (NullPointerException e) {};
}
}
private static BufferedImage resize(BufferedImage image, int width, int height) {
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
@Override
public void onFrameReady(TSDRLibrary lib, BufferedImage frame) {
if (snapshot) {
snapshot = false;
try {
final BufferedImage resized_frame = resize(frame, image_width, frame.getHeight());
final int freq = (int) Math.abs(((Long) spFrequency.getValue())/1000000.0d);
final String filename = "TSDR_"+(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")).format(new Date())+"_"+freq+"MHz"+"."+SNAPSHOT_FORMAT;
final File outputfile = new File(filename);
ImageIO.write(resized_frame, SNAPSHOT_FORMAT, outputfile);
visualizer.setOSD("Saved to "+outputfile.getAbsolutePath(), OSD_TIME);
} catch (Throwable e) {
visualizer.setOSD("Failed to capture snapshot", OSD_TIME);
e.printStackTrace();
}
}
visualizer.drawImage(frame, image_width);
}
@Override
public void onException(TSDRLibrary lib, Exception e) {
btnStartStop.setEnabled(true);
btnStartStop.setText("Start");
setPluginMenuEnabled(true);
displayException(frmTempestSdr, e);
System.gc();
}
@Override
public void onStopped(TSDRLibrary lib) {
btnStartStop.setEnabled(true);
btnStartStop.setText("Start");
setPluginMenuEnabled(true);
System.gc();
}
private final KeyAdapter keyhook = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
onKeyboardKeyPressed(e);
super.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
onKeyboardKeyReleased(e);
super.keyReleased(e);
}
};
private JMenuBar menuBar;
private JMenu mnTweaks;
private JMenuItem mntmTakeSnapshot;
private JCheckBoxMenuItem chckbxmntmNewCheckItem;
@Override
public void onParametersChanged(TSDRSource source) {
setPluginMenuEnabled(false);
if (!mSdrlib.isRunning()) btnStartStop.setEnabled(false);
try {
try {
mSdrlib.unloadPlugin();
} catch (TSDRLoadPluginException e) {};
mSdrlib.loadPlugin(source);
} catch (Throwable t) {
if (!mSdrlib.isRunning()) btnStartStop.setEnabled(false);
displayException(frmTempestSdr, t);
setPluginMenuEnabled(true);
return;
}
setPluginMenuEnabled(true);
btnStartStop.setEnabled(true);
// set the field with the text arguments
prefs.put(PREF_COMMAND_PREFIX+source, source.getParams());
}
@Override
public void onSetParam(PARAM param, long value) {
try {
if (mSdrlib != null)
mSdrlib.setParam(param, value);
} catch (Throwable e) {
displayException(frmTempestSdr, e);
return;
}
}
@Override
public void onSetParam(PARAM_DOUBLE param, double value) {
try {
if (mSdrlib != null)
mSdrlib.setParamDouble(param, value);
} catch (Throwable e) {
displayException(frmTempestSdr, e);
return;
}
}
@Override
public void onValueChanged(VALUE_ID id, double arg0, double arg1) {
switch (id) {
case PLL_FRAMERATE:
setFramerateValButDoNotSyncWithLibrary(arg0);
break;
case AUTOCORRECT_RESET:
btnReset.setSelected(false);
break;
case FRAMES_COUNT:
lblFrames.setText(Integer.toString((int) arg1));
break;
case AUTOGAIN:
autoScaleVisualizer.setValue(arg0, arg1);
break;
case SNR:
//snrLevelVisualizer.setSNRValue(arg0);
break;
case AUTOCORRECT_DUMPED:
tglbtnDmp.setSelected(false);
final File f = new File("autocorr.csv");
visualizer.setOSD(f.exists() ? "Autocorrelation dumped "+f.getAbsolutePath() : "Failed to dump autocorrelation", OSD_TIME);
break;
default:
System.out.println("Java Main received notification that value "+id+" has changed to arg0="+arg0+" and arg1="+arg1);
break;
}
}
private Long hashHeightAndFPS(double fps, int height) {
return (Long) (long) (fps * height);
}
@Override
public void onIncommingPlot(PLOT_ID id, int offset, double[] data, int size, long samplerate) {
btnReset.setSelected(false);
switch (id) {
case FRAME:
frame_plotter.plot(data, offset, size, samplerate);
if (auto_resolution) {
auto_resolution_fps_id = frame_plotter.getMaxIndex();
auto_resolution_fps_offset = frame_plotter.getOffset();
}
break;
case LINE:
line_plotter.plot(data, offset, size, samplerate);
if (auto_resolution && auto_resolution_fps_id != null) {
assert(auto_resolution_fps_offset != null);
assert(samplerate == line_plotter.getSamplerate());
if (frame_plotter.getSamplerate() == samplerate) {
final double fps = fps_transofmer.fromIndex(auto_resolution_fps_id, auto_resolution_fps_offset, samplerate);
final int height = roundData(height_transformer.fromIndexAndLength(line_plotter.getMaxIndex(), line_plotter.getOffset(), samplerate, auto_resolution_fps_id+auto_resolution_fps_offset));
final Long key = hashHeightAndFPS(fps, height);
Integer value = auto_resolution_map.get(key);
if (value != null && value == AUTO_FRAMERATE_CONVERGANCE_ITERATIONS) {
onResolutionChange(fps, height, "Detected %s");
btnAutoResolution.setSelected(false);
auto_resolution = false;
} else {
if (value == null) value = 0;
value++;
auto_resolution_map.put(key, value);
}
}
}
break;
default:
System.out.println("Java Main received unimplemented notification plot value "+id+" with size "+size);
break;
}
}
private class ActRegistrator implements ActionListenerRegistrator {
private final ArrayList<ActionListener> listeners = new ArrayList<ActionListener>();
private final ActionEvent e = new ActionEvent(Main.this, 0, null);
@Override
public void addActionListener(ActionListener l) {
listeners.add(l);
}
public void action() {
for (final ActionListener l : listeners)
l.actionPerformed(e);
}
}
private final TransformerAndCallback fps_transofmer = new TransformerAndCallback() {
@Override
public String getDescription(final double val, final int id) { return String.format("%.1f fps", val); }
@Override
public double fromIndex(int id, int offset, long samplerate) {
return samplerate / (double) (offset + id);
}
public void onMouseExited() {
height_transformer.setLength(null);
line_plotter.repaint();
}
public void onMouseMoved(int m_id, int offset, long samplerate) {
height_transformer.setLength(offset + m_id);
line_plotter.repaint();
}
public void executeIdSelected(int sel_id, int offset, long samplerate) {
if (plot_change_from_auto) return;
height_transformer.setLength(offset + sel_id);
final double fps = frame_plotter.getSelectedValue();
final int height = roundData(line_plotter.getSelectedValue());
onResolutionChange(fps, height, "Chosen %s");
}
@Override
public int toIndex(double val, int offset, long samplerate) {
return roundData (samplerate / val - offset);
}
};
private class TransformerAndCallbackHeight extends TransformerAndCallback {
private Integer length = null;
public void setLength(final Integer length) {
this.length = length;
}
@Override
public String getDescription(final double val, final int id) {
final int err = roundData( Math.max(Math.abs(line_plotter.getValueFromId(id+1)-val), Math.abs(line_plotter.getValueFromId(id-1)-val)) ) - 1;
if (err > 0)
return String.format("%d (±%d) px",roundData(val), err);
else
return String.format("%d px",roundData(val));
}
public double fromIndexAndLength(int id, int offset, long samplerate, double length) {
final double linelength = offset + id;
return length / linelength;
}
@Override
public double fromIndex(int id, int offset, long samplerate) {
return fromIndexAndLength(id, offset, samplerate, (this.length == null) ? ((double) (samplerate / framerate)) : ((double) this.length));
}
public void executeIdSelected(int sel_id, int offset, long samplerate) {
if (plot_change_from_auto) return;
final int height = roundData(line_plotter.getSelectedValue());
onResolutionChange(framerate, height, "Chosen %s");
}
@Override
public int toIndex(double val, int offset, long samplerate) {
final double length = (this.length == null) ? ((double) (samplerate / framerate)) : ((double) this.length);
return roundData (length / val - offset);
}
}
private final TransformerAndCallbackHeight height_transformer = new TransformerAndCallbackHeight();
private JCheckBoxMenuItem chckbxmntmHighQualityRendering;
private JCheckBoxMenuItem chckbxmntmLowpassBeforeSync;
private JCheckBoxMenuItem chckbxmntmAutoCorrectAfterProc;
}
| rtlsdrblog/TempestSDR | JavaGUI/src/martin/tempest/gui/Main.java |
179,950 | /*
* Copyright (c) 2010, 2019 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.jersey.message.internal;
import java.text.ParseException;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.inject.Singleton;
import org.glassfish.jersey.internal.LocalizationMessages;
import org.glassfish.jersey.spi.HeaderDelegateProvider;
import static org.glassfish.jersey.message.internal.Utils.throwIllegalArgumentExceptionIfNull;
/**
* Header delegate provider for MediaType.
*
* @author Marc Hadley
* @author Marek Potociar
* @author Martin Matula
*/
@Singleton
public class MediaTypeProvider implements HeaderDelegateProvider<MediaType> {
private static final String MEDIA_TYPE_IS_NULL = LocalizationMessages.MEDIA_TYPE_IS_NULL();
@Override
public boolean supports(Class<?> type) {
return MediaType.class.isAssignableFrom(type);
}
@Override
public String toString(MediaType header) {
throwIllegalArgumentExceptionIfNull(header, MEDIA_TYPE_IS_NULL);
StringBuilder b = new StringBuilder();
b.append(header.getType()).append('/').append(header.getSubtype());
for (Map.Entry<String, String> e : header.getParameters().entrySet()) {
b.append(";").append(e.getKey()).append('=');
StringBuilderUtils.appendQuotedIfNonToken(b, e.getValue());
}
return b.toString();
}
@Override
public MediaType fromString(String header) {
throwIllegalArgumentExceptionIfNull(header, MEDIA_TYPE_IS_NULL);
var commaIndex = header.indexOf(',');
if (commaIndex != -1) {
var colonIndex = header.indexOf(';', commaIndex);
if (colonIndex != -1)
header = header.substring(0, commaIndex) + header.substring(colonIndex);
else
header = header.substring(0, commaIndex);
}
try {
return valueOf(HttpHeaderReader.newInstance(header));
} catch (ParseException ex) {
throw new IllegalArgumentException(
"Error parsing media type '" + header + "'", ex);
}
}
/**
* Create a new {@link javax.ws.rs.core.MediaType} instance from a header reader.
*
* @param reader header reader.
* @return new {@code MediaType} instance.
*
* @throws ParseException in case of a header parsing error.
*/
public static MediaType valueOf(HttpHeaderReader reader) throws ParseException {
// Skip any white space
reader.hasNext();
// Get the type
final String type = reader.nextToken().toString();
reader.nextSeparator('/');
// Get the subtype
final String subType = reader.nextToken().toString();
Map<String, String> params = null;
if (reader.hasNext()) {
params = HttpHeaderReader.readParameters(reader);
}
return new MediaType(type, subType, params);
}
}
| theonedev/onedev | server-core/src/main/java/org/glassfish/jersey/message/internal/MediaTypeProvider.java |
179,951 | package com.dexvis.util;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import com.dexvis.dex.Dex;
import com.dexvis.dex.DexData;
/**
*
* This class defines useful utilities for dealing with the jdbc.
*
* @author Patrick E. Martin
* @version 1.0
*
*/
public class SqlUtil
{
private static Logger logger = Logger.getLogger(SqlUtil.class.getName());
/**
*
* Close a statement silently, handle all exceptions, should they occur.
*
* @param stmt
* The statement to close.
*
* @return Always a null value so the statement may be nulled out and closed
* in one line.
*
*/
public final static Statement close(Statement stmt)
{
try
{
if (stmt != null)
{
synchronized (stmt)
{
stmt.close();
}
}
}
catch(Exception ex)
{
logger.log(Level.SEVERE, "Couldn't close statement.", ex);
}
return null;
}
/**
*
* Close a statement silently, handle all exceptions, should they occur.
*
* @param stmt
* The statement to close.
*
* @return Always a null value so the statement may be nulled out and closed
* in one line.
*
*/
public final static Statement close(PreparedStatement pstmt)
{
try
{
if (pstmt != null)
{
synchronized (pstmt)
{
pstmt.close();
}
}
}
catch(Exception ex)
{
logger.log(Level.SEVERE, "Couldn't close statement.", ex);
}
return null;
}
/**
*
* Given an int datatype, return the java.sql.Types name for that datatype.
*
* @param dataType
* The int datatype for which we need the string datatype name.
*
* @return A string representation of the datatype name.
*
*/
public static String getTypeName(int dataType)
{
switch (dataType)
{
case Types.BIGINT:
return "BIGINT";
case Types.BINARY:
return "BINARY";
case Types.BIT:
return "BIT";
case Types.CHAR:
return "CHAR";
case Types.DATE:
return "DATE";
case Types.DECIMAL:
return "DECIMAL";
case Types.DOUBLE:
return "DOUBLE";
case Types.FLOAT:
return "FLOAT";
case Types.INTEGER:
return "INTEGER";
case Types.LONGVARBINARY:
return "LONGVARBINARY";
case Types.LONGVARCHAR:
return "LONGVARCHAR";
case Types.NULL:
return "NULL";
case Types.NUMERIC:
return "NUMERIC";
case Types.OTHER:
return "OTHER";
case Types.REAL:
return "REAL";
case Types.SMALLINT:
return "SMALLINT";
case Types.TIME:
return "TIME";
case Types.TIMESTAMP:
return "TIMESTAMP";
case Types.TINYINT:
return "TINYINT";
case Types.VARBINARY:
return "VARBINARY";
case Types.VARCHAR:
return "VARCHAR";
}
return "UNKNOWN";
}
/**
*
* Close a connection silently, handle all exceptions, should they occur.
*
* @param con
* The connection to close.
*
* @return Always a null value so the connection may be nulled out and closed
* in one line.
*
*/
public final static Connection close(Connection con)
{
try
{
if (con != null)
{
synchronized (con)
{
con.close();
}
}
}
catch(Exception ex)
{
logger.log(Level.SEVERE, "Couldn't close connection.", ex);
}
return null;
}
/**
*
* Close a ResultSet silently, handle all exceptions, should they occur.
*
* @param stmt
* The ResultSet to close.
*
* @return Always a null value so the ResultSet may be nulled out and closed
* in one line.
*
*/
public final static ResultSet close(ResultSet rs)
{
try
{
if (rs != null)
{
synchronized (rs)
{
rs.close();
}
}
}
catch(Exception ex)
{
logger.log(Level.SEVERE, "Couldn't close result set.", ex);
}
return null;
}
/**
*
* Print an exception, or series of exceptions to the designated output
* stream.
*
* @param os
* The output stream to print to.
* @param sqlEx
* The exception(s) to print.
*
*
*/
public static void printExceptions(OutputStream os, SQLException sqlEx)
{
PrintWriter pw = new PrintWriter(os, true);
while (sqlEx != null)
{
pw.println("----------------------------------------------");
pw.println("ERROR CODE : " + sqlEx.getErrorCode());
pw.println("ERROR STATE: " + sqlEx.getSQLState());
sqlEx.printStackTrace(pw);
sqlEx = sqlEx.getNextException();
}
}
public static List<Map<String, Object>> getResultSet(ResultSet rs)
throws SQLException
{
int i = 0;
Map<String, Object> row = null;
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
// Process the data.
if (rs != null)
{
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
for (int r = 1; rs.next(); r++)
{
row = new HashMap<String, Object>();
for (i = 1; i <= numCols; i++)
{
logger.fine(" COLUMN: '" + rsmd.getColumnName(i) + "'='"
+ rsmd.getColumnTypeName(i) + "'");
if (rsmd.getColumnTypeName(i).equals("DATE"))
{
row.put(rsmd.getColumnLabel(i).trim(), rs.getTimestamp(i));
}
else
{
row.put(rsmd.getColumnLabel(i).trim(),
"" + rs.getString(rsmd.getColumnLabel(i)));
}
}
logger.finest("ROW[" + r + "]: " + row);
resultList.add(row);
}
}
return resultList;
}
public static List<Map<String, Object>> getResultSetNew(ResultSet rs)
throws SQLException
{
int i = 0;
Map<String, Object> row = null;
List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
// Process the data.
if (rs != null)
{
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
while (rs.next())
{
row = new HashMap<String, Object>();
for (i = 1; i <= numCols; i++)
{
if (rsmd.getColumnTypeName(i).equals("DATE"))
{
row.put(rsmd.getColumnLabel(i).trim(), rs.getTimestamp(i));
}
else
{
row.put(rsmd.getColumnLabel(i),
"" + rs.getString(rsmd.getColumnLabel(i)));
}
}
logger.finest("ROW: " + row);
resultList.add(row);
}
}
return resultList;
}
public static Connection getConnection(DataSource ds, String username,
String password, int numTries, long retryWait) throws SQLException
{
Connection con = null;
for (int i = 0; i < numTries; i++)
{
try
{
con = ds.getConnection(username, password);
}
catch(SQLException sqlEx)
{
if (i < (numTries - 1))
{
logger
.severe("Attempt #"
+ (i + 1)
+ ", Unable to create connection from DataSource, trying again in "
+ retryWait + " ms.");
try
{
Thread.sleep(retryWait);
}
catch(Exception ex)
{
}
}
else
{
logger.severe("Unable to create connection from DataSource.");
throw (sqlEx);
}
}
}
return con;
}
public static Connection getConnection(DataSource ds, int numTries,
long retryWait) throws SQLException
{
Connection con = null;
for (int i = 0; i < numTries; i++)
{
try
{
con = ds.getConnection();
}
catch(SQLException sqlEx)
{
if (i < (numTries - 1))
{
logger
.severe("Attempt #"
+ (i + 1)
+ ", Unable to create connection from DataSource, trying again in "
+ retryWait + " ms.");
try
{
Thread.sleep(retryWait);
}
catch(Exception ex)
{
}
}
else
{
logger.severe("Unable to create connection from DataSource.");
throw (sqlEx);
}
}
}
return con;
}
}
| PatMartin/Dex | src/com/dexvis/util/SqlUtil.java |
179,952 | /*
* Copyright 2015 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.models;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.gitblit.Constants;
/**
* A FilestoreModel represents a file stored outside a repository but referenced by the repository using a unique objectID
*
* @author Paul Martin
*
*/
public class FilestoreModel implements Serializable, Comparable<FilestoreModel> {
private static final long serialVersionUID = 1L;
private static final String metaRegexText = new StringBuilder()
.append("version\\shttps://git-lfs.github.com/spec/v1\\s+")
.append("oid\\ssha256:(" + Constants.REGEX_SHA256 + ")\\s+")
.append("size\\s([0-9]+)")
.toString();
private static final Pattern metaRegex = Pattern.compile(metaRegexText);
private static final int metaRegexIndexSHA = 1;
private static final int metaRegexIndexSize = 2;
public final String oid;
private Long size;
private Status status;
//Audit
private String stateChangedBy;
private Date stateChangedOn;
//Access Control
private List<String> repositories;
public FilestoreModel(String id, long definedSize) {
oid = id;
size = definedSize;
status = Status.ReferenceOnly;
}
public FilestoreModel(String id, long expectedSize, UserModel user, String repo) {
oid = id;
size = expectedSize;
status = Status.Upload_Pending;
stateChangedBy = user.getName();
stateChangedOn = new Date();
repositories = new ArrayList<String>();
repositories.add(repo);
}
/*
* Attempts to create a FilestoreModel from the given meta string
*
* @return A valid FilestoreModel if successful, otherwise null
*/
public static FilestoreModel fromMetaString(String meta) {
Matcher m = metaRegex.matcher(meta);
if (m.find()) {
try
{
final Long size = Long.parseLong(m.group(metaRegexIndexSize));
final String sha = m.group(metaRegexIndexSHA);
return new FilestoreModel(sha, size);
} catch (Exception e) {
//Fail silent - it is not a valid filestore item
}
}
return null;
}
public synchronized long getSize() {
return size;
}
public synchronized Status getStatus() {
return status;
}
public synchronized String getChangedBy() {
return stateChangedBy;
}
public synchronized Date getChangedOn() {
return stateChangedOn;
}
public synchronized void setStatus(Status status, UserModel user) {
this.status = status;
stateChangedBy = user.getName();
stateChangedOn = new Date();
}
public synchronized void reset(UserModel user, long size) {
status = Status.Upload_Pending;
stateChangedBy = user.getName();
stateChangedOn = new Date();
this.size = size;
}
/*
* Handles possible race condition with concurrent connections
* @return true if action can proceed, false otherwise
*/
public synchronized boolean actionUpload(UserModel user) {
if (status == Status.Upload_Pending) {
status = Status.Upload_In_Progress;
stateChangedBy = user.getName();
stateChangedOn = new Date();
return true;
}
return false;
}
public synchronized boolean isInErrorState() {
return (this.status.value < 0);
}
public synchronized void addRepository(String repo) {
if (status != Status.ReferenceOnly) {
if (!repositories.contains(repo)) {
repositories.add(repo);
}
}
}
public synchronized void removeRepository(String repo) {
if (status != Status.ReferenceOnly) {
repositories.remove(repo);
}
}
public synchronized boolean isInRepositoryList(List<String> repoList) {
if (status != Status.ReferenceOnly) {
for (String name : repositories) {
if (repoList.contains(name)) {
return true;
}
}
}
return false;
}
public static enum Status {
ReferenceOnly(-42),
Deleted(-30),
AuthenticationRequired(-20),
Error_Unknown(-8),
Error_Unexpected_Stream_End(-7),
Error_Invalid_Oid(-6),
Error_Invalid_Size(-5),
Error_Hash_Mismatch(-4),
Error_Size_Mismatch(-3),
Error_Exceeds_Size_Limit(-2),
Error_Unauthorized(-1),
//Negative values provide additional information and may be treated as 0 when not required
Unavailable(0),
Upload_Pending(1),
Upload_In_Progress(2),
Available(3);
final int value;
Status(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return name().toLowerCase().replace('_', ' ');
}
public static Status fromState(int state) {
for (Status s : values()) {
if (s.getValue() == state) {
return s;
}
}
throw new NoSuchElementException(String.valueOf(state));
}
}
@Override
public int compareTo(FilestoreModel o) {
return this.oid.compareTo(o.oid);
}
}
| gitblit-org/gitblit | src/main/java/com/gitblit/models/FilestoreModel.java |
179,953 | /*
* Credits: ported to Java by Martin Paljak
* https://github.com/crocs-muni/roca
*
* ROCA detector using the moduli detector.
* This detector port is unmaintained. Please refer to the original Python implementation for more details.
*/
import java.math.BigInteger;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
public class BrokenKey {
private static final int[] prims = new int[]{3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167};
private static final BigInteger[] primes = new BigInteger[prims.length];
static {
for (int i = 0; i < prims.length; i++) {
primes[i] = BigInteger.valueOf(prims[i]);
}
}
private static final BigInteger[] markers = new BigInteger[]{
new BigInteger("6"),
new BigInteger("30"),
new BigInteger("126"),
new BigInteger("1026"),
new BigInteger("5658"),
new BigInteger("107286"),
new BigInteger("199410"),
new BigInteger("8388606"),
new BigInteger("536870910"),
new BigInteger("2147483646"),
new BigInteger("67109890"),
new BigInteger("2199023255550"),
new BigInteger("8796093022206"),
new BigInteger("140737488355326"),
new BigInteger("5310023542746834"),
new BigInteger("576460752303423486"),
new BigInteger("1455791217086302986"),
new BigInteger("147573952589676412926"),
new BigInteger("20052041432995567486"),
new BigInteger("6041388139249378920330"),
new BigInteger("207530445072488465666"),
new BigInteger("9671406556917033397649406"),
new BigInteger("618970019642690137449562110"),
new BigInteger("79228162521181866724264247298"),
new BigInteger("2535301200456458802993406410750"),
new BigInteger("1760368345969468176824550810518"),
new BigInteger("50079290986288516948354744811034"),
new BigInteger("473022961816146413042658758988474"),
new BigInteger("10384593717069655257060992658440190"),
new BigInteger("144390480366845522447407333004847678774"),
new BigInteger("2722258935367507707706996859454145691646"),
new BigInteger("174224571863520493293247799005065324265470"),
new BigInteger("696898287454081973172991196020261297061886"),
new BigInteger("713623846352979940529142984724747568191373310"),
new BigInteger("1800793591454480341970779146165214289059119882"),
new BigInteger("126304807362733370595828809000324029340048915994"),
new BigInteger("11692013098647223345629478661730264157247460343806"),
new BigInteger("187072209578355573530071658587684226515959365500926")
};
public static boolean isAffected(X509Certificate c) {
if (!(c.getPublicKey() instanceof RSAPublicKey))
return false;
return isAffected((RSAPublicKey) c.getPublicKey());
}
public static boolean isAffected(RSAPublicKey pubkey) {
BigInteger modulus = pubkey.getModulus();
for (int i = 0; i < primes.length; i++) {
if (BigInteger.ONE.shiftLeft(modulus.remainder(primes[i]).intValue()).and(markers[i]).equals(BigInteger.ZERO)) {
return false;
}
}
return true;
}
}
| crocs-muni/roca | java/BrokenKey.java |
179,954 | /*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna.gui2;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.input.KeyStroke;
import com.googlecode.lanterna.input.KeyType;
import com.googlecode.lanterna.input.MouseAction;
import com.googlecode.lanterna.input.MouseActionType;
/**
* This class is a list box implementation that displays a number of items that has actions associated with them. You
* can activate this action by pressing the Enter or Space keys on the keyboard and the action associated with the
* currently selected item will fire.
* @author Martin
*/
public class ActionListBox extends AbstractListBox<Runnable, ActionListBox> {
/**
* Default constructor, creates an {@code ActionListBox} with no pre-defined size that will request to be big enough
* to display all items
*/
public ActionListBox() {
this(null);
}
/**
* Creates a new {@code ActionListBox} with a pre-set size. If the items don't fit in within this size, scrollbars
* will be used to accommodate. Calling {@code new ActionListBox(null)} has the same effect as calling
* {@code new ActionListBox()}.
* @param preferredSize Preferred size of this {@link ActionListBox}
*/
public ActionListBox(TerminalSize preferredSize) {
super(preferredSize);
}
/**
* {@inheritDoc}
*
* The label of the item in the list box will be the result of calling {@code .toString()} on the runnable, which
* might not be what you want to have unless you explicitly declare it. Consider using
* {@code addItem(String label, Runnable action} instead, if you want to just set the label easily without having
* to override {@code .toString()}.
*
* @param object Runnable to execute when the action was selected and fired in the list
* @return Itself
*/
@Override
public ActionListBox addItem(Runnable object) {
return super.addItem(object);
}
/**
* Adds a new item to the list, which is displayed in the list using a supplied label.
* @param label Label to use in the list for the new item
* @param action Runnable to invoke when this action is selected and then triggered
* @return Itself
*/
public ActionListBox addItem(final String label, final Runnable action) {
return addItem(new Runnable() {
@Override
public void run() {
action.run();
}
@Override
public String toString() {
return label;
}
});
}
@Override
public TerminalPosition getCursorLocation() {
return null;
}
@Override
public Result handleKeyStroke(KeyStroke keyStroke) {
if (isKeyboardActivationStroke(keyStroke)) {
runSelectedItem();
return Result.HANDLED;
} else if (keyStroke.getKeyType() == KeyType.MOUSE_EVENT) {
MouseAction mouseAction = (MouseAction) keyStroke;
MouseActionType actionType = mouseAction.getActionType();
if (isMouseMove(keyStroke)
|| actionType == MouseActionType.CLICK_RELEASE
|| actionType == MouseActionType.SCROLL_UP
|| actionType == MouseActionType.SCROLL_DOWN) {
return super.handleKeyStroke(keyStroke);
}
// includes mouse drag
int existingIndex = getSelectedIndex();
int newIndex = getIndexByMouseAction(mouseAction);
if (existingIndex != newIndex || !isFocused() || actionType == MouseActionType.CLICK_DOWN) {
// the index has changed, or the focus needs to be obtained, or the user is clicking on the current selection to perform the action again
Result result = super.handleKeyStroke(keyStroke);
runSelectedItem();
return result;
}
return Result.HANDLED;
} else {
Result result = super.handleKeyStroke(keyStroke);
//runSelectedItem();
return result;
}
}
public void runSelectedItem() {
Object selectedItem = getSelectedItem();
if (selectedItem != null) {
((Runnable) selectedItem).run();
}
}
}
| mabe02/lanterna | src/main/java/com/googlecode/lanterna/gui2/ActionListBox.java |
179,956 | /*
* Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.io.ObjectStreamField;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Formatter;
import java.util.Locale;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* The {@code String} class represents character strings. All
* string literals in Java programs, such as {@code "abc"}, are
* implemented as instances of this class.
* <p>
* Strings are constant; their values cannot be changed after they
* are created. String buffers support mutable strings.
* Because String objects are immutable they can be shared. For example:
* <blockquote><pre>
* String str = "abc";
* </pre></blockquote><p>
* is equivalent to:
* <blockquote><pre>
* char data[] = {'a', 'b', 'c'};
* String str = new String(data);
* </pre></blockquote><p>
* Here are some more examples of how strings can be used:
* <blockquote><pre>
* System.out.println("abc");
* String cde = "cde";
* System.out.println("abc" + cde);
* String c = "abc".substring(2,3);
* String d = cde.substring(1, 2);
* </pre></blockquote>
* <p>
* The class {@code String} includes methods for examining
* individual characters of the sequence, for comparing strings, for
* searching strings, for extracting substrings, and for creating a
* copy of a string with all characters translated to uppercase or to
* lowercase. Case mapping is based on the Unicode Standard version
* specified by the {@link java.lang.Character Character} class.
* <p>
* The Java language provides special support for the string
* concatenation operator ( + ), and for conversion of
* other objects to strings. String concatenation is implemented
* through the {@code StringBuilder}(or {@code StringBuffer})
* class and its {@code append} method.
* String conversions are implemented through the method
* {@code toString}, defined by {@code Object} and
* inherited by all classes in Java. For additional information on
* string concatenation and conversion, see Gosling, Joy, and Steele,
* <i>The Java Language Specification</i>.
*
* <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
* <p>A {@code String} represents a string in the UTF-16 format
* in which <em>supplementary characters</em> are represented by <em>surrogate
* pairs</em> (see the section <a href="Character.html#unicode">Unicode
* Character Representations</a> in the {@code Character} class for
* more information).
* Index values refer to {@code char} code units, so a supplementary
* character uses two positions in a {@code String}.
* <p>The {@code String} class provides methods for dealing with
* Unicode code points (i.e., characters), in addition to those for
* dealing with Unicode code units (i.e., {@code char} values).
*
* @author Lee Boynton
* @author Arthur van Hoff
* @author Martin Buchholz
* @author Ulf Zibis
* @see java.lang.Object#toString()
* @see java.lang.StringBuffer
* @see java.lang.StringBuilder
* @see java.nio.charset.Charset
* @since JDK1.0
*/
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
/**
* Class String is special cased within the Serialization Stream Protocol.
*
* A String instance is written into an ObjectOutputStream according to
* <a href="{@docRoot}/../platform/serialization/spec/output.html">
* Object Serialization Specification, Section 6.2, "Stream Elements"</a>
*/
private static final ObjectStreamField[] serialPersistentFields =
new ObjectStreamField[0];
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String() {
this.value = "".value;
}
/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
/**
* Allocates a new {@code String} so that it represents the sequence of
* characters currently contained in the character array argument. The
* contents of the character array are copied; subsequent modification of
* the character array does not affect the newly created string.
*
* @param value
* The initial value of the string
*/
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
/**
* Allocates a new {@code String} that contains characters from a subarray
* of the character array argument. The {@code offset} argument is the
* index of the first character of the subarray and the {@code count}
* argument specifies the length of the subarray. The contents of the
* subarray are copied; subsequent modification of the character array does
* not affect the newly created string.
*
* @param value
* Array that is the source of characters
*
* @param offset
* The initial offset
*
* @param count
* The length
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code count} arguments index
* characters outside the bounds of the {@code value} array
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
/**
* Allocates a new {@code String} that contains characters from a subarray
* of the <a href="Character.html#unicode">Unicode code point</a> array
* argument. The {@code offset} argument is the index of the first code
* point of the subarray and the {@code count} argument specifies the
* length of the subarray. The contents of the subarray are converted to
* {@code char}s; subsequent modification of the {@code int} array does not
* affect the newly created string.
*
* @param codePoints
* Array that is the source of Unicode code points
*
* @param offset
* The initial offset
*
* @param count
* The length
*
* @throws IllegalArgumentException
* If any invalid Unicode code point is found in {@code
* codePoints}
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code count} arguments index
* characters outside the bounds of the {@code codePoints} array
*
* @since 1.5
*/
public String(int[] codePoints, int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= codePoints.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > codePoints.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
final int end = offset + count;
// Pass 1: Compute precise size of char[]
int n = count;
for (int i = offset; i < end; i++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
continue;
else if (Character.isValidCodePoint(c))
n++;
else throw new IllegalArgumentException(Integer.toString(c));
}
// Pass 2: Allocate and fill in char[]
final char[] v = new char[n];
for (int i = offset, j = 0; i < end; i++, j++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
v[j] = (char)c;
else
Character.toSurrogates(c, v, j++);
}
this.value = v;
}
/**
* Allocates a new {@code String} constructed from a subarray of an array
* of 8-bit integer values.
*
* <p> The {@code offset} argument is the index of the first byte of the
* subarray, and the {@code count} argument specifies the length of the
* subarray.
*
* <p> Each {@code byte} in the subarray is converted to a {@code char} as
* specified in the method above.
*
* @deprecated This method does not properly convert bytes into characters.
* As of JDK 1.1, the preferred way to do this is via the
* {@code String} constructors that take a {@link
* java.nio.charset.Charset}, charset name, or that use the platform's
* default charset.
*
* @param ascii
* The bytes to be converted to characters
*
* @param hibyte
* The top 8 bits of each 16-bit Unicode code unit
*
* @param offset
* The initial offset
* @param count
* The length
*
* @throws IndexOutOfBoundsException
* If the {@code offset} or {@code count} argument is invalid
*
* @see #String(byte[], int)
* @see #String(byte[], int, int, java.lang.String)
* @see #String(byte[], int, int, java.nio.charset.Charset)
* @see #String(byte[], int, int)
* @see #String(byte[], java.lang.String)
* @see #String(byte[], java.nio.charset.Charset)
* @see #String(byte[])
*/
@Deprecated
public String(byte ascii[], int hibyte, int offset, int count) {
checkBounds(ascii, offset, count);
char value[] = new char[count];
if (hibyte == 0) {
for (int i = count; i-- > 0;) {
value[i] = (char)(ascii[i + offset] & 0xff);
}
} else {
hibyte <<= 8;
for (int i = count; i-- > 0;) {
value[i] = (char)(hibyte | (ascii[i + offset] & 0xff));
}
}
this.value = value;
}
/**
* Allocates a new {@code String} containing characters constructed from
* an array of 8-bit integer values. Each character <i>c</i>in the
* resulting string is constructed from the corresponding component
* <i>b</i> in the byte array such that:
*
* <blockquote><pre>
* <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
* | (<b><i>b</i></b> & 0xff))
* </pre></blockquote>
*
* @deprecated This method does not properly convert bytes into
* characters. As of JDK 1.1, the preferred way to do this is via the
* {@code String} constructors that take a {@link
* java.nio.charset.Charset}, charset name, or that use the platform's
* default charset.
*
* @param ascii
* The bytes to be converted to characters
*
* @param hibyte
* The top 8 bits of each 16-bit Unicode code unit
*
* @see #String(byte[], int, int, java.lang.String)
* @see #String(byte[], int, int, java.nio.charset.Charset)
* @see #String(byte[], int, int)
* @see #String(byte[], java.lang.String)
* @see #String(byte[], java.nio.charset.Charset)
* @see #String(byte[])
*/
@Deprecated
public String(byte ascii[], int hibyte) {
this(ascii, hibyte, 0, ascii.length);
}
/* Common private utility method used to bounds check the byte array
* and requested offset & length values used by the String(byte[],..)
* constructors.
*/
private static void checkBounds(byte[] bytes, int offset, int length) {
if (length < 0)
throw new StringIndexOutOfBoundsException(length);
if (offset < 0)
throw new StringIndexOutOfBoundsException(offset);
if (offset > bytes.length - length)
throw new StringIndexOutOfBoundsException(offset + length);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of
* bytes using the specified charset. The length of the new {@code String}
* is a function of the charset, and hence may not be equal to the length
* of the subarray.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the given charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param offset
* The index of the first byte to decode
*
* @param length
* The number of bytes to decode
* @param charsetName
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code length} arguments index
* characters outside the bounds of the {@code bytes} array
*
* @since JDK1.1
*/
public String(byte bytes[], int offset, int length, String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null)
throw new NullPointerException("charsetName");
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(charsetName, bytes, offset, length);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of
* bytes using the specified {@linkplain java.nio.charset.Charset charset}.
* The length of the new {@code String} is a function of the charset, and
* hence may not be equal to the length of the subarray.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param offset
* The index of the first byte to decode
*
* @param length
* The number of bytes to decode
*
* @param charset
* The {@linkplain java.nio.charset.Charset charset} to be used to
* decode the {@code bytes}
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and {@code length} arguments index
* characters outside the bounds of the {@code bytes} array
*
* @since 1.6
*/
public String(byte bytes[], int offset, int length, Charset charset) {
if (charset == null)
throw new NullPointerException("charset");
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(charset, bytes, offset, length);
}
/**
* Constructs a new {@code String} by decoding the specified array of bytes
* using the specified {@linkplain java.nio.charset.Charset charset}. The
* length of the new {@code String} is a function of the charset, and hence
* may not be equal to the length of the byte array.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the given charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param charsetName
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @since JDK1.1
*/
public String(byte bytes[], String charsetName)
throws UnsupportedEncodingException {
this(bytes, 0, bytes.length, charsetName);
}
/**
* Constructs a new {@code String} by decoding the specified array of
* bytes using the specified {@linkplain java.nio.charset.Charset charset}.
* The length of the new {@code String} is a function of the charset, and
* hence may not be equal to the length of the byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param charset
* The {@linkplain java.nio.charset.Charset charset} to be used to
* decode the {@code bytes}
*
* @since 1.6
*/
public String(byte bytes[], Charset charset) {
this(bytes, 0, bytes.length, charset);
}
/**
* Constructs a new {@code String} by decoding the specified subarray of
* bytes using the platform's default charset. The length of the new
* {@code String} is a function of the charset, and hence may not be equal
* to the length of the subarray.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the default charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param bytes
* The bytes to be decoded into characters
*
* @param offset
* The index of the first byte to decode
*
* @param length
* The number of bytes to decode
*
* @throws IndexOutOfBoundsException
* If the {@code offset} and the {@code length} arguments index
* characters outside the bounds of the {@code bytes} array
*
* @since JDK1.1
*/
public String(byte bytes[], int offset, int length) {
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(bytes, offset, length);
}
/**
* Constructs a new {@code String} by decoding the specified array of bytes
* using the platform's default charset. The length of the new {@code
* String} is a function of the charset, and hence may not be equal to the
* length of the byte array.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the default charset is unspecified. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param bytes
* The bytes to be decoded into characters
*
* @since JDK1.1
*/
public String(byte bytes[]) {
this(bytes, 0, bytes.length);
}
/**
* Allocates a new string that contains the sequence of characters
* currently contained in the string buffer argument. The contents of the
* string buffer are copied; subsequent modification of the string buffer
* does not affect the newly created string.
*
* @param buffer
* A {@code StringBuffer}
*/
public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
/**
* Allocates a new string that contains the sequence of characters
* currently contained in the string builder argument. The contents of the
* string builder are copied; subsequent modification of the string builder
* does not affect the newly created string.
*
* <p> This constructor is provided to ease migration to {@code
* StringBuilder}. Obtaining a string from a string builder via the {@code
* toString} method is likely to run faster and is generally preferred.
*
* @param builder
* A {@code StringBuilder}
*
* @since 1.5
*/
public String(StringBuilder builder) {
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
/*
* Package private constructor which shares value array for speed.
* this constructor is always expected to be called with share==true.
* a separate constructor is needed because we already have a public
* String(char[]) constructor that makes a copy of the given char[].
*/
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
/**
* Returns the length of this string.
* The length is equal to the number of <a href="Character.html#unicode">Unicode
* code units</a> in the string.
*
* @return the length of the sequence of characters represented by this
* object.
*/
public int length() {
return value.length;
}
/**
* Returns {@code true} if, and only if, {@link #length()} is {@code 0}.
*
* @return {@code true} if {@link #length()} is {@code 0}, otherwise
* {@code false}
*
* @since 1.6
*/
public boolean isEmpty() {
return value.length == 0;
}
/**
* Returns the {@code char} value at the
* specified index. An index ranges from {@code 0} to
* {@code length() - 1}. The first {@code char} value of the sequence
* is at index {@code 0}, the next at index {@code 1},
* and so on, as for array indexing.
*
* <p>If the {@code char} value specified by the index is a
* <a href="Character.html#unicode">surrogate</a>, the surrogate
* value is returned.
*
* @param index the index of the {@code char} value.
* @return the {@code char} value at the specified index of this string.
* The first {@code char} value is at index {@code 0}.
* @exception IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* string.
*/
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
/**
* Returns the character (Unicode code point) at the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 0} to
* {@link #length()}{@code - 1}.
*
* <p> If the {@code char} value specified at the given index
* is in the high-surrogate range, the following index is less
* than the length of this {@code String}, and the
* {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
* the {@code char} value at the given index is returned.
*
* @param index the index to the {@code char} values
* @return the code point value of the character at the
* {@code index}
* @exception IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* string.
* @since 1.5
*/
public int codePointAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAtImpl(value, index, value.length);
}
/**
* Returns the character (Unicode code point) before the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 1} to {@link
* CharSequence#length() length}.
*
* <p> If the {@code char} value at {@code (index - 1)}
* is in the low-surrogate range, {@code (index - 2)} is not
* negative, and the {@code char} value at {@code (index -
* 2)} is in the high-surrogate range, then the
* supplementary code point value of the surrogate pair is
* returned. If the {@code char} value at {@code index -
* 1} is an unpaired low-surrogate or a high-surrogate, the
* surrogate value is returned.
*
* @param index the index following the code point that should be returned
* @return the Unicode code point value before the given index.
* @exception IndexOutOfBoundsException if the {@code index}
* argument is less than 1 or greater than the length
* of this string.
* @since 1.5
*/
public int codePointBefore(int index) {
int i = index - 1;
if ((i < 0) || (i >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointBeforeImpl(value, index, 0);
}
/**
* Returns the number of Unicode code points in the specified text
* range of this {@code String}. The text range begins at the
* specified {@code beginIndex} and extends to the
* {@code char} at index {@code endIndex - 1}. Thus the
* length (in {@code char}s) of the text range is
* {@code endIndex-beginIndex}. Unpaired surrogates within
* the text range count as one code point each.
*
* @param beginIndex the index to the first {@code char} of
* the text range.
* @param endIndex the index after the last {@code char} of
* the text range.
* @return the number of Unicode code points in the specified text
* range
* @exception IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or {@code endIndex}
* is larger than the length of this {@code String}, or
* {@code beginIndex} is larger than {@code endIndex}.
* @since 1.5
*/
public int codePointCount(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);
}
/**
* Returns the index within this {@code String} that is
* offset from the given {@code index} by
* {@code codePointOffset} code points. Unpaired surrogates
* within the text range given by {@code index} and
* {@code codePointOffset} count as one code point each.
*
* @param index the index to be offset
* @param codePointOffset the offset in code points
* @return the index within this {@code String}
* @exception IndexOutOfBoundsException if {@code index}
* is negative or larger then the length of this
* {@code String}, or if {@code codePointOffset} is positive
* and the substring starting with {@code index} has fewer
* than {@code codePointOffset} code points,
* or if {@code codePointOffset} is negative and the substring
* before {@code index} has fewer than the absolute value
* of {@code codePointOffset} code points.
* @since 1.5
*/
public int offsetByCodePoints(int index, int codePointOffset) {
if (index < 0 || index > value.length) {
throw new IndexOutOfBoundsException();
}
return Character.offsetByCodePointsImpl(value, 0, value.length,
index, codePointOffset);
}
/**
* Copy characters from this string into dst starting at dstBegin.
* This method doesn't perform any range checking.
*/
void getChars(char dst[], int dstBegin) {
System.arraycopy(value, 0, dst, dstBegin, value.length);
}
/**
* Copies characters from this string into the destination character
* array.
* <p>
* The first character to be copied is at index {@code srcBegin};
* the last character to be copied is at index {@code srcEnd-1}
* (thus the total number of characters to be copied is
* {@code srcEnd-srcBegin}). The characters are copied into the
* subarray of {@code dst} starting at index {@code dstBegin}
* and ending at index:
* <blockquote><pre>
* dstBegin + (srcEnd-srcBegin) - 1
* </pre></blockquote>
*
* @param srcBegin index of the first character in the string
* to copy.
* @param srcEnd index after the last character in the string
* to copy.
* @param dst the destination array.
* @param dstBegin the start offset in the destination array.
* @exception IndexOutOfBoundsException If any of the following
* is true:
* <ul><li>{@code srcBegin} is negative.
* <li>{@code srcBegin} is greater than {@code srcEnd}
* <li>{@code srcEnd} is greater than the length of this
* string
* <li>{@code dstBegin} is negative
* <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than
* {@code dst.length}</ul>
*/
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
/**
* Copies characters from this string into the destination byte array. Each
* byte receives the 8 low-order bits of the corresponding character. The
* eight high-order bits of each character are not copied and do not
* participate in the transfer in any way.
*
* <p> The first character to be copied is at index {@code srcBegin}; the
* last character to be copied is at index {@code srcEnd-1}. The total
* number of characters to be copied is {@code srcEnd-srcBegin}. The
* characters, converted to bytes, are copied into the subarray of {@code
* dst} starting at index {@code dstBegin} and ending at index:
*
* <blockquote><pre>
* dstBegin + (srcEnd-srcBegin) - 1
* </pre></blockquote>
*
* @deprecated This method does not properly convert characters into
* bytes. As of JDK 1.1, the preferred way to do this is via the
* {@link #getBytes()} method, which uses the platform's default charset.
*
* @param srcBegin
* Index of the first character in the string to copy
*
* @param srcEnd
* Index after the last character in the string to copy
*
* @param dst
* The destination array
*
* @param dstBegin
* The start offset in the destination array
*
* @throws IndexOutOfBoundsException
* If any of the following is true:
* <ul>
* <li> {@code srcBegin} is negative
* <li> {@code srcBegin} is greater than {@code srcEnd}
* <li> {@code srcEnd} is greater than the length of this String
* <li> {@code dstBegin} is negative
* <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
* dst.length}
* </ul>
*/
@Deprecated
public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
Objects.requireNonNull(dst);
int j = dstBegin;
int n = srcEnd;
int i = srcBegin;
char[] val = value; /* avoid getfield opcode */
while (i < n) {
dst[j++] = (byte)val[i++];
}
}
/**
* Encodes this {@code String} into a sequence of bytes using the named
* charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in
* the given charset is unspecified. The {@link
* java.nio.charset.CharsetEncoder} class should be used when more control
* over the encoding process is required.
*
* @param charsetName
* The name of a supported {@linkplain java.nio.charset.Charset
* charset}
*
* @return The resultant byte array
*
* @throws UnsupportedEncodingException
* If the named charset is not supported
*
* @since JDK1.1
*/
public byte[] getBytes(String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null) throw new NullPointerException();
return StringCoding.encode(charsetName, value, 0, value.length);
}
/**
* Encodes this {@code String} into a sequence of bytes using the given
* {@linkplain java.nio.charset.Charset charset}, storing the result into a
* new byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement byte array. The
* {@link java.nio.charset.CharsetEncoder} class should be used when more
* control over the encoding process is required.
*
* @param charset
* The {@linkplain java.nio.charset.Charset} to be used to encode
* the {@code String}
*
* @return The resultant byte array
*
* @since 1.6
*/
public byte[] getBytes(Charset charset) {
if (charset == null) throw new NullPointerException();
return StringCoding.encode(charset, value, 0, value.length);
}
/**
* Encodes this {@code String} into a sequence of bytes using the
* platform's default charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in
* the default charset is unspecified. The {@link
* java.nio.charset.CharsetEncoder} class should be used when more control
* over the encoding process is required.
*
* @return The resultant byte array
*
* @since JDK1.1
*/
public byte[] getBytes() {
return StringCoding.encode(value, 0, value.length);
}
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
/**
* Compares this string to the specified {@code StringBuffer}. The result
* is {@code true} if and only if this {@code String} represents the same
* sequence of characters as the specified {@code StringBuffer}. This method
* synchronizes on the {@code StringBuffer}.
*
* @param sb
* The {@code StringBuffer} to compare this {@code String} against
*
* @return {@code true} if this {@code String} represents the same
* sequence of characters as the specified {@code StringBuffer},
* {@code false} otherwise
*
* @since 1.4
*/
public boolean contentEquals(StringBuffer sb) {
return contentEquals((CharSequence)sb);
}
private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
char v1[] = value;
char v2[] = sb.getValue();
int n = v1.length;
if (n != sb.length()) {
return false;
}
for (int i = 0; i < n; i++) {
if (v1[i] != v2[i]) {
return false;
}
}
return true;
}
/**
* Compares this string to the specified {@code CharSequence}. The
* result is {@code true} if and only if this {@code String} represents the
* same sequence of char values as the specified sequence. Note that if the
* {@code CharSequence} is a {@code StringBuffer} then the method
* synchronizes on it.
*
* @param cs
* The sequence to compare this {@code String} against
*
* @return {@code true} if this {@code String} represents the same
* sequence of char values as the specified sequence, {@code
* false} otherwise
*
* @since 1.5
*/
public boolean contentEquals(CharSequence cs) {
// Argument is a StringBuffer, StringBuilder
if (cs instanceof AbstractStringBuilder) {
if (cs instanceof StringBuffer) {
synchronized(cs) {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
} else {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
}
// Argument is a String
if (cs instanceof String) {
return equals(cs);
}
// Argument is a generic CharSequence
char v1[] = value;
int n = v1.length;
if (n != cs.length()) {
return false;
}
for (int i = 0; i < n; i++) {
if (v1[i] != cs.charAt(i)) {
return false;
}
}
return true;
}
/**
* Compares this {@code String} to another {@code String}, ignoring case
* considerations. Two strings are considered equal ignoring case if they
* are of the same length and corresponding characters in the two strings
* are equal ignoring case.
*
* <p> Two characters {@code c1} and {@code c2} are considered the same
* ignoring case if at least one of the following is true:
* <ul>
* <li> The two characters are the same (as compared by the
* {@code ==} operator)
* <li> Applying the method {@link
* java.lang.Character#toUpperCase(char)} to each character
* produces the same result
* <li> Applying the method {@link
* java.lang.Character#toLowerCase(char)} to each character
* produces the same result
* </ul>
*
* @param anotherString
* The {@code String} to compare this {@code String} against
*
* @return {@code true} if the argument is not {@code null} and it
* represents an equivalent {@code String} ignoring case; {@code
* false} otherwise
*
* @see #equals(Object)
*/
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
/**
* Compares two strings lexicographically.
* The comparison is based on the Unicode value of each character in
* the strings. The character sequence represented by this
* {@code String} object is compared lexicographically to the
* character sequence represented by the argument string. The result is
* a negative integer if this {@code String} object
* lexicographically precedes the argument string. The result is a
* positive integer if this {@code String} object lexicographically
* follows the argument string. The result is zero if the strings
* are equal; {@code compareTo} returns {@code 0} exactly when
* the {@link #equals(Object)} method would return {@code true}.
* <p>
* This is the definition of lexicographic ordering. If two strings are
* different, then either they have different characters at some index
* that is a valid index for both strings, or their lengths are different,
* or both. If they have different characters at one or more index
* positions, let <i>k</i> be the smallest such index; then the string
* whose character at position <i>k</i> has the smaller value, as
* determined by using the < operator, lexicographically precedes the
* other string. In this case, {@code compareTo} returns the
* difference of the two character values at position {@code k} in
* the two string -- that is, the value:
* <blockquote><pre>
* this.charAt(k)-anotherString.charAt(k)
* </pre></blockquote>
* If there is no index position at which they differ, then the shorter
* string lexicographically precedes the longer string. In this case,
* {@code compareTo} returns the difference of the lengths of the
* strings -- that is, the value:
* <blockquote><pre>
* this.length()-anotherString.length()
* </pre></blockquote>
*
* @param anotherString the {@code String} to be compared.
* @return the value {@code 0} if the argument string is equal to
* this string; a value less than {@code 0} if this string
* is lexicographically less than the string argument; and a
* value greater than {@code 0} if this string is
* lexicographically greater than the string argument.
*/
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
/**
* A Comparator that orders {@code String} objects as by
* {@code compareToIgnoreCase}. This comparator is serializable.
* <p>
* Note that this Comparator does <em>not</em> take locale into account,
* and will result in an unsatisfactory ordering for certain locales.
* The java.text package provides <em>Collators</em> to allow
* locale-sensitive ordering.
*
* @see java.text.Collator#compare(String, String)
* @since 1.2
*/
public static final Comparator<String> CASE_INSENSITIVE_ORDER
= new CaseInsensitiveComparator();
private static class CaseInsensitiveComparator
implements Comparator<String>, java.io.Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 8575799808933029326L;
public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
// No overflow because of numeric promotion
return c1 - c2;
}
}
}
}
return n1 - n2;
}
/** Replaces the de-serialized object. */
private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
}
/**
* Compares two strings lexicographically, ignoring case
* differences. This method returns an integer whose sign is that of
* calling {@code compareTo} with normalized versions of the strings
* where case differences have been eliminated by calling
* {@code Character.toLowerCase(Character.toUpperCase(character))} on
* each character.
* <p>
* Note that this method does <em>not</em> take locale into account,
* and will result in an unsatisfactory ordering for certain locales.
* The java.text package provides <em>collators</em> to allow
* locale-sensitive ordering.
*
* @param str the {@code String} to be compared.
* @return a negative integer, zero, or a positive integer as the
* specified String is greater than, equal to, or less
* than this String, ignoring case considerations.
* @see java.text.Collator#compare(String, String)
* @since 1.2
*/
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
/**
* Tests if two string regions are equal.
* <p>
* A substring of this {@code String} object is compared to a substring
* of the argument other. The result is true if these substrings
* represent identical character sequences. The substring of this
* {@code String} object to be compared begins at index {@code toffset}
* and has length {@code len}. The substring of other to be compared
* begins at index {@code ooffset} and has length {@code len}. The
* result is {@code false} if and only if at least one of the following
* is true:
* <ul><li>{@code toffset} is negative.
* <li>{@code ooffset} is negative.
* <li>{@code toffset+len} is greater than the length of this
* {@code String} object.
* <li>{@code ooffset+len} is greater than the length of the other
* argument.
* <li>There is some nonnegative integer <i>k</i> less than {@code len}
* such that:
* {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + }
* <i>k</i>{@code )}
* </ul>
*
* @param toffset the starting offset of the subregion in this string.
* @param other the string argument.
* @param ooffset the starting offset of the subregion in the string
* argument.
* @param len the number of characters to compare.
* @return {@code true} if the specified subregion of this string
* exactly matches the specified subregion of the string argument;
* {@code false} otherwise.
*/
public boolean regionMatches(int toffset, String other, int ooffset,
int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
/**
* Tests if two string regions are equal.
* <p>
* A substring of this {@code String} object is compared to a substring
* of the argument {@code other}. The result is {@code true} if these
* substrings represent character sequences that are the same, ignoring
* case if and only if {@code ignoreCase} is true. The substring of
* this {@code String} object to be compared begins at index
* {@code toffset} and has length {@code len}. The substring of
* {@code other} to be compared begins at index {@code ooffset} and
* has length {@code len}. The result is {@code false} if and only if
* at least one of the following is true:
* <ul><li>{@code toffset} is negative.
* <li>{@code ooffset} is negative.
* <li>{@code toffset+len} is greater than the length of this
* {@code String} object.
* <li>{@code ooffset+len} is greater than the length of the other
* argument.
* <li>{@code ignoreCase} is {@code false} and there is some nonnegative
* integer <i>k</i> less than {@code len} such that:
* <blockquote><pre>
* this.charAt(toffset+k) != other.charAt(ooffset+k)
* </pre></blockquote>
* <li>{@code ignoreCase} is {@code true} and there is some nonnegative
* integer <i>k</i> less than {@code len} such that:
* <blockquote><pre>
* Character.toLowerCase(this.charAt(toffset+k)) !=
Character.toLowerCase(other.charAt(ooffset+k))
* </pre></blockquote>
* and:
* <blockquote><pre>
* Character.toUpperCase(this.charAt(toffset+k)) !=
* Character.toUpperCase(other.charAt(ooffset+k))
* </pre></blockquote>
* </ul>
*
* @param ignoreCase if {@code true}, ignore case when comparing
* characters.
* @param toffset the starting offset of the subregion in this
* string.
* @param other the string argument.
* @param ooffset the starting offset of the subregion in the string
* argument.
* @param len the number of characters to compare.
* @return {@code true} if the specified subregion of this string
* matches the specified subregion of the string argument;
* {@code false} otherwise. Whether the matching is exact
* or case insensitive depends on the {@code ignoreCase}
* argument.
*/
public boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
char c1 = ta[to++];
char c2 = pa[po++];
if (c1 == c2) {
continue;
}
if (ignoreCase) {
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
// If the results match, then the comparison scan should
// continue.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) {
continue;
}
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting.
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
/**
* Tests if the substring of this string beginning at the
* specified index starts with the specified prefix.
*
* @param prefix the prefix.
* @param toffset where to begin looking in this string.
* @return {@code true} if the character sequence represented by the
* argument is a prefix of the substring of this object starting
* at index {@code toffset}; {@code false} otherwise.
* The result is {@code false} if {@code toffset} is
* negative or greater than the length of this
* {@code String} object; otherwise the result is the same
* as the result of the expression
* <pre>
* this.substring(toffset).startsWith(prefix)
* </pre>
*/
public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = toffset;
char pa[] = prefix.value;
int po = 0;
int pc = prefix.value.length;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
/**
* Tests if this string starts with the specified prefix.
*
* @param prefix the prefix.
* @return {@code true} if the character sequence represented by the
* argument is a prefix of the character sequence represented by
* this string; {@code false} otherwise.
* Note also that {@code true} will be returned if the
* argument is an empty string or is equal to this
* {@code String} object as determined by the
* {@link #equals(Object)} method.
* @since 1. 0
*/
public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}
/**
* Tests if this string ends with the specified suffix.
*
* @param suffix the suffix.
* @return {@code true} if the character sequence represented by the
* argument is a suffix of the character sequence represented by
* this object; {@code false} otherwise. Note that the
* result will be {@code true} if the argument is the
* empty string or is equal to this {@code String} object
* as determined by the {@link #equals(Object)} method.
*/
public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}
/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
/**
* Returns the index within this string of the first occurrence of
* the specified character. If a character with value
* {@code ch} occurs in the character sequence represented by
* this {@code String} object, then the index (in Unicode
* code units) of the first such occurrence is returned. For
* values of {@code ch} in the range from 0 to 0xFFFF
* (inclusive), this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned.
*
* @param ch a character (Unicode code point).
* @return the index of the first occurrence of the character in the
* character sequence represented by this object, or
* {@code -1} if the character does not occur.
*/
public int indexOf(int ch) {
return indexOf(ch, 0);
}
/**
* Returns the index within this string of the first occurrence of the
* specified character, starting the search at the specified index.
* <p>
* If a character with value {@code ch} occurs in the
* character sequence represented by this {@code String}
* object at an index no smaller than {@code fromIndex}, then
* the index of the first such occurrence is returned. For values
* of {@code ch} in the range from 0 to 0xFFFF (inclusive),
* this is the smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* smallest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> >= fromIndex)
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string at or after position {@code fromIndex}, then
* {@code -1} is returned.
*
* <p>
* There is no restriction on the value of {@code fromIndex}. If it
* is negative, it has the same effect as if it were zero: this entire
* string may be searched. If it is greater than the length of this
* string, it has the same effect as if it were equal to the length of
* this string: {@code -1} is returned.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* @param ch a character (Unicode code point).
* @param fromIndex the index to start the search from.
* @return the index of the first occurrence of the character in the
* character sequence represented by this object that is greater
* than or equal to {@code fromIndex}, or {@code -1}
* if the character does not occur.
*/
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
// Note: fromIndex might be near -1>>>1.
return -1;
}
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
/**
* Handles (rare) calls of indexOf with a supplementary character.
*/
private int indexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
final char hi = Character.highSurrogate(ch);
final char lo = Character.lowSurrogate(ch);
final int max = value.length - 1;
for (int i = fromIndex; i < max; i++) {
if (value[i] == hi && value[i + 1] == lo) {
return i;
}
}
}
return -1;
}
/**
* Returns the index within this string of the last occurrence of
* the specified character. For values of {@code ch} in the
* range from 0 to 0xFFFF (inclusive), the index (in Unicode code
* units) returned is the largest value <i>k</i> such that:
* <blockquote><pre>
* this.charAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* this.codePointAt(<i>k</i>) == ch
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string, then {@code -1} is returned. The
* {@code String} is searched backwards starting at the last
* character.
*
* @param ch a character (Unicode code point).
* @return the index of the last occurrence of the character in the
* character sequence represented by this object, or
* {@code -1} if the character does not occur.
*/
public int lastIndexOf(int ch) {
return lastIndexOf(ch, value.length - 1);
}
/**
* Returns the index within this string of the last occurrence of
* the specified character, searching backward starting at the
* specified index. For values of {@code ch} in the range
* from 0 to 0xFFFF (inclusive), the index returned is the largest
* value <i>k</i> such that:
* <blockquote><pre>
* (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
* </pre></blockquote>
* is true. For other values of {@code ch}, it is the
* largest value <i>k</i> such that:
* <blockquote><pre>
* (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> <= fromIndex)
* </pre></blockquote>
* is true. In either case, if no such character occurs in this
* string at or before position {@code fromIndex}, then
* {@code -1} is returned.
*
* <p>All indices are specified in {@code char} values
* (Unicode code units).
*
* @param ch a character (Unicode code point).
* @param fromIndex the index to start the search from. There is no
* restriction on the value of {@code fromIndex}. If it is
* greater than or equal to the length of this string, it has
* the same effect as if it were equal to one less than the
* length of this string: this entire string may be searched.
* If it is negative, it has the same effect as if it were -1:
* -1 is returned.
* @return the index of the last occurrence of the character in the
* character sequence represented by this object that is less
* than or equal to {@code fromIndex}, or {@code -1}
* if the character does not occur before that point.
*/
public int lastIndexOf(int ch, int fromIndex) {
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
int i = Math.min(fromIndex, value.length - 1);
for (; i >= 0; i--) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return lastIndexOfSupplementary(ch, fromIndex);
}
}
/**
* Handles (rare) calls of lastIndexOf with a supplementary character.
*/
private int lastIndexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
char hi = Character.highSurrogate(ch);
char lo = Character.lowSurrogate(ch);
int i = Math.min(fromIndex, value.length - 2);
for (; i >= 0; i--) {
if (value[i] == hi && value[i + 1] == lo) {
return i;
}
}
}
return -1;
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the first occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str) {
return indexOf(str, 0);
}
/**
* Returns the index within this string of the first occurrence of the
* specified substring, starting at the specified index.
*
* <p>The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* <i>k</i> >= fromIndex {@code &&} this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index from which to start the search.
* @return the index of the first occurrence of the specified substring,
* starting at the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
/**
* Code shared by String and AbstractStringBuilder to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param fromIndex the index to begin searching from.
*/
static int indexOf(char[] source, int sourceOffset, int sourceCount,
String target, int fromIndex) {
return indexOf(source, sourceOffset, sourceCount,
target.value, 0, target.value.length,
fromIndex);
}
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param targetOffset offset of the target string.
* @param targetCount count of the target string.
* @param fromIndex the index to begin searching from.
*/
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring. The last occurrence of the empty string ""
* is considered to occur at the index value {@code this.length()}.
*
* <p>The returned index is the largest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @return the index of the last occurrence of the specified substring,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(String str) {
return lastIndexOf(str, value.length);
}
/**
* Returns the index within this string of the last occurrence of the
* specified substring, searching backward starting at the specified index.
*
* <p>The returned index is the largest value <i>k</i> for which:
* <blockquote><pre>
* <i>k</i> {@code <=} fromIndex {@code &&} this.startsWith(str, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param str the substring to search for.
* @param fromIndex the index to start the search from.
* @return the index of the last occurrence of the specified substring,
* searching backward from the specified index,
* or {@code -1} if there is no such occurrence.
*/
public int lastIndexOf(String str, int fromIndex) {
return lastIndexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
/**
* Code shared by String and AbstractStringBuilder to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param fromIndex the index to begin searching from.
*/
static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
String target, int fromIndex) {
return lastIndexOf(source, sourceOffset, sourceCount,
target.value, 0, target.value.length,
fromIndex);
}
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param targetOffset offset of the target string.
* @param targetCount count of the target string.
* @param fromIndex the index to begin searching from.
*/
static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
/*
* Check arguments; return immediately where possible. For
* consistency, don't check for null str.
*/
int rightIndex = sourceCount - targetCount;
if (fromIndex < 0) {
return -1;
}
if (fromIndex > rightIndex) {
fromIndex = rightIndex;
}
/* Empty string always matches. */
if (targetCount == 0) {
return fromIndex;
}
int strLastIndex = targetOffset + targetCount - 1;
char strLastChar = target[strLastIndex];
int min = sourceOffset + targetCount - 1;
int i = min + fromIndex;
startSearchForLastChar:
while (true) {
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {
return -1;
}
int j = i - 1;
int start = j - (targetCount - 1);
int k = strLastIndex - 1;
while (j > start) {
if (source[j--] != target[k--]) {
i--;
continue startSearchForLastChar;
}
}
return start - sourceOffset + 1;
}
}
/**
* Returns a string that is a substring of this string. The
* substring begins with the character at the specified index and
* extends to the end of this string. <p>
* Examples:
* <blockquote><pre>
* "unhappy".substring(2) returns "happy"
* "Harbison".substring(3) returns "bison"
* "emptiness".substring(9) returns "" (an empty string)
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if
* {@code beginIndex} is negative or larger than the
* length of this {@code String} object.
*/
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
/**
* Returns a string that is a substring of this string. The
* substring begins at the specified {@code beginIndex} and
* extends to the character at index {@code endIndex - 1}.
* Thus the length of the substring is {@code endIndex-beginIndex}.
* <p>
* Examples:
* <blockquote><pre>
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or
* {@code endIndex} is larger than the length of
* this {@code String} object, or
* {@code beginIndex} is larger than
* {@code endIndex}.
*/
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
/**
* Returns a character sequence that is a subsequence of this sequence.
*
* <p> An invocation of this method of the form
*
* <blockquote><pre>
* str.subSequence(begin, end)</pre></blockquote>
*
* behaves in exactly the same way as the invocation
*
* <blockquote><pre>
* str.substring(begin, end)</pre></blockquote>
*
* @apiNote
* This method is defined so that the {@code String} class can implement
* the {@link CharSequence} interface.
*
* @param beginIndex the begin index, inclusive.
* @param endIndex the end index, exclusive.
* @return the specified subsequence.
*
* @throws IndexOutOfBoundsException
* if {@code beginIndex} or {@code endIndex} is negative,
* if {@code endIndex} is greater than {@code length()},
* or if {@code beginIndex} is greater than {@code endIndex}
*
* @since 1.4
* @spec JSR-51
*/
public CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
/**
* Concatenates the specified string to the end of this string.
* <p>
* If the length of the argument string is {@code 0}, then this
* {@code String} object is returned. Otherwise, a
* {@code String} object is returned that represents a character
* sequence that is the concatenation of the character sequence
* represented by this {@code String} object and the character
* sequence represented by the argument string.<p>
* Examples:
* <blockquote><pre>
* "cares".concat("s") returns "caress"
* "to".concat("get").concat("her") returns "together"
* </pre></blockquote>
*
* @param str the {@code String} that is concatenated to the end
* of this {@code String}.
* @return a string that represents the concatenation of this object's
* characters followed by the string argument's characters.
*/
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
/**
* Returns a string resulting from replacing all occurrences of
* {@code oldChar} in this string with {@code newChar}.
* <p>
* If the character {@code oldChar} does not occur in the
* character sequence represented by this {@code String} object,
* then a reference to this {@code String} object is returned.
* Otherwise, a {@code String} object is returned that
* represents a character sequence identical to the character sequence
* represented by this {@code String} object, except that every
* occurrence of {@code oldChar} is replaced by an occurrence
* of {@code newChar}.
* <p>
* Examples:
* <blockquote><pre>
* "mesquite in your cellar".replace('e', 'o')
* returns "mosquito in your collar"
* "the war of baronets".replace('r', 'y')
* returns "the way of bayonets"
* "sparring with a purple porpoise".replace('p', 't')
* returns "starring with a turtle tortoise"
* "JonL".replace('q', 'x') returns "JonL" (no change)
* </pre></blockquote>
*
* @param oldChar the old character.
* @param newChar the new character.
* @return a string derived from this string by replacing every
* occurrence of {@code oldChar} with {@code newChar}.
*/
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
/**
* Tells whether or not this string matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the
* same result as the expression
*
* <blockquote>
* {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(String,CharSequence)
* matches(<i>regex</i>, <i>str</i>)}
* </blockquote>
*
* @param regex
* the regular expression to which this string is to be matched
*
* @return {@code true} if, and only if, this string matches the
* given regular expression
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
* @spec JSR-51
*/
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
/**
* Returns true if and only if this string contains the specified
* sequence of char values.
*
* @param s the sequence to search for
* @return true if this string contains {@code s}, false otherwise
* @since 1.5
*/
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
/**
* Replaces the first substring of this string that matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a> with the
* given replacement.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
* yields exactly the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
* java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>)
* </code>
* </blockquote>
*
*<p>
* Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
* replacement string may cause the results to be different than if it were
* being treated as a literal replacement string; see
* {@link java.util.regex.Matcher#replaceFirst}.
* Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
* meaning of these characters, if desired.
*
* @param regex
* the regular expression to which this string is to be matched
* @param replacement
* the string to be substituted for the first match
*
* @return The resulting {@code String}
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
* @spec JSR-51
*/
public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}
/**
* Replaces each substring of this string that matches the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a> with the
* given replacement.
*
* <p> An invocation of this method of the form
* <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )}
* yields exactly the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link
* java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>)
* </code>
* </blockquote>
*
*<p>
* Note that backslashes ({@code \}) and dollar signs ({@code $}) in the
* replacement string may cause the results to be different than if it were
* being treated as a literal replacement string; see
* {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
* Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
* meaning of these characters, if desired.
*
* @param regex
* the regular expression to which this string is to be matched
* @param replacement
* the string to be substituted for each match
*
* @return The resulting {@code String}
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
* @spec JSR-51
*/
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
/**
* Replaces each substring of this string that matches the literal target
* sequence with the specified literal replacement sequence. The
* replacement proceeds from the beginning of the string to the end, for
* example, replacing "aa" with "b" in the string "aaa" will result in
* "ba" rather than "ab".
*
* @param target The sequence of char values to be replaced
* @param replacement The replacement sequence of char values
* @return The resulting string
* @since 1.5
*/
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
/**
* Splits this string around matches of the given
* <a href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> The array returned by this method contains each substring of this
* string that is terminated by another substring that matches the given
* expression or is terminated by the end of the string. The substrings in
* the array are in the order in which they occur in this string. If the
* expression does not match any part of the input then the resulting array
* has just one element, namely this string.
*
* <p> When there is a positive-width match at the beginning of this
* string then an empty leading substring is included at the beginning
* of the resulting array. A zero-width match at the beginning however
* never produces such empty leading substring.
*
* <p> The {@code limit} parameter controls the number of times the
* pattern is applied and therefore affects the length of the resulting
* array. If the limit <i>n</i> is greater than zero then the pattern
* will be applied at most <i>n</i> - 1 times, the array's
* length will be no greater than <i>n</i>, and the array's last entry
* will contain all input beyond the last matched delimiter. If <i>n</i>
* is non-positive then the pattern will be applied as many times as
* possible and the array can have any length. If <i>n</i> is zero then
* the pattern will be applied as many times as possible, the array can
* have any length, and trailing empty strings will be discarded.
*
* <p> The string {@code "boo:and:foo"}, for example, yields the
* following results with these parameters:
*
* <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
* <tr>
* <th>Regex</th>
* <th>Limit</th>
* <th>Result</th>
* </tr>
* <tr><td align=center>:</td>
* <td align=center>2</td>
* <td>{@code { "boo", "and:foo" }}</td></tr>
* <tr><td align=center>:</td>
* <td align=center>5</td>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><td align=center>:</td>
* <td align=center>-2</td>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><td align=center>o</td>
* <td align=center>5</td>
* <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
* <tr><td align=center>o</td>
* <td align=center>-2</td>
* <td>{@code { "b", "", ":and:f", "", "" }}</td></tr>
* <tr><td align=center>o</td>
* <td align=center>0</td>
* <td>{@code { "b", "", ":and:f" }}</td></tr>
* </table></blockquote>
*
* <p> An invocation of this method of the form
* <i>str.</i>{@code split(}<i>regex</i>{@code ,} <i>n</i>{@code )}
* yields the same result as the expression
*
* <blockquote>
* <code>
* {@link java.util.regex.Pattern}.{@link
* java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link
* java.util.regex.Pattern#split(java.lang.CharSequence,int) split}(<i>str</i>, <i>n</i>)
* </code>
* </blockquote>
*
*
* @param regex
* the delimiting regular expression
*
* @param limit
* the result threshold, as described above
*
* @return the array of strings computed by splitting this string
* around matches of the given regular expression
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
* @spec JSR-51
*/
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the
RegEx's meta characters ".$|()[{^?*+\\", or
(2)two-char String and the first char is the backslash and
the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
}
/**
* Splits this string around matches of the given <a
* href="../util/regex/Pattern.html#sum">regular expression</a>.
*
* <p> This method works as if by invoking the two-argument {@link
* #split(String, int) split} method with the given expression and a limit
* argument of zero. Trailing empty strings are therefore not included in
* the resulting array.
*
* <p> The string {@code "boo:and:foo"}, for example, yields the following
* results with these expressions:
*
* <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
* <tr>
* <th>Regex</th>
* <th>Result</th>
* </tr>
* <tr><td align=center>:</td>
* <td>{@code { "boo", "and", "foo" }}</td></tr>
* <tr><td align=center>o</td>
* <td>{@code { "b", "", ":and:f" }}</td></tr>
* </table></blockquote>
*
*
* @param regex
* the delimiting regular expression
*
* @return the array of strings computed by splitting this string
* around matches of the given regular expression
*
* @throws PatternSyntaxException
* if the regular expression's syntax is invalid
*
* @see java.util.regex.Pattern
*
* @since 1.4
* @spec JSR-51
*/
public String[] split(String regex) {
return split(regex, 0);
}
/**
* Returns a new String composed of copies of the
* {@code CharSequence elements} joined together with a copy of
* the specified {@code delimiter}.
*
* <blockquote>For example,
* <pre>{@code
* String message = String.join("-", "Java", "is", "cool");
* // message returned is: "Java-is-cool"
* }</pre></blockquote>
*
* Note that if an element is null, then {@code "null"} is added.
*
* @param delimiter the delimiter that separates each element
* @param elements the elements to join together.
*
* @return a new {@code String} that is composed of the {@code elements}
* separated by the {@code delimiter}
*
* @throws NullPointerException If {@code delimiter} or {@code elements}
* is {@code null}
*
* @see java.util.StringJoiner
* @since 1.8
*/
public static String join(CharSequence delimiter, CharSequence... elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
// Number of elements not likely worth Arrays.stream overhead.
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: elements) {
joiner.add(cs);
}
return joiner.toString();
}
/**
* Returns a new {@code String} composed of copies of the
* {@code CharSequence elements} joined together with a copy of the
* specified {@code delimiter}.
*
* <blockquote>For example,
* <pre>{@code
* List<String> strings = new LinkedList<>();
* strings.add("Java");strings.add("is");
* strings.add("cool");
* String message = String.join(" ", strings);
* //message returned is: "Java is cool"
*
* Set<String> strings = new LinkedHashSet<>();
* strings.add("Java"); strings.add("is");
* strings.add("very"); strings.add("cool");
* String message = String.join("-", strings);
* //message returned is: "Java-is-very-cool"
* }</pre></blockquote>
*
* Note that if an individual element is {@code null}, then {@code "null"} is added.
*
* @param delimiter a sequence of characters that is used to separate each
* of the {@code elements} in the resulting {@code String}
* @param elements an {@code Iterable} that will have its {@code elements}
* joined together.
*
* @return a new {@code String} that is composed from the {@code elements}
* argument
*
* @throws NullPointerException If {@code delimiter} or {@code elements}
* is {@code null}
*
* @see #join(CharSequence,CharSequence...)
* @see java.util.StringJoiner
* @since 1.8
*/
public static String join(CharSequence delimiter,
Iterable<? extends CharSequence> elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: elements) {
joiner.add(cs);
}
return joiner.toString();
}
/**
* Converts all of the characters in this {@code String} to lower
* case using the rules of the given {@code Locale}. Case mapping is based
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
* class. Since case mappings are not always 1:1 char mappings, the resulting
* {@code String} may be a different length than the original {@code String}.
* <p>
* Examples of lowercase mappings are in the following table:
* <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
* <tr>
* <th>Language Code of Locale</th>
* <th>Upper Case</th>
* <th>Lower Case</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0130</td>
* <td>\u0069</td>
* <td>capital letter I with dot above -> small letter i</td>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0049</td>
* <td>\u0131</td>
* <td>capital letter I -> small letter dotless i </td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>French Fries</td>
* <td>french fries</td>
* <td>lowercased all chars in String</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
* <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
* <img src="doc-files/capsigma.gif" alt="capsigma"></td>
* <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
* <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
* <img src="doc-files/sigma1.gif" alt="sigma"></td>
* <td>lowercased all chars in String</td>
* </tr>
* </table>
*
* @param locale use the case transformation rules for this locale
* @return the {@code String}, converted to lowercase.
* @see java.lang.String#toLowerCase()
* @see java.lang.String#toUpperCase()
* @see java.lang.String#toUpperCase(Locale)
* @since 1.1
*/
public String toLowerCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstUpper;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstUpper = 0 ; firstUpper < len; ) {
char c = value[firstUpper];
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
int supplChar = codePointAt(firstUpper);
if (supplChar != Character.toLowerCase(supplChar)) {
break scan;
}
firstUpper += Character.charCount(supplChar);
} else {
if (c != Character.toLowerCase(c)) {
break scan;
}
firstUpper++;
}
}
return this;
}
char[] result = new char[len];
int resultOffset = 0; /* result may grow, so i+resultOffset
* is the write location in result */
/* Just copy the first few lowerCase characters. */
System.arraycopy(value, 0, result, 0, firstUpper);
String lang = locale.getLanguage();
boolean localeDependent =
(lang == "tr" || lang == "az" || lang == "lt");
char[] lowerCharArray;
int lowerChar;
int srcChar;
int srcCount;
for (int i = firstUpper; i < len; i += srcCount) {
srcChar = (int)value[i];
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
&& (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
srcChar = codePointAt(i);
srcCount = Character.charCount(srcChar);
} else {
srcCount = 1;
}
if (localeDependent ||
srcChar == '\u03A3' || // GREEK CAPITAL LETTER SIGMA
srcChar == '\u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVE
lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
} else {
lowerChar = Character.toLowerCase(srcChar);
}
if ((lowerChar == Character.ERROR)
|| (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
if (lowerChar == Character.ERROR) {
lowerCharArray =
ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
} else if (srcCount == 2) {
resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
continue;
} else {
lowerCharArray = Character.toChars(lowerChar);
}
/* Grow result if needed */
int mapLen = lowerCharArray.length;
if (mapLen > srcCount) {
char[] result2 = new char[result.length + mapLen - srcCount];
System.arraycopy(result, 0, result2, 0, i + resultOffset);
result = result2;
}
for (int x = 0; x < mapLen; ++x) {
result[i + resultOffset + x] = lowerCharArray[x];
}
resultOffset += (mapLen - srcCount);
} else {
result[i + resultOffset] = (char)lowerChar;
}
}
return new String(result, 0, len + resultOffset);
}
/**
* Converts all of the characters in this {@code String} to lower
* case using the rules of the default locale. This is equivalent to calling
* {@code toLowerCase(Locale.getDefault())}.
* <p>
* <b>Note:</b> This method is locale sensitive, and may produce unexpected
* results if used for strings that are intended to be interpreted locale
* independently.
* Examples are programming language identifiers, protocol keys, and HTML
* tags.
* For instance, {@code "TITLE".toLowerCase()} in a Turkish locale
* returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the
* LATIN SMALL LETTER DOTLESS I character.
* To obtain correct results for locale insensitive strings, use
* {@code toLowerCase(Locale.ROOT)}.
* <p>
* @return the {@code String}, converted to lowercase.
* @see java.lang.String#toLowerCase(Locale)
*/
public String toLowerCase() {
return toLowerCase(Locale.getDefault());
}
/**
* Converts all of the characters in this {@code String} to upper
* case using the rules of the given {@code Locale}. Case mapping is based
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
* class. Since case mappings are not always 1:1 char mappings, the resulting
* {@code String} may be a different length than the original {@code String}.
* <p>
* Examples of locale-sensitive and 1:M case mappings are in the following table.
*
* <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
* <tr>
* <th>Language Code of Locale</th>
* <th>Lower Case</th>
* <th>Upper Case</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0069</td>
* <td>\u0130</td>
* <td>small letter i -> capital letter I with dot above</td>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0131</td>
* <td>\u0049</td>
* <td>small letter dotless i -> capital letter I</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>\u00df</td>
* <td>\u0053 \u0053</td>
* <td>small letter sharp s -> two letters: SS</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>Fahrvergnügen</td>
* <td>FAHRVERGNÜGEN</td>
* <td></td>
* </tr>
* </table>
* @param locale use the case transformation rules for this locale
* @return the {@code String}, converted to uppercase.
* @see java.lang.String#toUpperCase()
* @see java.lang.String#toLowerCase()
* @see java.lang.String#toLowerCase(Locale)
* @since 1.1
*/
public String toUpperCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstLower;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstLower = 0 ; firstLower < len; ) {
int c = (int)value[firstLower];
int srcCount;
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
c = codePointAt(firstLower);
srcCount = Character.charCount(c);
} else {
srcCount = 1;
}
int upperCaseChar = Character.toUpperCaseEx(c);
if ((upperCaseChar == Character.ERROR)
|| (c != upperCaseChar)) {
break scan;
}
firstLower += srcCount;
}
return this;
}
/* result may grow, so i+resultOffset is the write location in result */
int resultOffset = 0;
char[] result = new char[len]; /* may grow */
/* Just copy the first few upperCase characters. */
System.arraycopy(value, 0, result, 0, firstLower);
String lang = locale.getLanguage();
boolean localeDependent =
(lang == "tr" || lang == "az" || lang == "lt");
char[] upperCharArray;
int upperChar;
int srcChar;
int srcCount;
for (int i = firstLower; i < len; i += srcCount) {
srcChar = (int)value[i];
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
(char)srcChar <= Character.MAX_HIGH_SURROGATE) {
srcChar = codePointAt(i);
srcCount = Character.charCount(srcChar);
} else {
srcCount = 1;
}
if (localeDependent) {
upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
} else {
upperChar = Character.toUpperCaseEx(srcChar);
}
if ((upperChar == Character.ERROR)
|| (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
if (upperChar == Character.ERROR) {
if (localeDependent) {
upperCharArray =
ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
} else {
upperCharArray = Character.toUpperCaseCharArray(srcChar);
}
} else if (srcCount == 2) {
resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
continue;
} else {
upperCharArray = Character.toChars(upperChar);
}
/* Grow result if needed */
int mapLen = upperCharArray.length;
if (mapLen > srcCount) {
char[] result2 = new char[result.length + mapLen - srcCount];
System.arraycopy(result, 0, result2, 0, i + resultOffset);
result = result2;
}
for (int x = 0; x < mapLen; ++x) {
result[i + resultOffset + x] = upperCharArray[x];
}
resultOffset += (mapLen - srcCount);
} else {
result[i + resultOffset] = (char)upperChar;
}
}
return new String(result, 0, len + resultOffset);
}
/**
* Converts all of the characters in this {@code String} to upper
* case using the rules of the default locale. This method is equivalent to
* {@code toUpperCase(Locale.getDefault())}.
* <p>
* <b>Note:</b> This method is locale sensitive, and may produce unexpected
* results if used for strings that are intended to be interpreted locale
* independently.
* Examples are programming language identifiers, protocol keys, and HTML
* tags.
* For instance, {@code "title".toUpperCase()} in a Turkish locale
* returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the
* LATIN CAPITAL LETTER I WITH DOT ABOVE character.
* To obtain correct results for locale insensitive strings, use
* {@code toUpperCase(Locale.ROOT)}.
* <p>
* @return the {@code String}, converted to uppercase.
* @see java.lang.String#toUpperCase(Locale)
*/
public String toUpperCase() {
return toUpperCase(Locale.getDefault());
}
/**
* Returns a string whose value is this string, with any leading and trailing
* whitespace removed.
* <p>
* If this {@code String} object represents an empty character
* sequence, or the first and last characters of character sequence
* represented by this {@code String} object both have codes
* greater than {@code '\u005Cu0020'} (the space character), then a
* reference to this {@code String} object is returned.
* <p>
* Otherwise, if there is no character with a code greater than
* {@code '\u005Cu0020'} in the string, then a
* {@code String} object representing an empty string is
* returned.
* <p>
* Otherwise, let <i>k</i> be the index of the first character in the
* string whose code is greater than {@code '\u005Cu0020'}, and let
* <i>m</i> be the index of the last character in the string whose code
* is greater than {@code '\u005Cu0020'}. A {@code String}
* object is returned, representing the substring of this string that
* begins with the character at index <i>k</i> and ends with the
* character at index <i>m</i>-that is, the result of
* {@code this.substring(k, m + 1)}.
* <p>
* This method may be used to trim whitespace (as defined above) from
* the beginning and end of a string.
*
* @return A string whose value is this string, with any leading and trailing white
* space removed, or this string if it has no leading or
* trailing white space.
*/
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}
/**
* Converts this string to a new character array.
*
* @return a newly allocated character array whose length is the length
* of this string and whose contents are initialized to contain
* the character sequence represented by this string.
*/
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
/**
* Returns a formatted string using the specified format string and
* arguments.
*
* <p> The locale always used is the one returned by {@link
* java.util.Locale#getDefault() Locale.getDefault()}.
*
* @param format
* A <a href="../util/Formatter.html#syntax">format string</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
* The behaviour on a
* {@code null} argument depends on the <a
* href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification.
*
* @return A formatted string
*
* @see java.util.Formatter
* @since 1.5
*/
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
/**
* Returns a formatted string using the specified locale, format string,
* and arguments.
*
* @param l
* The {@linkplain java.util.Locale locale} to apply during
* formatting. If {@code l} is {@code null} then no localization
* is applied.
*
* @param format
* A <a href="../util/Formatter.html#syntax">format string</a>
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
* The behaviour on a
* {@code null} argument depends on the
* <a href="../util/Formatter.html#syntax">conversion</a>.
*
* @throws java.util.IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the <a
* href="../util/Formatter.html#detail">Details</a> section of the
* formatter class specification
*
* @return A formatted string
*
* @see java.util.Formatter
* @since 1.5
*/
public static String format(Locale l, String format, Object... args) {
return new Formatter(l).format(format, args).toString();
}
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
/**
* Returns the string representation of the {@code char} array
* argument. The contents of the character array are copied; subsequent
* modification of the character array does not affect the returned
* string.
*
* @param data the character array.
* @return a {@code String} that contains the characters of the
* character array.
*/
public static String valueOf(char data[]) {
return new String(data);
}
/**
* Returns the string representation of a specific subarray of the
* {@code char} array argument.
* <p>
* The {@code offset} argument is the index of the first
* character of the subarray. The {@code count} argument
* specifies the length of the subarray. The contents of the subarray
* are copied; subsequent modification of the character array does not
* affect the returned string.
*
* @param data the character array.
* @param offset initial offset of the subarray.
* @param count length of the subarray.
* @return a {@code String} that contains the characters of the
* specified subarray of the character array.
* @exception IndexOutOfBoundsException if {@code offset} is
* negative, or {@code count} is negative, or
* {@code offset+count} is larger than
* {@code data.length}.
*/
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
/**
* Equivalent to {@link #valueOf(char[], int, int)}.
*
* @param data the character array.
* @param offset initial offset of the subarray.
* @param count length of the subarray.
* @return a {@code String} that contains the characters of the
* specified subarray of the character array.
* @exception IndexOutOfBoundsException if {@code offset} is
* negative, or {@code count} is negative, or
* {@code offset+count} is larger than
* {@code data.length}.
*/
public static String copyValueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
/**
* Equivalent to {@link #valueOf(char[])}.
*
* @param data the character array.
* @return a {@code String} that contains the characters of the
* character array.
*/
public static String copyValueOf(char data[]) {
return new String(data);
}
/**
* Returns the string representation of the {@code boolean} argument.
*
* @param b a {@code boolean}.
* @return if the argument is {@code true}, a string equal to
* {@code "true"} is returned; otherwise, a string equal to
* {@code "false"} is returned.
*/
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
/**
* Returns the string representation of the {@code char}
* argument.
*
* @param c a {@code char}.
* @return a string of length {@code 1} containing
* as its single character the argument {@code c}.
*/
public static String valueOf(char c) {
char data[] = {c};
return new String(data, true);
}
/**
* Returns the string representation of the {@code int} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Integer.toString} method of one argument.
*
* @param i an {@code int}.
* @return a string representation of the {@code int} argument.
* @see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
/**
* Returns the string representation of the {@code long} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Long.toString} method of one argument.
*
* @param l a {@code long}.
* @return a string representation of the {@code long} argument.
* @see java.lang.Long#toString(long)
*/
public static String valueOf(long l) {
return Long.toString(l);
}
/**
* Returns the string representation of the {@code float} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Float.toString} method of one argument.
*
* @param f a {@code float}.
* @return a string representation of the {@code float} argument.
* @see java.lang.Float#toString(float)
*/
public static String valueOf(float f) {
return Float.toString(f);
}
/**
* Returns the string representation of the {@code double} argument.
* <p>
* The representation is exactly the one returned by the
* {@code Double.toString} method of one argument.
*
* @param d a {@code double}.
* @return a string representation of the {@code double} argument.
* @see java.lang.Double#toString(double)
*/
public static String valueOf(double d) {
return Double.toString(d);
}
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/java/lang/String.java |
179,957 | /* Copyright (C) 2011-2012 Brian P. Hinz
* Copyright (C) 2012 D. R. Commander. All Rights Reserved.
* Copyright (C) 2010 TigerVNC Team
* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
* Copyright (C) 2005 Martin Koegler
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*/
package com.turbovnc.rdr;
import java.nio.channels.*;
import javax.net.ssl.*;
import com.turbovnc.network.*;
public class TLSInStream extends InStream {
static final int DEFAULT_BUF_SIZE = 16384;
public TLSInStream(InStream in_, SSLEngineManager manager_) {
in = (FdInStream)in_;
manager = manager_;
offset = 0;
SSLSession session = manager.getSession();
bufSize = session.getApplicationBufferSize();
b = new byte[bufSize];
ptr = end = start = 0;
}
public final int pos() {
return offset + ptr - start;
}
public final void startTiming() {
in.startTiming();
}
public final void stopTiming() {
in.stopTiming();
}
public final long kbitsPerSecond() {
return in.kbitsPerSecond();
}
public final long timeWaited() {
return in.timeWaited();
}
protected final int overrun(int itemSize, int nItems, boolean wait) {
if (itemSize > bufSize)
throw new ErrorException("TLSInStream overrun: max itemSize exceeded");
if (end - ptr != 0)
System.arraycopy(b, ptr, b, 0, end - ptr);
offset += ptr - start;
end -= ptr - start;
ptr = start;
while (end < start + itemSize) {
int n = readTLS(b, end, start + bufSize - end, wait);
if (!wait && n == 0)
return 0;
end += n;
}
if (itemSize * nItems > end - ptr)
nItems = (end - ptr) / itemSize;
return nItems;
}
protected int readTLS(byte[] buf, int bufPtr, int len, boolean wait) {
int n = -1;
//n = in.check(1, 1, wait);
//if (n == 0)
// return 0;
try {
n = manager.read(buf, bufPtr, len);
} catch (java.io.IOException e) {
throw new ErrorException("TLS read error: " + e.getMessage());
}
if (n < 0) throw new ErrorException("TLS read error");
return n;
}
private SSLEngineManager manager;
private int offset;
private int start;
private int bufSize;
private FdInStream in;
}
| TurboVNC/turbovnc | java/com/turbovnc/rdr/TLSInStream.java |
179,958 | package org.jgroups.auth;
import org.ietf.jgss.GSSException;
import org.jgroups.Message;
import org.jgroups.annotations.Experimental;
import org.jgroups.annotations.Property;
import org.jgroups.util.Util;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Properties;
/**
* JGroups AuthToken Class to for Kerberos v5 authentication.
* @author Martin Swales
* @author Claudio Corsi
* @since 3.4
*/
@Experimental
public class Krb5Token extends AuthToken {
private static final String JASS_SECURITY_CONFIG = "JGoupsKrb5TokenSecurityConf";
public static final String CLIENT_PRINCIPAL_NAME = "client_principal_name";
public static final String CLIENT_PASSWORD = "client_password";
public static final String SERVICE_PRINCIPAL_NAME = "service_principal_name";
@Property protected String client_principal_name;
@Property(exposeAsManagedAttribute=false) protected String client_password;
@Property protected String service_principal_name;
private Subject subject;
private byte[] krbServiceTicket;
private byte[] remoteKrbServiceTicket;
public Krb5Token() { // Need an empty constructor
}
public void setValue(Properties properties) {
String value;
if((value = properties.getProperty(CLIENT_PRINCIPAL_NAME)) != null){
this.client_principal_name= value;
properties.remove(CLIENT_PRINCIPAL_NAME);
}
if((value = properties.getProperty(CLIENT_PASSWORD)) != null){
this.client_password= value;
properties.remove(CLIENT_PASSWORD);
}
if((value = properties.getProperty(SERVICE_PRINCIPAL_NAME)) != null){
this.service_principal_name= value;
properties.remove(SERVICE_PRINCIPAL_NAME);
}
try {
authenticateClientPrincipal();
}
catch (Exception e) {
// If we get any kind of exception then blank the subject
log.warn("Krb5Token failed to authenticate", e);
subject = null;
}
}
public String getName() {
return Krb5Token.class.getName();
}
public boolean authenticate(AuthToken token, Message msg) {
if (!isAuthenticated()) {
log.error(Util.getMessage("Krb5TokenFailedToSetupCorrectlyCannotAuthenticateAnyPeers"));
return false;
}
if(token instanceof Krb5Token) {
Krb5Token remoteToken = (Krb5Token)token;
try {
validateRemoteServiceTicket(remoteToken);
return true;
}
catch (Exception e) {
log.error(Util.getMessage("Krb5TokenServiceTicketValidationFailed"), e);
return false;
}
/*
if((remoteToken.fingerPrint != null) &&
(this.fingerPrint.equalsIgnoreCase(remoteToken.fingerPrint))) {
log.debug(" : Krb5Token authenticate match");
return true;
}else {
log.debug(" : Krb5Token authenticate fail");
return false;
}
*/
}
return false;
}
@Override
public void writeTo(DataOutput out) throws IOException {
if (isAuthenticated()) {
generateServiceTicket();
writeServiceTicketToSream(out);
}
}
@Override
public void readFrom(DataInput in) throws IOException {
// This method is called from within a temporary token so it has not authenticated to a client principal
// This token is passed to the authenticate
readRemoteServiceTicketFromStream(in);
}
public int size() {
return Util.size(krbServiceTicket);
}
/******************************************************
*
* Private Methods
*
*/
private boolean isAuthenticated() {
return (subject != null);
}
private void authenticateClientPrincipal() throws LoginException {
subject = Krb5TokenUtils.generateSecuritySubject(JASS_SECURITY_CONFIG, client_principal_name, client_password);
}
private void generateServiceTicket() throws IOException {
try {
krbServiceTicket = Krb5TokenUtils.initiateSecurityContext(subject,service_principal_name);
}
catch(GSSException ge) {
throw new IOException("Failed to generate serviceticket", ge);
}
}
private void validateRemoteServiceTicket(Krb5Token remoteToken) throws Exception {
byte[] remoteKrbServiceTicketLocal = remoteToken.remoteKrbServiceTicket;
String clientPrincipalName = Krb5TokenUtils.validateSecurityContext(subject, remoteKrbServiceTicketLocal);
if (!clientPrincipalName.equals(this.client_principal_name))
throw new Exception("Client Principal Names did not match");
}
private void writeServiceTicketToSream(DataOutput out) throws IOException {
try {
Krb5TokenUtils.encodeDataToStream(krbServiceTicket, out);
} catch(IOException ioe) {
throw ioe;
} catch(Exception e) {
throw new IOException(e);
}
}
private void readRemoteServiceTicketFromStream(DataInput in) throws IOException {
try {
remoteKrbServiceTicket = Krb5TokenUtils.decodeDataFromStream(in);
} catch(IOException ioe) {
throw ioe;
} catch(Exception e) {
throw new IOException(e);
}
}
}
| belaban/JGroups | src/org/jgroups/auth/Krb5Token.java |
179,960 | /*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.lang.ProcessBuilder.Redirect;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import sun.security.action.GetPropertyAction;
/* This class is for the exclusive use of ProcessBuilder.start() to
* create new processes.
*
* @author Martin Buchholz
* @since 1.5
*/
final class ProcessImpl extends Process {
private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
= sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
/**
* Open a file for writing. If {@code append} is {@code true} then the file
* is opened for atomic append directly and a FileOutputStream constructed
* with the resulting handle. This is because a FileOutputStream created
* to append to a file does not open the file in a manner that guarantees
* that writes by the child process will be atomic.
*/
private static FileOutputStream newFileOutputStream(File f, boolean append)
throws IOException
{
if (append) {
String path = f.getPath();
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkWrite(path);
long handle = openForAtomicAppend(path);
final FileDescriptor fd = new FileDescriptor();
fdAccess.setHandle(fd, handle);
return AccessController.doPrivileged(
new PrivilegedAction<FileOutputStream>() {
public FileOutputStream run() {
return new FileOutputStream(fd);
}
}
);
} else {
return new FileOutputStream(f);
}
}
// System-dependent portion of ProcessBuilder.start()
static Process start(String cmdarray[],
java.util.Map<String,String> environment,
String dir,
ProcessBuilder.Redirect[] redirects,
boolean redirectErrorStream)
throws IOException
{
String envblock = ProcessEnvironment.toEnvironmentBlock(environment);
FileInputStream f0 = null;
FileOutputStream f1 = null;
FileOutputStream f2 = null;
try {
long[] stdHandles;
if (redirects == null) {
stdHandles = new long[] { -1L, -1L, -1L };
} else {
stdHandles = new long[3];
if (redirects[0] == Redirect.PIPE)
stdHandles[0] = -1L;
else if (redirects[0] == Redirect.INHERIT)
stdHandles[0] = fdAccess.getHandle(FileDescriptor.in);
else {
f0 = new FileInputStream(redirects[0].file());
stdHandles[0] = fdAccess.getHandle(f0.getFD());
}
if (redirects[1] == Redirect.PIPE)
stdHandles[1] = -1L;
else if (redirects[1] == Redirect.INHERIT)
stdHandles[1] = fdAccess.getHandle(FileDescriptor.out);
else {
f1 = newFileOutputStream(redirects[1].file(),
redirects[1].append());
stdHandles[1] = fdAccess.getHandle(f1.getFD());
}
if (redirects[2] == Redirect.PIPE)
stdHandles[2] = -1L;
else if (redirects[2] == Redirect.INHERIT)
stdHandles[2] = fdAccess.getHandle(FileDescriptor.err);
else {
f2 = newFileOutputStream(redirects[2].file(),
redirects[2].append());
stdHandles[2] = fdAccess.getHandle(f2.getFD());
}
}
return new ProcessImpl(cmdarray, envblock, dir,
stdHandles, redirectErrorStream);
} finally {
// In theory, close() can throw IOException
// (although it is rather unlikely to happen here)
try { if (f0 != null) f0.close(); }
finally {
try { if (f1 != null) f1.close(); }
finally { if (f2 != null) f2.close(); }
}
}
}
private static class LazyPattern {
// Escape-support version:
// "(\")((?:\\\\\\1|.)+?)\\1|([^\\s\"]+)";
private static final Pattern PATTERN =
Pattern.compile("[^\\s\"]+|\"[^\"]*\"");
};
/* Parses the command string parameter into the executable name and
* program arguments.
*
* The command string is broken into tokens. The token separator is a space
* or quota character. The space inside quotation is not a token separator.
* There are no escape sequences.
*/
private static String[] getTokensFromCommand(String command) {
ArrayList<String> matchList = new ArrayList<>(8);
Matcher regexMatcher = LazyPattern.PATTERN.matcher(command);
while (regexMatcher.find())
matchList.add(regexMatcher.group());
return matchList.toArray(new String[matchList.size()]);
}
private static final int VERIFICATION_CMD_BAT = 0;
private static final int VERIFICATION_WIN32 = 1;
private static final int VERIFICATION_WIN32_SAFE = 2; // inside quotes not allowed
private static final int VERIFICATION_LEGACY = 3;
// See Command shell overview for documentation of special characters.
// https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490954(v=technet.10)
private static final char ESCAPE_VERIFICATION[][] = {
// We guarantee the only command file execution for implicit [cmd.exe] run.
// http://technet.microsoft.com/en-us/library/bb490954.aspx
{' ', '\t', '\"', '<', '>', '&', '|', '^'},
{' ', '\t', '\"', '<', '>'},
{' ', '\t', '\"', '<', '>'},
{' ', '\t'}
};
private static String createCommandLine(int verificationType,
final String executablePath,
final String cmd[])
{
StringBuilder cmdbuf = new StringBuilder(80);
cmdbuf.append(executablePath);
for (int i = 1; i < cmd.length; ++i) {
cmdbuf.append(' ');
String s = cmd[i];
if (needsEscaping(verificationType, s)) {
cmdbuf.append('"');
if (verificationType == VERIFICATION_WIN32_SAFE) {
// Insert the argument, adding '\' to quote any interior quotes
int length = s.length();
for (int j = 0; j < length; j++) {
char c = s.charAt(j);
if (c == DOUBLEQUOTE) {
int count = countLeadingBackslash(verificationType, s, j);
while (count-- > 0) {
cmdbuf.append(BACKSLASH); // double the number of backslashes
}
cmdbuf.append(BACKSLASH); // backslash to quote the quote
}
cmdbuf.append(c);
}
} else {
cmdbuf.append(s);
}
// The code protects the [java.exe] and console command line
// parser, that interprets the [\"] combination as an escape
// sequence for the ["] char.
// http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
//
// If the argument is an FS path, doubling of the tail [\]
// char is not a problem for non-console applications.
//
// The [\"] sequence is not an escape sequence for the [cmd.exe]
// command line parser. The case of the [""] tail escape
// sequence could not be realized due to the argument validation
// procedure.
int count = countLeadingBackslash(verificationType, s, s.length());
while (count-- > 0) {
cmdbuf.append(BACKSLASH); // double the number of backslashes
}
cmdbuf.append('"');
} else {
cmdbuf.append(s);
}
}
return cmdbuf.toString();
}
/**
* Return the argument without quotes (1st and last) if properly quoted, else the arg.
* A properly quoted string has first and last characters as quote and
* the last quote is not escaped.
* @param str a string
* @return the string without quotes
*/
private static String unQuote(String str) {
if (!str.startsWith("\"") || !str.endsWith("\"") || str.length() < 2)
return str; // no beginning or ending quote, or too short not quoted
if (str.endsWith("\\\"")) {
return str; // not properly quoted, treat as unquoted
}
// Strip leading and trailing quotes
return str.substring(1, str.length() - 1);
}
private static boolean needsEscaping(int verificationType, String arg) {
if (arg.isEmpty())
return true; // Empty string is to be quoted
// Switch off MS heuristic for internal ["].
// Please, use the explicit [cmd.exe] call
// if you need the internal ["].
// Example: "cmd.exe", "/C", "Extended_MS_Syntax"
// For [.exe] or [.com] file the unpaired/internal ["]
// in the argument is not a problem.
String unquotedArg = unQuote(arg);
boolean argIsQuoted = !arg.equals(unquotedArg);
boolean embeddedQuote = unquotedArg.indexOf(DOUBLEQUOTE) >= 0;
switch (verificationType) {
case VERIFICATION_CMD_BAT:
if (embeddedQuote) {
throw new IllegalArgumentException("Argument has embedded quote, " +
"use the explicit CMD.EXE call.");
}
break; // break determine whether to quote
case VERIFICATION_WIN32_SAFE:
if (argIsQuoted && embeddedQuote) {
throw new IllegalArgumentException("Malformed argument has embedded quote: "
+ unquotedArg);
}
break;
default:
break;
}
if (!argIsQuoted) {
char testEscape[] = ESCAPE_VERIFICATION[verificationType];
for (int i = 0; i < testEscape.length; ++i) {
if (arg.indexOf(testEscape[i]) >= 0) {
return true;
}
}
}
return false;
}
private static String getExecutablePath(String path)
throws IOException
{
String name = unQuote(path);
if (name.indexOf(DOUBLEQUOTE) >= 0) {
throw new IllegalArgumentException("Executable name has embedded quote, " +
"split the arguments: " + name);
}
// Win32 CreateProcess requires path to be normalized
File fileToRun = new File(name);
// From the [CreateProcess] function documentation:
//
// "If the file name does not contain an extension, .exe is appended.
// Therefore, if the file name extension is .com, this parameter
// must include the .com extension. If the file name ends in
// a period (.) with no extension, or if the file name contains a path,
// .exe is not appended."
//
// "If the file name !does not contain a directory path!,
// the system searches for the executable file in the following
// sequence:..."
//
// In practice ANY non-existent path is extended by [.exe] extension
// in the [CreateProcess] function with the only exception:
// the path ends by (.)
return fileToRun.getPath();
}
/**
* An executable is any program that is an EXE or does not have an extension
* and the Windows createProcess will be looking for .exe.
* The comparison is case insensitive based on the name.
* @param executablePath the executable file
* @return true if the path ends in .exe or does not have an extension.
*/
private boolean isExe(String executablePath) {
File file = new File(executablePath);
String upName = file.getName().toUpperCase(Locale.ROOT);
return (upName.endsWith(".EXE") || upName.indexOf('.') < 0);
}
// Old version that can be bypassed
private boolean isShellFile(String executablePath) {
String upPath = executablePath.toUpperCase();
return (upPath.endsWith(".CMD") || upPath.endsWith(".BAT"));
}
private String quoteString(String arg) {
StringBuilder argbuf = new StringBuilder(arg.length() + 2);
return argbuf.append('"').append(arg).append('"').toString();
}
// Count backslashes before start index of string.
// .bat files don't include backslashes as part of the quote
private static int countLeadingBackslash(int verificationType,
CharSequence input, int start) {
if (verificationType == VERIFICATION_CMD_BAT)
return 0;
int j;
for (j = start - 1; j >= 0 && input.charAt(j) == BACKSLASH; j--) {
// just scanning backwards
}
return (start - 1) - j; // number of BACKSLASHES
}
private static final char DOUBLEQUOTE = '\"';
private static final char BACKSLASH = '\\';
private long handle = 0;
private OutputStream stdin_stream;
private InputStream stdout_stream;
private InputStream stderr_stream;
private ProcessImpl(String cmd[],
final String envblock,
final String path,
final long[] stdHandles,
final boolean redirectErrorStream)
throws IOException
{
String cmdstr;
final SecurityManager security = System.getSecurityManager();
String propertyValue = GetPropertyAction.
privilegedGetProperty("jdk.lang.Process.allowAmbiguousCommands");
final String value = propertyValue != null ? propertyValue
: (security == null ? "true" : "false");
final boolean allowAmbiguousCommands = !"false".equalsIgnoreCase(value);
if (allowAmbiguousCommands && security == null) {
// Legacy mode.
// Normalize path if possible.
String executablePath = new File(cmd[0]).getPath();
// No worry about internal, unpaired ["], and redirection/piping.
if (needsEscaping(VERIFICATION_LEGACY, executablePath) )
executablePath = quoteString(executablePath);
cmdstr = createCommandLine(
//legacy mode doesn't worry about extended verification
VERIFICATION_LEGACY,
executablePath,
cmd);
} else {
String executablePath;
try {
executablePath = getExecutablePath(cmd[0]);
} catch (IllegalArgumentException e) {
// Workaround for the calls like
// Runtime.getRuntime().exec("\"C:\\Program Files\\foo\" bar")
// No chance to avoid CMD/BAT injection, except to do the work
// right from the beginning. Otherwise we have too many corner
// cases from
// Runtime.getRuntime().exec(String[] cmd [, ...])
// calls with internal ["] and escape sequences.
// Restore original command line.
StringBuilder join = new StringBuilder();
// terminal space in command line is ok
for (String s : cmd)
join.append(s).append(' ');
// Parse the command line again.
cmd = getTokensFromCommand(join.toString());
executablePath = getExecutablePath(cmd[0]);
// Check new executable name once more
if (security != null)
security.checkExec(executablePath);
}
// Quotation protects from interpretation of the [path] argument as
// start of longer path with spaces. Quotation has no influence to
// [.exe] extension heuristic.
boolean isShell = allowAmbiguousCommands ? isShellFile(executablePath)
: !isExe(executablePath);
cmdstr = createCommandLine(
// We need the extended verification procedures
isShell ? VERIFICATION_CMD_BAT
: (allowAmbiguousCommands ? VERIFICATION_WIN32 : VERIFICATION_WIN32_SAFE),
quoteString(executablePath),
cmd);
}
handle = create(cmdstr, envblock, path,
stdHandles, redirectErrorStream);
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
if (stdHandles[0] == -1L)
stdin_stream = ProcessBuilder.NullOutputStream.INSTANCE;
else {
FileDescriptor stdin_fd = new FileDescriptor();
fdAccess.setHandle(stdin_fd, stdHandles[0]);
stdin_stream = new BufferedOutputStream(
new FileOutputStream(stdin_fd));
}
if (stdHandles[1] == -1L)
stdout_stream = ProcessBuilder.NullInputStream.INSTANCE;
else {
FileDescriptor stdout_fd = new FileDescriptor();
fdAccess.setHandle(stdout_fd, stdHandles[1]);
stdout_stream = new BufferedInputStream(
new FileInputStream(stdout_fd));
}
if (stdHandles[2] == -1L)
stderr_stream = ProcessBuilder.NullInputStream.INSTANCE;
else {
FileDescriptor stderr_fd = new FileDescriptor();
fdAccess.setHandle(stderr_fd, stdHandles[2]);
stderr_stream = new FileInputStream(stderr_fd);
}
return null; }});
}
public OutputStream getOutputStream() {
return stdin_stream;
}
public InputStream getInputStream() {
return stdout_stream;
}
public InputStream getErrorStream() {
return stderr_stream;
}
protected void finalize() {
closeHandle(handle);
}
private static final int STILL_ACTIVE = getStillActive();
private static native int getStillActive();
public int exitValue() {
int exitCode = getExitCodeProcess(handle);
if (exitCode == STILL_ACTIVE)
throw new IllegalThreadStateException("process has not exited");
return exitCode;
}
private static native int getExitCodeProcess(long handle);
public int waitFor() throws InterruptedException {
waitForInterruptibly(handle);
if (Thread.interrupted())
throw new InterruptedException();
return exitValue();
}
private static native void waitForInterruptibly(long handle);
@Override
public boolean waitFor(long timeout, TimeUnit unit)
throws InterruptedException
{
long remainingNanos = unit.toNanos(timeout); // throw NPE before other conditions
if (getExitCodeProcess(handle) != STILL_ACTIVE) return true;
if (timeout <= 0) return false;
long deadline = System.nanoTime() + remainingNanos;
do {
// Round up to next millisecond
long msTimeout = TimeUnit.NANOSECONDS.toMillis(remainingNanos + 999_999L);
if (msTimeout < 0) {
// if wraps around then wait a long while
msTimeout = Integer.MAX_VALUE;
}
waitForTimeoutInterruptibly(handle, msTimeout);
if (Thread.interrupted())
throw new InterruptedException();
if (getExitCodeProcess(handle) != STILL_ACTIVE) {
return true;
}
remainingNanos = deadline - System.nanoTime();
} while (remainingNanos > 0);
return (getExitCodeProcess(handle) != STILL_ACTIVE);
}
private static native void waitForTimeoutInterruptibly(
long handle, long timeoutMillis);
public void destroy() { terminateProcess(handle); }
@Override
public Process destroyForcibly() {
destroy();
return this;
}
private static native void terminateProcess(long handle);
@Override
public boolean isAlive() {
return isProcessAlive(handle);
}
private static native boolean isProcessAlive(long handle);
/**
* Create a process using the win32 function CreateProcess.
* The method is synchronized due to MS kb315939 problem.
* All native handles should restore the inherit flag at the end of call.
*
* @param cmdstr the Windows command line
* @param envblock NUL-separated, double-NUL-terminated list of
* environment strings in VAR=VALUE form
* @param dir the working directory of the process, or null if
* inheriting the current directory from the parent process
* @param stdHandles array of windows HANDLEs. Indexes 0, 1, and
* 2 correspond to standard input, standard output and
* standard error, respectively. On input, a value of -1
* means to create a pipe to connect child and parent
* processes. On output, a value which is not -1 is the
* parent pipe handle corresponding to the pipe which has
* been created. An element of this array is -1 on input
* if and only if it is <em>not</em> -1 on output.
* @param redirectErrorStream redirectErrorStream attribute
* @return the native subprocess HANDLE returned by CreateProcess
*/
private static synchronized native long create(String cmdstr,
String envblock,
String dir,
long[] stdHandles,
boolean redirectErrorStream)
throws IOException;
/**
* Opens a file for atomic append. The file is created if it doesn't
* already exist.
*
* @param file the file to open or create
* @return the native HANDLE
*/
private static native long openForAtomicAppend(String path)
throws IOException;
private static native boolean closeHandle(long handle);
}
| dragonwell-project/dragonwell8 | jdk/src/windows/classes/java/lang/ProcessImpl.java |
179,962 | // Targeted by JavaCPP version 1.5.11-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.pytorch;
import org.bytedeco.pytorch.Allocator;
import org.bytedeco.pytorch.Function;
import org.bytedeco.pytorch.functions.*;
import org.bytedeco.pytorch.Module;
import org.bytedeco.javacpp.annotation.Cast;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import static org.bytedeco.pytorch.global.torch.*;
/** A stateful dataset that support hierarchical sampling and prefetching of
* entre chunks.
*
* Unlike regular dataset, chunk dataset require two samplers to operate and
* keeps an internal state. {@code ChunkSampler} selects, which chunk to load next,
* while the {@code ExampleSampler} determins the order of Examples that are returned
* in each {@code get_batch} call. The hierarchical sampling approach used here is
* inspired by this paper http://martin.zinkevich.org/publications/nips2010.pdf */
@Name("torch::data::datasets::ChunkDataset<JavaCPP_torch_0003a_0003adata_0003a_0003adatasets_0003a_0003aChunkDataReader_0003ctorch_0003a_0003adata_0003a_0003aExample_0003ctorch_0003a_0003aTensor_0002ctorch_0003a_0003aTensor_0003e_0002cstd_0003a_0003avector_0003ctorch_0003a_0003adata_0003a_0003aExample_0003ctorch_0003a_0003aTensor_0002ctorch_0003a_0003aTensor_0003e_00020_0003e_00020_0003e,torch::data::samplers::RandomSampler,torch::data::samplers::RandomSampler>") @NoOffset @Properties(inherit = org.bytedeco.pytorch.presets.torch.class)
public class ChunkDataset extends ChunkStatefulDataset {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public ChunkDataset(Pointer p) { super(p); }
public ChunkDataset(
ChunkDataReader chunk_reader,
RandomSampler chunk_sampler,
RandomSampler example_sampler,
ChunkDatasetOptions options) { super((Pointer)null); allocate(chunk_reader, chunk_sampler, example_sampler, options, null); }
public ChunkDataset(
ChunkDataReader chunk_reader,
RandomSampler chunk_sampler,
RandomSampler example_sampler,
ChunkDatasetOptions options,
Pointer preprocessing_policy) { super((Pointer)null); allocate(chunk_reader, chunk_sampler, example_sampler, options, preprocessing_policy); }
private native void allocate(
@ByVal @Cast("JavaCPP_torch_0003a_0003adata_0003a_0003adatasets_0003a_0003aChunkDataReader_0003ctorch_0003a_0003adata_0003a_0003aExample_0003ctorch_0003a_0003aTensor_0002ctorch_0003a_0003aTensor_0003e_0002cstd_0003a_0003avector_0003ctorch_0003a_0003adata_0003a_0003aExample_0003ctorch_0003a_0003aTensor_0002ctorch_0003a_0003aTensor_0003e_00020_0003e_00020_0003e*") ChunkDataReader chunk_reader,
@ByVal RandomSampler chunk_sampler,
@ByVal RandomSampler example_sampler,
@ByVal ChunkDatasetOptions options,
@ByVal(nullValue = "std::function<void(std::vector<torch::data::Example<torch::Tensor,torch::Tensor>>&)>()") @Cast("std::function<void(std::vector<torch::data::Example<torch::Tensor,torch::Tensor>>&)>*") Pointer preprocessing_policy);
/** Default get_batch method of BatchDataset. This method returns
* Example batches created from the preloaded chunks. The implemenation
* is dataset agnostic and does not need overriding in different chunk
* datasets. */
public native @ByVal ExampleVectorOptional get_batch(@Cast("size_t") long batch_size);
/** Helper method around get_batch as {@code batch_size} is not strictly necessary */
public native @ByVal ExampleVectorOptional get_batch();
/** This will clear any internal state and starts the internal prefetching
* mechanism for the chunk dataset. */
public native void reset();
/** size is not used for chunk dataset. */
public native @ByVal SizeTOptional size();
// provide a references to chunk sampler. Used mainly in distributed data
// loading to set the epoch number for the sampler.
public native @Cast("torch::data::datasets::ChunkDataset<JavaCPP_torch_0003a_0003adata_0003a_0003adatasets_0003a_0003aChunkDataReader_0003ctorch_0003a_0003adata_0003a_0003aExample_0003ctorch_0003a_0003aTensor_0002ctorch_0003a_0003aTensor_0003e_0002cstd_0003a_0003avector_0003ctorch_0003a_0003adata_0003a_0003aExample_0003ctorch_0003a_0003aTensor_0002ctorch_0003a_0003aTensor_0003e_00020_0003e_00020_0003e,torch::data::samplers::RandomSampler,torch::data::samplers::RandomSampler>::ChunkSamplerType*") @ByRef RandomSampler chunk_sampler();
public native void save(@ByRef OutputArchive archive);
public native void load(@ByRef InputArchive archive);
}
| bytedeco/javacpp-presets | pytorch/src/gen/java/org/bytedeco/pytorch/ChunkDataset.java |
179,963 | /*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.jpa;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import com.example.data.jpa.model.Author;
import com.example.data.jpa.model.Book;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
class CLR implements CommandLineRunner {
private final AuthorRepository authorRepository;
CLR(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Override
@Transactional
public void run(String... args) {
var authors = insertAuthors();
listAllAuthors();
findById(authors);
findByPartialName();
queryFindByName();
deleteAll();
}
private void deleteAll() {
this.authorRepository.deleteAll();
long count = this.authorRepository.count();
System.out.printf("deleteAll(): count = %d%n", count);
}
private void queryFindByName() {
Author author1 = this.authorRepository.queryFindByName("Josh Long").orElse(null);
Author author2 = this.authorRepository.queryFindByName("Martin Kleppmann").orElse(null);
System.out.printf("queryFindByName(): author1 = %s%n", author1);
System.out.printf("queryFindByName(): author2 = %s%n", author2);
}
private void findByPartialName() {
Author author1 = this.authorRepository.findByNameContainingIgnoreCase("sh lo").orElse(null);
Author author2 = this.authorRepository.findByNameContainingIgnoreCase("in kl").orElse(null);
System.out.printf("findByPartialName(): author1 = %s%n", author1);
System.out.printf("findByPartialName(): author2 = %s%n", author2);
}
private void findById(List<Author> authors) {
Author author1 = this.authorRepository.findById(authors.get(0).getId()).orElse(null);
Author author2 = this.authorRepository.findById(authors.get(1).getId()).orElse(null);
System.out.printf("findById(): author1 = %s%n", author1);
System.out.printf("findById(): author2 = %s%n", author2);
}
private void listAllAuthors() {
List<Author> authors = this.authorRepository.findAll();
for (Author author : authors) {
System.out.printf("listAllAuthors(): author = %s%n", author);
for (Book book : author.getBooks()) {
System.out.printf("\t%s%n", book);
}
}
}
private List<Author> insertAuthors() {
Author author1 = this.authorRepository.save(new Author(null, "Josh Long",
Set.of(new Book(null, "Reactive Spring"), new Book(null, "Cloud Native Java"))));
Author author2 = this.authorRepository.save(
new Author(null, "Martin Kleppmann", Set.of(new Book(null, "Designing Data Intensive Applications"))));
System.out.printf("insertAuthors(): author1 = %s%n", author1);
System.out.printf("insertAuthors(): author2 = %s%n", author2);
return Arrays.asList(author1, author2);
}
}
| spring-projects/spring-data-examples | jpa/graalvm-native/src/main/java/com/example/data/jpa/CLR.java |
179,964 | /*
* Copyright (C) 2003 Sun Microsystems, Inc.
* Copyright (C) 2003-2010 Martin Koegler
* Copyright (C) 2006 OCCAM Financial Technology
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
package com.iiordanov.bVNC;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import com.undatech.opaque.RemoteClientLibConstants;
import com.undatech.opaque.RfbConnectable;
import java.io.ByteArrayInputStream;
import java.net.Socket;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class X509Tunnel extends TLSTunnelBase {
private static final String TAG = "X509Tunnel";
Certificate cert;
RfbConnectable rfb;
Handler handler;
public X509Tunnel(Socket sock_, String certstr, Handler handler, RfbConnectable rfb)
throws CertificateException {
super(sock_);
Log.i(TAG, "X509Tunnel began.");
this.rfb = rfb;
this.handler = handler;
if (certstr != null && !certstr.equals("")) {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream in = new ByteArrayInputStream(Base64.decode(certstr, Base64.DEFAULT));
cert = (X509Certificate) certFactory.generateCertificate(in);
}
Log.i(TAG, "X509Tunnel ended.");
}
private boolean tlsIsOrNewerThan1_2(String[] protocols) {
boolean result = false;
for (String s : protocols) {
if (s.matches("TLSv1.[2-9]") || s.matches("TLSv[2-9].*")) {
result = true;
}
}
return result;
}
protected void setParam(SSLSocket sock) {
String[] supported;
ArrayList<String> enabled = new ArrayList<String>();
supported = sock.getSupportedCipherSuites();
String[] protocols = sock.getEnabledProtocols();
;
Log.d(TAG, "Supported TLS Protocols: " + Arrays.toString(protocols));
for (int i = 0; i < supported.length; i++) {
if (!supported[i].matches(".*DH_anon.*") &&
!(tlsIsOrNewerThan1_2(protocols) && supported[i].equals("TLS_FALLBACK_SCSV"))) {
Log.d(TAG, "Adding cipher: " + supported[i]);
enabled.add(supported[i]);
} else {
Log.d(TAG, "Omitting cipher: " + supported[i]);
}
}
sock.setEnabledCipherSuites((String[]) enabled.toArray(new String[0]));
}
protected void initContext(SSLContext sc) throws java.security.GeneralSecurityException {
TrustManager[] myTM;
//if (cert != null) {
myTM = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws CertificateException {
throw new CertificateException("no clients");
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws CertificateException {
if (certs == null || certs.length < 1) {
throw new CertificateException("no certs");
}
if (certs == null || certs.length > 1) {
throw new CertificateException("cert path too long");
}
boolean ca_match = false;
if (cert == null) {
// Send a message containing the certificate to our handler.
Message m = new Message();
m.setTarget(handler);
m.what = RemoteClientLibConstants.DIALOG_X509_CERT;
m.obj = certs[0];
handler.sendMessage(m);
synchronized (rfb) {
// Block indefinitely until the x509 cert is accepted.
while (!rfb.isCertificateAccepted()) {
try {
rfb.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
// We have exited the loop, thus the certificate was accepted.
ca_match = true;
}
if (!ca_match) {
try {
PublicKey cakey = cert.getPublicKey();
certs[0].verify(cakey);
ca_match = true;
} catch (Exception e) {
ca_match = false;
}
if (!cert.equals(certs[0])) {
throw new CertificateException("certificate does not match");
}
}
}
}
};
/*
} else {
TrustManagerFactory tmf = TrustManagerFactory.getInstance ("X509");
KeyStore ks = KeyStore.getInstance (KeyStore.getDefaultType ());
tmf.init (ks);
myTM = tmf.getTrustManagers();
}*/
sc.init(null, myTM, new SecureRandom());
}
}
| iiordanov/remote-desktop-clients | bVNC/src/main/java/com/iiordanov/bVNC/X509Tunnel.java |
179,966 | /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* This class is used to create operating system processes.
*
* <p>Each {@code ProcessBuilder} instance manages a collection
* of process attributes. The {@link #start()} method creates a new
* {@link Process} instance with those attributes. The {@link
* #start()} method can be invoked repeatedly from the same instance
* to create new subprocesses with identical or related attributes.
*
* <p>Each process builder manages these process attributes:
*
* <ul>
*
* <li>a <i>command</i>, a list of strings which signifies the
* external program file to be invoked and its arguments, if any.
* Which string lists represent a valid operating system command is
* system-dependent. For example, it is common for each conceptual
* argument to be an element in this list, but there are operating
* systems where programs are expected to tokenize command line
* strings themselves - on such a system a Java implementation might
* require commands to contain exactly two elements.
*
* <li>an <i>environment</i>, which is a system-dependent mapping from
* <i>variables</i> to <i>values</i>. The initial value is a copy of
* the environment of the current process (see {@link System#getenv()}).
*
* <li>a <i>working directory</i>. The default value is the current
* working directory of the current process, usually the directory
* named by the system property {@code user.dir}.
*
* <li><a name="redirect-input">a source of <i>standard input</i></a>.
* By default, the subprocess reads input from a pipe. Java code
* can access this pipe via the output stream returned by
* {@link Process#getOutputStream()}. However, standard input may
* be redirected to another source using
* {@link #redirectInput(Redirect) redirectInput}.
* In this case, {@link Process#getOutputStream()} will return a
* <i>null output stream</i>, for which:
*
* <ul>
* <li>the {@link OutputStream#write(int) write} methods always
* throw {@code IOException}
* <li>the {@link OutputStream#close() close} method does nothing
* </ul>
*
* <li><a name="redirect-output">a destination for <i>standard output</i>
* and <i>standard error</i></a>. By default, the subprocess writes standard
* output and standard error to pipes. Java code can access these pipes
* via the input streams returned by {@link Process#getInputStream()} and
* {@link Process#getErrorStream()}. However, standard output and
* standard error may be redirected to other destinations using
* {@link #redirectOutput(Redirect) redirectOutput} and
* {@link #redirectError(Redirect) redirectError}.
* In this case, {@link Process#getInputStream()} and/or
* {@link Process#getErrorStream()} will return a <i>null input
* stream</i>, for which:
*
* <ul>
* <li>the {@link InputStream#read() read} methods always return
* {@code -1}
* <li>the {@link InputStream#available() available} method always returns
* {@code 0}
* <li>the {@link InputStream#close() close} method does nothing
* </ul>
*
* <li>a <i>redirectErrorStream</i> property. Initially, this property
* is {@code false}, meaning that the standard output and error
* output of a subprocess are sent to two separate streams, which can
* be accessed using the {@link Process#getInputStream()} and {@link
* Process#getErrorStream()} methods.
*
* <p>If the value is set to {@code true}, then:
*
* <ul>
* <li>standard error is merged with the standard output and always sent
* to the same destination (this makes it easier to correlate error
* messages with the corresponding output)
* <li>the common destination of standard error and standard output can be
* redirected using
* {@link #redirectOutput(Redirect) redirectOutput}
* <li>any redirection set by the
* {@link #redirectError(Redirect) redirectError}
* method is ignored when creating a subprocess
* <li>the stream returned from {@link Process#getErrorStream()} will
* always be a <a href="#redirect-output">null input stream</a>
* </ul>
*
* </ul>
*
* <p>Modifying a process builder's attributes will affect processes
* subsequently started by that object's {@link #start()} method, but
* will never affect previously started processes or the Java process
* itself.
*
* <p>Most error checking is performed by the {@link #start()} method.
* It is possible to modify the state of an object so that {@link
* #start()} will fail. For example, setting the command attribute to
* an empty list will not throw an exception unless {@link #start()}
* is invoked.
*
* <p><strong>Note that this class is not synchronized.</strong>
* If multiple threads access a {@code ProcessBuilder} instance
* concurrently, and at least one of the threads modifies one of the
* attributes structurally, it <i>must</i> be synchronized externally.
*
* <p>Starting a new process which uses the default working directory
* and environment is easy:
*
* <pre> {@code
* Process p = new ProcessBuilder("myCommand", "myArg").start();
* }</pre>
*
* <p>Here is an example that starts a process with a modified working
* directory and environment, and redirects standard output and error
* to be appended to a log file:
*
* <pre> {@code
* ProcessBuilder pb =
* new ProcessBuilder("myCommand", "myArg1", "myArg2");
* Map<String, String> env = pb.environment();
* env.put("VAR1", "myValue");
* env.remove("OTHERVAR");
* env.put("VAR2", env.get("VAR1") + "suffix");
* pb.directory(new File("myDir"));
* File log = new File("log");
* pb.redirectErrorStream(true);
* pb.redirectOutput(Redirect.appendTo(log));
* Process p = pb.start();
* assert pb.redirectInput() == Redirect.PIPE;
* assert pb.redirectOutput().file() == log;
* assert p.getInputStream().read() == -1;
* }</pre>
*
* <p>To start a process with an explicit set of environment
* variables, first call {@link java.util.Map#clear() Map.clear()}
* before adding environment variables.
*
* @author Martin Buchholz
* @since 1.5
*/
public final class ProcessBuilder
{
private List<String> command;
private File directory;
private Map<String,String> environment;
private boolean redirectErrorStream;
private Redirect[] redirects;
/**
* Constructs a process builder with the specified operating
* system program and arguments. This constructor does <i>not</i>
* make a copy of the {@code command} list. Subsequent
* updates to the list will be reflected in the state of the
* process builder. It is not checked whether
* {@code command} corresponds to a valid operating system
* command.
*
* @param command the list containing the program and its arguments
* @throws NullPointerException if the argument is null
*/
public ProcessBuilder(List<String> command) {
if (command == null)
throw new NullPointerException();
this.command = command;
}
/**
* Constructs a process builder with the specified operating
* system program and arguments. This is a convenience
* constructor that sets the process builder's command to a string
* list containing the same strings as the {@code command}
* array, in the same order. It is not checked whether
* {@code command} corresponds to a valid operating system
* command.
*
* @param command a string array containing the program and its arguments
*/
public ProcessBuilder(String... command) {
this.command = new ArrayList<>(command.length);
for (String arg : command)
this.command.add(arg);
}
/**
* Sets this process builder's operating system program and
* arguments. This method does <i>not</i> make a copy of the
* {@code command} list. Subsequent updates to the list will
* be reflected in the state of the process builder. It is not
* checked whether {@code command} corresponds to a valid
* operating system command.
*
* @param command the list containing the program and its arguments
* @return this process builder
*
* @throws NullPointerException if the argument is null
*/
public ProcessBuilder command(List<String> command) {
if (command == null)
throw new NullPointerException();
this.command = command;
return this;
}
/**
* Sets this process builder's operating system program and
* arguments. This is a convenience method that sets the command
* to a string list containing the same strings as the
* {@code command} array, in the same order. It is not
* checked whether {@code command} corresponds to a valid
* operating system command.
*
* @param command a string array containing the program and its arguments
* @return this process builder
*/
public ProcessBuilder command(String... command) {
this.command = new ArrayList<>(command.length);
for (String arg : command)
this.command.add(arg);
return this;
}
/**
* Returns this process builder's operating system program and
* arguments. The returned list is <i>not</i> a copy. Subsequent
* updates to the list will be reflected in the state of this
* process builder.
*
* @return this process builder's program and its arguments
*/
public List<String> command() {
return command;
}
/**
* Returns a string map view of this process builder's environment.
*
* Whenever a process builder is created, the environment is
* initialized to a copy of the current process environment (see
* {@link System#getenv()}). Subprocesses subsequently started by
* this object's {@link #start()} method will use this map as
* their environment.
*
* <p>The returned object may be modified using ordinary {@link
* java.util.Map Map} operations. These modifications will be
* visible to subprocesses started via the {@link #start()}
* method. Two {@code ProcessBuilder} instances always
* contain independent process environments, so changes to the
* returned map will never be reflected in any other
* {@code ProcessBuilder} instance or the values returned by
* {@link System#getenv System.getenv}.
*
* <p>If the system does not support environment variables, an
* empty map is returned.
*
* <p>The returned map does not permit null keys or values.
* Attempting to insert or query the presence of a null key or
* value will throw a {@link NullPointerException}.
* Attempting to query the presence of a key or value which is not
* of type {@link String} will throw a {@link ClassCastException}.
*
* <p>The behavior of the returned map is system-dependent. A
* system may not allow modifications to environment variables or
* may forbid certain variable names or values. For this reason,
* attempts to modify the map may fail with
* {@link UnsupportedOperationException} or
* {@link IllegalArgumentException}
* if the modification is not permitted by the operating system.
*
* <p>Since the external format of environment variable names and
* values is system-dependent, there may not be a one-to-one
* mapping between them and Java's Unicode strings. Nevertheless,
* the map is implemented in such a way that environment variables
* which are not modified by Java code will have an unmodified
* native representation in the subprocess.
*
* <p>The returned map and its collection views may not obey the
* general contract of the {@link Object#equals} and
* {@link Object#hashCode} methods.
*
* <p>The returned map is typically case-sensitive on all platforms.
*
* <p>If a security manager exists, its
* {@link SecurityManager#checkPermission checkPermission} method
* is called with a
* {@link RuntimePermission}{@code ("getenv.*")} permission.
* This may result in a {@link SecurityException} being thrown.
*
* <p>When passing information to a Java subprocess,
* <a href=System.html#EnvironmentVSSystemProperties>system properties</a>
* are generally preferred over environment variables.
*
* @return this process builder's environment
*
* @throws SecurityException
* if a security manager exists and its
* {@link SecurityManager#checkPermission checkPermission}
* method doesn't allow access to the process environment
*
* @see Runtime#exec(String[],String[],java.io.File)
* @see System#getenv()
*/
public Map<String,String> environment() {
SecurityManager security = System.getSecurityManager();
if (security != null)
security.checkPermission(new RuntimePermission("getenv.*"));
if (environment == null)
environment = ProcessEnvironment.environment();
assert environment != null;
return environment;
}
// Only for use by Runtime.exec(...envp...)
ProcessBuilder environment(String[] envp) {
assert environment == null;
if (envp != null) {
environment = ProcessEnvironment.emptyEnvironment(envp.length);
assert environment != null;
for (String envstring : envp) {
// Before 1.5, we blindly passed invalid envstrings
// to the child process.
// We would like to throw an exception, but do not,
// for compatibility with old broken code.
// Silently discard any trailing junk.
if (envstring.indexOf((int) '\u0000') != -1)
envstring = envstring.replaceFirst("\u0000.*", "");
int eqlsign =
envstring.indexOf('=', ProcessEnvironment.MIN_NAME_LENGTH);
// Silently ignore envstrings lacking the required `='.
if (eqlsign != -1)
environment.put(envstring.substring(0,eqlsign),
envstring.substring(eqlsign+1));
}
}
return this;
}
/**
* Returns this process builder's working directory.
*
* Subprocesses subsequently started by this object's {@link
* #start()} method will use this as their working directory.
* The returned value may be {@code null} -- this means to use
* the working directory of the current Java process, usually the
* directory named by the system property {@code user.dir},
* as the working directory of the child process.
*
* @return this process builder's working directory
*/
public File directory() {
return directory;
}
/**
* Sets this process builder's working directory.
*
* Subprocesses subsequently started by this object's {@link
* #start()} method will use this as their working directory.
* The argument may be {@code null} -- this means to use the
* working directory of the current Java process, usually the
* directory named by the system property {@code user.dir},
* as the working directory of the child process.
*
* @param directory the new working directory
* @return this process builder
*/
public ProcessBuilder directory(File directory) {
this.directory = directory;
return this;
}
// ---------------- I/O Redirection ----------------
/**
* Implements a <a href="#redirect-output">null input stream</a>.
*/
static class NullInputStream extends InputStream {
static final NullInputStream INSTANCE = new NullInputStream();
private NullInputStream() {}
public int read() { return -1; }
public int available() { return 0; }
}
/**
* Implements a <a href="#redirect-input">null output stream</a>.
*/
static class NullOutputStream extends OutputStream {
static final NullOutputStream INSTANCE = new NullOutputStream();
private NullOutputStream() {}
public void write(int b) throws IOException {
throw new IOException("Stream closed");
}
}
/**
* Represents a source of subprocess input or a destination of
* subprocess output.
*
* Each {@code Redirect} instance is one of the following:
*
* <ul>
* <li>the special value {@link #PIPE Redirect.PIPE}
* <li>the special value {@link #INHERIT Redirect.INHERIT}
* <li>a redirection to read from a file, created by an invocation of
* {@link Redirect#from Redirect.from(File)}
* <li>a redirection to write to a file, created by an invocation of
* {@link Redirect#to Redirect.to(File)}
* <li>a redirection to append to a file, created by an invocation of
* {@link Redirect#appendTo Redirect.appendTo(File)}
* </ul>
*
* <p>Each of the above categories has an associated unique
* {@link Type Type}.
*
* @since 1.7
*/
public static abstract class Redirect {
/**
* The type of a {@link Redirect}.
*/
public enum Type {
/**
* The type of {@link Redirect#PIPE Redirect.PIPE}.
*/
PIPE,
/**
* The type of {@link Redirect#INHERIT Redirect.INHERIT}.
*/
INHERIT,
/**
* The type of redirects returned from
* {@link Redirect#from Redirect.from(File)}.
*/
READ,
/**
* The type of redirects returned from
* {@link Redirect#to Redirect.to(File)}.
*/
WRITE,
/**
* The type of redirects returned from
* {@link Redirect#appendTo Redirect.appendTo(File)}.
*/
APPEND
};
/**
* Returns the type of this {@code Redirect}.
* @return the type of this {@code Redirect}
*/
public abstract Type type();
/**
* Indicates that subprocess I/O will be connected to the
* current Java process over a pipe.
*
* This is the default handling of subprocess standard I/O.
*
* <p>It will always be true that
* <pre> {@code
* Redirect.PIPE.file() == null &&
* Redirect.PIPE.type() == Redirect.Type.PIPE
* }</pre>
*/
public static final Redirect PIPE = new Redirect() {
public Type type() { return Type.PIPE; }
public String toString() { return type().toString(); }};
/**
* Indicates that subprocess I/O source or destination will be the
* same as those of the current process. This is the normal
* behavior of most operating system command interpreters (shells).
*
* <p>It will always be true that
* <pre> {@code
* Redirect.INHERIT.file() == null &&
* Redirect.INHERIT.type() == Redirect.Type.INHERIT
* }</pre>
*/
public static final Redirect INHERIT = new Redirect() {
public Type type() { return Type.INHERIT; }
public String toString() { return type().toString(); }};
/**
* Returns the {@link File} source or destination associated
* with this redirect, or {@code null} if there is no such file.
*
* @return the file associated with this redirect,
* or {@code null} if there is no such file
*/
public File file() { return null; }
/**
* When redirected to a destination file, indicates if the output
* is to be written to the end of the file.
*/
boolean append() {
throw new UnsupportedOperationException();
}
/**
* Returns a redirect to read from the specified file.
*
* <p>It will always be true that
* <pre> {@code
* Redirect.from(file).file() == file &&
* Redirect.from(file).type() == Redirect.Type.READ
* }</pre>
*
* @param file The {@code File} for the {@code Redirect}.
* @throws NullPointerException if the specified file is null
* @return a redirect to read from the specified file
*/
public static Redirect from(final File file) {
if (file == null)
throw new NullPointerException();
return new Redirect() {
public Type type() { return Type.READ; }
public File file() { return file; }
public String toString() {
return "redirect to read from file \"" + file + "\"";
}
};
}
/**
* Returns a redirect to write to the specified file.
* If the specified file exists when the subprocess is started,
* its previous contents will be discarded.
*
* <p>It will always be true that
* <pre> {@code
* Redirect.to(file).file() == file &&
* Redirect.to(file).type() == Redirect.Type.WRITE
* }</pre>
*
* @param file The {@code File} for the {@code Redirect}.
* @throws NullPointerException if the specified file is null
* @return a redirect to write to the specified file
*/
public static Redirect to(final File file) {
if (file == null)
throw new NullPointerException();
return new Redirect() {
public Type type() { return Type.WRITE; }
public File file() { return file; }
public String toString() {
return "redirect to write to file \"" + file + "\"";
}
boolean append() { return false; }
};
}
/**
* Returns a redirect to append to the specified file.
* Each write operation first advances the position to the
* end of the file and then writes the requested data.
* Whether the advancement of the position and the writing
* of the data are done in a single atomic operation is
* system-dependent and therefore unspecified.
*
* <p>It will always be true that
* <pre> {@code
* Redirect.appendTo(file).file() == file &&
* Redirect.appendTo(file).type() == Redirect.Type.APPEND
* }</pre>
*
* @param file The {@code File} for the {@code Redirect}.
* @throws NullPointerException if the specified file is null
* @return a redirect to append to the specified file
*/
public static Redirect appendTo(final File file) {
if (file == null)
throw new NullPointerException();
return new Redirect() {
public Type type() { return Type.APPEND; }
public File file() { return file; }
public String toString() {
return "redirect to append to file \"" + file + "\"";
}
boolean append() { return true; }
};
}
/**
* Compares the specified object with this {@code Redirect} for
* equality. Returns {@code true} if and only if the two
* objects are identical or both objects are {@code Redirect}
* instances of the same type associated with non-null equal
* {@code File} instances.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof Redirect))
return false;
Redirect r = (Redirect) obj;
if (r.type() != this.type())
return false;
assert this.file() != null;
return this.file().equals(r.file());
}
/**
* Returns a hash code value for this {@code Redirect}.
* @return a hash code value for this {@code Redirect}
*/
public int hashCode() {
File file = file();
if (file == null)
return super.hashCode();
else
return file.hashCode();
}
/**
* No public constructors. Clients must use predefined
* static {@code Redirect} instances or factory methods.
*/
private Redirect() {}
}
private Redirect[] redirects() {
if (redirects == null)
redirects = new Redirect[] {
Redirect.PIPE, Redirect.PIPE, Redirect.PIPE
};
return redirects;
}
/**
* Sets this process builder's standard input source.
*
* Subprocesses subsequently started by this object's {@link #start()}
* method obtain their standard input from this source.
*
* <p>If the source is {@link Redirect#PIPE Redirect.PIPE}
* (the initial value), then the standard input of a
* subprocess can be written to using the output stream
* returned by {@link Process#getOutputStream()}.
* If the source is set to any other value, then
* {@link Process#getOutputStream()} will return a
* <a href="#redirect-input">null output stream</a>.
*
* @param source the new standard input source
* @return this process builder
* @throws IllegalArgumentException
* if the redirect does not correspond to a valid source
* of data, that is, has type
* {@link Redirect.Type#WRITE WRITE} or
* {@link Redirect.Type#APPEND APPEND}
* @since 1.7
*/
public ProcessBuilder redirectInput(Redirect source) {
if (source.type() == Redirect.Type.WRITE ||
source.type() == Redirect.Type.APPEND)
throw new IllegalArgumentException(
"Redirect invalid for reading: " + source);
redirects()[0] = source;
return this;
}
/**
* Sets this process builder's standard output destination.
*
* Subprocesses subsequently started by this object's {@link #start()}
* method send their standard output to this destination.
*
* <p>If the destination is {@link Redirect#PIPE Redirect.PIPE}
* (the initial value), then the standard output of a subprocess
* can be read using the input stream returned by {@link
* Process#getInputStream()}.
* If the destination is set to any other value, then
* {@link Process#getInputStream()} will return a
* <a href="#redirect-output">null input stream</a>.
*
* @param destination the new standard output destination
* @return this process builder
* @throws IllegalArgumentException
* if the redirect does not correspond to a valid
* destination of data, that is, has type
* {@link Redirect.Type#READ READ}
* @since 1.7
*/
public ProcessBuilder redirectOutput(Redirect destination) {
if (destination.type() == Redirect.Type.READ)
throw new IllegalArgumentException(
"Redirect invalid for writing: " + destination);
redirects()[1] = destination;
return this;
}
/**
* Sets this process builder's standard error destination.
*
* Subprocesses subsequently started by this object's {@link #start()}
* method send their standard error to this destination.
*
* <p>If the destination is {@link Redirect#PIPE Redirect.PIPE}
* (the initial value), then the error output of a subprocess
* can be read using the input stream returned by {@link
* Process#getErrorStream()}.
* If the destination is set to any other value, then
* {@link Process#getErrorStream()} will return a
* <a href="#redirect-output">null input stream</a>.
*
* <p>If the {@link #redirectErrorStream redirectErrorStream}
* attribute has been set {@code true}, then the redirection set
* by this method has no effect.
*
* @param destination the new standard error destination
* @return this process builder
* @throws IllegalArgumentException
* if the redirect does not correspond to a valid
* destination of data, that is, has type
* {@link Redirect.Type#READ READ}
* @since 1.7
*/
public ProcessBuilder redirectError(Redirect destination) {
if (destination.type() == Redirect.Type.READ)
throw new IllegalArgumentException(
"Redirect invalid for writing: " + destination);
redirects()[2] = destination;
return this;
}
/**
* Sets this process builder's standard input source to a file.
*
* <p>This is a convenience method. An invocation of the form
* {@code redirectInput(file)}
* behaves in exactly the same way as the invocation
* {@link #redirectInput(Redirect) redirectInput}
* {@code (Redirect.from(file))}.
*
* @param file the new standard input source
* @return this process builder
* @since 1.7
*/
public ProcessBuilder redirectInput(File file) {
return redirectInput(Redirect.from(file));
}
/**
* Sets this process builder's standard output destination to a file.
*
* <p>This is a convenience method. An invocation of the form
* {@code redirectOutput(file)}
* behaves in exactly the same way as the invocation
* {@link #redirectOutput(Redirect) redirectOutput}
* {@code (Redirect.to(file))}.
*
* @param file the new standard output destination
* @return this process builder
* @since 1.7
*/
public ProcessBuilder redirectOutput(File file) {
return redirectOutput(Redirect.to(file));
}
/**
* Sets this process builder's standard error destination to a file.
*
* <p>This is a convenience method. An invocation of the form
* {@code redirectError(file)}
* behaves in exactly the same way as the invocation
* {@link #redirectError(Redirect) redirectError}
* {@code (Redirect.to(file))}.
*
* @param file the new standard error destination
* @return this process builder
* @since 1.7
*/
public ProcessBuilder redirectError(File file) {
return redirectError(Redirect.to(file));
}
/**
* Returns this process builder's standard input source.
*
* Subprocesses subsequently started by this object's {@link #start()}
* method obtain their standard input from this source.
* The initial value is {@link Redirect#PIPE Redirect.PIPE}.
*
* @return this process builder's standard input source
* @since 1.7
*/
public Redirect redirectInput() {
return (redirects == null) ? Redirect.PIPE : redirects[0];
}
/**
* Returns this process builder's standard output destination.
*
* Subprocesses subsequently started by this object's {@link #start()}
* method redirect their standard output to this destination.
* The initial value is {@link Redirect#PIPE Redirect.PIPE}.
*
* @return this process builder's standard output destination
* @since 1.7
*/
public Redirect redirectOutput() {
return (redirects == null) ? Redirect.PIPE : redirects[1];
}
/**
* Returns this process builder's standard error destination.
*
* Subprocesses subsequently started by this object's {@link #start()}
* method redirect their standard error to this destination.
* The initial value is {@link Redirect#PIPE Redirect.PIPE}.
*
* @return this process builder's standard error destination
* @since 1.7
*/
public Redirect redirectError() {
return (redirects == null) ? Redirect.PIPE : redirects[2];
}
/**
* Sets the source and destination for subprocess standard I/O
* to be the same as those of the current Java process.
*
* <p>This is a convenience method. An invocation of the form
* <pre> {@code
* pb.inheritIO()
* }</pre>
* behaves in exactly the same way as the invocation
* <pre> {@code
* pb.redirectInput(Redirect.INHERIT)
* .redirectOutput(Redirect.INHERIT)
* .redirectError(Redirect.INHERIT)
* }</pre>
*
* This gives behavior equivalent to most operating system
* command interpreters, or the standard C library function
* {@code system()}.
*
* @return this process builder
* @since 1.7
*/
public ProcessBuilder inheritIO() {
Arrays.fill(redirects(), Redirect.INHERIT);
return this;
}
/**
* Tells whether this process builder merges standard error and
* standard output.
*
* <p>If this property is {@code true}, then any error output
* generated by subprocesses subsequently started by this object's
* {@link #start()} method will be merged with the standard
* output, so that both can be read using the
* {@link Process#getInputStream()} method. This makes it easier
* to correlate error messages with the corresponding output.
* The initial value is {@code false}.
*
* @return this process builder's {@code redirectErrorStream} property
*/
public boolean redirectErrorStream() {
return redirectErrorStream;
}
/**
* Sets this process builder's {@code redirectErrorStream} property.
*
* <p>If this property is {@code true}, then any error output
* generated by subprocesses subsequently started by this object's
* {@link #start()} method will be merged with the standard
* output, so that both can be read using the
* {@link Process#getInputStream()} method. This makes it easier
* to correlate error messages with the corresponding output.
* The initial value is {@code false}.
*
* @param redirectErrorStream the new property value
* @return this process builder
*/
public ProcessBuilder redirectErrorStream(boolean redirectErrorStream) {
this.redirectErrorStream = redirectErrorStream;
return this;
}
/**
* Starts a new process using the attributes of this process builder.
*
* <p>The new process will
* invoke the command and arguments given by {@link #command()},
* in a working directory as given by {@link #directory()},
* with a process environment as given by {@link #environment()}.
*
* <p>This method checks that the command is a valid operating
* system command. Which commands are valid is system-dependent,
* but at the very least the command must be a non-empty list of
* non-null strings.
*
* <p>A minimal set of system dependent environment variables may
* be required to start a process on some operating systems.
* As a result, the subprocess may inherit additional environment variable
* settings beyond those in the process builder's {@link #environment()}.
*
* <p>If there is a security manager, its
* {@link SecurityManager#checkExec checkExec}
* method is called with the first component of this object's
* {@code command} array as its argument. This may result in
* a {@link SecurityException} being thrown.
*
* <p>Starting an operating system process is highly system-dependent.
* Among the many things that can go wrong are:
* <ul>
* <li>The operating system program file was not found.
* <li>Access to the program file was denied.
* <li>The working directory does not exist.
* </ul>
*
* <p>In such cases an exception will be thrown. The exact nature
* of the exception is system-dependent, but it will always be a
* subclass of {@link IOException}.
*
* <p>Subsequent modifications to this process builder will not
* affect the returned {@link Process}.
*
* @return a new {@link Process} object for managing the subprocess
*
* @throws NullPointerException
* if an element of the command list is null
*
* @throws IndexOutOfBoundsException
* if the command is an empty list (has size {@code 0})
*
* @throws SecurityException
* if a security manager exists and
* <ul>
*
* <li>its
* {@link SecurityManager#checkExec checkExec}
* method doesn't allow creation of the subprocess, or
*
* <li>the standard input to the subprocess was
* {@linkplain #redirectInput redirected from a file}
* and the security manager's
* {@link SecurityManager#checkRead checkRead} method
* denies read access to the file, or
*
* <li>the standard output or standard error of the
* subprocess was
* {@linkplain #redirectOutput redirected to a file}
* and the security manager's
* {@link SecurityManager#checkWrite checkWrite} method
* denies write access to the file
*
* </ul>
*
* @throws IOException if an I/O error occurs
*
* @see Runtime#exec(String[], String[], java.io.File)
*/
public Process start() throws IOException {
// Must convert to array first -- a malicious user-supplied
// list might try to circumvent the security check.
String[] cmdarray = command.toArray(new String[command.size()]);
cmdarray = cmdarray.clone();
for (String arg : cmdarray)
if (arg == null)
throw new NullPointerException();
// Throws IndexOutOfBoundsException if command is empty
String prog = cmdarray[0];
SecurityManager security = System.getSecurityManager();
if (security != null)
security.checkExec(prog);
String dir = directory == null ? null : directory.toString();
for (String s : cmdarray) {
if (s.indexOf('\u0000') >= 0) {
throw new IOException("invalid null character in command");
}
}
try {
return ProcessImpl.start(cmdarray,
environment,
dir,
redirects,
redirectErrorStream);
} catch (IOException | IllegalArgumentException e) {
String exceptionInfo = ": " + e.getMessage();
Throwable cause = e;
if ((e instanceof IOException) && security != null) {
// Can not disclose the fail reason for read-protected files.
try {
security.checkRead(prog);
} catch (SecurityException se) {
exceptionInfo = "";
cause = se;
}
}
// It's much easier for us to create a high-quality error
// message than the low-level C code which found the problem.
throw new IOException(
"Cannot run program \"" + prog + "\""
+ (dir == null ? "" : " (in directory \"" + dir + "\")")
+ exceptionInfo,
cause);
}
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/java/lang/ProcessBuilder.java |
179,967 | /*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna.input;
import com.googlecode.lanterna.TerminalPosition;
/**
* MouseAction, a KeyStroke in disguise, this class contains the information of a single mouse action event.
*/
public class MouseAction extends KeyStroke {
private final MouseActionType actionType;
private final int button;
private final TerminalPosition position;
/**
* Constructs a MouseAction based on an action type, a button and a location on the screen
* @param actionType The kind of mouse event
* @param button Which button is involved (no button = 0, left button = 1, middle (wheel) button = 2,
* right button = 3, scroll wheel up = 4, scroll wheel down = 5)
* @param position Where in the terminal is the mouse cursor located
*/
public MouseAction(MouseActionType actionType, int button, TerminalPosition position) {
super(KeyType.MOUSE_EVENT, false, false);
this.actionType = actionType;
this.button = button;
this.position = position;
}
/**
* Returns the mouse action type so the caller can determine which kind of action was performed.
* @return The action type of the mouse event
*/
public MouseActionType getActionType() {
return actionType;
}
/**
* Which button was involved in this event. Please note that for CLICK_RELEASE events, there is no button
* information available (getButton() will return 0). The standard xterm mapping is:
* <ul>
* <li>No button = 0</li>
* <li>Left button = 1</li>
* <li>Middle (wheel) button = 2</li>
* <li>Right button = 3</li>
* <li>Wheel up = 4</li>
* <li>Wheel down = 5</li>
* </ul>
* @return The button which is clicked down when this event was generated
*/
public int getButton() {
return button;
}
/**
* The location of the mouse cursor when this event was generated.
* @return Location of the mouse cursor
*/
public TerminalPosition getPosition() {
return position;
}
public boolean isMouseDown() {
return actionType == MouseActionType.CLICK_DOWN;
}
public boolean isMouseDrag() {
return actionType == MouseActionType.DRAG;
}
public boolean isMouseMove() {
return actionType == MouseActionType.MOVE;
}
public boolean isMouseUp() {
return actionType == MouseActionType.CLICK_RELEASE;
}
@Override
public String toString() {
return "MouseAction{actionType=" + actionType + ", button=" + button + ", position=" + position + '}';
}
}
| mabe02/lanterna | src/main/java/com/googlecode/lanterna/input/MouseAction.java |
179,968 | /*
* Logisim-evolution - digital logic design tool and simulator
* Copyright by the Logisim-evolution developers
*
* https://github.com/logisim-evolution/
*
* This is free software released under GNU GPLv3 license
*/
/* This file is adopted from the MIPS.jar library by
* Martin Dybdal <dybber@dybber.dk> and
* Anders Boesen Lindbo Larsen <abll@diku.dk>.
* It was developed for the computer architecture class at the Department of
* Computer Science, University of Copenhagen.
*/
package com.cburch.logisim.std.gates;
import static com.cburch.logisim.std.Strings.S;
import com.cburch.logisim.data.AbstractAttributeSet;
import com.cburch.logisim.data.Attribute;
import com.cburch.logisim.data.AttributeSet;
import com.cburch.logisim.data.Attributes;
import com.cburch.logisim.data.BitWidth;
import com.cburch.logisim.data.Bounds;
import com.cburch.logisim.data.Direction;
import com.cburch.logisim.data.Value;
import com.cburch.logisim.fpga.designrulecheck.CorrectLabel;
import com.cburch.logisim.gui.main.Frame;
import com.cburch.logisim.instance.Instance;
import com.cburch.logisim.instance.InstanceFactory;
import com.cburch.logisim.instance.InstancePainter;
import com.cburch.logisim.instance.InstanceState;
import com.cburch.logisim.instance.Port;
import com.cburch.logisim.instance.StdAttr;
import com.cburch.logisim.proj.Project;
import com.cburch.logisim.tools.MenuExtender;
import com.cburch.logisim.util.GraphicsUtil;
import java.awt.Color;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
class Pla extends InstanceFactory {
/**
* Unique identifier of the tool, used as reference in project files. Do NOT change as it will
* prevent project files from loading.
*
* <p>Identifier value must MUST be unique string among all tools.
*/
public static final String _ID = "PLA";
static final int IN_PORT = 0;
static final int OUT_PORT = 1;
static final Attribute<BitWidth> ATTR_IN_WIDTH =
Attributes.forBitWidth("in_width", S.getter("plaBitWidthIn"));
static final Attribute<BitWidth> ATTR_OUT_WIDTH =
Attributes.forBitWidth("out_width", S.getter("plaBitWidthOut"));
static final Attribute<PlaTable> ATTR_TABLE = new TruthTableAttribute();
public static final InstanceFactory FACTORY = new Pla();
private static final Color BACKGROUND_COLOR = new Color(230, 230, 230);
private static final List<Attribute<?>> ATTRIBUTES =
Arrays.asList(
StdAttr.FACING,
ATTR_IN_WIDTH,
ATTR_OUT_WIDTH,
ATTR_TABLE,
StdAttr.LABEL,
StdAttr.LABEL_LOC,
StdAttr.LABEL_FONT);
private static class TruthTableAttribute extends Attribute<PlaTable> {
public TruthTableAttribute() {
super("table", S.getter("plaProgram"));
}
@Override
public java.awt.Component getCellEditor(Window source, PlaTable tt) {
PlaTable.EditorDialog dialog = new PlaTable.EditorDialog((Frame) source);
dialog.setValue(tt);
return dialog;
}
@Override
public String toDisplayString(PlaTable value) {
return S.get("plaClickToEdit");
}
@Override
public String toStandardString(PlaTable tt) {
return tt.toStandardString();
}
@Override
public PlaTable parse(String str) {
return PlaTable.parse(str);
}
}
private static class PLAAttributes extends AbstractAttributeSet {
private String label = "";
private Direction facing = Direction.EAST;
private Font labelFont = StdAttr.DEFAULT_LABEL_FONT;
private Object labelLoc = Direction.NORTH;
private BitWidth widthIn = BitWidth.create(2);
private BitWidth widthOut = BitWidth.create(2);
private PlaTable tt = new PlaTable(2, 2, "PLA");
@Override
protected void copyInto(AbstractAttributeSet destObj) {
PLAAttributes dest = (PLAAttributes) destObj;
dest.label = this.label;
dest.facing = this.facing;
dest.labelFont = this.labelFont;
dest.labelLoc = this.labelLoc;
dest.widthIn = this.widthIn;
dest.widthOut = this.widthOut;
dest.tt = new PlaTable(this.tt);
dest.tt.setLabel(dest.label);
}
@Override
public List<Attribute<?>> getAttributes() {
return ATTRIBUTES;
}
@Override
@SuppressWarnings("unchecked")
public <V> V getValue(Attribute<V> attr) {
if (attr == StdAttr.FACING) return (V) facing;
if (attr == ATTR_IN_WIDTH) return (V) widthIn;
if (attr == ATTR_OUT_WIDTH) return (V) widthOut;
if (attr == ATTR_TABLE) return (V) tt;
if (attr == StdAttr.LABEL) return (V) label;
if (attr == StdAttr.LABEL_LOC) return (V) labelLoc;
if (attr == StdAttr.LABEL_FONT) return (V) labelFont;
return null;
}
@Override
public <V> void setValue(Attribute<V> attr, V value) {
if (attr == StdAttr.LABEL_LOC) {
labelLoc = value;
} else if (attr == StdAttr.FACING) {
facing = (Direction) value;
} else if (attr == ATTR_IN_WIDTH) {
widthIn = (BitWidth) value;
tt.setInSize(widthIn.getWidth());
} else if (attr == ATTR_OUT_WIDTH) {
widthOut = (BitWidth) value;
tt.setOutSize(widthOut.getWidth());
} else if (attr == ATTR_TABLE) {
tt = (PlaTable) value;
tt.setLabel(label);
if (tt.inSize() != widthIn.getWidth())
setValue(ATTR_IN_WIDTH, BitWidth.create(tt.inSize()));
if (tt.outSize() != widthOut.getWidth())
setValue(ATTR_OUT_WIDTH, BitWidth.create(tt.outSize()));
} else if (attr == StdAttr.LABEL) {
label = (String) value;
tt.setLabel(label);
} else if (attr == StdAttr.LABEL_FONT) {
labelFont = (Font) value;
}
fireAttributeValueChanged(attr, value, null);
}
}
public Pla() {
super(_ID, S.getter("PLA"), new PlaHdlGeneratorFactory(), true);
setIconName("pla.gif");
setFacingAttribute(StdAttr.FACING);
}
@Override
public AttributeSet createAttributeSet() {
return new PLAAttributes();
}
@Override
protected void configureNewInstance(Instance instance) {
super.configureNewInstance(instance);
final var attributes = (PLAAttributes) instance.getAttributeSet();
attributes.tt = new PlaTable(instance.getAttributeValue(ATTR_TABLE));
attributes.tt.setLabel(instance.getAttributeValue(StdAttr.LABEL));
instance.addAttributeListener();
updatePorts(instance);
instance.computeLabelTextField(Instance.AVOID_LEFT | Instance.AVOID_RIGHT);
}
private void updatePorts(Instance instance) {
final var dir = instance.getAttributeValue(StdAttr.FACING);
int dx = 0, dy = 0;
if (dir == Direction.WEST) dx = -50;
else if (dir == Direction.NORTH) dy = -50;
else if (dir == Direction.SOUTH) dy = 50;
else dx = 50;
Port[] ps = {
new Port(0, 0, Port.INPUT, ATTR_IN_WIDTH), new Port(dx, dy, Port.OUTPUT, ATTR_OUT_WIDTH)
};
ps[IN_PORT].setToolTip(S.getter("input"));
ps[OUT_PORT].setToolTip(S.getter("output"));
instance.setPorts(ps);
}
@Override
protected void instanceAttributeChanged(Instance instance, Attribute<?> attr) {
if (attr == StdAttr.FACING
|| attr == ATTR_IN_WIDTH
|| attr == ATTR_OUT_WIDTH
|| attr == StdAttr.LABEL
|| attr == StdAttr.LABEL_LOC) {
instance.recomputeBounds();
instance.computeLabelTextField(Instance.AVOID_LEFT | Instance.AVOID_RIGHT);
updatePorts(instance);
} else if (attr == ATTR_TABLE) {
instance.fireInvalidated();
}
}
@Override
public void propagate(InstanceState state) {
final var outWidth = state.getAttributeValue(ATTR_OUT_WIDTH);
final var tt = state.getAttributeValue(ATTR_TABLE);
final var input = state.getPortValue(IN_PORT);
long val = tt.valueFor(input.toLongValue());
state.setPort(1, Value.createKnown(outWidth, val), 1);
}
@Override
public Bounds getOffsetBounds(AttributeSet attrs) {
final var dir = attrs.getValue(StdAttr.FACING);
return Bounds.create(0, -25, 50, 50).rotate(Direction.EAST, dir, 0, 0);
}
@Override
public void paintGhost(InstancePainter painter) {
paintInstance(painter, true);
}
@Override
public void paintInstance(InstancePainter painter) {
paintInstance(painter, false);
}
void paintInstance(InstancePainter painter, boolean ghost) {
final var g = painter.getGraphics();
final var bds = painter.getBounds();
int x = bds.getX();
int y = bds.getY();
int w = bds.getWidth();
int h = bds.getHeight();
if (!ghost && painter.shouldDrawColor()) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(x, y, w, h);
}
if (!ghost) g.setColor(Color.BLACK);
GraphicsUtil.switchToWidth(g, 2);
g.drawRect(x, y, bds.getWidth(), bds.getHeight());
g.setFont(painter.getAttributeValue(StdAttr.LABEL_FONT));
GraphicsUtil.drawCenteredText(g, "PLA", x + w / 2, y + h / 3);
if (!ghost) {
if (painter.getShowState()) {
PlaTable tt = painter.getAttributeValue(ATTR_TABLE);
Value input = painter.getPortValue(IN_PORT);
String comment = tt.commentFor(input.toLongValue());
int jj = comment.indexOf("#"); // don't display secondary comment
if (jj >= 0) comment = comment.substring(0, jj).trim();
GraphicsUtil.drawCenteredText(g, comment, x + w / 2, y + 2 * h / 3);
}
painter.drawLabel();
painter.drawPorts();
}
}
@Override
public String getHDLName(AttributeSet attrs) {
final var name = CorrectLabel.getCorrectLabel(attrs.getValue(StdAttr.LABEL));
if (name.length() == 0) return "PLA";
else return "PLA_" + name;
}
@Override
protected Object getInstanceFeature(Instance instance, Object key) {
if (key == MenuExtender.class) {
return new PLAMenu(this, instance);
}
return super.getInstanceFeature(instance, key);
}
static class PLAMenu implements ActionListener, MenuExtender {
private final Instance instance;
private Frame frame;
private JMenuItem edit;
PLAMenu(Pla factory, Instance instance) {
this.instance = instance;
}
@Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == edit) doEdit();
}
@Override
public void configureMenu(JPopupMenu menu, Project proj) {
this.frame = proj.getFrame();
edit = new JMenuItem(S.get("plaEditMenuItem"));
edit.setEnabled(true);
edit.addActionListener(this);
menu.addSeparator();
menu.add(edit);
}
private void doEdit() {
PlaTable tt = instance.getAttributeValue(ATTR_TABLE);
PlaTable.EditorDialog dialog = new PlaTable.EditorDialog(frame);
dialog.setValue(tt);
dialog.setVisible(true);
dialog.toFront();
}
}
}
| logisim-evolution/logisim-evolution | src/main/java/com/cburch/logisim/std/gates/Pla.java |
179,971 | /*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by IAIK of Graz University of
* Technology."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Graz University of Technology" and "IAIK of Graz University of
* Technology" must not be used to endorse or promote products derived from
* this software without prior written permission.
*
* 5. Products derived from this software may not be called
* "IAIK PKCS Wrapper", nor may "IAIK" appear in their name, without prior
* written permission of Graz University of Technology.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package sun.security.pkcs11.wrapper;
import java.security.ProviderException;
/**
* class CK_MECHANISM_INFO provides information about a particular mechanism.
* <p>
* <B>PKCS#11 structure:</B>
* <PRE>
* typedef struct CK_MECHANISM_INFO {
* CK_ULONG ulMinKeySize;
* CK_ULONG ulMaxKeySize;
* CK_FLAGS flags;
* } CK_MECHANISM_INFO;
* </PRE>
*
* @author Karl Scheibelhofer <Karl.Scheibelhofer@iaik.at>
* @author Martin Schlaeffer <schlaeff@sbox.tugraz.at>
*/
public class CK_MECHANISM_INFO {
/**
* <B>PKCS#11:</B>
* <PRE>
* CK_ULONG ulMinKeySize;
* </PRE>
*/
public long ulMinKeySize;
// the integer version of ulMinKeySize for doing the actual range
// check in SunPKCS11 provider, defaults to 0
public final int iMinKeySize;
/**
* <B>PKCS#11:</B>
* <PRE>
* CK_ULONG ulMaxKeySize;
* </PRE>
*/
public long ulMaxKeySize;
// the integer version of ulMaxKeySize for doing the actual range
// check in SunPKCS11 provider, defaults to Integer.MAX_VALUE
public final int iMaxKeySize;
/**
* <B>PKCS#11:</B>
* <PRE>
* CK_FLAGS flags;
* </PRE>
*/
public long flags;
public CK_MECHANISM_INFO(long minKeySize, long maxKeySize,
long flags) {
this.ulMinKeySize = minKeySize;
this.ulMaxKeySize = maxKeySize;
this.iMinKeySize = ((minKeySize < Integer.MAX_VALUE && minKeySize > 0)?
(int)minKeySize : 0);
this.iMaxKeySize = ((maxKeySize < Integer.MAX_VALUE && maxKeySize > 0)?
(int)maxKeySize : Integer.MAX_VALUE);
this.flags = flags;
}
/**
* Returns the string representation of CK_MECHANISM_INFO.
*
* @return the string representation of CK_MECHANISM_INFO
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(Constants.INDENT);
buffer.append("ulMinKeySize: ");
buffer.append(String.valueOf(ulMinKeySize));
buffer.append(Constants.NEWLINE);
buffer.append(Constants.INDENT);
buffer.append("ulMaxKeySize: ");
buffer.append(String.valueOf(ulMaxKeySize));
buffer.append(Constants.NEWLINE);
buffer.append(Constants.INDENT);
buffer.append("flags: ");
buffer.append(String.valueOf(flags));
buffer.append(" = ");
buffer.append(Functions.mechanismInfoFlagsToString(flags));
//buffer.append(Constants.NEWLINE);
return buffer.toString() ;
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/security/pkcs11/wrapper/CK_MECHANISM_INFO.java |
179,972 | /**
*
* Sicherman Dice in Choco3.
*
* From http://en.wikipedia.org/wiki/Sicherman_dice
* ""
* Sicherman dice are the only pair of 6-sided dice which are not normal dice,
* bear only positive integers, and have the same probability distribution for
* the sum as normal dice.
*
* The faces on the dice are numbered 1, 2, 2, 3, 3, 4 and 1, 3, 4, 5, 6, 8.
* ""
*
* I read about this problem in a book/column by Martin Gardner long
* time ago, and got inspired to model it now by the WolframBlog post
* "Sicherman Dice": http://blog.wolfram.com/2010/07/13/sicherman-dice/
*
* This model gets the two different ways, first the standard way and
* then the Sicherman dice:
*
* x1 = [1, 2, 3, 4, 5, 6]
* x2 = [1, 2, 3, 4, 5, 6]
* ----------
* x1 = [1, 2, 2, 3, 3, 4]
* x2 = [1, 3, 4, 5, 6, 8]
*
*
* Extra: If we also allow 0 (zero) as a valid value then the
* following two solutions are also valid:
*
* x1 = [0, 1, 1, 2, 2, 3]
* x2 = [2, 4, 5, 6, 7, 9]
* ----------
* x1 = [0, 1, 2, 3, 4, 5]
* x2 = [2, 3, 4, 5, 6, 7]
*
* These two extra cases are mentioned here:
* http://mathworld.wolfram.com/SichermanDice.html
*
*
* Choco3 model by Hakan Kjellerstrand (hakank@gmail.com)
* http://www.hakank.org/choco3/
*
*/
import org.kohsuke.args4j.Option;
import org.slf4j.LoggerFactory;
import samples.AbstractProblem;
import solver.ResolutionPolicy;
import solver.Solver;
import solver.constraints.Constraint;
import solver.constraints.IntConstraintFactory;
import solver.constraints.IntConstraintFactory.*;
import solver.search.strategy.IntStrategyFactory;
import solver.constraints.LogicalConstraintFactory;
import solver.variables.IntVar;
import solver.variables.BoolVar;
import solver.variables.VariableFactory;
import solver.search.strategy.strategy.AbstractStrategy;
import solver.search.strategy.selectors.variables.*;
import util.ESat;
import util.tools.ArrayUtils;
public class SichermanDice extends AbstractProblem {
@Option(name = "-lowest_value", usage = "Lowest value of a die (default 1).", required = false)
int lowest_value = 1;
int n = 6;
int m = 10;
int[] standard_dist = {1,2,3,4,5,6,5,4,3,2,1};
IntVar[] x1;
IntVar[] x2;
@Override
public void buildModel() {
x1 = VariableFactory.enumeratedArray("x1", n, lowest_value, m, solver);
x2 = VariableFactory.enumeratedArray("x2", n, lowest_value, m, solver);
int len = standard_dist.length;
for(int k = 0; k < len; k++) {
BoolVar[][] b = VariableFactory.boolMatrix("b", n, n, solver);
IntVar k2 = VariableFactory.fixed(-(k+2), solver);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
IntVar ss = VariableFactory.enumerated("ss", -2*m, 2*m, solver);
solver.post(IntConstraintFactory.sum(new IntVar[] {x1[i],x2[j],k2}, ss));
solver.post(LogicalConstraintFactory.ifThenElse(b[i][j],
IntConstraintFactory.arithm(ss,"=",0),
IntConstraintFactory.arithm(ss,"!=",0)));
}
}
solver.post(IntConstraintFactory.sum(ArrayUtils.flatten(b), VariableFactory.fixed(standard_dist[k], solver)));
}
// symmetry breaking
for(int i = 0; i < n-1; i++) {
solver.post(IntConstraintFactory.arithm(x1[i], "<=", x1[i+1])); // increasing x1
solver.post(IntConstraintFactory.arithm(x2[i], "<=", x2[i+1])); // increasing x2
solver.post(IntConstraintFactory.arithm(x1[i], "<=", x2[i])); // x1 <= x2
}
}
@Override
public void createSolver() {
solver = new Solver("SichermanDice");
}
@Override
public void configureSearch() {
solver.set(IntStrategyFactory.maxReg_InDomainMin(ArrayUtils.append(x1,x2)));
}
@Override
public void solve() {
solver.findSolution();
}
@Override
public void prettyOut() {
if (solver.isFeasible() == ESat.TRUE) {
int num_solutions = 0;
do {
System.out.print("x1: ");
for(int i = 0; i < n; i++) {
System.out.print(x1[i].getValue() + " ");
}
System.out.print("\nx2: ");
for(int i = 0; i < n; i++) {
System.out.print(x2[i].getValue() + " ");
}
System.out.println();
num_solutions++;
} while (solver.nextSolution() == Boolean.TRUE);
System.out.println("It was " + num_solutions + " solutions.");
} else {
System.out.println("No solution.");
}
}
public static void main(String args[]) {
new SichermanDice().execute(args);
}
}
| hakank/hakank | choco3/SichermanDice.java |
179,977 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jctools.queues;
import static org.jctools.util.UnsafeAccess.UNSAFE;
import static org.jctools.util.UnsafeAccess.fieldOffset;
import static org.jctools.util.UnsafeRefArrayAccess.*;
abstract class MpscArrayQueueL1Pad<E> extends ConcurrentCircularArrayQueue<E>
{
byte b000,b001,b002,b003,b004,b005,b006,b007;// 8b
byte b010,b011,b012,b013,b014,b015,b016,b017;// 16b
byte b020,b021,b022,b023,b024,b025,b026,b027;// 24b
byte b030,b031,b032,b033,b034,b035,b036,b037;// 32b
byte b040,b041,b042,b043,b044,b045,b046,b047;// 40b
byte b050,b051,b052,b053,b054,b055,b056,b057;// 48b
byte b060,b061,b062,b063,b064,b065,b066,b067;// 56b
byte b070,b071,b072,b073,b074,b075,b076,b077;// 64b
byte b100,b101,b102,b103,b104,b105,b106,b107;// 72b
byte b110,b111,b112,b113,b114,b115,b116,b117;// 80b
byte b120,b121,b122,b123,b124,b125,b126,b127;// 88b
byte b130,b131,b132,b133,b134,b135,b136,b137;// 96b
byte b140,b141,b142,b143,b144,b145,b146,b147;//104b
byte b150,b151,b152,b153,b154,b155,b156,b157;//112b
byte b160,b161,b162,b163,b164,b165,b166,b167;//120b
// byte b170,b171,b172,b173,b174,b175,b176,b177;//128b
MpscArrayQueueL1Pad(int capacity)
{
super(capacity);
}
}
//$gen:ordered-fields
abstract class MpscArrayQueueProducerIndexField<E> extends MpscArrayQueueL1Pad<E>
{
private final static long P_INDEX_OFFSET = fieldOffset(MpscArrayQueueProducerIndexField.class, "producerIndex");
private volatile long producerIndex;
MpscArrayQueueProducerIndexField(int capacity)
{
super(capacity);
}
@Override
public final long lvProducerIndex()
{
return producerIndex;
}
final boolean casProducerIndex(long expect, long newValue)
{
return UNSAFE.compareAndSwapLong(this, P_INDEX_OFFSET, expect, newValue);
}
}
abstract class MpscArrayQueueMidPad<E> extends MpscArrayQueueProducerIndexField<E>
{
byte b000,b001,b002,b003,b004,b005,b006,b007;// 8b
byte b010,b011,b012,b013,b014,b015,b016,b017;// 16b
byte b020,b021,b022,b023,b024,b025,b026,b027;// 24b
byte b030,b031,b032,b033,b034,b035,b036,b037;// 32b
byte b040,b041,b042,b043,b044,b045,b046,b047;// 40b
byte b050,b051,b052,b053,b054,b055,b056,b057;// 48b
byte b060,b061,b062,b063,b064,b065,b066,b067;// 56b
byte b070,b071,b072,b073,b074,b075,b076,b077;// 64b
byte b100,b101,b102,b103,b104,b105,b106,b107;// 72b
byte b110,b111,b112,b113,b114,b115,b116,b117;// 80b
byte b120,b121,b122,b123,b124,b125,b126,b127;// 88b
byte b130,b131,b132,b133,b134,b135,b136,b137;// 96b
byte b140,b141,b142,b143,b144,b145,b146,b147;//104b
byte b150,b151,b152,b153,b154,b155,b156,b157;//112b
byte b160,b161,b162,b163,b164,b165,b166,b167;//120b
byte b170,b171,b172,b173,b174,b175,b176,b177;//128b
MpscArrayQueueMidPad(int capacity)
{
super(capacity);
}
}
//$gen:ordered-fields
abstract class MpscArrayQueueProducerLimitField<E> extends MpscArrayQueueMidPad<E>
{
private final static long P_LIMIT_OFFSET = fieldOffset(MpscArrayQueueProducerLimitField.class, "producerLimit");
// First unavailable index the producer may claim up to before rereading the consumer index
private volatile long producerLimit;
MpscArrayQueueProducerLimitField(int capacity)
{
super(capacity);
this.producerLimit = capacity;
}
final long lvProducerLimit()
{
return producerLimit;
}
final void soProducerLimit(long newValue)
{
UNSAFE.putOrderedLong(this, P_LIMIT_OFFSET, newValue);
}
}
abstract class MpscArrayQueueL2Pad<E> extends MpscArrayQueueProducerLimitField<E>
{
byte b000,b001,b002,b003,b004,b005,b006,b007;// 8b
byte b010,b011,b012,b013,b014,b015,b016,b017;// 16b
byte b020,b021,b022,b023,b024,b025,b026,b027;// 24b
byte b030,b031,b032,b033,b034,b035,b036,b037;// 32b
byte b040,b041,b042,b043,b044,b045,b046,b047;// 40b
byte b050,b051,b052,b053,b054,b055,b056,b057;// 48b
byte b060,b061,b062,b063,b064,b065,b066,b067;// 56b
byte b070,b071,b072,b073,b074,b075,b076,b077;// 64b
byte b100,b101,b102,b103,b104,b105,b106,b107;// 72b
byte b110,b111,b112,b113,b114,b115,b116,b117;// 80b
byte b120,b121,b122,b123,b124,b125,b126,b127;// 88b
byte b130,b131,b132,b133,b134,b135,b136,b137;// 96b
byte b140,b141,b142,b143,b144,b145,b146,b147;//104b
byte b150,b151,b152,b153,b154,b155,b156,b157;//112b
byte b160,b161,b162,b163,b164,b165,b166,b167;//120b
// byte b170,b171,b172,b173,b174,b175,b176,b177;//128b
MpscArrayQueueL2Pad(int capacity)
{
super(capacity);
}
}
//$gen:ordered-fields
abstract class MpscArrayQueueConsumerIndexField<E> extends MpscArrayQueueL2Pad<E>
{
private final static long C_INDEX_OFFSET = fieldOffset(MpscArrayQueueConsumerIndexField.class, "consumerIndex");
private volatile long consumerIndex;
MpscArrayQueueConsumerIndexField(int capacity)
{
super(capacity);
}
@Override
public final long lvConsumerIndex()
{
return consumerIndex;
}
final long lpConsumerIndex()
{
return UNSAFE.getLong(this, C_INDEX_OFFSET);
}
final void soConsumerIndex(long newValue)
{
UNSAFE.putOrderedLong(this, C_INDEX_OFFSET, newValue);
}
}
abstract class MpscArrayQueueL3Pad<E> extends MpscArrayQueueConsumerIndexField<E>
{
byte b000,b001,b002,b003,b004,b005,b006,b007;// 8b
byte b010,b011,b012,b013,b014,b015,b016,b017;// 16b
byte b020,b021,b022,b023,b024,b025,b026,b027;// 24b
byte b030,b031,b032,b033,b034,b035,b036,b037;// 32b
byte b040,b041,b042,b043,b044,b045,b046,b047;// 40b
byte b050,b051,b052,b053,b054,b055,b056,b057;// 48b
byte b060,b061,b062,b063,b064,b065,b066,b067;// 56b
byte b070,b071,b072,b073,b074,b075,b076,b077;// 64b
byte b100,b101,b102,b103,b104,b105,b106,b107;// 72b
byte b110,b111,b112,b113,b114,b115,b116,b117;// 80b
byte b120,b121,b122,b123,b124,b125,b126,b127;// 88b
byte b130,b131,b132,b133,b134,b135,b136,b137;// 96b
byte b140,b141,b142,b143,b144,b145,b146,b147;//104b
byte b150,b151,b152,b153,b154,b155,b156,b157;//112b
byte b160,b161,b162,b163,b164,b165,b166,b167;//120b
byte b170,b171,b172,b173,b174,b175,b176,b177;//128b
MpscArrayQueueL3Pad(int capacity)
{
super(capacity);
}
}
/**
* A Multi-Producer-Single-Consumer queue based on a {@link org.jctools.queues.ConcurrentCircularArrayQueue}. This
* implies that any thread may call the offer method, but only a single thread may call poll/peek for correctness to
* maintained. <br>
* This implementation follows patterns documented on the package level for False Sharing protection.<br>
* This implementation is using the <a href="http://sourceforge.net/projects/mc-fastflow/">Fast Flow</a>
* method for polling from the queue (with minor change to correctly publish the index) and an extension of
* the Leslie Lamport concurrent queue algorithm (originated by Martin Thompson) on the producer side.
*/
public class MpscArrayQueue<E> extends MpscArrayQueueL3Pad<E>
{
public MpscArrayQueue(final int capacity)
{
super(capacity);
}
/**
* {@link #offer}} if {@link #size()} is less than threshold.
*
* @param e the object to offer onto the queue, not null
* @param threshold the maximum allowable size
* @return true if the offer is successful, false if queue size exceeds threshold
* @since 1.0.1
*/
public boolean offerIfBelowThreshold(final E e, int threshold)
{
if (null == e)
{
throw new NullPointerException();
}
final long mask = this.mask;
final long capacity = mask + 1;
long producerLimit = lvProducerLimit();
long pIndex;
do
{
pIndex = lvProducerIndex();
long available = producerLimit - pIndex;
long size = capacity - available;
if (size >= threshold)
{
final long cIndex = lvConsumerIndex();
size = pIndex - cIndex;
if (size >= threshold)
{
return false; // the size exceeds threshold
}
else
{
// update producer limit to the next index that we must recheck the consumer index
producerLimit = cIndex + capacity;
// this is racy, but the race is benign
soProducerLimit(producerLimit);
}
}
}
while (!casProducerIndex(pIndex, pIndex + 1));
/*
* NOTE: the new producer index value is made visible BEFORE the element in the array. If we relied on
* the index visibility to poll() we would need to handle the case where the element is not visible.
*/
// Won CAS, move on to storing
final long offset = calcCircularRefElementOffset(pIndex, mask);
soRefElement(buffer, offset, e);
return true; // AWESOME :)
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Lock free offer using a single CAS. As class name suggests access is permitted to many threads
* concurrently.
*
* @see java.util.Queue#offer
* @see org.jctools.queues.MessagePassingQueue#offer
*/
@Override
public boolean offer(final E e)
{
if (null == e)
{
throw new NullPointerException();
}
// use a cached view on consumer index (potentially updated in loop)
final long mask = this.mask;
long producerLimit = lvProducerLimit();
long pIndex;
do
{
pIndex = lvProducerIndex();
if (pIndex >= producerLimit)
{
final long cIndex = lvConsumerIndex();
producerLimit = cIndex + mask + 1;
if (pIndex >= producerLimit)
{
return false; // FULL :(
}
else
{
// update producer limit to the next index that we must recheck the consumer index
// this is racy, but the race is benign
soProducerLimit(producerLimit);
}
}
}
while (!casProducerIndex(pIndex, pIndex + 1));
/*
* NOTE: the new producer index value is made visible BEFORE the element in the array. If we relied on
* the index visibility to poll() we would need to handle the case where the element is not visible.
*/
// Won CAS, move on to storing
final long offset = calcCircularRefElementOffset(pIndex, mask);
soRefElement(buffer, offset, e);
return true; // AWESOME :)
}
/**
* A wait free alternative to offer which fails on CAS failure.
*
* @param e new element, not null
* @return 1 if next element cannot be filled, -1 if CAS failed, 0 if successful
*/
public final int failFastOffer(final E e)
{
if (null == e)
{
throw new NullPointerException();
}
final long mask = this.mask;
final long capacity = mask + 1;
final long pIndex = lvProducerIndex();
long producerLimit = lvProducerLimit();
if (pIndex >= producerLimit)
{
final long cIndex = lvConsumerIndex();
producerLimit = cIndex + capacity;
if (pIndex >= producerLimit)
{
return 1; // FULL :(
}
else
{
// update producer limit to the next index that we must recheck the consumer index
soProducerLimit(producerLimit);
}
}
// look Ma, no loop!
if (!casProducerIndex(pIndex, pIndex + 1))
{
return -1; // CAS FAIL :(
}
// Won CAS, move on to storing
final long offset = calcCircularRefElementOffset(pIndex, mask);
soRefElement(buffer, offset, e);
return 0; // AWESOME :)
}
/**
* {@inheritDoc}
* <p>
* IMPLEMENTATION NOTES:<br>
* Lock free poll using ordered loads/stores. As class name suggests access is limited to a single thread.
*
* @see java.util.Queue#poll
* @see org.jctools.queues.MessagePassingQueue#poll
*/
@Override
public E poll()
{
final long cIndex = lpConsumerIndex();
final long offset = calcCircularRefElementOffset(cIndex, mask);
// Copy field to avoid re-reading after volatile load
final E[] buffer = this.buffer;
// If we can't see the next available element we can't poll
E e = lvRefElement(buffer, offset);
if (null == e)
{
/*
* NOTE: Queue may not actually be empty in the case of a producer (P1) being interrupted after
* winning the CAS on offer but before storing the element in the queue. Other producers may go on
* to fill up the queue after this element.
*/
if (cIndex != lvProducerIndex())
{
do
{
e = lvRefElement(buffer, offset);
}
while (e == null);
}
else
{
return null;
}
}
spRefElement(buffer, offset, null);
soConsumerIndex(cIndex + 1);
return e;
}
/**
* {@inheritDoc}
* <p>
* IMPLEMENTATION NOTES:<br>
* Lock free peek using ordered loads. As class name suggests access is limited to a single thread.
*
* @see java.util.Queue#poll
* @see org.jctools.queues.MessagePassingQueue#poll
*/
@Override
public E peek()
{
// Copy field to avoid re-reading after volatile load
final E[] buffer = this.buffer;
final long cIndex = lpConsumerIndex();
final long offset = calcCircularRefElementOffset(cIndex, mask);
E e = lvRefElement(buffer, offset);
if (null == e)
{
/*
* NOTE: Queue may not actually be empty in the case of a producer (P1) being interrupted after
* winning the CAS on offer but before storing the element in the queue. Other producers may go on
* to fill up the queue after this element.
*/
if (cIndex != lvProducerIndex())
{
do
{
e = lvRefElement(buffer, offset);
}
while (e == null);
}
else
{
return null;
}
}
return e;
}
@Override
public boolean relaxedOffer(E e)
{
return offer(e);
}
@Override
public E relaxedPoll()
{
final E[] buffer = this.buffer;
final long cIndex = lpConsumerIndex();
final long offset = calcCircularRefElementOffset(cIndex, mask);
// If we can't see the next available element we can't poll
E e = lvRefElement(buffer, offset);
if (null == e)
{
return null;
}
spRefElement(buffer, offset, null);
soConsumerIndex(cIndex + 1);
return e;
}
@Override
public E relaxedPeek()
{
final E[] buffer = this.buffer;
final long mask = this.mask;
final long cIndex = lpConsumerIndex();
return lvRefElement(buffer, calcCircularRefElementOffset(cIndex, mask));
}
@Override
public int drain(final Consumer<E> c, final int limit)
{
if (null == c)
throw new IllegalArgumentException("c is null");
if (limit < 0)
throw new IllegalArgumentException("limit is negative: " + limit);
if (limit == 0)
return 0;
final E[] buffer = this.buffer;
final long mask = this.mask;
final long cIndex = lpConsumerIndex();
for (int i = 0; i < limit; i++)
{
final long index = cIndex + i;
final long offset = calcCircularRefElementOffset(index, mask);
final E e = lvRefElement(buffer, offset);
if (null == e)
{
return i;
}
spRefElement(buffer, offset, null);
soConsumerIndex(index + 1); // ordered store -> atomic and ordered for size()
c.accept(e);
}
return limit;
}
@Override
public int fill(Supplier<E> s, int limit)
{
if (null == s)
throw new IllegalArgumentException("supplier is null");
if (limit < 0)
throw new IllegalArgumentException("limit is negative:" + limit);
if (limit == 0)
return 0;
final long mask = this.mask;
final long capacity = mask + 1;
long producerLimit = lvProducerLimit();
long pIndex;
int actualLimit;
do
{
pIndex = lvProducerIndex();
long available = producerLimit - pIndex;
if (available <= 0)
{
final long cIndex = lvConsumerIndex();
producerLimit = cIndex + capacity;
available = producerLimit - pIndex;
if (available <= 0)
{
return 0; // FULL :(
}
else
{
// update producer limit to the next index that we must recheck the consumer index
soProducerLimit(producerLimit);
}
}
actualLimit = Math.min((int) available, limit);
}
while (!casProducerIndex(pIndex, pIndex + actualLimit));
// right, now we claimed a few slots and can fill them with goodness
final E[] buffer = this.buffer;
for (int i = 0; i < actualLimit; i++)
{
// Won CAS, move on to storing
final long offset = calcCircularRefElementOffset(pIndex + i, mask);
soRefElement(buffer, offset, s.get());
}
return actualLimit;
}
@Override
public int drain(Consumer<E> c)
{
return drain(c, capacity());
}
@Override
public int fill(Supplier<E> s)
{
return MessagePassingQueueUtil.fillBounded(this, s);
}
@Override
public void drain(Consumer<E> c, WaitStrategy w, ExitCondition exit)
{
MessagePassingQueueUtil.drain(this, c, w, exit);
}
@Override
public void fill(Supplier<E> s, WaitStrategy wait, ExitCondition exit)
{
MessagePassingQueueUtil.fill(this, s, wait, exit);
}
}
| JCTools/JCTools | jctools-core/src/main/java/org/jctools/queues/MpscArrayQueue.java |
179,978 | // SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-FileCopyrightText: Copyright (C) 2008-2009 The Android Open Source Project
// SPDX-License-Identifier: BSD-3-Clause AND Apache-2.0
package com.kitware.JavaVTK;
import android.content.Context;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;
/**
* A simple GLSurfaceView sub-class that demonstrate how to perform
* OpenGL ES 2.0 rendering into a GL Surface. Note the following important
* details:
*
* - The class must use a custom context factory to enable 2.0 rendering.
* See ContextFactory class definition below.
*
* - The class must use a custom EGLConfigChooser to be able to select
* an EGLConfig that supports 2.0. This is done by providing a config
* specification to eglChooseConfig() that has the attribute
* EGL10.ELG_RENDERABLE_TYPE containing the EGL_OPENGL_ES2_BIT flag
* set. See ConfigChooser class definition below.
*
* - The class must select the surface's format, then choose an EGLConfig
* that matches it exactly (with regards to red/green/blue/alpha channels
* bit depths). Failure to do so would result in an EGL_BAD_MATCH error.
*/
class JavaVTKView extends GLSurfaceView
{
private static String TAG = "JavaVTKView";
private Renderer myRenderer;
public JavaVTKView(Context context)
{
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
setEGLContextFactory(new ContextFactory());
setEGLConfigChooser(new ConfigChooser(8, 8, 8, 0, 8, 0));
/* Set the renderer responsible for frame rendering */
this.myRenderer = new Renderer();
this.setRenderer(myRenderer);
this.setRenderMode(RENDERMODE_WHEN_DIRTY);
}
private static class ContextFactory implements GLSurfaceView.EGLContextFactory
{
private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig)
{
Log.w(TAG, "creating OpenGL ES 2.0 context");
checkEglError("Before eglCreateContext", egl);
int[] attrib_list = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE };
EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
checkEglError("After eglCreateContext", egl);
return context;
}
public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context)
{
egl.eglDestroyContext(display, context);
}
}
private static void checkEglError(String prompt, EGL10 egl)
{
int error;
while ((error = egl.eglGetError()) != EGL10.EGL_SUCCESS)
{
Log.e(TAG, String.format("%s: EGL error: 0x%x", prompt, error));
}
}
private static class ConfigChooser implements GLSurfaceView.EGLConfigChooser
{
public ConfigChooser(int r, int g, int b, int a, int depth, int stencil)
{
mRedSize = r;
mGreenSize = g;
mBlueSize = b;
mAlphaSize = a;
mDepthSize = depth;
mStencilSize = stencil;
}
/* This EGL config specification is used to specify 2.0 rendering.
* We use a minimum size of 4 bits for red/green/blue, but will
* perform actual matching in chooseConfig() below.
*/
private static int EGL_OPENGL_ES2_BIT = 4;
private static int[] s_configAttribs2 =
{
EGL10.EGL_RED_SIZE, 4,
EGL10.EGL_GREEN_SIZE, 4,
EGL10.EGL_BLUE_SIZE, 4,
EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL10.EGL_NONE
};
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display)
{
// Get the number of minimally matching EGL configurations
int[] num_config = new int[1];
egl.eglChooseConfig(display, s_configAttribs2, null, 0, num_config);
int numConfigs = num_config[0];
if (numConfigs <= 0)
{
throw new IllegalArgumentException("No configs match configSpec");
}
// Allocate then read the array of minimally matching EGL configs
EGLConfig[] configs = new EGLConfig[numConfigs];
egl.eglChooseConfig(display, s_configAttribs2, configs, numConfigs, num_config);
// Now return the "best" one
return chooseConfig(egl, display, configs);
}
public EGLConfig chooseConfig(EGL10 egl, EGLDisplay display,
EGLConfig[] configs)
{
for(EGLConfig config : configs)
{
int d = findConfigAttrib(egl, display, config,
EGL10.EGL_DEPTH_SIZE, 0);
int s = findConfigAttrib(egl, display, config,
EGL10.EGL_STENCIL_SIZE, 0);
// We need at least mDepthSize and mStencilSize bits
if (d < mDepthSize || s < mStencilSize)
continue;
// We want an *exact* match for red/green/blue/alpha
int r = findConfigAttrib(egl, display, config,
EGL10.EGL_RED_SIZE, 0);
int g = findConfigAttrib(egl, display, config,
EGL10.EGL_GREEN_SIZE, 0);
int b = findConfigAttrib(egl, display, config,
EGL10.EGL_BLUE_SIZE, 0);
int a = findConfigAttrib(egl, display, config,
EGL10.EGL_ALPHA_SIZE, 0);
if (r == mRedSize && g == mGreenSize && b == mBlueSize && a == mAlphaSize)
return config;
}
return null;
}
private int findConfigAttrib(EGL10 egl, EGLDisplay display,
EGLConfig config, int attribute, int defaultValue)
{
if (egl.eglGetConfigAttrib(display, config, attribute, mValue))
{
return mValue[0];
}
return defaultValue;
}
// Subclasses can adjust these values:
protected int mRedSize;
protected int mGreenSize;
protected int mBlueSize;
protected int mAlphaSize;
protected int mDepthSize;
protected int mStencilSize;
private int[] mValue = new int[1];
}
private static class Renderer implements GLSurfaceView.Renderer
{
private long vtkContext;
public void onDrawFrame(GL10 gl)
{
JavaVTKLib.render(vtkContext);
}
// forward events to VTK for it to handle
public void onKeyEvent(boolean down, KeyEvent ke)
{
JavaVTKLib.onKeyEvent(vtkContext, down, ke.getKeyCode(),
ke.getMetaState(),
ke.getRepeatCount());
}
// forward events to VTK for it to handle
public void onMotionEvent(final MotionEvent me)
{
try {
int numPtrs = me.getPointerCount();
float [] xPos = new float[numPtrs];
float [] yPos = new float[numPtrs];
int [] ids = new int[numPtrs];
for (int i = 0; i < numPtrs; ++i)
{
ids[i] = me.getPointerId(i);
xPos[i] = me.getX(i);
yPos[i] = me.getY(i);
}
int actionIndex = me.getActionIndex();
int actionMasked = me.getActionMasked();
int actionId = me.getPointerId(actionIndex);
if (actionMasked != 2)
{
Log.e(TAG, "Got action " + actionMasked + " on index " + actionIndex + " has id " + actionId);
}
JavaVTKLib.onMotionEvent(vtkContext,
actionMasked,
actionId,
numPtrs, xPos, yPos, ids,
me.getMetaState());
} catch (IllegalArgumentException e) {
Log.e(TAG, "Bogus motion event");
}
}
public void onSurfaceChanged(GL10 gl, int width, int height)
{
vtkContext = JavaVTKLib.init(width, height);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
// Do nothing.
}
}
// forward events to rendering thread for it to handle
public boolean onKeyUp(int keyCode, KeyEvent event)
{
final KeyEvent keyEvent = event;
queueEvent(new Runnable()
{
public void run()
{
myRenderer.onKeyEvent(false, keyEvent);
}
});
return true;
}
// forward events to rendering thread for it to handle
public boolean onKeyDown(int keyCode, KeyEvent event)
{
final KeyEvent keyEvent = event;
queueEvent(new Runnable()
{
public void run()
{
myRenderer.onKeyEvent(true, keyEvent);
}
});
return true;
}
// forward events to rendering thread for it to handle
public boolean onTouchEvent(MotionEvent event)
{
final MotionEvent motionEvent = event;
queueEvent(new Runnable()
{
public void run()
{
myRenderer.onMotionEvent(motionEvent);
}
});
return true;
}
}
| Kitware/VTK | Examples/Android/JavaVTK/src/com/kitware/JavaVTK/JavaVTKView.java |
179,980 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written by Doug Lea and Martin Buchholz with assistance from members of
* JCP JSR-166 Expert Group and released to the public domain, as explained
* at http://creativecommons.org/publicdomain/zero/1.0/
*/
package io.undertow.util;
import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException;
import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Queue;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* A modified version of ConcurrentLinkedDeque which includes direct
* removal. Like the original, it relies on Unsafe for better performance.
*
* More specifically, an unbounded concurrent {@linkplain Deque deque} based on linked nodes.
* Concurrent insertion, removal, and access operations execute safely
* across multiple threads.
* A {@code ConcurrentLinkedDeque} is an appropriate choice when
* many threads will share access to a common collection.
* Like most other concurrent collection implementations, this class
* does not permit the use of {@code null} elements.
*
* <p>Iterators and spliterators are
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>Beware that, unlike in most collections, the {@code size} method
* is <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these deques, determining the current number
* of elements requires a traversal of the elements, and so may report
* inaccurate results if this collection is modified during traversal.
*
* <p>Bulk operations that add, remove, or examine multiple elements,
* such as {@link #addAll}, {@link #removeIf} or {@link #forEach},
* are <em>not</em> guaranteed to be performed atomically.
* For example, a {@code forEach} traversal concurrent with an {@code
* addAll} operation might observe only some of the added elements.
*
* <p>This class and its iterator implement all of the <em>optional</em>
* methods of the {@link Deque} and {@link Iterator} interfaces.
*
* <p>Memory consistency effects: As with other concurrent collections,
* actions in a thread prior to placing an object into a
* {@code ConcurrentLinkedDeque}
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
* actions subsequent to the access or removal of that element from
* the {@code ConcurrentLinkedDeque} in another thread.
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* Based on revision 1.88 of ConcurrentLinkedDeque
* (see http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java?revision=1.88&view=markup)
* This is the version used in JDK 9 b156.
*
* @since 1.7
* @author Doug Lea
* @author Martin Buchholz
* @author Jason T. Grene
* @param <E> the type of elements held in this deque
*/
public class FastConcurrentDirectDeque<E>
extends ConcurrentDirectDeque<E> implements Deque<E>, Serializable {
/*
* This is an implementation of a concurrent lock-free deque
* supporting interior removes but not interior insertions, as
* required to support the entire Deque interface.
*
* We extend the techniques developed for ConcurrentLinkedQueue and
* LinkedTransferQueue (see the internal docs for those classes).
* Understanding the ConcurrentLinkedQueue implementation is a
* prerequisite for understanding the implementation of this class.
*
* The data structure is a symmetrical doubly-linked "GC-robust"
* linked list of nodes. We minimize the number of volatile writes
* using two techniques: advancing multiple hops with a single CAS
* and mixing volatile and non-volatile writes of the same memory
* locations.
*
* A node contains the expected E ("item") and links to predecessor
* ("prev") and successor ("next") nodes:
*
* class Node<E> { volatile Node<E> prev, next; volatile E item; }
*
* A node p is considered "live" if it contains a non-null item
* (p.item != null). When an item is CASed to null, the item is
* atomically logically deleted from the collection.
*
* At any time, there is precisely one "first" node with a null
* prev reference that terminates any chain of prev references
* starting at a live node. Similarly there is precisely one
* "last" node terminating any chain of next references starting at
* a live node. The "first" and "last" nodes may or may not be live.
* The "first" and "last" nodes are always mutually reachable.
*
* A new element is added atomically by CASing the null prev or
* next reference in the first or last node to a fresh node
* containing the element. The element's node atomically becomes
* "live" at that point.
*
* A node is considered "active" if it is a live node, or the
* first or last node. Active nodes cannot be unlinked.
*
* A "self-link" is a next or prev reference that is the same node:
* p.prev == p or p.next == p
* Self-links are used in the node unlinking process. Active nodes
* never have self-links.
*
* A node p is active if and only if:
*
* p.item != null ||
* (p.prev == null && p.next != p) ||
* (p.next == null && p.prev != p)
*
* The deque object has two node references, "head" and "tail".
* The head and tail are only approximations to the first and last
* nodes of the deque. The first node can always be found by
* following prev pointers from head; likewise for tail. However,
* it is permissible for head and tail to be referring to deleted
* nodes that have been unlinked and so may not be reachable from
* any live node.
*
* There are 3 stages of node deletion;
* "logical deletion", "unlinking", and "gc-unlinking".
*
* 1. "logical deletion" by CASing item to null atomically removes
* the element from the collection, and makes the containing node
* eligible for unlinking.
*
* 2. "unlinking" makes a deleted node unreachable from active
* nodes, and thus eventually reclaimable by GC. Unlinked nodes
* may remain reachable indefinitely from an iterator.
*
* Physical node unlinking is merely an optimization (albeit a
* critical one), and so can be performed at our convenience. At
* any time, the set of live nodes maintained by prev and next
* links are identical, that is, the live nodes found via next
* links from the first node is equal to the elements found via
* prev links from the last node. However, this is not true for
* nodes that have already been logically deleted - such nodes may
* be reachable in one direction only.
*
* 3. "gc-unlinking" takes unlinking further by making active
* nodes unreachable from deleted nodes, making it easier for the
* GC to reclaim future deleted nodes. This step makes the data
* structure "gc-robust", as first described in detail by Boehm
* (http://portal.acm.org/citation.cfm?doid=503272.503282).
*
* GC-unlinked nodes may remain reachable indefinitely from an
* iterator, but unlike unlinked nodes, are never reachable from
* head or tail.
*
* Making the data structure GC-robust will eliminate the risk of
* unbounded memory retention with conservative GCs and is likely
* to improve performance with generational GCs.
*
* When a node is dequeued at either end, e.g. via poll(), we would
* like to break any references from the node to active nodes. We
* develop further the use of self-links that was very effective in
* other concurrent collection classes. The idea is to replace
* prev and next pointers with special values that are interpreted
* to mean off-the-list-at-one-end. These are approximations, but
* good enough to preserve the properties we want in our
* traversals, e.g. we guarantee that a traversal will never visit
* the same element twice, but we don't guarantee whether a
* traversal that runs out of elements will be able to see more
* elements later after enqueues at that end. Doing gc-unlinking
* safely is particularly tricky, since any node can be in use
* indefinitely (for example by an iterator). We must ensure that
* the nodes pointed at by head/tail never get gc-unlinked, since
* head/tail are needed to get "back on track" by other nodes that
* are gc-unlinked. gc-unlinking accounts for much of the
* implementation complexity.
*
* Since neither unlinking nor gc-unlinking are necessary for
* correctness, there are many implementation choices regarding
* frequency (eagerness) of these operations. Since volatile
* reads are likely to be much cheaper than CASes, saving CASes by
* unlinking multiple adjacent nodes at a time may be a win.
* gc-unlinking can be performed rarely and still be effective,
* since it is most important that long chains of deleted nodes
* are occasionally broken.
*
* The actual representation we use is that p.next == p means to
* goto the first node (which in turn is reached by following prev
* pointers from head), and p.next == null && p.prev == p means
* that the iteration is at an end and that p is a (static final)
* dummy node, NEXT_TERMINATOR, and not the last active node.
* Finishing the iteration when encountering such a TERMINATOR is
* good enough for read-only traversals, so such traversals can use
* p.next == null as the termination condition. When we need to
* find the last (active) node, for enqueueing a new node, we need
* to check whether we have reached a TERMINATOR node; if so,
* restart traversal from tail.
*
* The implementation is completely directionally symmetrical,
* except that most public methods that iterate through the list
* follow next pointers ("forward" direction).
*
* We believe (without full proof) that all single-element deque
* operations (e.g., addFirst, peekLast, pollLast) are linearizable
* (see Herlihy and Shavit's book). However, some combinations of
* operations are known not to be linearizable. In particular,
* when an addFirst(A) is racing with pollFirst() removing B, it is
* possible for an observer iterating over the elements to observe
* A B C and subsequently observe A C, even though no interior
* removes are ever performed. Nevertheless, iterators behave
* reasonably, providing the "weakly consistent" guarantees.
*
* Empirically, microbenchmarks suggest that this class adds about
* 40% overhead relative to ConcurrentLinkedQueue, which feels as
* good as we can hope for.
*/
private static final long serialVersionUID = 876323262645176354L;
/**
* A node from which the first node on list (that is, the unique node p
* with p.prev == null && p.next != p) can be reached in O(1) time.
* Invariants:
* - the first node is always O(1) reachable from head via prev links
* - all live nodes are reachable from the first node via succ()
* - head != null
* - (tmp = head).next != tmp || tmp != head
* - head is never gc-unlinked (but may be unlinked)
* Non-invariants:
* - head.item may or may not be null
* - head may not be reachable from the first or last node, or from tail
*/
private transient volatile Node<E> head;
/**
* A node from which the last node on list (that is, the unique node p
* with p.next == null && p.prev != p) can be reached in O(1) time.
* Invariants:
* - the last node is always O(1) reachable from tail via next links
* - all live nodes are reachable from the last node via pred()
* - tail != null
* - tail is never gc-unlinked (but may be unlinked)
* Non-invariants:
* - tail.item may or may not be null
* - tail may not be reachable from the first or last node, or from head
*/
private transient volatile Node<E> tail;
private static final Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR;
@SuppressWarnings("unchecked")
Node<E> prevTerminator() {
return (Node<E>) PREV_TERMINATOR;
}
@SuppressWarnings("unchecked")
Node<E> nextTerminator() {
return (Node<E>) NEXT_TERMINATOR;
}
static final class Node<E> {
volatile Node<E> prev;
volatile E item;
volatile Node<E> next;
}
/**
* Returns a new node holding item. Uses relaxed write because item
* can only be seen after piggy-backing publication via CAS.
*/
static <E> Node<E> newNode(E item) {
Node<E> node = new Node<>();
ITEM.set(node, item);
return node;
}
/**
* Links e as first element.
*/
private Node linkFirst(E e) {
final Node<E> newNode = newNode(Objects.requireNonNull(e));
restartFromHead:
for (;;)
for (Node<E> h = head, p = h, q;;) {
if ((q = p.prev) != null &&
(q = (p = q).prev) != null)
// Check for head updates every other hop.
// If p == q, we are sure to follow head instead.
p = (h != (h = head)) ? h : q;
else if (p.next == p) // PREV_TERMINATOR
continue restartFromHead;
else {
// p is first node
NEXT.set(newNode, p); // CAS piggyback
if (PREV.compareAndSet(p, null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this deque,
// and for newNode to become "live".
if (p != h) // hop two nodes at a time; failure is OK
HEAD.weakCompareAndSet(this, h, newNode);
return newNode;
}
// Lost CAS race to another thread; re-read prev
}
}
}
/**
* Links e as last element.
*/
private Node linkLast(E e) {
final Node<E> newNode = newNode(Objects.requireNonNull(e));
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p.prev == p) // NEXT_TERMINATOR
continue restartFromTail;
else {
// p is last node
PREV.set(newNode, p); // CAS piggyback
if (NEXT.compareAndSet(p, null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this deque,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time; failure is OK
TAIL.weakCompareAndSet(this, t, newNode);
return newNode;
}
// Lost CAS race to another thread; re-read next
}
}
}
private static final int HOPS = 2;
/**
* Unlinks non-null node x.
*/
void unlink(Node<E> x) {
// assert x != null;
// assert x.item == null;
// assert x != PREV_TERMINATOR;
// assert x != NEXT_TERMINATOR;
final Node<E> prev = x.prev;
final Node<E> next = x.next;
if (prev == null) {
unlinkFirst(x, next);
} else if (next == null) {
unlinkLast(x, prev);
} else {
// Unlink interior node.
//
// This is the common case, since a series of polls at the
// same end will be "interior" removes, except perhaps for
// the first one, since end nodes cannot be unlinked.
//
// At any time, all active nodes are mutually reachable by
// following a sequence of either next or prev pointers.
//
// Our strategy is to find the unique active predecessor
// and successor of x. Try to fix up their links so that
// they point to each other, leaving x unreachable from
// active nodes. If successful, and if x has no live
// predecessor/successor, we additionally try to gc-unlink,
// leaving active nodes unreachable from x, by rechecking
// that the status of predecessor and successor are
// unchanged and ensuring that x is not reachable from
// tail/head, before setting x's prev/next links to their
// logical approximate replacements, self/TERMINATOR.
Node<E> activePred, activeSucc;
boolean isFirst, isLast;
int hops = 1;
// Find active predecessor
for (Node<E> p = prev; ; ++hops) {
if (p.item != null) {
activePred = p;
isFirst = false;
break;
}
Node<E> q = p.prev;
if (q == null) {
if (p.next == p)
return;
activePred = p;
isFirst = true;
break;
}
else if (p == q)
return;
else
p = q;
}
// Find active successor
for (Node<E> p = next; ; ++hops) {
if (p.item != null) {
activeSucc = p;
isLast = false;
break;
}
Node<E> q = p.next;
if (q == null) {
if (p.prev == p)
return;
activeSucc = p;
isLast = true;
break;
}
else if (p == q)
return;
else
p = q;
}
// TODO: better HOP heuristics
if (hops < HOPS
// always squeeze out interior deleted nodes
&& (isFirst | isLast))
return;
// Squeeze out deleted nodes between activePred and
// activeSucc, including x.
skipDeletedSuccessors(activePred);
skipDeletedPredecessors(activeSucc);
// Try to gc-unlink, if possible
if ((isFirst | isLast) &&
// Recheck expected state of predecessor and successor
(activePred.next == activeSucc) &&
(activeSucc.prev == activePred) &&
(isFirst ? activePred.prev == null : activePred.item != null) &&
(isLast ? activeSucc.next == null : activeSucc.item != null)) {
updateHead(); // Ensure x is not reachable from head
updateTail(); // Ensure x is not reachable from tail
// Finally, actually gc-unlink
PREV.setRelease(x, isFirst ? prevTerminator() : x);
NEXT.setRelease(x, isLast ? nextTerminator() : x);
}
}
}
/**
* Unlinks non-null first node.
*/
private void unlinkFirst(Node<E> first, Node<E> next) {
// assert first != null;
// assert next != null;
// assert first.item == null;
for (Node<E> o = null, p = next, q;;) {
if (p.item != null || (q = p.next) == null) {
if (o != null && p.prev != p &&
NEXT.compareAndSet(first, next, p)) {
skipDeletedPredecessors(p);
if (first.prev == null &&
(p.next == null || p.item != null) &&
p.prev == first) {
updateHead(); // Ensure o is not reachable from head
updateTail(); // Ensure o is not reachable from tail
// Finally, actually gc-unlink
NEXT.setRelease(o, o);
PREV.setRelease(o, prevTerminator());
}
}
return;
}
else if (p == q)
return;
else {
o = p;
p = q;
}
}
}
/**
* Unlinks non-null last node.
*/
private void unlinkLast(Node<E> last, Node<E> prev) {
// assert last != null;
// assert prev != null;
// assert last.item == null;
for (Node<E> o = null, p = prev, q;;) {
if (p.item != null || (q = p.prev) == null) {
if (o != null && p.next != p &&
PREV.compareAndSet(last, prev, p)) {
skipDeletedSuccessors(p);
if (last.next == null &&
(p.prev == null || p.item != null) &&
p.next == last) {
updateHead(); // Ensure o is not reachable from head
updateTail(); // Ensure o is not reachable from tail
// Finally, actually gc-unlink
PREV.setRelease(o, o);
NEXT.setRelease(o, nextTerminator());
}
}
return;
}
else if (p == q)
return;
else {
o = p;
p = q;
}
}
}
/**
* Guarantees that any node which was unlinked before a call to
* this method will be unreachable from head after it returns.
* Does not guarantee to eliminate slack, only that head will
* point to a node that was active while this method was running.
*/
private void updateHead() {
// Either head already points to an active node, or we keep
// trying to cas it to the first node until it does.
Node<E> h, p, q;
restartFromHead:
while ((h = head).item == null && (p = h.prev) != null) {
for (;;) {
if ((q = p.prev) == null ||
(q = (p = q).prev) == null) {
// It is possible that p is PREV_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
if (HEAD.compareAndSet(this, h, p))
return;
else
continue restartFromHead;
}
else if (h != head)
continue restartFromHead;
else
p = q;
}
}
}
/**
* Guarantees that any node which was unlinked before a call to
* this method will be unreachable from tail after it returns.
* Does not guarantee to eliminate slack, only that tail will
* point to a node that was active while this method was running.
*/
private void updateTail() {
// Either tail already points to an active node, or we keep
// trying to cas it to the last node until it does.
Node<E> t, p, q;
restartFromTail:
while ((t = tail).item == null && (p = t.next) != null) {
for (;;) {
if ((q = p.next) == null ||
(q = (p = q).next) == null) {
// It is possible that p is NEXT_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
if (TAIL.compareAndSet(this, t, p))
return;
else
continue restartFromTail;
}
else if (t != tail)
continue restartFromTail;
else
p = q;
}
}
}
private void skipDeletedPredecessors(Node<E> x) {
whileActive:
do {
Node<E> prev = x.prev;
// assert prev != null;
// assert x != NEXT_TERMINATOR;
// assert x != PREV_TERMINATOR;
Node<E> p = prev;
findActive:
for (;;) {
if (p.item != null)
break findActive;
Node<E> q = p.prev;
if (q == null) {
if (p.next == p)
continue whileActive;
break findActive;
}
else if (p == q)
continue whileActive;
else
p = q;
}
// found active CAS target
if (prev == p || PREV.compareAndSet(x, prev, p))
return;
} while (x.item != null || x.next == null);
}
private void skipDeletedSuccessors(Node<E> x) {
whileActive:
do {
Node<E> next = x.next;
// assert next != null;
// assert x != NEXT_TERMINATOR;
// assert x != PREV_TERMINATOR;
Node<E> p = next;
findActive:
for (;;) {
if (p.item != null)
break findActive;
Node<E> q = p.next;
if (q == null) {
if (p.prev == p)
continue whileActive;
break findActive;
}
else if (p == q)
continue whileActive;
else
p = q;
}
// found active CAS target
if (next == p || NEXT.compareAndSet(x, next, p))
return;
} while (x.item != null || x.prev == null);
}
/**
* Returns the successor of p, or the first node if p.next has been
* linked to self, which will only be true if traversing with a
* stale pointer that is now off the list.
*/
final Node<E> succ(Node<E> p) {
// TODO: should we skip deleted nodes here?
if (p == (p = p.next))
p = first();
return p;
}
/**
* Returns the predecessor of p, or the last node if p.prev has been
* linked to self, which will only be true if traversing with a
* stale pointer that is now off the list.
*/
final Node<E> pred(Node<E> p) {
Node<E> q = p.prev;
return (p == q) ? last() : q;
}
/**
* Returns the first node, the unique node p for which:
* p.prev == null && p.next != p
* The returned node may or may not be logically deleted.
* Guarantees that head is set to the returned node.
*/
Node<E> first() {
restartFromHead:
for (;;)
for (Node<E> h = head, p = h, q;;) {
if ((q = p.prev) != null &&
(q = (p = q).prev) != null)
// Check for head updates every other hop.
// If p == q, we are sure to follow head instead.
p = (h != (h = head)) ? h : q;
else if (p == h
// It is possible that p is PREV_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
|| HEAD.compareAndSet(this, h, p))
return p;
else
continue restartFromHead;
}
}
/**
* Returns the last node, the unique node p for which:
* p.next == null && p.prev != p
* The returned node may or may not be logically deleted.
* Guarantees that tail is set to the returned node.
*/
Node<E> last() {
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p == t
// It is possible that p is NEXT_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
|| TAIL.compareAndSet(this, t, p))
return p;
else
continue restartFromTail;
}
}
// Minor convenience utilities
/**
* Returns element unless it is null, in which case throws
* NoSuchElementException.
*
* @param v the element
* @return the element
*/
private E screenNullResult(E v) {
if (v == null)
throw new NoSuchElementException();
return v;
}
/**
* Constructs an empty deque.
*/
public FastConcurrentDirectDeque() {
head = tail = new Node<>();
}
/**
* Constructs a deque initially containing the elements of
* the given collection, added in traversal order of the
* collection's iterator.
*
* @param c the collection of elements to initially contain
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public FastConcurrentDirectDeque(Collection<? extends E> c) {
// Copy c into a private chain of Nodes
Node<E> h = null, t = null;
for (E e : c) {
Node<E> newNode = newNode(Objects.requireNonNull(e));
if (h == null)
h = t = newNode;
else {
NEXT.set(t, newNode);
PREV.set(newNode, t);
t = newNode;
}
}
initHeadTail(h, t);
}
/**
* Initializes head and tail, ensuring invariants hold.
*/
private void initHeadTail(Node<E> h, Node<E> t) {
if (h == t) {
if (h == null)
h = t = new Node<>();
else {
// Avoid edge case of a single Node with non-null item.
Node<E> newNode = new Node<>();
NEXT.set(t, newNode);
PREV.set(newNode, t);
t = newNode;
}
}
head = h;
tail = t;
}
/**
* Inserts the specified element at the front of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException}.
*
* @throws NullPointerException if the specified element is null
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Inserts the specified element at the end of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException}.
*
* <p>This method is equivalent to {@link #add}.
*
* @throws NullPointerException if the specified element is null
*/
public void addLast(E e) {
linkLast(e);
}
/**
* Inserts the specified element at the front of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @throws NullPointerException if the specified element is null
*/
public boolean offerFirst(E e) {
linkFirst(e);
return true;
}
public Object offerFirstAndReturnToken(E e) {
return linkFirst(e);
}
public Object offerLastAndReturnToken(E e) {
return linkLast(e);
}
public void removeToken(Object token) {
if (!(token instanceof Node)) {
throw new IllegalArgumentException();
}
Node node = (Node) (token);
while (! ITEM.compareAndSet(node, node.item, null)) {}
unlink(node);
}
/**
* Inserts the specified element at the end of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* <p>This method is equivalent to {@link #add}.
*
* @return {@code true} (as specified by {@link Deque#offerLast})
* @throws NullPointerException if the specified element is null
*/
public boolean offerLast(E e) {
linkLast(e);
return true;
}
public E peekFirst() {
for (Node<E> p = first(); p != null; p = succ(p)) {
final E item;
if ((item = p.item) != null)
return item;
}
return null;
}
public E peekLast() {
for (Node<E> p = last(); p != null; p = pred(p)) {
final E item;
if ((item = p.item) != null)
return item;
}
return null;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getFirst() {
return screenNullResult(peekFirst());
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E getLast() {
return screenNullResult(peekLast());
}
public E pollFirst() {
for (Node<E> p = first(); p != null; p = succ(p)) {
final E item;
if ((item = p.item) != null
&& ITEM.compareAndSet(p, item, null)) {
unlink(p);
return item;
}
}
return null;
}
public E pollLast() {
for (Node<E> p = last(); p != null; p = pred(p)) {
final E item;
if ((item = p.item) != null
&& ITEM.compareAndSet(p, item, null)) {
unlink(p);
return item;
}
}
return null;
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeFirst() {
return screenNullResult(pollFirst());
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E removeLast() {
return screenNullResult(pollLast());
}
// *** Queue and stack methods ***
/**
* Inserts the specified element at the tail of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* @return {@code true} (as specified by {@link Queue#offer})
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
return offerLast(e);
}
/**
* Inserts the specified element at the tail of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException} or return {@code false}.
*
* @return {@code true} (as specified by {@link Collection#add})
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
return offerLast(e);
}
public E poll() {
return pollFirst();
}
public E peek() {
return peekFirst();
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E remove() {
return removeFirst();
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E pop() {
return removeFirst();
}
/**
* @throws NoSuchElementException {@inheritDoc}
*/
public E element() {
return getFirst();
}
/**
* @throws NullPointerException {@inheritDoc}
*/
public void push(E e) {
addFirst( e );
}
/**
* Removes the first occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element {@code e} such that
* {@code o.equals(e)} (if such an element exists).
* Returns {@code true} if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean removeFirstOccurrence(Object o) {
Objects.requireNonNull(o);
for (Node<E> p = first(); p != null; p = succ(p)) {
final E item;
if ((item = p.item) != null
&& o.equals(item)
&& ITEM.compareAndSet(p, item, null)) {
unlink(p);
return true;
}
}
return false;
}
/**
* Removes the last occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the last element {@code e} such that
* {@code o.equals(e)} (if such an element exists).
* Returns {@code true} if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean removeLastOccurrence(Object o) {
Objects.requireNonNull(o);
for (Node<E> p = last(); p != null; p = pred(p)) {
final E item;
if ((item = p.item) != null
&& o.equals(item)
&& ITEM.compareAndSet(p, item, null)) {
unlink(p);
return true;
}
}
return false;
}
/**
* Returns {@code true} if this deque contains the specified element.
* More formally, returns {@code true} if and only if this deque contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o element whose presence in this deque is to be tested
* @return {@code true} if this deque contains the specified element
*/
public boolean contains(Object o) {
if (o != null) {
for (Node<E> p = first(); p != null; p = succ(p)) {
final E item;
if ((item = p.item) != null && o.equals(item))
return true;
}
}
return false;
}
/**
* Returns {@code true} if this collection contains no elements.
*
* @return {@code true} if this collection contains no elements
*/
public boolean isEmpty() {
return peekFirst() == null;
}
/**
* Returns the number of elements in this deque. If this deque
* contains more than {@code Integer.MAX_VALUE} elements, it
* returns {@code Integer.MAX_VALUE}.
*
* <p>Beware that, unlike in most collections, this method is
* <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these deques, determining the current
* number of elements requires traversing them all to count them.
* Additionally, it is possible for the size to change during
* execution of this method, in which case the returned result
* will be inaccurate. Thus, this method is typically not very
* useful in concurrent applications.
*
* @return the number of elements in this deque
*/
public int size() {
restartFromHead: for (;;) {
int count = 0;
for (Node<E> p = first(); p != null;) {
if (p.item != null)
if (++count == Integer.MAX_VALUE)
break; // @see Collection.size()
if (p == (p = p.next))
continue restartFromHead;
}
return count;
}
}
/**
* Removes the first occurrence of the specified element from this deque.
* If the deque does not contain the element, it is unchanged.
* More formally, removes the first element {@code e} such that
* {@code o.equals(e)} (if such an element exists).
* Returns {@code true} if this deque contained the specified element
* (or equivalently, if this deque changed as a result of the call).
*
* <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
/**
* Appends all of the elements in the specified collection to the end of
* this deque, in the order that they are returned by the specified
* collection's iterator. Attempts to {@code addAll} of a deque to
* itself result in {@code IllegalArgumentException}.
*
* @param c the elements to be inserted into this deque
* @return {@code true} if this deque changed as a result of the call
* @throws NullPointerException if the specified collection or any
* of its elements are null
* @throws IllegalArgumentException if the collection is this deque
*/
public boolean addAll(Collection<? extends E> c) {
if (c == this)
// As historically specified in AbstractQueue#addAll
throw new IllegalArgumentException();
// Copy c into a private chain of Nodes
Node<E> beginningOfTheEnd = null, last = null;
for (E e : c) {
Node<E> newNode = newNode(Objects.requireNonNull(e));
if (beginningOfTheEnd == null)
beginningOfTheEnd = last = newNode;
else {
NEXT.set(last, newNode);
PREV.set(newNode, last);
last = newNode;
}
}
if (beginningOfTheEnd == null)
return false;
// Atomically append the chain at the tail of this collection
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p.prev == p) // NEXT_TERMINATOR
continue restartFromTail;
else {
// p is last node
PREV.set(beginningOfTheEnd, p); // CAS piggyback
if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) {
// Successful CAS is the linearization point
// for all elements to be added to this deque.
if (!TAIL.weakCompareAndSet(this, t, last)) {
// Try a little harder to update tail,
// since we may be adding many elements.
t = tail;
if (last.next == null)
TAIL.weakCompareAndSet(this, t, last);
}
return true;
}
// Lost CAS race to another thread; re-read next
}
}
}
/**
* Removes all of the elements from this deque.
*/
public void clear() {
while (pollFirst() != null) {}
}
public String toString() {
String[] a = null;
restartFromHead: for (;;) {
int charLength = 0;
int size = 0;
for (Node<E> p = first(); p != null;) {
final E item;
if ((item = p.item) != null) {
if (a == null)
a = new String[4];
else if (size == a.length)
a = Arrays.copyOf(a, 2 * size);
String s = item.toString();
a[size++] = s;
charLength += s.length();
}
if (p == (p = p.next))
continue restartFromHead;
}
if (size == 0)
return "[]";
return toString(a, size, charLength);
}
}
private Object[] toArrayInternal(Object[] a) {
Object[] x = a;
restartFromHead: for (;;) {
int size = 0;
for (Node<E> p = first(); p != null;) {
final E item;
if ((item = p.item) != null) {
if (x == null)
x = new Object[4];
else if (size == x.length)
x = Arrays.copyOf(x, 2 * (size + 4));
x[size++] = item;
}
if (p == (p = p.next))
continue restartFromHead;
}
if (x == null)
return new Object[0];
else if (a != null && size <= a.length) {
if (a != x)
System.arraycopy(x, 0, a, 0, size);
if (size < a.length)
a[size] = null;
return a;
}
return (size == x.length) ? x : Arrays.copyOf(x, size);
}
}
/**
* Returns an array containing all of the elements in this deque, in
* proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this deque. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this deque
*/
public Object[] toArray() {
return toArrayInternal(null);
}
/**
* Returns an array containing all of the elements in this deque,
* in proper sequence (from first to last element); the runtime
* type of the returned array is that of the specified array. If
* the deque fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of
* the specified array and the size of this deque.
*
* <p>If this deque fits in the specified array with room to spare
* (i.e., the array has more elements than this deque), the element in
* the array immediately following the end of the deque is set to
* {@code null}.
*
* <p>Like the {@link #toArray()} method, this method acts as
* bridge between array-based and collection-based APIs. Further,
* this method allows precise control over the runtime type of the
* output array, and may, under certain circumstances, be used to
* save allocation costs.
*
* <p>Suppose {@code x} is a deque known to contain only strings.
* The following code can be used to dump the deque into a newly
* allocated array of {@code String}:
*
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the deque are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this deque
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this deque
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
return (T[]) toArrayInternal(checkNotNullParamWithNullPointerException("a", a));
}
/**
* Returns an iterator over the elements in this deque in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
*
* <p>The returned iterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* @return an iterator over the elements in this deque in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* Returns an iterator over the elements in this deque in reverse
* sequential order. The elements will be returned in order from
* last (tail) to first (head).
*
* <p>The returned iterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* @return an iterator over the elements in this deque in reverse order
*/
public Iterator<E> descendingIterator() {
return new DescendingItr();
}
// From Helpers 1.2
// http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/Helpers.java?revision=1.2
/**
* Like Arrays.toString(), but caller guarantees that size > 0,
* each element with index 0 <= i < size is a non-null String,
* and charLength is the sum of the lengths of the input Strings.
*/
private String toString(Object[] a, int size, int charLength) {
// assert a != null;
// assert size > 0;
// Copy each string into a perfectly sized char[]
// Length of [ , , , ] == 2 * size
final char[] chars = new char[charLength + 2 * size];
chars[0] = '[';
int j = 1;
for (int i = 0; i < size; i++) {
if (i > 0) {
chars[j++] = ',';
chars[j++] = ' ';
}
String s = (String) a[i];
int len = s.length();
s.getChars(0, len, chars, j);
j += len;
}
chars[j] = ']';
// assert j == chars.length - 1;
return new String(chars);
}
private abstract class AbstractItr implements Iterator<E> {
/**
* Next node to return item for.
*/
private Node<E> nextNode;
/**
* nextItem holds on to item fields because once we claim
* that an element exists in hasNext(), we must return it in
* the following next() call even if it was in the process of
* being removed when hasNext() was called.
*/
private E nextItem;
/**
* Node returned by most recent call to next. Needed by remove.
* Reset to null if this element is deleted by a call to remove.
*/
private Node<E> lastRet;
abstract Node<E> startNode();
abstract Node<E> nextNode(Node<E> p);
AbstractItr() {
advance();
}
/**
* Sets nextNode and nextItem to next valid node, or to null
* if no such.
*/
private void advance() {
lastRet = nextNode;
Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
for (;; p = nextNode(p)) {
if (p == null) {
// might be at active end or TERMINATOR node; both are OK
nextNode = null;
nextItem = null;
break;
}
final E item;
if ((item = p.item) != null) {
nextNode = p;
nextItem = item;
break;
}
}
}
public boolean hasNext() {
return nextItem != null;
}
public E next() {
E item = nextItem;
if (item == null) throw new NoSuchElementException();
advance();
return item;
}
public void remove() {
Node<E> l = lastRet;
if (l == null) throw new IllegalStateException();
l.item = null;
unlink(l);
lastRet = null;
}
}
/**
* Forward iterator
*/
private class Itr extends AbstractItr {
Itr() {} // prevent access constructor creation
Node<E> startNode() {
return first();
}
Node<E> nextNode(Node<E> p) {
return succ( p );
}
}
/**
* Descending iterator
*/
private class DescendingItr extends AbstractItr {
DescendingItr() {} // prevent access constructor creation
Node<E> startNode() {
return last();
}
Node<E> nextNode(Node<E> p) {
return pred( p );
}
}
/** A customized variant of Spliterators.IteratorSpliterator */
final class CLDSpliterator implements Spliterator<E> {
static final int MAX_BATCH = 1 << 25; // max batch array size;
Node<E> current; // current node; null until initialized
int batch; // batch size for splits
boolean exhausted; // true when no more nodes
public Spliterator<E> trySplit() {
Node<E> p, q;
if ((p = current()) == null || (q = p.next) == null)
return null;
int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH);
Object[] a = null;
do {
final E e;
if ((e = p.item) != null) {
if (a == null)
a = new Object[n];
a[i++] = e;
}
if (p == (p = q))
p = first();
} while (p != null && (q = p.next) != null && i < n);
setCurrent(p);
return (i == 0) ? null :
Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED |
Spliterator.NONNULL |
Spliterator.CONCURRENT));
}
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
Node<E> p;
if ((p = current()) != null) {
current = null;
exhausted = true;
do {
final E e;
if ((e = p.item) != null)
action.accept(e);
if (p == (p = p.next))
p = first();
} while (p != null);
}
}
public boolean tryAdvance(Consumer<? super E> action) {
Objects.requireNonNull(action);
Node<E> p;
if ((p = current()) != null) {
E e;
do {
e = p.item;
if (p == (p = p.next))
p = first();
} while (e == null && p != null);
setCurrent(p);
if (e != null) {
action.accept(e);
return true;
}
}
return false;
}
private void setCurrent(Node<E> p) {
if ((current = p) == null)
exhausted = true;
}
private Node<E> current() {
Node<E> p;
if ((p = current) == null && !exhausted)
setCurrent(p = first());
return p;
}
public long estimateSize() {
return Long.MAX_VALUE;
}
public int characteristics() {
return (Spliterator.ORDERED |
Spliterator.NONNULL |
Spliterator.CONCURRENT);
}
}
/**
* Returns a {@link Spliterator} over the elements in this deque.
*
* <p>The returned spliterator is
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>.
*
* <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT},
* {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}.
*
* @implNote
* The {@code Spliterator} implements {@code trySplit} to permit limited
* parallelism.
*
* @return a {@code Spliterator} over the elements in this deque
* @since 1.8
*/
public Spliterator<E> spliterator() {
return new CLDSpliterator();
}
/**
* Saves this deque to a stream (that is, serializes it).
*
* @param s the stream
* @throws java.io.IOException if an I/O error occurs
* @serialData All of the elements (each an {@code E}) in
* the proper order, followed by a null
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden stuff
s.defaultWriteObject();
// Write out all elements in the proper order.
for (Node<E> p = first(); p != null; p = succ(p)) {
final E item;
if ((item = p.item) != null)
s.writeObject(item);
}
// Use trailing null as sentinel
s.writeObject(null);
}
/**
* Reconstitutes this deque from a stream (that is, deserializes it).
* @param s the stream
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
* @throws java.io.IOException if an I/O error occurs
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in elements until trailing null sentinel found
Node<E> h = null, t = null;
for (Object item; (item = s.readObject()) != null; ) {
@SuppressWarnings("unchecked")
Node<E> newNode = newNode((E) item);
if (h == null)
h = t = newNode;
else {
NEXT.set(t, newNode);
PREV.set(newNode, t);
t = newNode;
}
}
initHeadTail(h, t);
}
/**
* @throws NullPointerException {@inheritDoc}
*/
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
return bulkRemove(filter);
}
/**
* @throws NullPointerException {@inheritDoc}
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return bulkRemove(e -> c.contains(e));
}
/**
* @throws NullPointerException {@inheritDoc}
*/
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return bulkRemove(e -> !c.contains(e));
}
/** Implementation of bulk remove methods. */
private boolean bulkRemove(Predicate<? super E> filter) {
boolean removed = false;
for (Node<E> p = first(), succ; p != null; p = succ) {
succ = succ(p);
final E item;
if ((item = p.item) != null
&& filter.test(item)
&& ITEM.compareAndSet(p, item, null)) {
unlink(p);
removed = true;
}
}
return removed;
}
/**
* @throws NullPointerException {@inheritDoc}
*/
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
E item;
for (Node<E> p = first(); p != null; p = succ(p))
if ((item = p.item) != null)
action.accept(item);
}
// VarHandle mechanics
private static final VarHandle HEAD;
private static final VarHandle TAIL;
private static final VarHandle PREV;
private static final VarHandle NEXT;
private static final VarHandle ITEM;
static {
PREV_TERMINATOR = new Node<>();
PREV_TERMINATOR.next = PREV_TERMINATOR;
NEXT_TERMINATOR = new Node<>();
NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
try {
MethodHandles.Lookup l = MethodHandles.lookup();
HEAD = l.findVarHandle(FastConcurrentDirectDeque.class, "head",
Node.class);
TAIL = l.findVarHandle(FastConcurrentDirectDeque.class, "tail",
Node.class);
PREV = l.findVarHandle(Node.class, "prev", Node.class);
NEXT = l.findVarHandle(Node.class, "next", Node.class);
ITEM = l.findVarHandle(Node.class, "item", Object.class);
} catch (ReflectiveOperationException e) {
throw new Error(e);
}
}
}
| undertow-io/undertow | core/src/main/java/io/undertow/util/FastConcurrentDirectDeque.java |
179,981 | /*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
*/
/* Copyright (c) 2002 Graz University of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by IAIK of Graz University of
* Technology."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Graz University of Technology" and "IAIK of Graz University of
* Technology" must not be used to endorse or promote products derived from
* this software without prior written permission.
*
* 5. Products derived from this software may not be called
* "IAIK PKCS Wrapper", nor may "IAIK" appear in their name, without prior
* written permission of Graz University of Technology.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package sun.security.pkcs11.wrapper;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
/**
* This is the default implementation of the PKCS11 interface. IT connects to
* the pkcs11wrapper.dll file, which is the native part of this library.
* The strange and awkward looking initialization was chosen to avoid calling
* loadLibrary from a static initialization block, because this would complicate
* the use in applets.
*
* @author Karl Scheibelhofer <Karl.Scheibelhofer@iaik.at>
* @author Martin Schlaeffer <schlaeff@sbox.tugraz.at>
* @invariants (pkcs11ModulePath_ <> null)
*/
public class PKCS11 {
/**
* The name of the native part of the wrapper; i.e. the filename without
* the extension (e.g. ".DLL" or ".so").
*/
private static final String PKCS11_WRAPPER = "j2pkcs11";
static {
// cannot use LoadLibraryAction because that would make the native
// library available to the bootclassloader, but we run in the
// extension classloader.
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
System.loadLibrary(PKCS11_WRAPPER);
return null;
}
});
initializeLibrary();
}
public static void loadNative() {
// dummy method that can be called to make sure the native
// portion has been loaded. actual loading happens in the
// static initializer, hence this method is empty.
}
/* *****************************************************************************
* Utility, Resource Clean up
******************************************************************************/
// always return 0L
public static native long freeMechanism(long hMechanism);
/**
* The PKCS#11 module to connect to. This is the PKCS#11 driver of the token;
* e.g. pk2priv.dll.
*/
private final String pkcs11ModulePath;
private long pNativeData;
/**
* This method does the initialization of the native library. It is called
* exactly once for this class.
*
* @preconditions
* @postconditions
*/
private static native void initializeLibrary();
// XXX
/**
* This method does the finalization of the native library. It is called
* exactly once for this class. The library uses this method for a clean-up
* of any resources.
*
* @preconditions
* @postconditions
*/
private static native void finalizeLibrary();
private static final Map<String,PKCS11> moduleMap =
new HashMap<String,PKCS11>();
/**
* Connects to the PKCS#11 driver given. The filename must contain the
* path, if the driver is not in the system's search path.
*
* @param pkcs11ModulePath the PKCS#11 library path
* @preconditions (pkcs11ModulePath <> null)
* @postconditions
*/
PKCS11(String pkcs11ModulePath, String functionListName)
throws IOException {
connect(pkcs11ModulePath, functionListName);
this.pkcs11ModulePath = pkcs11ModulePath;
}
public static synchronized PKCS11 getInstance(String pkcs11ModulePath,
String functionList, CK_C_INITIALIZE_ARGS pInitArgs,
boolean omitInitialize) throws IOException, PKCS11Exception {
// we may only call C_Initialize once per native .so/.dll
// so keep a cache using the (non-canonicalized!) path
PKCS11 pkcs11 = moduleMap.get(pkcs11ModulePath);
if (pkcs11 == null) {
if ((pInitArgs != null)
&& ((pInitArgs.flags & CKF_OS_LOCKING_OK) != 0)) {
pkcs11 = new PKCS11(pkcs11ModulePath, functionList);
} else {
pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList);
}
if (omitInitialize == false) {
try {
pkcs11.C_Initialize(pInitArgs);
} catch (PKCS11Exception e) {
// ignore already-initialized error code
// rethrow all other errors
if (e.getErrorCode() != CKR_CRYPTOKI_ALREADY_INITIALIZED) {
throw e;
}
}
}
moduleMap.put(pkcs11ModulePath, pkcs11);
}
return pkcs11;
}
/**
* Connects this object to the specified PKCS#11 library. This method is for
* internal use only.
* Declared private, because incorrect handling may result in errors in the
* native part.
*
* @param pkcs11ModulePath The PKCS#11 library path.
* @preconditions (pkcs11ModulePath <> null)
* @postconditions
*/
private native void connect(String pkcs11ModulePath, String functionListName)
throws IOException;
/**
* Disconnects the PKCS#11 library from this object. After calling this
* method, this object is no longer connected to a native PKCS#11 module
* and any subsequent calls to C_ methods will fail. This method is for
* internal use only.
* Declared private, because incorrect handling may result in errors in the
* native part.
*
* @preconditions
* @postconditions
*/
private native void disconnect();
// Implementation of PKCS11 methods delegated to native pkcs11wrapper library
/* *****************************************************************************
* General-purpose
******************************************************************************/
/**
* C_Initialize initializes the Cryptoki library.
* (General-purpose)
*
* @param pInitArgs if pInitArgs is not NULL it gets casted to
* CK_C_INITIALIZE_ARGS_PTR and dereferenced
* (PKCS#11 param: CK_VOID_PTR pInitArgs)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
native void C_Initialize(Object pInitArgs) throws PKCS11Exception;
/**
* C_Finalize indicates that an application is done with the
* Cryptoki library
* (General-purpose)
*
* @param pReserved is reserved. Should be NULL_PTR
* (PKCS#11 param: CK_VOID_PTR pReserved)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pReserved == null)
* @postconditions
*/
public native void C_Finalize(Object pReserved) throws PKCS11Exception;
/**
* C_GetInfo returns general information about Cryptoki.
* (General-purpose)
*
* @return the information.
* (PKCS#11 param: CK_INFO_PTR pInfo)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native CK_INFO C_GetInfo() throws PKCS11Exception;
/* *****************************************************************************
* Slot and token management
******************************************************************************/
/**
* C_GetSlotList obtains a list of slots in the system.
* (Slot and token management)
*
* @param tokenPresent if true only Slot IDs with a token are returned
* (PKCS#11 param: CK_BBOOL tokenPresent)
* @return a long array of slot IDs and number of Slot IDs
* (PKCS#11 param: CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native long[] C_GetSlotList(boolean tokenPresent)
throws PKCS11Exception;
/**
* C_GetSlotInfo obtains information about a particular slot in
* the system.
* (Slot and token management)
*
* @param slotID the ID of the slot
* (PKCS#11 param: CK_SLOT_ID slotID)
* @return the slot information
* (PKCS#11 param: CK_SLOT_INFO_PTR pInfo)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native CK_SLOT_INFO C_GetSlotInfo(long slotID) throws PKCS11Exception;
/**
* C_GetTokenInfo obtains information about a particular token
* in the system.
* (Slot and token management)
*
* @param slotID ID of the token's slot
* (PKCS#11 param: CK_SLOT_ID slotID)
* @return the token information
* (PKCS#11 param: CK_TOKEN_INFO_PTR pInfo)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native CK_TOKEN_INFO C_GetTokenInfo(long slotID)
throws PKCS11Exception;
/**
* C_GetMechanismList obtains a list of mechanism types
* supported by a token.
* (Slot and token management)
*
* @param slotID ID of the token's slot
* (PKCS#11 param: CK_SLOT_ID slotID)
* @return a long array of mechanism types and number of mechanism types
* (PKCS#11 param: CK_MECHANISM_TYPE_PTR pMechanismList,
* CK_ULONG_PTR pulCount)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native long[] C_GetMechanismList(long slotID) throws PKCS11Exception;
/**
* C_GetMechanismInfo obtains information about a particular
* mechanism possibly supported by a token.
* (Slot and token management)
*
* @param slotID ID of the token's slot
* (PKCS#11 param: CK_SLOT_ID slotID)
* @param type type of mechanism
* (PKCS#11 param: CK_MECHANISM_TYPE type)
* @return the mechanism info
* (PKCS#11 param: CK_MECHANISM_INFO_PTR pInfo)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native CK_MECHANISM_INFO C_GetMechanismInfo(long slotID, long type)
throws PKCS11Exception;
/**
* C_InitToken initializes a token.
* (Slot and token management)
*
* @param slotID ID of the token's slot
* (PKCS#11 param: CK_SLOT_ID slotID)
* @param pPin the SO's initial PIN and the length in bytes of the PIN
* (PKCS#11 param: CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
* @param pLabel 32-byte token label (blank padded)
* (PKCS#11 param: CK_UTF8CHAR_PTR pLabel)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
// public native void C_InitToken(long slotID, char[] pPin, char[] pLabel)
// throws PKCS11Exception;
/**
* C_InitPIN initializes the normal user's PIN.
* (Slot and token management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pPin the normal user's PIN and the length in bytes of the PIN
* (PKCS#11 param: CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
// public native void C_InitPIN(long hSession, char[] pPin)
// throws PKCS11Exception;
/**
* C_SetPIN modifies the PIN of the user who is logged in.
* (Slot and token management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pOldPin the old PIN and the length of the old PIN
* (PKCS#11 param: CK_CHAR_PTR pOldPin, CK_ULONG ulOldLen)
* @param pNewPin the new PIN and the length of the new PIN
* (PKCS#11 param: CK_CHAR_PTR pNewPin, CK_ULONG ulNewLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
// public native void C_SetPIN(long hSession, char[] pOldPin, char[] pNewPin)
// throws PKCS11Exception;
/* *****************************************************************************
* Session management
******************************************************************************/
/**
* C_OpenSession opens a session between an application and a
* token.
* (Session management)
*
* @param slotID the slot's ID
* (PKCS#11 param: CK_SLOT_ID slotID)
* @param flags of CK_SESSION_INFO
* (PKCS#11 param: CK_FLAGS flags)
* @param pApplication passed to callback
* (PKCS#11 param: CK_VOID_PTR pApplication)
* @param Notify the callback function
* (PKCS#11 param: CK_NOTIFY Notify)
* @return the session handle
* (PKCS#11 param: CK_SESSION_HANDLE_PTR phSession)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native long C_OpenSession(long slotID, long flags,
Object pApplication, CK_NOTIFY Notify) throws PKCS11Exception;
/**
* C_CloseSession closes a session between an application and a
* token.
* (Session management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_CloseSession(long hSession) throws PKCS11Exception;
/**
* C_CloseAllSessions closes all sessions with a token.
* (Session management)
*
* @param slotID the ID of the token's slot
* (PKCS#11 param: CK_SLOT_ID slotID)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
// public native void C_CloseAllSessions(long slotID) throws PKCS11Exception;
/**
* C_GetSessionInfo obtains information about the session.
* (Session management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @return the session info
* (PKCS#11 param: CK_SESSION_INFO_PTR pInfo)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native CK_SESSION_INFO C_GetSessionInfo(long hSession)
throws PKCS11Exception;
/**
* C_GetOperationState obtains the state of the cryptographic operation
* in a session.
* (Session management)
*
* @param hSession session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @return the state and the state length
* (PKCS#11 param: CK_BYTE_PTR pOperationState,
* CK_ULONG_PTR pulOperationStateLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native byte[] C_GetOperationState(long hSession)
throws PKCS11Exception;
/**
* C_SetOperationState restores the state of the cryptographic
* operation in a session.
* (Session management)
*
* @param hSession session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pOperationState the state and the state length
* (PKCS#11 param: CK_BYTE_PTR pOperationState,
* CK_ULONG ulOperationStateLen)
* @param hEncryptionKey en/decryption key
* (PKCS#11 param: CK_OBJECT_HANDLE hEncryptionKey)
* @param hAuthenticationKey sign/verify key
* (PKCS#11 param: CK_OBJECT_HANDLE hAuthenticationKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_SetOperationState(long hSession, byte[] pOperationState,
long hEncryptionKey, long hAuthenticationKey) throws PKCS11Exception;
/**
* C_Login logs a user into a token.
* (Session management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param userType the user type
* (PKCS#11 param: CK_USER_TYPE userType)
* @param pPin the user's PIN and the length of the PIN
* (PKCS#11 param: CK_CHAR_PTR pPin, CK_ULONG ulPinLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_Login(long hSession, long userType, char[] pPin)
throws PKCS11Exception;
/**
* C_Logout logs a user out from a token.
* (Session management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_Logout(long hSession) throws PKCS11Exception;
/* *****************************************************************************
* Object management
******************************************************************************/
/**
* C_CreateObject creates a new object.
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pTemplate the object's template and number of attributes in
* template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @return the object's handle
* (PKCS#11 param: CK_OBJECT_HANDLE_PTR phObject)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native long C_CreateObject(long hSession, CK_ATTRIBUTE[] pTemplate)
throws PKCS11Exception;
/**
* C_CopyObject copies an object, creating a new object for the
* copy.
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param hObject the object's handle
* (PKCS#11 param: CK_OBJECT_HANDLE hObject)
* @param pTemplate the template for the new object and number of attributes
* in template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @return the handle of the copy
* (PKCS#11 param: CK_OBJECT_HANDLE_PTR phNewObject)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native long C_CopyObject(long hSession, long hObject,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception;
/**
* C_DestroyObject destroys an object.
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param hObject the object's handle
* (PKCS#11 param: CK_OBJECT_HANDLE hObject)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_DestroyObject(long hSession, long hObject)
throws PKCS11Exception;
/**
* C_GetObjectSize gets the size of an object in bytes.
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param hObject the object's handle
* (PKCS#11 param: CK_OBJECT_HANDLE hObject)
* @return the size of the object
* (PKCS#11 param: CK_ULONG_PTR pulSize)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
// public native long C_GetObjectSize(long hSession, long hObject)
// throws PKCS11Exception;
/**
* C_GetAttributeValue obtains the value of one or more object
* attributes. The template attributes also receive the values.
* (Object management)
* note: in PKCS#11 pTemplate and the result template are the same
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param hObject the object's handle
* (PKCS#11 param: CK_OBJECT_HANDLE hObject)
* @param pTemplate specifies the attributes and number of attributes to get
* The template attributes also receive the values.
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pTemplate <> null)
* @postconditions (result <> null)
*/
public native void C_GetAttributeValue(long hSession, long hObject,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception;
/**
* C_SetAttributeValue modifies the value of one or more object
* attributes
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param hObject the object's handle
* (PKCS#11 param: CK_OBJECT_HANDLE hObject)
* @param pTemplate specifies the attributes and values to get; number of
* attributes in the template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pTemplate <> null)
* @postconditions
*/
public native void C_SetAttributeValue(long hSession, long hObject,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception;
/**
* C_FindObjectsInit initializes a search for token and session
* objects that match a template.
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pTemplate the object's attribute values to match and the number of
* attributes in search template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_FindObjectsInit(long hSession, CK_ATTRIBUTE[] pTemplate)
throws PKCS11Exception;
/**
* C_FindObjects continues a search for token and session
* objects that match a template, obtaining additional object
* handles.
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param ulMaxObjectCount the max. object handles to get
* (PKCS#11 param: CK_ULONG ulMaxObjectCount)
* @return the object's handles and the actual number of objects returned
* (PKCS#11 param: CK_ULONG_PTR pulObjectCount)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native long[] C_FindObjects(long hSession, long ulMaxObjectCount)
throws PKCS11Exception;
/**
* C_FindObjectsFinal finishes a search for token and session
* objects.
* (Object management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_FindObjectsFinal(long hSession) throws PKCS11Exception;
/* *****************************************************************************
* Encryption and decryption
******************************************************************************/
/**
* C_EncryptInit initializes an encryption operation.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the encryption mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hKey the handle of the encryption key
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_EncryptInit(long hSession, CK_MECHANISM pMechanism,
long hKey) throws PKCS11Exception;
/**
* C_Encrypt encrypts single-part data.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param directIn the address of the to-be-encrypted data
* @param in buffer containing the to-be-encrypted data
* @param inOfs buffer offset of the to-be-encrypted data
* @param inLen length of the to-be-encrypted data
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
* @param directOut the address for the encrypted data
* @param out buffer for the encrypted data
* @param outOfs buffer offset for the encrypted data
* @param outLen buffer size for the encrypted data
* @return the length of encrypted data
* (PKCS#11 param: CK_BYTE_PTR pEncryptedData,
* CK_ULONG_PTR pulEncryptedDataLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native int C_Encrypt(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs,
int outLen) throws PKCS11Exception;
/**
* C_EncryptUpdate continues a multiple-part encryption
* operation.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param directIn the address of the to-be-encrypted data
* @param in buffer containing the to-be-encrypted data
* @param inOfs buffer offset of the to-be-encrypted data
* @param inLen length of the to-be-encrypted data
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
* @param directOut the address for the encrypted data
* @param out buffer for the encrypted data
* @param outOfs buffer offset for the encrypted data
* @param outLen buffer size for the encrypted data
* @return the length of encrypted data for this update
* (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
CK_ULONG_PTR pulEncryptedPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native int C_EncryptUpdate(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs,
int outLen) throws PKCS11Exception;
/**
* C_EncryptFinal finishes a multiple-part encryption
* operation.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param directOut the address for the encrypted data
* @param out buffer for the encrypted data
* @param outOfs buffer offset for the encrypted data
* @param outLen buffer size for the encrypted data
* @return the length of the last part of the encrypted data
* (PKCS#11 param: CK_BYTE_PTR pLastEncryptedPart,
CK_ULONG_PTR pulLastEncryptedPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native int C_EncryptFinal(long hSession, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception;
/**
* C_DecryptInit initializes a decryption operation.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the decryption mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hKey the handle of the decryption key
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_DecryptInit(long hSession, CK_MECHANISM pMechanism,
long hKey) throws PKCS11Exception;
/**
* C_Decrypt decrypts encrypted data in a single part.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param directIn the address of the to-be-decrypted data
* @param in buffer containing the to-be-decrypted data
* @param inOfs buffer offset of the to-be-decrypted data
* @param inLen length of the to-be-decrypted data
* (PKCS#11 param: CK_BYTE_PTR pDecryptedData,
* CK_ULONG ulDecryptedDataLen)
* @param directOut the address for the decrypted data
* @param out buffer for the decrypted data
* @param outOfs buffer offset for the decrypted data
* @param outLen buffer size for the decrypted data
* @return the length of decrypted data
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native int C_Decrypt(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs,
int outLen) throws PKCS11Exception;
/**
* C_DecryptUpdate continues a multiple-part decryption
* operation.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param directIn the address of the to-be-decrypted data
* @param in buffer containing the to-be-decrypted data
* @param inOfs buffer offset of the to-be-decrypted data
* @param inLen length of the to-be-decrypted data
* (PKCS#11 param: CK_BYTE_PTR pDecryptedPart,
* CK_ULONG ulDecryptedPartLen)
* @param directOut the address for the decrypted data
* @param out buffer for the decrypted data
* @param outOfs buffer offset for the decrypted data
* @param outLen buffer size for the decrypted data
* @return the length of decrypted data for this update
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native int C_DecryptUpdate(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs,
int outLen) throws PKCS11Exception;
/**
* C_DecryptFinal finishes a multiple-part decryption
* operation.
* (Encryption and decryption)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param directOut the address for the decrypted data
* @param out buffer for the decrypted data
* @param outOfs buffer offset for the decrypted data
* @param outLen buffer size for the decrypted data
* @return the length of this last part of decrypted data
* (PKCS#11 param: CK_BYTE_PTR pLastPart,
* CK_ULONG_PTR pulLastPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native int C_DecryptFinal(long hSession, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception;
/* *****************************************************************************
* Message digesting
******************************************************************************/
/**
* C_DigestInit initializes a message-digesting operation.
* (Message digesting)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the digesting mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_DigestInit(long hSession, CK_MECHANISM pMechanism)
throws PKCS11Exception;
// note that C_DigestSingle does not exist in PKCS#11
// we combined the C_DigestInit and C_Digest into a single function
// to save on Java<->C transitions and save 5-10% on small digests
// this made the C_Digest method redundant, it has been removed
/**
* C_Digest digests data in a single part.
* (Message digesting)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param data the data to get digested and the data's length
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
* @return the message digest and the length of the message digest
* (PKCS#11 param: CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (data <> null)
* @postconditions (result <> null)
*/
public native int C_DigestSingle(long hSession, CK_MECHANISM pMechanism,
byte[] in, int inOfs, int inLen, byte[] digest, int digestOfs,
int digestLen) throws PKCS11Exception;
/**
* C_DigestUpdate continues a multiple-part message-digesting
* operation.
* (Message digesting)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pPart the data to get digested and the data's length
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pPart <> null)
* @postconditions
*/
public native void C_DigestUpdate(long hSession, long directIn, byte[] in,
int inOfs, int inLen) throws PKCS11Exception;
/**
* C_DigestKey continues a multi-part message-digesting
* operation, by digesting the value of a secret key as part of
* the data already digested.
* (Message digesting)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param hKey the handle of the secret key to be digested
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_DigestKey(long hSession, long hKey)
throws PKCS11Exception;
/**
* C_DigestFinal finishes a multiple-part message-digesting
* operation.
* (Message digesting)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @return the message digest and the length of the message digest
* (PKCS#11 param: CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native int C_DigestFinal(long hSession, byte[] pDigest, int digestOfs,
int digestLen) throws PKCS11Exception;
/* *****************************************************************************
* Signing and MACing
******************************************************************************/
/**
* C_SignInit initializes a signature (private key encryption)
* operation, where the signature is (will be) an appendix to
* the data, and plaintext cannot be recovered from the
* signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the signature mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hKey the handle of the signature key
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_SignInit(long hSession, CK_MECHANISM pMechanism,
long hKey) throws PKCS11Exception;
/**
* C_Sign signs (encrypts with private key) data in a single
* part, where the signature is (will be) an appendix to the
* data, and plaintext cannot be recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pData the data to sign and the data's length
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
* @return the signature and the signature's length
* (PKCS#11 param: CK_BYTE_PTR pSignature,
* CK_ULONG_PTR pulSignatureLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pData <> null)
* @postconditions (result <> null)
*/
public native byte[] C_Sign(long hSession, byte[] pData)
throws PKCS11Exception;
/**
* C_SignUpdate continues a multiple-part signature operation,
* where the signature is (will be) an appendix to the data,
* and plaintext cannot be recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pPart the data part to sign and the data part's length
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pPart <> null)
* @postconditions
*/
public native void C_SignUpdate(long hSession, long directIn, byte[] in,
int inOfs, int inLen) throws PKCS11Exception;
/**
* C_SignFinal finishes a multiple-part signature operation,
* returning the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param expectedLen expected signature length, can be 0 if unknown
* @return the signature and the signature's length
* (PKCS#11 param: CK_BYTE_PTR pSignature,
* CK_ULONG_PTR pulSignatureLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native byte[] C_SignFinal(long hSession, int expectedLen)
throws PKCS11Exception;
/**
* C_SignRecoverInit initializes a signature operation, where
* the data can be recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the signature mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hKey the handle of the signature key
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_SignRecoverInit(long hSession, CK_MECHANISM pMechanism,
long hKey) throws PKCS11Exception;
/**
* C_SignRecover signs data in a single operation, where the
* data can be recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pData the data to sign and the data's length
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
* @return the signature and the signature's length
* (PKCS#11 param: CK_BYTE_PTR pSignature,
* CK_ULONG_PTR pulSignatureLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pData <> null)
* @postconditions (result <> null)
*/
public native int C_SignRecover(long hSession, byte[] in, int inOfs,
int inLen, byte[] out, int outOufs, int outLen)
throws PKCS11Exception;
/* *****************************************************************************
* Verifying signatures and MACs
******************************************************************************/
/**
* C_VerifyInit initializes a verification operation, where the
* signature is an appendix to the data, and plaintext cannot
* cannot be recovered from the signature (e.g. DSA).
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the verification mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hKey the handle of the verification key
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_VerifyInit(long hSession, CK_MECHANISM pMechanism,
long hKey) throws PKCS11Exception;
/**
* C_Verify verifies a signature in a single-part operation,
* where the signature is an appendix to the data, and plaintext
* cannot be recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pData the signed data and the signed data's length
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG ulDataLen)
* @param pSignature the signature to verify and the signature's length
* (PKCS#11 param: CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pData <> null) and (pSignature <> null)
* @postconditions
*/
public native void C_Verify(long hSession, byte[] pData, byte[] pSignature)
throws PKCS11Exception;
/**
* C_VerifyUpdate continues a multiple-part verification
* operation, where the signature is an appendix to the data,
* and plaintext cannot be recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pPart the signed data part and the signed data part's length
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pPart <> null)
* @postconditions
*/
public native void C_VerifyUpdate(long hSession, long directIn, byte[] in,
int inOfs, int inLen) throws PKCS11Exception;
/**
* C_VerifyFinal finishes a multiple-part verification
* operation, checking the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pSignature the signature to verify and the signature's length
* (PKCS#11 param: CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pSignature <> null)
* @postconditions
*/
public native void C_VerifyFinal(long hSession, byte[] pSignature)
throws PKCS11Exception;
/**
* C_VerifyRecoverInit initializes a signature verification
* operation, where the data is recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the verification mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hKey the handle of the verification key
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native void C_VerifyRecoverInit(long hSession,
CK_MECHANISM pMechanism, long hKey) throws PKCS11Exception;
/**
* C_VerifyRecover verifies a signature in a single-part
* operation, where the data is recovered from the signature.
* (Signing and MACing)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pSignature the signature to verify and the signature's length
* (PKCS#11 param: CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen)
* @return the recovered data and the recovered data's length
* (PKCS#11 param: CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pSignature <> null)
* @postconditions (result <> null)
*/
public native int C_VerifyRecover(long hSession, byte[] in, int inOfs,
int inLen, byte[] out, int outOufs, int outLen)
throws PKCS11Exception;
/* *****************************************************************************
* Dual-function cryptographic operations
******************************************************************************/
/**
* C_DigestEncryptUpdate continues a multiple-part digesting
* and encryption operation.
* (Dual-function cryptographic operations)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pPart the data part to digest and to encrypt and the data's length
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
* @return the digested and encrypted data part and the data part's length
* (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
* CK_ULONG_PTR pulEncryptedPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pPart <> null)
* @postconditions
*/
// public native byte[] C_DigestEncryptUpdate(long hSession, byte[] pPart)
// throws PKCS11Exception;
/**
* C_DecryptDigestUpdate continues a multiple-part decryption and
* digesting operation.
* (Dual-function cryptographic operations)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pEncryptedPart the encrypted data part to decrypt and to digest
* and encrypted data part's length
* (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
* CK_ULONG ulEncryptedPartLen)
* @return the decrypted and digested data part and the data part's length
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pEncryptedPart <> null)
* @postconditions
*/
// public native byte[] C_DecryptDigestUpdate(long hSession,
// byte[] pEncryptedPart) throws PKCS11Exception;
/**
* C_SignEncryptUpdate continues a multiple-part signing and
* encryption operation.
* (Dual-function cryptographic operations)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pPart the data part to sign and to encrypt and the data part's
* length
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG ulPartLen)
* @return the signed and encrypted data part and the data part's length
* (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
* CK_ULONG_PTR pulEncryptedPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pPart <> null)
* @postconditions
*/
// public native byte[] C_SignEncryptUpdate(long hSession, byte[] pPart)
// throws PKCS11Exception;
/**
* C_DecryptVerifyUpdate continues a multiple-part decryption and
* verify operation.
* (Dual-function cryptographic operations)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pEncryptedPart the encrypted data part to decrypt and to verify
* and the data part's length
* (PKCS#11 param: CK_BYTE_PTR pEncryptedPart,
* CK_ULONG ulEncryptedPartLen)
* @return the decrypted and verified data part and the data part's length
* (PKCS#11 param: CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pEncryptedPart <> null)
* @postconditions
*/
// public native byte[] C_DecryptVerifyUpdate(long hSession,
// byte[] pEncryptedPart) throws PKCS11Exception;
/* *****************************************************************************
* Key management
******************************************************************************/
/**
* getNativeKeyInfo gets the key object attributes and values as an opaque
* byte array to be used in createNativeKey method.
* (Key management)
*
* @param hSession the session's handle
* @param hKey key's handle
* @param hWrappingKey key handle for wrapping the extracted sensitive keys.
* -1 if not used.
* @param pWrappingMech mechanism for wrapping the extracted sensitive keys
* @return an opaque byte array containing the key object attributes
* and values
* @exception PKCS11Exception If an internal PKCS#11 function returns other
* value than CKR_OK.
* @preconditions
* @postconditions
*/
public native byte[] getNativeKeyInfo(long hSession, long hKey,
long hWrappingKey, CK_MECHANISM pWrappingMech) throws PKCS11Exception;
/**
* createNativeKey creates a key object with attributes and values
* specified by parameter as an opaque byte array.
* (Key management)
*
* @param hSession the session's handle
* @param keyInfo opaque byte array containing key object attributes
* and values
* @param hWrappingKey key handle for unwrapping the extracted sensitive keys.
* -1 if not used.
* @param pWrappingMech mechanism for unwrapping the extracted sensitive keys
* @return key object handle
* @exception PKCS11Exception If an internal PKCS#11 function returns other
* value than CKR_OK.
* @preconditions
* @postconditions
*/
public native long createNativeKey(long hSession, byte[] keyInfo,
long hWrappingKey, CK_MECHANISM pWrappingMech) throws PKCS11Exception;
/**
* C_GenerateKey generates a secret key, creating a new key
* object.
* (Key management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the key generation mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param pTemplate the template for the new key and the number of
* attributes in the template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @return the handle of the new key
* (PKCS#11 param: CK_OBJECT_HANDLE_PTR phKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native long C_GenerateKey(long hSession, CK_MECHANISM pMechanism,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception;
/**
* C_GenerateKeyPair generates a public-key/private-key pair,
* creating new key objects.
* (Key management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the key generation mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param pPublicKeyTemplate the template for the new public key and the
* number of attributes in the template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pPublicKeyTemplate,
* CK_ULONG ulPublicKeyAttributeCount)
* @param pPrivateKeyTemplate the template for the new private key and the
* number of attributes in the template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pPrivateKeyTemplate
* CK_ULONG ulPrivateKeyAttributeCount)
* @return a long array with exactly two elements and the public key handle
* as the first element and the private key handle as the second
* element
* (PKCS#11 param: CK_OBJECT_HANDLE_PTR phPublicKey,
* CK_OBJECT_HANDLE_PTR phPrivateKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pMechanism <> null)
* @postconditions (result <> null) and (result.length == 2)
*/
public native long[] C_GenerateKeyPair(long hSession,
CK_MECHANISM pMechanism, CK_ATTRIBUTE[] pPublicKeyTemplate,
CK_ATTRIBUTE[] pPrivateKeyTemplate) throws PKCS11Exception;
/**
* C_WrapKey wraps (i.e., encrypts) a key.
* (Key management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the wrapping mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hWrappingKey the handle of the wrapping key
* (PKCS#11 param: CK_OBJECT_HANDLE hWrappingKey)
* @param hKey the handle of the key to be wrapped
* (PKCS#11 param: CK_OBJECT_HANDLE hKey)
* @return the wrapped key and the length of the wrapped key
* (PKCS#11 param: CK_BYTE_PTR pWrappedKey,
* CK_ULONG_PTR pulWrappedKeyLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions (result <> null)
*/
public native byte[] C_WrapKey(long hSession, CK_MECHANISM pMechanism,
long hWrappingKey, long hKey) throws PKCS11Exception;
/**
* C_UnwrapKey unwraps (decrypts) a wrapped key, creating a new
* key object.
* (Key management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the unwrapping mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hUnwrappingKey the handle of the unwrapping key
* (PKCS#11 param: CK_OBJECT_HANDLE hUnwrappingKey)
* @param pWrappedKey the wrapped key to unwrap and the wrapped key's length
* (PKCS#11 param: CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen)
* @param pTemplate the template for the new key and the number of
* attributes in the template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @return the handle of the unwrapped key
* (PKCS#11 param: CK_OBJECT_HANDLE_PTR phKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pWrappedKey <> null)
* @postconditions
*/
public native long C_UnwrapKey(long hSession, CK_MECHANISM pMechanism,
long hUnwrappingKey, byte[] pWrappedKey, CK_ATTRIBUTE[] pTemplate)
throws PKCS11Exception;
/**
* C_DeriveKey derives a key from a base key, creating a new key
* object.
* (Key management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pMechanism the key derivation mechanism
* (PKCS#11 param: CK_MECHANISM_PTR pMechanism)
* @param hBaseKey the handle of the base key
* (PKCS#11 param: CK_OBJECT_HANDLE hBaseKey)
* @param pTemplate the template for the new key and the number of
* attributes in the template
* (PKCS#11 param: CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount)
* @return the handle of the derived key
* (PKCS#11 param: CK_OBJECT_HANDLE_PTR phKey)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
public native long C_DeriveKey(long hSession, CK_MECHANISM pMechanism,
long hBaseKey, CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception;
/* *****************************************************************************
* Random number generation
******************************************************************************/
/**
* C_SeedRandom mixes additional seed material into the token's
* random number generator.
* (Random number generation)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param pSeed the seed material and the seed material's length
* (PKCS#11 param: CK_BYTE_PTR pSeed, CK_ULONG ulSeedLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pSeed <> null)
* @postconditions
*/
public native void C_SeedRandom(long hSession, byte[] pSeed)
throws PKCS11Exception;
/**
* C_GenerateRandom generates random data.
* (Random number generation)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @param RandomData receives the random data and the length of RandomData
* is the length of random data to be generated
* (PKCS#11 param: CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (randomData <> null)
* @postconditions
*/
public native void C_GenerateRandom(long hSession, byte[] randomData)
throws PKCS11Exception;
/* *****************************************************************************
* Parallel function management
******************************************************************************/
/**
* C_GetFunctionStatus is a legacy function; it obtains an
* updated status of a function running in parallel with an
* application.
* (Parallel function management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
// public native void C_GetFunctionStatus(long hSession)
// throws PKCS11Exception;
/**
* C_CancelFunction is a legacy function; it cancels a function
* running in parallel.
* (Parallel function management)
*
* @param hSession the session's handle
* (PKCS#11 param: CK_SESSION_HANDLE hSession)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions
* @postconditions
*/
// public native void C_CancelFunction(long hSession) throws PKCS11Exception;
/* *****************************************************************************
* Functions added in for Cryptoki Version 2.01 or later
******************************************************************************/
/**
* C_WaitForSlotEvent waits for a slot event (token insertion,
* removal, etc.) to occur.
* (General-purpose)
*
* @param flags blocking/nonblocking flag
* (PKCS#11 param: CK_FLAGS flags)
* @param pReserved reserved. Should be null
* (PKCS#11 param: CK_VOID_PTR pReserved)
* @return the slot ID where the event occurred
* (PKCS#11 param: CK_SLOT_ID_PTR pSlot)
* @exception PKCS11Exception If function returns other value than CKR_OK.
* @preconditions (pRserved == null)
* @postconditions
*/
// public native long C_WaitForSlotEvent(long flags, Object pRserved)
// throws PKCS11Exception;
/**
* Returns the string representation of this object.
*
* @return The string representation of object
*/
public String toString() {
return "Module name: " + pkcs11ModulePath;
}
/**
* Calls disconnect() to cleanup the native part of the wrapper. Once this
* method is called, this object cannot be used any longer. Any subsequent
* call to a C_* method will result in a runtime exception.
*
* @exception Throwable If finalization fails.
*/
protected void finalize() throws Throwable {
disconnect();
}
// PKCS11 subclass that has all methods synchronized and delegating to the
// parent. Used for tokens that only support single threaded access
static class SynchronizedPKCS11 extends PKCS11 {
SynchronizedPKCS11(String pkcs11ModulePath, String functionListName)
throws IOException {
super(pkcs11ModulePath, functionListName);
}
synchronized void C_Initialize(Object pInitArgs) throws PKCS11Exception {
super.C_Initialize(pInitArgs);
}
public synchronized void C_Finalize(Object pReserved)
throws PKCS11Exception {
super.C_Finalize(pReserved);
}
public synchronized CK_INFO C_GetInfo() throws PKCS11Exception {
return super.C_GetInfo();
}
public synchronized long[] C_GetSlotList(boolean tokenPresent)
throws PKCS11Exception {
return super.C_GetSlotList(tokenPresent);
}
public synchronized CK_SLOT_INFO C_GetSlotInfo(long slotID)
throws PKCS11Exception {
return super.C_GetSlotInfo(slotID);
}
public synchronized CK_TOKEN_INFO C_GetTokenInfo(long slotID)
throws PKCS11Exception {
return super.C_GetTokenInfo(slotID);
}
public synchronized long[] C_GetMechanismList(long slotID)
throws PKCS11Exception {
return super.C_GetMechanismList(slotID);
}
public synchronized CK_MECHANISM_INFO C_GetMechanismInfo(long slotID,
long type) throws PKCS11Exception {
return super.C_GetMechanismInfo(slotID, type);
}
public synchronized long C_OpenSession(long slotID, long flags,
Object pApplication, CK_NOTIFY Notify) throws PKCS11Exception {
return super.C_OpenSession(slotID, flags, pApplication, Notify);
}
public synchronized void C_CloseSession(long hSession)
throws PKCS11Exception {
super.C_CloseSession(hSession);
}
public synchronized CK_SESSION_INFO C_GetSessionInfo(long hSession)
throws PKCS11Exception {
return super.C_GetSessionInfo(hSession);
}
public synchronized void C_Login(long hSession, long userType, char[] pPin)
throws PKCS11Exception {
super.C_Login(hSession, userType, pPin);
}
public synchronized void C_Logout(long hSession) throws PKCS11Exception {
super.C_Logout(hSession);
}
public synchronized long C_CreateObject(long hSession,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
return super.C_CreateObject(hSession, pTemplate);
}
public synchronized long C_CopyObject(long hSession, long hObject,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
return super.C_CopyObject(hSession, hObject, pTemplate);
}
public synchronized void C_DestroyObject(long hSession, long hObject)
throws PKCS11Exception {
super.C_DestroyObject(hSession, hObject);
}
public synchronized void C_GetAttributeValue(long hSession, long hObject,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
super.C_GetAttributeValue(hSession, hObject, pTemplate);
}
public synchronized void C_SetAttributeValue(long hSession, long hObject,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
super.C_SetAttributeValue(hSession, hObject, pTemplate);
}
public synchronized void C_FindObjectsInit(long hSession,
CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
super.C_FindObjectsInit(hSession, pTemplate);
}
public synchronized long[] C_FindObjects(long hSession,
long ulMaxObjectCount) throws PKCS11Exception {
return super.C_FindObjects(hSession, ulMaxObjectCount);
}
public synchronized void C_FindObjectsFinal(long hSession)
throws PKCS11Exception {
super.C_FindObjectsFinal(hSession);
}
public synchronized void C_EncryptInit(long hSession,
CK_MECHANISM pMechanism, long hKey) throws PKCS11Exception {
super.C_EncryptInit(hSession, pMechanism, hKey);
}
public synchronized int C_Encrypt(long hSession, long directIn, byte[] in,
int inOfs, int inLen, long directOut, byte[] out, int outOfs, int outLen)
throws PKCS11Exception {
return super.C_Encrypt(hSession, directIn, in, inOfs, inLen,
directOut, out, outOfs, outLen);
}
public synchronized int C_EncryptUpdate(long hSession, long directIn,
byte[] in, int inOfs, int inLen, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception {
return super.C_EncryptUpdate(hSession, directIn, in, inOfs, inLen,
directOut, out, outOfs, outLen);
}
public synchronized int C_EncryptFinal(long hSession, long directOut,
byte[] out, int outOfs, int outLen) throws PKCS11Exception {
return super.C_EncryptFinal(hSession, directOut, out, outOfs, outLen);
}
public synchronized void C_DecryptInit(long hSession,
CK_MECHANISM pMechanism, long hKey) throws PKCS11Exception {
super.C_DecryptInit(hSession, pMechanism, hKey);
}
public synchronized int C_Decrypt(long hSession, long directIn,
byte[] in, int inOfs, int inLen, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception {
return super.C_Decrypt(hSession, directIn, in, inOfs, inLen,
directOut, out, outOfs, outLen);
}
public synchronized int C_DecryptUpdate(long hSession, long directIn,
byte[] in, int inOfs, int inLen, long directOut, byte[] out,
int outOfs, int outLen) throws PKCS11Exception {
return super.C_DecryptUpdate(hSession, directIn, in, inOfs, inLen,
directOut, out, outOfs, outLen);
}
public synchronized int C_DecryptFinal(long hSession, long directOut,
byte[] out, int outOfs, int outLen) throws PKCS11Exception {
return super.C_DecryptFinal(hSession, directOut, out, outOfs, outLen);
}
public synchronized void C_DigestInit(long hSession, CK_MECHANISM pMechanism)
throws PKCS11Exception {
super.C_DigestInit(hSession, pMechanism);
}
public synchronized int C_DigestSingle(long hSession,
CK_MECHANISM pMechanism, byte[] in, int inOfs, int inLen,
byte[] digest, int digestOfs, int digestLen) throws PKCS11Exception {
return super.C_DigestSingle(hSession, pMechanism, in, inOfs, inLen,
digest, digestOfs, digestLen);
}
public synchronized void C_DigestUpdate(long hSession, long directIn,
byte[] in, int inOfs, int inLen) throws PKCS11Exception {
super.C_DigestUpdate(hSession, directIn, in, inOfs, inLen);
}
public synchronized void C_DigestKey(long hSession, long hKey)
throws PKCS11Exception {
super.C_DigestKey(hSession, hKey);
}
public synchronized int C_DigestFinal(long hSession, byte[] pDigest,
int digestOfs, int digestLen) throws PKCS11Exception {
return super.C_DigestFinal(hSession, pDigest, digestOfs, digestLen);
}
public synchronized void C_SignInit(long hSession, CK_MECHANISM pMechanism,
long hKey) throws PKCS11Exception {
super.C_SignInit(hSession, pMechanism, hKey);
}
public synchronized byte[] C_Sign(long hSession, byte[] pData)
throws PKCS11Exception {
return super.C_Sign(hSession, pData);
}
public synchronized void C_SignUpdate(long hSession, long directIn,
byte[] in, int inOfs, int inLen) throws PKCS11Exception {
super.C_SignUpdate(hSession, directIn, in, inOfs, inLen);
}
public synchronized byte[] C_SignFinal(long hSession, int expectedLen)
throws PKCS11Exception {
return super.C_SignFinal(hSession, expectedLen);
}
public synchronized void C_SignRecoverInit(long hSession,
CK_MECHANISM pMechanism, long hKey) throws PKCS11Exception {
super.C_SignRecoverInit(hSession, pMechanism, hKey);
}
public synchronized int C_SignRecover(long hSession, byte[] in, int inOfs,
int inLen, byte[] out, int outOufs, int outLen)
throws PKCS11Exception {
return super.C_SignRecover(hSession, in, inOfs, inLen, out, outOufs,
outLen);
}
public synchronized void C_VerifyInit(long hSession, CK_MECHANISM pMechanism,
long hKey) throws PKCS11Exception {
super.C_VerifyInit(hSession, pMechanism, hKey);
}
public synchronized void C_Verify(long hSession, byte[] pData,
byte[] pSignature) throws PKCS11Exception {
super.C_Verify(hSession, pData, pSignature);
}
public synchronized void C_VerifyUpdate(long hSession, long directIn,
byte[] in, int inOfs, int inLen) throws PKCS11Exception {
super.C_VerifyUpdate(hSession, directIn, in, inOfs, inLen);
}
public synchronized void C_VerifyFinal(long hSession, byte[] pSignature)
throws PKCS11Exception {
super.C_VerifyFinal(hSession, pSignature);
}
public synchronized void C_VerifyRecoverInit(long hSession,
CK_MECHANISM pMechanism, long hKey) throws PKCS11Exception {
super.C_VerifyRecoverInit(hSession, pMechanism, hKey);
}
public synchronized int C_VerifyRecover(long hSession, byte[] in, int inOfs,
int inLen, byte[] out, int outOufs, int outLen)
throws PKCS11Exception {
return super.C_VerifyRecover(hSession, in, inOfs, inLen, out, outOufs,
outLen);
}
public synchronized long C_GenerateKey(long hSession,
CK_MECHANISM pMechanism, CK_ATTRIBUTE[] pTemplate)
throws PKCS11Exception {
return super.C_GenerateKey(hSession, pMechanism, pTemplate);
}
public synchronized long[] C_GenerateKeyPair(long hSession,
CK_MECHANISM pMechanism, CK_ATTRIBUTE[] pPublicKeyTemplate,
CK_ATTRIBUTE[] pPrivateKeyTemplate)
throws PKCS11Exception {
return super.C_GenerateKeyPair(hSession, pMechanism, pPublicKeyTemplate,
pPrivateKeyTemplate);
}
public synchronized byte[] C_WrapKey(long hSession, CK_MECHANISM pMechanism,
long hWrappingKey, long hKey) throws PKCS11Exception {
return super.C_WrapKey(hSession, pMechanism, hWrappingKey, hKey);
}
public synchronized long C_UnwrapKey(long hSession, CK_MECHANISM pMechanism,
long hUnwrappingKey, byte[] pWrappedKey, CK_ATTRIBUTE[] pTemplate)
throws PKCS11Exception {
return super.C_UnwrapKey(hSession, pMechanism, hUnwrappingKey,
pWrappedKey, pTemplate);
}
public synchronized long C_DeriveKey(long hSession, CK_MECHANISM pMechanism,
long hBaseKey, CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
return super.C_DeriveKey(hSession, pMechanism, hBaseKey, pTemplate);
}
public synchronized void C_SeedRandom(long hSession, byte[] pSeed)
throws PKCS11Exception {
super.C_SeedRandom(hSession, pSeed);
}
public synchronized void C_GenerateRandom(long hSession, byte[] randomData)
throws PKCS11Exception {
super.C_GenerateRandom(hSession, randomData);
}
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11.java |
179,982 | /*
* LookupService.java
*
* Copyright (C) 2003 MaxMind LLC. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.maxmind.geoip;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Provides a lookup service for information based on an IP address. The
* location of a database file is supplied when creating a lookup service
* instance. The edition of the database determines what information is
* available about an IP address. See the DatabaseInfo class for further
* details.
* <p>
*
* The following code snippet demonstrates looking up the country that an IP
* address is from:
*
* <pre>
* // First, create a LookupService instance with the location of the database.
* LookupService lookupService = new LookupService("c:\\geoip.dat");
* // Assume we have a String ipAddress (in dot-decimal form).
* Country country = lookupService.getCountry(ipAddress);
* System.out.println("The country is: " + country.getName());
* System.out.println("The country code is: " + country.getCode());
* </pre>
*
* In general, a single LookupService instance should be created and then reused
* repeatedly.
* <p>
*
* <i>Tip:</i> Those deploying the GeoIP API as part of a web application may
* find it difficult to pass in a File to create the lookup service, as the
* location of the database may vary per deployment or may even be part of the
* web-application. In this case, the database should be added to the classpath
* of the web-app. For example, by putting it into the WEB-INF/classes directory
* of the web application. The following code snippet demonstrates how to create
* a LookupService using a database that can be found on the classpath:
*
* <pre>
* String fileName = getClass().getResource("/GeoIP.dat").toExternalForm()
* .substring(6);
* LookupService lookupService = new LookupService(fileName);
* </pre>
*
* @author Matt Tucker (matt@jivesoftware.com)
*/
public class LookupService {
/**
* Database file.
*/
private RandomAccessFile file;
private final File databaseFile;
/**
* Information about the database.
*/
private DatabaseInfo databaseInfo;
private static final Charset charset = Charset.forName("ISO-8859-1");
private final CharsetDecoder charsetDecoder = charset.newDecoder();
/**
* The database type. Default is the country edition.
*/
private byte databaseType = DatabaseInfo.COUNTRY_EDITION;
private int[] databaseSegments;
private int recordLength;
private int dboptions;
private byte[] dbbuffer;
private byte[] index_cache;
private long mtime;
private int last_netmask;
private static final int US_OFFSET = 1;
private static final int CANADA_OFFSET = 677;
private static final int WORLD_OFFSET = 1353;
private static final int FIPS_RANGE = 360;
private static final int COUNTRY_BEGIN = 16776960;
private static final int STATE_BEGIN_REV0 = 16700000;
private static final int STATE_BEGIN_REV1 = 16000000;
private static final int STRUCTURE_INFO_MAX_SIZE = 20;
private static final int DATABASE_INFO_MAX_SIZE = 100;
public static final int GEOIP_STANDARD = 0;
public static final int GEOIP_MEMORY_CACHE = 1;
public static final int GEOIP_CHECK_CACHE = 2;
public static final int GEOIP_INDEX_CACHE = 4;
public static final int GEOIP_UNKNOWN_SPEED = 0;
public static final int GEOIP_DIALUP_SPEED = 1;
public static final int GEOIP_CABLEDSL_SPEED = 2;
public static final int GEOIP_CORPORATE_SPEED = 3;
private static final int SEGMENT_RECORD_LENGTH = 3;
private static final int STANDARD_RECORD_LENGTH = 3;
private static final int ORG_RECORD_LENGTH = 4;
private static final int MAX_RECORD_LENGTH = 4;
private static final int MAX_ORG_RECORD_LENGTH = 300;
private static final int FULL_RECORD_LENGTH = 60;
private final Country UNKNOWN_COUNTRY = new Country("--", "N/A");
private static final String[] countryCode = { "--", "AP", "EU", "AD", "AE",
"AF", "AG", "AI", "AL", "AM", "CW", "AO", "AQ", "AR", "AS", "AT",
"AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI",
"BJ", "BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ",
"CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN",
"CO", "CR", "CU", "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM",
"DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ",
"FK", "FM", "FO", "FR", "SX", "GA", "GB", "GD", "GE", "GF", "GH",
"GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW",
"GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN",
"IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH",
"KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC",
"LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD",
"MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS",
"MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF",
"NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE",
"PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW",
"PY", "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE",
"SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST",
"SV", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TM",
"TN", "TO", "TL", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM",
"US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF",
"WS", "YE", "YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1",
"AX", "GG", "IM", "JE", "BL", "MF", "BQ", "SS", "O1" };
private static final String[] countryName = { "N/A", "Asia/Pacific Region",
"Europe", "Andorra", "United Arab Emirates", "Afghanistan",
"Antigua and Barbuda", "Anguilla", "Albania", "Armenia", "Curacao",
"Angola", "Antarctica", "Argentina", "American Samoa", "Austria",
"Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina",
"Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria",
"Bahrain", "Burundi", "Benin", "Bermuda", "Brunei Darussalam",
"Bolivia", "Brazil", "Bahamas", "Bhutan", "Bouvet Island",
"Botswana", "Belarus", "Belize", "Canada",
"Cocos (Keeling) Islands", "Congo, The Democratic Republic of the",
"Central African Republic", "Congo", "Switzerland",
"Cote D'Ivoire", "Cook Islands", "Chile", "Cameroon", "China",
"Colombia", "Costa Rica", "Cuba", "Cape Verde", "Christmas Island",
"Cyprus", "Czech Republic", "Germany", "Djibouti", "Denmark",
"Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia",
"Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia",
"Finland", "Fiji", "Falkland Islands (Malvinas)",
"Micronesia, Federated States of", "Faroe Islands", "France",
"Sint Maarten (Dutch part)", "Gabon", "United Kingdom", "Grenada",
"Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland",
"Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece",
"South Georgia and the South Sandwich Islands", "Guatemala",
"Guam", "Guinea-Bissau", "Guyana", "Hong Kong",
"Heard Island and McDonald Islands", "Honduras", "Croatia",
"Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India",
"British Indian Ocean Territory", "Iraq",
"Iran, Islamic Republic of", "Iceland", "Italy", "Jamaica",
"Jordan", "Japan", "Kenya", "Kyrgyzstan", "Cambodia", "Kiribati",
"Comoros", "Saint Kitts and Nevis",
"Korea, Democratic People's Republic of", "Korea, Republic of",
"Kuwait", "Cayman Islands", "Kazakhstan",
"Lao People's Democratic Republic", "Lebanon", "Saint Lucia",
"Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania",
"Luxembourg", "Latvia", "Libya", "Morocco", "Monaco",
"Moldova, Republic of", "Madagascar", "Marshall Islands",
"Macedonia", "Mali", "Myanmar", "Mongolia", "Macau",
"Northern Mariana Islands", "Martinique", "Mauritania",
"Montserrat", "Malta", "Mauritius", "Maldives", "Malawi", "Mexico",
"Malaysia", "Mozambique", "Namibia", "New Caledonia", "Niger",
"Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway",
"Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru",
"French Polynesia", "Papua New Guinea", "Philippines", "Pakistan",
"Poland", "Saint Pierre and Miquelon", "Pitcairn Islands",
"Puerto Rico", "Palestinian Territory", "Portugal", "Palau",
"Paraguay", "Qatar", "Reunion", "Romania", "Russian Federation",
"Rwanda", "Saudi Arabia", "Solomon Islands", "Seychelles", "Sudan",
"Sweden", "Singapore", "Saint Helena", "Slovenia",
"Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino",
"Senegal", "Somalia", "Suriname", "Sao Tome and Principe",
"El Salvador", "Syrian Arab Republic", "Swaziland",
"Turks and Caicos Islands", "Chad", "French Southern Territories",
"Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan",
"Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago",
"Tuvalu", "Taiwan", "Tanzania, United Republic of", "Ukraine",
"Uganda", "United States Minor Outlying Islands", "United States",
"Uruguay", "Uzbekistan", "Holy See (Vatican City State)",
"Saint Vincent and the Grenadines", "Venezuela",
"Virgin Islands, British", "Virgin Islands, U.S.", "Vietnam",
"Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte",
"Serbia", "South Africa", "Zambia", "Montenegro", "Zimbabwe",
"Anonymous Proxy", "Satellite Provider", "Other", "Aland Islands",
"Guernsey", "Isle of Man", "Jersey", "Saint Barthelemy",
"Saint Martin", "Bonaire, Saint Eustatius and Saba", "South Sudan",
"Other" };
/* init the hashmap once at startup time */
static {
if (countryCode.length != countryName.length) {
throw new AssertionError("countryCode.length!=countryName.length");
}
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile
* String representation of the database file.
* @throws IOException
* if an error occured creating the lookup service from the
* database file.
*/
public LookupService(String databaseFile) throws IOException {
this(new File(databaseFile));
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile
* the database file.
* @throws IOException
* if an error occured creating the lookup service from the
* database file.
*/
public LookupService(File databaseFile) throws IOException {
this.databaseFile = databaseFile;
file = new RandomAccessFile(databaseFile, "r");
init();
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile
* String representation of the database file.
* @param options
* database flags to use when opening the database GEOIP_STANDARD
* read database from disk GEOIP_MEMORY_CACHE cache the database
* in RAM and read it from RAM
* @throws IOException
* if an error occured creating the lookup service from the
* database file.
*/
public LookupService(String databaseFile, int options) throws IOException {
this(new File(databaseFile), options);
}
/**
* Create a new lookup service using the specified database file.
*
* @param databaseFile
* the database file.
* @param options
* database flags to use when opening the database GEOIP_STANDARD
* read database from disk GEOIP_MEMORY_CACHE cache the database
* in RAM and read it from RAM
* @throws IOException
* if an error occured creating the lookup service from the
* database file.
*/
public LookupService(File databaseFile, int options) throws IOException {
this.databaseFile = databaseFile;
file = new RandomAccessFile(databaseFile, "r");
dboptions = options;
init();
}
/**
* Reads meta-data from the database file.
*
* @throws IOException
* if an error occurs reading from the database file.
*/
private synchronized void init() throws IOException {
byte[] delim = new byte[3];
byte[] buf = new byte[SEGMENT_RECORD_LENGTH];
if (file == null) {
return;
}
if ((dboptions & GEOIP_CHECK_CACHE) != 0) {
mtime = databaseFile.lastModified();
}
file.seek(file.length() - 3);
for (int i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) {
file.readFully(delim);
if (delim[0] == -1 && delim[1] == -1 && delim[2] == -1) {
databaseType = file.readByte();
if (databaseType >= 106) {
// Backward compatibility with databases from April 2003 and
// earlier
databaseType -= 105;
}
// Determine the database type.
if (databaseType == DatabaseInfo.REGION_EDITION_REV0) {
databaseSegments = new int[1];
databaseSegments[0] = STATE_BEGIN_REV0;
recordLength = STANDARD_RECORD_LENGTH;
} else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) {
databaseSegments = new int[1];
databaseSegments[0] = STATE_BEGIN_REV1;
recordLength = STANDARD_RECORD_LENGTH;
} else if (databaseType == DatabaseInfo.CITY_EDITION_REV0
|| databaseType == DatabaseInfo.CITY_EDITION_REV1
|| databaseType == DatabaseInfo.ORG_EDITION
|| databaseType == DatabaseInfo.ORG_EDITION_V6
|| databaseType == DatabaseInfo.ISP_EDITION
|| databaseType == DatabaseInfo.ISP_EDITION_V6
|| databaseType == DatabaseInfo.DOMAIN_EDITION
|| databaseType == DatabaseInfo.DOMAIN_EDITION_V6
|| databaseType == DatabaseInfo.ASNUM_EDITION
|| databaseType == DatabaseInfo.ASNUM_EDITION_V6
|| databaseType == DatabaseInfo.NETSPEED_EDITION_REV1
|| databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6
|| databaseType == DatabaseInfo.CITY_EDITION_REV0_V6
|| databaseType == DatabaseInfo.CITY_EDITION_REV1_V6) {
databaseSegments = new int[1];
databaseSegments[0] = 0;
if (databaseType == DatabaseInfo.CITY_EDITION_REV0
|| databaseType == DatabaseInfo.CITY_EDITION_REV1
|| databaseType == DatabaseInfo.ASNUM_EDITION_V6
|| databaseType == DatabaseInfo.NETSPEED_EDITION_REV1
|| databaseType == DatabaseInfo.NETSPEED_EDITION_REV1_V6
|| databaseType == DatabaseInfo.CITY_EDITION_REV0_V6
|| databaseType == DatabaseInfo.CITY_EDITION_REV1_V6
|| databaseType == DatabaseInfo.ASNUM_EDITION) {
recordLength = STANDARD_RECORD_LENGTH;
} else {
recordLength = ORG_RECORD_LENGTH;
}
file.readFully(buf);
for (int j = 0; j < SEGMENT_RECORD_LENGTH; j++) {
databaseSegments[0] += (unsignedByteToInt(buf[j]) << (j * 8));
}
}
break;
} else {
file.seek(file.getFilePointer() - 4);
}
}
if ((databaseType == DatabaseInfo.COUNTRY_EDITION)
|| (databaseType == DatabaseInfo.COUNTRY_EDITION_V6)
|| (databaseType == DatabaseInfo.PROXY_EDITION)
|| (databaseType == DatabaseInfo.NETSPEED_EDITION)) {
databaseSegments = new int[1];
databaseSegments[0] = COUNTRY_BEGIN;
recordLength = STANDARD_RECORD_LENGTH;
}
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
int l = (int) file.length();
dbbuffer = new byte[l];
file.seek(0);
file.readFully(dbbuffer, 0, l);
databaseInfo = getDatabaseInfo();
file.close();
}
if ((dboptions & GEOIP_INDEX_CACHE) != 0) {
int l = databaseSegments[0] * recordLength * 2;
index_cache = new byte[l];
file.seek(0);
file.readFully(index_cache, 0, l);
} else {
index_cache = null;
}
}
/**
* Closes the lookup service.
*/
public synchronized void close() {
try {
if (file != null) {
file.close();
}
file = null;
} catch (IOException e) {
// Here for backward compatibility.
}
}
/**
* @return The list of all known country names
*/
public List<String> getAllCountryNames() {
return Arrays.asList(Arrays.copyOf(countryName, countryName.length));
}
/**
* @return The list of all known country codes
*/
public List<String> getAllCountryCodes() {
return Arrays.asList(Arrays.copyOf(countryCode, countryCode.length));
}
/**
* Returns the country the IP address is in.
*
* @param ipAddress
* String version of an IPv6 address, i.e. "::127.0.0.1"
* @return the country the IP address is from.
*/
public Country getCountryV6(String ipAddress) {
InetAddress addr;
try {
addr = InetAddress.getByName(ipAddress);
} catch (UnknownHostException e) {
return UNKNOWN_COUNTRY;
}
return getCountryV6(addr);
}
/**
* Returns the country the IP address is in.
*
* @param ipAddress
* String version of an IP address, i.e. "127.0.0.1"
* @return the country the IP address is from.
*/
public Country getCountry(String ipAddress) {
InetAddress addr;
try {
addr = InetAddress.getByName(ipAddress);
} catch (UnknownHostException e) {
return UNKNOWN_COUNTRY;
}
return getCountry(addr);
}
/**
* Returns the country the IP address is in.
*
* @param ipAddress
* the IP address.
* @return the country the IP address is from.
*/
public synchronized Country getCountry(InetAddress ipAddress) {
return getCountry(bytesToLong(ipAddress.getAddress()));
}
/**
* Returns the country the IP address is in.
*
* @param addr
* the IP address as Inet6Address.
* @return the country the IP address is from.
*/
public synchronized Country getCountryV6(InetAddress addr) {
if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) {
throw new IllegalStateException("Database has been closed.");
}
int ret = seekCountryV6(addr) - COUNTRY_BEGIN;
if (ret == 0) {
return UNKNOWN_COUNTRY;
} else {
return new Country(countryCode[ret], countryName[ret]);
}
}
/**
* Returns the country the IP address is in.
*
* @param ipAddress
* the IP address in long format.
* @return the country the IP address is from.
*/
public synchronized Country getCountry(long ipAddress) {
if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) {
throw new IllegalStateException("Database has been closed.");
}
int ret = seekCountry(ipAddress) - COUNTRY_BEGIN;
if (ret == 0) {
return UNKNOWN_COUNTRY;
} else {
return new Country(countryCode[ret], countryName[ret]);
}
}
/**
* I2P -
* Write all IPv4 address ranges for the given country to out.
*
* @param country two-letter case-insensitive
* @param out caller must close
* @since 0.9.48
*/
public synchronized void countryToIP(String country, Writer out) throws IOException {
if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) {
throw new IllegalStateException("Database has been closed.");
}
country = country.toUpperCase(Locale.US);
// get the country ID we're looking for
int id = 0;
for (int i = 0; i < countryCode.length; i++) {
if (countryCode[i].equals(country)) {
id = i;
break;
}
}
if (id <= 0)
return;
// segment
id += COUNTRY_BEGIN;
Walker walker = new Walker(id, out);
out.write("# IPs for country " + country + " from GeoIP database\n");
walker.walk();
}
/**
* I2P
* @since 0.9.48
*/
private class Walker {
private final int _country;
private final Writer _out;
private final byte[] _buf = new byte[2 * MAX_RECORD_LENGTH];
private final int[] _x = new int[2];
private final int _dbs0 = databaseSegments[0];
/**
* @param country the segment
*/
public Walker(int country, Writer out) throws IOException {
_country = country;
_out = out;
}
/** only call once */
public void walk() throws IOException {
walk(0, 0, 31);
}
/**
* Recursive, depth first
* @param ip big endian
*/
private void walk(int offset, int ip, int depth) throws IOException {
if (offset >= _dbs0) {
if (offset == _country) {
String sip = ((ip >> 24) & 0xff) + "." +
((ip >> 16) & 0xff) + '.' +
((ip >> 8) & 0xff) + '.' +
(ip & 0xff);
_out.write(sip);
if (depth >= 0) {
_out.write('/');
_out.write(Integer.toString(31 - depth));
}
_out.write('\n');
}
return;
}
if (depth < 0)
return;
readNode(_buf, _x, offset);
int x1 = _x[1];
walk(_x[0], ip, depth - 1);
ip |= 1 << depth;
walk(x1, ip, depth - 1);
}
}
public int getID(String ipAddress) {
InetAddress addr;
try {
addr = InetAddress.getByName(ipAddress);
} catch (UnknownHostException e) {
return 0;
}
return getID(bytesToLong(addr.getAddress()));
}
public int getID(InetAddress ipAddress) {
return getID(bytesToLong(ipAddress.getAddress()));
}
public synchronized int getID(long ipAddress) {
if (file == null && (dboptions & GEOIP_MEMORY_CACHE) == 0) {
throw new IllegalStateException("Database has been closed.");
}
return seekCountry(ipAddress) - databaseSegments[0];
}
public int last_netmask() {
return last_netmask;
}
public void netmask(int nm) {
last_netmask = nm;
}
/**
* Returns information about the database.
*
* @return database info.
*/
public synchronized DatabaseInfo getDatabaseInfo() {
if (databaseInfo != null) {
return databaseInfo;
}
try {
_check_mtime();
boolean hasStructureInfo = false;
byte[] delim = new byte[3];
// Advance to part of file where database info is stored.
file.seek(file.length() - 3);
for (int i = 0; i < STRUCTURE_INFO_MAX_SIZE; i++) {
int read = file.read(delim);
if (read == 3 && (delim[0] & 0xFF) == 255
&& (delim[1] & 0xFF) == 255 && (delim[2] & 0xFF) == 255) {
hasStructureInfo = true;
break;
}
file.seek(file.getFilePointer() - 4);
}
if (hasStructureInfo) {
file.seek(file.getFilePointer() - 6);
} else {
// No structure info, must be pre Sep 2002 database, go back to
// end.
file.seek(file.length() - 3);
}
// Find the database info string.
for (int i = 0; i < DATABASE_INFO_MAX_SIZE; i++) {
file.readFully(delim);
if (delim[0] == 0 && delim[1] == 0 && delim[2] == 0) {
byte[] dbInfo = new byte[i];
file.readFully(dbInfo);
// Create the database info object using the string.
databaseInfo = new DatabaseInfo(new String(dbInfo, charset));
return databaseInfo;
}
file.seek(file.getFilePointer() - 4);
}
} catch (IOException e) {
throw new InvalidDatabaseException("Error reading database info", e);
}
return new DatabaseInfo("");
}
synchronized void _check_mtime() {
try {
if ((dboptions & GEOIP_CHECK_CACHE) != 0) {
long t = databaseFile.lastModified();
if (t != mtime) {
/* GeoIP Database file updated */
/* refresh filehandle */
close();
file = new RandomAccessFile(databaseFile, "r");
databaseInfo = null;
init();
}
}
} catch (IOException e) {
throw new InvalidDatabaseException("Database not found", e);
}
}
// for GeoIP City only
public Location getLocationV6(String str) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
} catch (UnknownHostException e) {
return null;
}
return getLocationV6(addr);
}
// for GeoIP City only
public Location getLocation(InetAddress addr) {
return getLocation(bytesToLong(addr.getAddress()));
}
// for GeoIP City only
public Location getLocation(String str) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
} catch (UnknownHostException e) {
return null;
}
return getLocation(addr);
}
public synchronized Region getRegion(String str) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
} catch (UnknownHostException e) {
return null;
}
return getRegion(bytesToLong(addr.getAddress()));
}
public synchronized Region getRegion(InetAddress addr) {
return getRegion(bytesToLong(addr.getAddress()));
}
public synchronized Region getRegion(long ipnum) {
Region record = new Region();
int seek_region;
if (databaseType == DatabaseInfo.REGION_EDITION_REV0) {
seek_region = seekCountry(ipnum) - STATE_BEGIN_REV0;
char[] ch = new char[2];
if (seek_region >= 1000) {
record.countryCode = "US";
record.countryName = "United States";
ch[0] = (char) (((seek_region - 1000) / 26) + 65);
ch[1] = (char) (((seek_region - 1000) % 26) + 65);
record.region = new String(ch);
} else {
record.countryCode = countryCode[seek_region];
record.countryName = countryName[seek_region];
record.region = "";
}
} else if (databaseType == DatabaseInfo.REGION_EDITION_REV1) {
seek_region = seekCountry(ipnum) - STATE_BEGIN_REV1;
char[] ch = new char[2];
if (seek_region < US_OFFSET) {
record.countryCode = "";
record.countryName = "";
record.region = "";
} else if (seek_region < CANADA_OFFSET) {
record.countryCode = "US";
record.countryName = "United States";
ch[0] = (char) (((seek_region - US_OFFSET) / 26) + 65);
ch[1] = (char) (((seek_region - US_OFFSET) % 26) + 65);
record.region = new String(ch);
} else if (seek_region < WORLD_OFFSET) {
record.countryCode = "CA";
record.countryName = "Canada";
ch[0] = (char) (((seek_region - CANADA_OFFSET) / 26) + 65);
ch[1] = (char) (((seek_region - CANADA_OFFSET) % 26) + 65);
record.region = new String(ch);
} else {
record.countryCode = countryCode[(seek_region - WORLD_OFFSET)
/ FIPS_RANGE];
record.countryName = countryName[(seek_region - WORLD_OFFSET)
/ FIPS_RANGE];
record.region = "";
}
}
return record;
}
public synchronized Location getLocationV6(InetAddress addr) {
int seek_country;
try {
seek_country = seekCountryV6(addr);
return readCityRecord(seek_country);
} catch (IOException e) {
throw new InvalidDatabaseException("Error while seting up segments", e);
}
}
public synchronized Location getLocation(long ipnum) {
int seek_country;
try {
seek_country = seekCountry(ipnum);
return readCityRecord(seek_country);
} catch (IOException e) {
throw new InvalidDatabaseException("Error while seting up segments", e);
}
}
private Location readCityRecord(int seekCountry) throws IOException {
if (seekCountry == databaseSegments[0]) {
return null;
}
ByteBuffer buffer = readRecordBuf(seekCountry, FULL_RECORD_LENGTH);
Location record = new Location();
int country = unsignedByteToInt(buffer.get());
// get country
record.countryCode = countryCode[country];
record.countryName = countryName[country];
record.region = readString(buffer);
record.city = readString(buffer);
record.postalCode = readString(buffer);
record.latitude = readAngle(buffer);
record.longitude = readAngle(buffer);
if (databaseType == DatabaseInfo.CITY_EDITION_REV1) {
// get DMA code
if ("US".equals(record.countryCode)) {
int metroarea_combo = readMetroAreaCombo(buffer);
record.metro_code = record.dma_code = metroarea_combo / 1000;
record.area_code = metroarea_combo % 1000;
}
}
return record;
}
private ByteBuffer readRecordBuf(int seek, int maxLength) throws IOException {
int recordPointer = seek + (2 * recordLength - 1)
* databaseSegments[0];
ByteBuffer buffer;
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
buffer = ByteBuffer.wrap(dbbuffer, recordPointer, Math
.min(dbbuffer.length - recordPointer, maxLength));
} else {
byte[] recordBuf = new byte[maxLength];
// read from disk
file.seek(recordPointer);
file.read(recordBuf);
buffer = ByteBuffer.wrap(recordBuf);
}
return buffer;
}
private String readString(ByteBuffer buffer) throws CharacterCodingException {
int start = buffer.position();
int oldLimit = buffer.limit();
while (buffer.hasRemaining() && buffer.get() != 0) {}
int end = buffer.position() - 1;
String str = null;
if (end > start) {
buffer.position(start);
buffer.limit(end);
str = charsetDecoder.decode(buffer).toString();
buffer.limit(oldLimit);
}
buffer.position(end + 1);
return str;
}
private static float readAngle(ByteBuffer buffer) {
if (buffer.remaining() < 3) {
throw new InvalidDatabaseException("Unexpected end of data record when reading angle");
}
double num = 0;
for (int j = 0; j < 3; j++) {
num += unsignedByteToInt(buffer.get()) << (j * 8);
}
return (float) num / 10000 - 180;
}
private static int readMetroAreaCombo(ByteBuffer buffer) {
if (buffer.remaining() < 3) {
throw new InvalidDatabaseException("Unexpected end of data record when reading metro area");
}
int metroareaCombo = 0;
for (int j = 0; j < 3; j++) {
metroareaCombo += unsignedByteToInt(buffer.get()) << (j * 8);
}
return metroareaCombo;
}
public String getOrg(InetAddress addr) {
return getOrg(bytesToLong(addr.getAddress()));
}
public String getOrg(String str) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
} catch (UnknownHostException e) {
return null;
}
return getOrg(addr);
}
// GeoIP Organization and ISP Edition methods
public synchronized String getOrg(long ipnum) {
try {
int seekOrg = seekCountry(ipnum);
return readOrgRecord(seekOrg);
} catch (IOException e) {
throw new InvalidDatabaseException("Error while reading org", e);
}
}
public String getOrgV6(String str) {
InetAddress addr;
try {
addr = InetAddress.getByName(str);
} catch (UnknownHostException e) {
return null;
}
return getOrgV6(addr);
}
// GeoIP Organization and ISP Edition methods
public synchronized String getOrgV6(InetAddress addr) {
try {
int seekOrg = seekCountryV6(addr);
return readOrgRecord(seekOrg);
} catch (IOException e) {
throw new InvalidDatabaseException("Error while reading org", e);
}
}
private String readOrgRecord(int seekOrg) throws IOException {
if (seekOrg == databaseSegments[0]) {
return null;
}
ByteBuffer buf = readRecordBuf(seekOrg, MAX_ORG_RECORD_LENGTH);
return readString(buf);
}
/**
* Finds the country index value given an IPv6 address.
*
* @param addr
* the ip address to find in long format.
* @return the country index.
*/
private synchronized int seekCountryV6(InetAddress addr) {
byte[] v6vec = addr.getAddress();
if (v6vec.length == 4) {
// sometimes java returns an ipv4 address for IPv6 input
// we have to work around that feature
// It happens for ::ffff:24.24.24.24
byte[] t = new byte[16];
System.arraycopy(v6vec, 0, t, 12, 4);
v6vec = t;
}
byte[] buf = new byte[2 * MAX_RECORD_LENGTH];
int[] x = new int[2];
int offset = 0;
_check_mtime();
for (int depth = 127; depth >= 0; depth--) {
readNode(buf, x, offset);
int bnum = 127 - depth;
int idx = bnum >> 3;
int b_mask = 1 << (bnum & 7 ^ 7);
if ((v6vec[idx] & b_mask) > 0) {
if (x[1] >= databaseSegments[0]) {
last_netmask = 128 - depth;
return x[1];
}
offset = x[1];
} else {
if (x[0] >= databaseSegments[0]) {
last_netmask = 128 - depth;
return x[0];
}
offset = x[0];
}
}
throw new InvalidDatabaseException("Error seeking country while searching for "
+ addr.getHostAddress());
}
/**
* Finds the country index value given an IP address.
*
* @param ipAddress
* the ip address to find in long format.
* @return the country index.
*/
private synchronized int seekCountry(long ipAddress) {
byte[] buf = new byte[2 * MAX_RECORD_LENGTH];
int[] x = new int[2];
int offset = 0;
_check_mtime();
for (int depth = 31; depth >= 0; depth--) {
readNode(buf, x, offset);
if ((ipAddress & (1 << depth)) > 0) {
if (x[1] >= databaseSegments[0]) {
last_netmask = 32 - depth;
return x[1];
}
offset = x[1];
} else {
if (x[0] >= databaseSegments[0]) {
last_netmask = 32 - depth;
return x[0];
}
offset = x[0];
}
}
throw new InvalidDatabaseException("Error seeking country while searching for "
+ ipAddress);
}
private void readNode(byte[] buf, int[] x, int offset) {
if ((dboptions & GEOIP_MEMORY_CACHE) == 1) {
// read from memory
System.arraycopy(dbbuffer, (2 * recordLength * offset), buf, 0, 2 * recordLength);
} else if ((dboptions & GEOIP_INDEX_CACHE) != 0) {
// read from index cache
System.arraycopy(index_cache, (2 * recordLength * offset), buf, 0, 2 * recordLength);
} else {
// read from disk
try {
file.seek(2 * recordLength * offset);
file.read(buf);
} catch (IOException e) {
throw new InvalidDatabaseException("Error seeking in database", e);
}
}
for (int i = 0; i < 2; i++) {
x[i] = 0;
for (int j = 0; j < recordLength; j++) {
int y = buf[i * recordLength + j];
if (y < 0) {
y += 256;
}
x[i] += (y << (j * 8));
}
}
}
/**
* Returns the long version of an IP address given an InetAddress object.
*
* @param address
* the InetAddress.
* @return the long form of the IP address.
*/
private static long bytesToLong(byte[] address) {
long ipnum = 0;
for (int i = 0; i < 4; ++i) {
long y = address[i];
if (y < 0) {
y += 256;
}
ipnum += y << ((3 - i) * 8);
}
return ipnum;
}
private static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}
| i2p/i2p.i2p | router/java/src/com/maxmind/geoip/LookupService.java |
179,983 | package freenet.clients.http.geoip;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import freenet.clients.http.StaticToadlet;
import freenet.node.Node;
import freenet.support.HTMLNode;
import freenet.support.Logger;
public class IPConverter {
// Regex indicating ipranges start
private static final String START = "##start##";
final int MAX_ENTRIES = 100;
// Local cache
@SuppressWarnings("serial")
private final HashMap<Integer, Country> cache = new LinkedHashMap<Integer, Country>() {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Country> eldest) {
return size() > MAX_ENTRIES;
}
};
// Cached DB file content
private SoftReference<Cache> fullCache;
// Reference to singleton object
private static IPConverter instance;
// File containing IP ranges
private File dbFile;
private boolean dbFileCorrupt;
public enum Country {
L0("localhost"), I0("IntraNet"), A1("Anonymous Proxy"), A2(
"Satellite Provider"), AP("AP Asia/Pacific Region"), AF(
"AFGHANISTAN"), AX("ALAND ISLANDS"), AL("ALBANIA"), AN(
"NETHERLANDS ANTILLES"), DZ("ALGERIA"), AS("AMERICAN SAMOA"), AD(
"ANDORRA"), AO("ANGOLA"), AI("ANGUILLA"), AQ("ANTARCTICA"), AG(
"ANTIGUA AND BARBUDA"), AR("ARGENTINA"), AM("ARMENIA"), AW(
"ARUBA"), AU("AUSTRALIA"), AT("AUSTRIA"), AZ("AZERBAIJAN"), BS(
"BAHAMAS"), BH("BAHRAIN "), BD("BANGLADESH "), BB("BARBADOS "), BY(
"BELARUS "), BE("BELGIUM "), BZ("BELIZE "), BJ("BENIN "), BM(
"BERMUDA "), BT("BHUTAN "), BO(
"BOLIVIA, PLURINATIONAL STATE OF "), BQ(
"BONAIRE, SAINT EUSTATIUS AND SABA "), BA(
"BOSNIA AND HERZEGOVINA "), BW("BOTSWANA "), BV(
"BOUVET ISLAND "), BR("BRAZIL "), IO(
"BRITISH INDIAN OCEAN TERRITORY "), BN("BRUNEI DARUSSALAM "), BG(
"BULGARIA "), BF("BURKINA FASO "), BI("BURUNDI "), KH(
"CAMBODIA "), CM("CAMEROON "), CA("CANADA "), CV("CAPE VERDE "), KY(
"CAYMAN ISLANDS "), CF("CENTRAL AFRICAN REPUBLIC "), TD("CHAD "), CL(
"CHILE "), CN("CHINA "), CX("CHRISTMAS ISLAND "), CC(
"COCOS (KEELING) ISLANDS "), CO("COLOMBIA "), KM("COMOROS "), CG(
"CONGO "), CD("CONGO, THE DEMOCRATIC REPUBLIC OF THE "), CK(
"COOK ISLANDS "), CR("COSTA RICA "), CI("COTE D'IVOIRE "), HR(
"CROATIA "), CU("CUBA "), CW("CURACAO "), CY("CYPRUS "), CZ(
"CZECH REPUBLIC "), DK("DENMARK "), DJ("DJIBOUTI "), DM(
"DOMINICA "), DO("DOMINICAN REPUBLIC "), EC("ECUADOR "), EG(
"EGYPT "), SV("EL SALVADOR "), GQ("EQUATORIAL GUINEA "), ER(
"ERITREA "), EE("ESTONIA "), ET("ETHIOPIA "), FK(
"FALKLAND ISLANDS (MALVINAS) "), FO("FAROE ISLANDS "), FJ(
"FIJI "), FI("FINLAND "), FR("FRANCE "), GF("FRENCH GUIANA "), PF(
"FRENCH POLYNESIA "), TF("FRENCH SOUTHERN TERRITORIES "), GA(
"GABON "), GM("GAMBIA "), GE("GEORGIA "), DE("GERMANY "), GH(
"GHANA "), GI("GIBRALTAR "), GR("GREECE "), GL("GREENLAND "), GD(
"GRENADA "), GP("GUADELOUPE "), GU("GUAM "), GT("GUATEMALA "), GG(
"GUERNSEY "), GN("GUINEA "), GW("GUINEA-BISSAU "), GY("GUYANA "), HT(
"HAITI "), HM("HEARD ISLAND AND MCDONALD ISLANDS "), VA(
"HOLY SEE (VATICAN CITY STATE) "), HN("HONDURAS "), HK(
"HONG KONG "), HU("HUNGARY "), IS("ICELAND "), IN("INDIA "), ID(
"INDONESIA "), IR("IRAN, ISLAMIC REPUBLIC OF "), IQ("IRAQ "), IE(
"IRELAND "), IM("ISLE OF MAN "), IL("ISRAEL "), IT("ITALY "), JM(
"JAMAICA "), JP("JAPAN "), JE("JERSEY "), JO("JORDAN "), KZ(
"KAZAKHSTAN "), KE("KENYA "), KI("KIRIBATI "), KP(
"KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF "), KR(
"KOREA, REPUBLIC OF "), KW("KUWAIT "), KG("KYRGYZSTAN "), LA(
"LAO PEOPLE'S DEMOCRATIC REPUBLIC "), LV("LATVIA "), LB(
"LEBANON "), LS("LESOTHO "), LR("LIBERIA "), LY(
"LIBYAN ARAB JAMAHIRIYA "), LI("LIECHTENSTEIN "), LT(
"LITHUANIA "), LU("LUXEMBOURG "), MO("MACAO "), MK(
"MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF "), MG(
"MADAGASCAR "), MW("MALAWI "), MY("MALAYSIA "), MV("MALDIVES "), ML(
"MALI "), MT("MALTA "), MH("MARSHALL ISLANDS "), MQ(
"MARTINIQUE "), MR("MAURITANIA "), MU("MAURITIUS "), YT(
"MAYOTTE "), MX("MEXICO "), FM(
"MICRONESIA, FEDERATED STATES OF "), MD("MOLDOVA, REPUBLIC OF "), MC(
"MONACO "), MN("MONGOLIA "), ME("MONTENEGRO "), MS(
"MONTSERRAT "), MA("MOROCCO "), MZ("MOZAMBIQUE "), MM(
"MYANMAR "), NA("NAMIBIA "), NR("NAURU "), NP("NEPAL "), NL(
"NETHERLANDS "), NC("NEW CALEDONIA "), NZ("NEW ZEALAND "), NI(
"NICARAGUA "), NE("NIGER "), NG("NIGERIA "), NU("NIUE "), NF(
"NORFOLK ISLAND "), MP("NORTHERN MARIANA ISLANDS "), NO(
"NORWAY "), OM("OMAN "), PK("PAKISTAN "), PW("PALAU "), PS(
"PALESTINIAN TERRITORY, OCCUPIED "), PA("PANAMA "), PG(
"PAPUA NEW GUINEA "), PY("PARAGUAY "), PE("PERU "), PH(
"PHILIPPINES "), PN("PITCAIRN "), PL("POLAND "), PT("PORTUGAL "), PR(
"PUERTO RICO "), QA("QATAR "), RE("REUNION "), RO("ROMANIA "), RU(
"RUSSIAN FEDERATION "), RW("RWANDA "), BL("SAINT BARTHELEMY "), SH(
"SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA "), KN(
"SAINT KITTS AND NEVIS "), LC("SAINT LUCIA "), MF(
"SAINT MARTIN (FRENCH PART) "), PM("SAINT PIERRE AND MIQUELON "), VC(
"SAINT VINCENT AND THE GRENADINES "), WS("SAMOA "), SM(
"SAN MARINO "), ST("SAO TOME AND PRINCIPE "), SA(
"SAUDI ARABIA "), SN("SENEGAL "), RS("SERBIA "), SC(
"SEYCHELLES "), SL("SIERRA LEONE "), SG("SINGAPORE "), SX(
"SINT MAARTEN (DUTCH PART) "), SK("SLOVAKIA "), SI("SLOVENIA "), SB(
"SOLOMON ISLANDS "), SO("SOMALIA "), ZA("SOUTH AFRICA "), GS(
"SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS "), SS("SOUTH SUDAN"), ES(
"SPAIN "), LK("SRI LANKA "), SD("SUDAN "), SR("SURINAME "), SJ(
"SVALBARD AND JAN MAYEN "), SZ("SWAZILAND "), SE("SWEDEN "), CH(
"SWITZERLAND "), SY("SYRIAN ARAB REPUBLIC "), TW(
"TAIWAN, PROVINCE OF CHINA "), TJ("TAJIKISTAN "), TZ(
"TANZANIA, UNITED REPUBLIC OF "), TH("THAILAND "), TL(
"TIMOR-LESTE "), TG("TOGO "), TK("TOKELAU "), TO("TONGA "), TT(
"TRINIDAD AND TOBAGO "), TN("TUNISIA "), TR("TURKEY "), TM(
"TURKMENISTAN "), TC("TURKS AND CAICOS ISLANDS "), TV("TUVALU "), UG(
"UGANDA "), UA("UKRAINE "), AE("UNITED ARAB EMIRATES "), GB(
"UNITED KINGDOM "), US("UNITED STATES "), UM(
"UNITED STATES MINOR OUTLYING ISLANDS "), UY("URUGUAY "), UZ(
"UZBEKISTAN "), VU("VANUATU "), VE(
"VENEZUELA, BOLIVARIAN REPUBLIC OF "), VN("VIET NAM "), VG(
"VIRGIN ISLANDS, BRITISH "), VI("VIRGIN ISLANDS, U.S. "), WF(
"WALLIS AND FUTUNA "), EH("WESTERN SAHARA "), YE("YEMEN "), ZM(
"ZAMBIA "), ZW("ZIMBABWE "), ZZ("NA"), EU("European Union");
private String name;
private boolean hasFlag;
private boolean checkedHasFlag;
Country(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void renderFlagIcon(HTMLNode parent) {
String flagPath = getFlagIconPath();
if(flagPath != null)
parent.addChild("img", new String[] { "src", "class", "title" }, new String[] { StaticToadlet.ROOT_URL + flagPath, "flag", getName()});
}
public boolean hasFlagIcon() {
return getFlagIconPath() != null;
}
/** Doesn't check whether it exists. Relative to the top of staticfiles. */
private String flagIconPath() {
return "icon/flags/"+toString().toLowerCase()+".png";
}
/** Relative to top of static files */
public String getFlagIconPath() {
String flagPath = flagIconPath();
synchronized(this) {
if(!checkedHasFlag) {
hasFlag = StaticToadlet.haveFile(flagPath);
checkedHasFlag = true;
}
return hasFlag ? flagPath : null;
}
}
/** cached values(). Never modify or pass this array to outside code! */
private static final Country[] values = values();
}
// Base85 Decoding table
private final static char[] base85 = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '.', ',', ';', '\'', '"', '`', '<', '>', '{', '}',
'[', ']', '=', '+', '-', '~', '*', '@', '#', '%', '$', '&', '!',
'?' };
private final static int base = base85.length;
// XXX this is actually base86, not base85!
private final static byte[] base85inv = new byte [128-32];
static {
Arrays.fill(base85inv, (byte)-1);
for(int i = 0; i < base85.length; i++) {
assert(base85[i] >= (char)32 && base85[i] < (char)128);
base85inv[(int)base85[i]-32] = (byte)i;
}
}
/**
* Constructs a new {@link IPConverter}
*
* @param node
* reference to freenet {@link Node}
*/
private IPConverter(File dbFile) {
this.dbFile = dbFile;
}
/**
* Returns the reference to singleton object of this class.
*
* @return singleton object
*/
public static IPConverter getInstance(File file) {
if (instance == null) {
instance = new IPConverter(file);
} else if(!instance.getDBFile().equals(file)) {
instance = new IPConverter(file);
}
return instance;
}
/**
* Copies all IP ranges from given String to memory as a
* {@link WeakReference}.
*
* @param line
* {@link String} containing IP ranges
* @throws IOException
*/
private Cache readRanges() {
RandomAccessFile raf;
try {
raf = new RandomAccessFile(dbFile, "r");
String line;
do {
line = raf.readLine();
} while (!line.startsWith(START));
// Remove ##start##
line = line.substring(START.length());
// Count of entries (each being 7 Bytes)
int size = line.length() / 7;
// Arrays to form a Cache
short[] codes = new short[size];
int[] ips = new int[size];
// Read ips and add it to ip table
for (int i = 0, offset = 0; i < size; i++, offset += 7) {
// Code
String code = line.substring(offset, offset + 2);
// Ip
String ipcode = line.substring(offset + 2, offset + 7);
long ip = decodeBase85(ipcode.getBytes("ISO-8859-1"));
try {
Country country = Country.valueOf(code);
codes[i] = (short) country.ordinal();
} catch (IllegalArgumentException e) {
// Does not invalidate the whole file, just means the country list is out of date.
Logger.error(this, "Country not in list: "+code);
codes[i] = (short)-1;
}
ips[i] = (int)ip;
}
raf.close();
return new Cache(codes, ips);
} catch (FileNotFoundException e) {
// Not downloaded yet
Logger.warning(this, "Database file not found!", e);
} catch (IOException e) {
Logger.error(this, e.getMessage());
} catch (IPConverterParseException e) {
Logger.error(this, "IP to country datbase file is corrupt: "+e, e);
// Don't try again until next restart.
// FIXME add a callback to clear the flag when we download a new copy.
dbFileCorrupt = true;
}
return null;
}
/**
* Converts a given IP4 in a long number
*
* @param ip
* IP in "XX.XX.XX.XX" format
* @return IP in long format
* @throws NumberFormatException If the string is not an IP address.
*/
public long ip2num(String ip) {
String[] split = ip.split("\\.");
if(split.length != 4) throw new NumberFormatException();
long num = 0;
long coef = (256 << 16);
for (int i = 0; i < split.length; i++) {
long modulo = Integer.parseInt(split[i]) % 256;
num += (modulo * coef);
coef >>= 8;
}
return num;
}
/**
* Returns a {@link Country} respecting given IP4.
*
* @param ip
* IP in "XX.XX.XX.XX" format
* @return {@link Country} of given IP, or null if the passed in string is
* not an IP address or we fail to load the ip to country data file.
* @throws IOException
*/
public Country locateIP(String ip) {
if(ip == null) return null;
long longip;
try {
longip = ip2num(ip);
} catch (NumberFormatException e) {
return null; // Not an IP address.
}
return locateIP(longip);
}
public Country locateIP(byte[] ip) {
if(ip == null) return null;
if(ip.length == 16) {
/* Convert some special IPv6 addresses to IPv4 */
if(ip[0] == (byte)0x20 && ip[1] == (byte)0x02) {
// 2002::/16, 6to4 tunnels
ip = Arrays.copyOfRange(ip, 2,6);
} else if(( ip[ 0] == (byte)0 && ip[ 1] == (byte)0 &&
ip[ 2] == (byte)0 && ip[ 3] == (byte)0 &&
ip[ 4] == (byte)0 && ip[ 5] == (byte)0 &&
ip[ 6] == (byte)0 && ip[ 7] == (byte)0 &&
ip[ 8] == (byte)0 && ip[ 9] == (byte)0 &&
ip[10] == (byte)0 && ip[11] == (byte)0)) {
// ::/96, deprecated IPv4-compatible IPv6
ip = Arrays.copyOfRange(ip, 12,16);
} else if(( ip[0] == (byte)0x20 && ip[1] == (byte)0x01 &&
ip[2] == (byte)0x00 && ip[3] == (byte)0x00)) {
// 2001:0::/32, Teredo tunnels
// 4..8 = server adderss
// 9..10 = flags
// 10..11 = client port (inverted)
// 12..16 = client address (inverted)
ip = Arrays.copyOfRange(ip, 12, 16);
ip[0] ^= (byte)0xff; // deinvert
ip[1] ^= (byte)0xff;
ip[2] ^= (byte)0xff;
ip[3] ^= (byte)0xff;
}
/* we cannot handle other IPv6 addresses (yet) */
}
if(ip.length != 4) return null;
long longip = (
((ip[0] << 24) & 0xff000000l) |
((ip[1] << 16) & 0x00ff0000l) |
((ip[2] << 8) & 0x0000ff00l) |
( ip[3] & 0x000000ffl));
return locateIP(longip);
}
private Country locateIP(long longip) {
// Check cache first
Country cached = cache.get((int)longip);
if (cached != null) {
return cached;
}
Cache memCache = getCache();
if(memCache == null) return null;
int[] ips = memCache.getIps();
short[] codes = memCache.getCodes();
// Binary search
int start = 0;
int last = ips.length - 1;
int mid;
while ((mid = (last - start) / 2) > 0) {
int midpos = mid + start;
long midip = ips[midpos] & 0xffffffffl;
if (longip >= midip) {
last = midpos;
} else {
start = midpos;
}
}
short countryOrdinal = codes[last];
if(countryOrdinal < 0) return null;
Country country = Country.values[countryOrdinal];
cache.put((int)longip, country);
return country;
}
/**
* Returns {@link Cache} containing IPranges
*
* @return {@link Cache}
*/
private Cache getCache() {
Cache memCache = null;
synchronized (IPConverter.class) {
if(fullCache != null)
memCache = fullCache.get();
if(memCache == null) {
if(dbFileCorrupt) return null;
fullCache = new SoftReference<Cache>(memCache = readRanges());
}
}
return memCache;
}
/**
* Decodes a ASCII85 code into a long number.
*
* @param code
* encoded bytes
* @return decoded long
* @throws IPConverterParseException
*/
private long decodeBase85(byte[] code) throws IPConverterParseException {
long result = 0;
if (code.length != 5)
throw new IPConverterParseException();
for (int i = 0; i < code.length; i++) {
if (code[i] < (byte)32 || base85inv[code[i] - 32] < (byte)0)
throw new IPConverterParseException();
result = (result * base) + base85inv[code[i] - 32];
}
return result;
}
/**
* Returns database file containing IP ranges
* @return database file
*/
File getDBFile() {
return this.dbFile;
}
}
| hyphanet/fred | src/freenet/clients/http/geoip/IPConverter.java |
179,984 | /*
* This file is part of lanterna (https://github.com/mabe02/lanterna).
*
* lanterna is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2010-2020 Martin Berglund
*/
package com.googlecode.lanterna.screen;
import com.googlecode.lanterna.TextCharacter;
import com.googlecode.lanterna.graphics.Scrollable;
import com.googlecode.lanterna.graphics.TextGraphics;
import com.googlecode.lanterna.input.InputProvider;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;
import java.io.Closeable;
import java.io.IOException;
/**
* Screen is a fundamental layer in Lanterna, presenting the terminal as a bitmap-like surface where you can perform
* smaller in-memory operations to a back-buffer, effectively painting out the terminal as you'd like it, and then call
* {@code refresh} to have the screen automatically apply the changes in the back-buffer to the real terminal. The
* screen tracks what's visible through a front-buffer, but this is completely managed internally and cannot be expected
* to know what the terminal looks like if it's being modified externally.
* <p>
* If you want to do more complicated drawing operations, please see the class {@code DefaultScreenWriter} which has many
* utility methods that works on Screens.
*
* @author Martin
*/
public interface Screen extends InputProvider, Scrollable, Closeable {
/**
* This is the character Screen implementations should use as a filler is there are areas not set to any particular
* character.
*/
TextCharacter DEFAULT_CHARACTER = new TextCharacter(' ');
/**
* Before you can use a Screen, you need to start it. By starting the screen, Lanterna will make sure the terminal
* is in private mode (Screen only supports private mode), clears it (so that is can set the front and back buffers
* to a known value) and places the cursor in the top left corner. After calling startScreen(), you can begin using
* the other methods on this interface. When you want to exit from the screen and return to what you had before,
* you can call {@code stopScreen()}.
*
* @throws IOException if there was an underlying IO error when exiting from private mode
*/
void startScreen() throws IOException;
/**
* Same as calling {@link #stopScreen()} and then closing the underlying
* {@link com.googlecode.lanterna.terminal.Terminal} (where applicable), which will restore things like echo mode,
* icanon and other tty properties
*
* @throws IOException if there was an underlying IO error when exiting from private mode or closing the terminal
*/
@Override
void close() throws IOException;
/**
* Calling this method will make the underlying terminal leave private mode, effectively going back to whatever
* state the terminal was in before calling {@code startScreen()}. Once a screen has been stopped, you can start it
* again with {@code startScreen()} which will restore the screens content to the terminal.
*
* @throws IOException if there was an underlying IO error when exiting from private mode
*/
void stopScreen() throws IOException;
/**
* Erases all the characters on the screen, effectively giving you a blank area. The default background color will
* be used. This is effectively the same as calling
* <pre>fill(TerminalPosition.TOP_LEFT_CORNER, getSize(), TextColor.ANSI.Default)</pre>.
* <p>
* Please note that calling this method will only affect the back buffer, you need to call refresh to make the
* change visible.
*/
void clear();
/**
* A screen implementation typically keeps a location on the screen where the cursor will be placed after drawing
* and refreshing the buffers, this method returns that location. If it returns null, it means that the terminal
* will attempt to hide the cursor (if supported by the terminal).
*
* @return Position where the cursor will be located after the screen has been refreshed or {@code null} if the
* cursor is not visible
*/
TerminalPosition getCursorPosition();
/**
* A screen implementation typically keeps a location on the screen where the cursor will be placed after drawing
* and refreshing the buffers, this method controls that location. If you pass null, it means that the terminal
* will attempt to hide the cursor (if supported by the terminal).
*
* @param position TerminalPosition of the new position where the cursor should be placed after refresh(), or if
* {@code null}, hides the cursor
*/
void setCursorPosition(TerminalPosition position);
/**
* Gets the behaviour for what to do about tab characters. If a tab character is written to the Screen, it would
* cause issues because we don't know how the terminal emulator would render it and we wouldn't know what state the
* front-buffer is in. Because of this, we convert tabs to a determined number of spaces depending on different
* rules that are available.
*
* @return Tab behaviour that is used currently
* @see TabBehaviour
*/
TabBehaviour getTabBehaviour();
/**
* Sets the behaviour for what to do about tab characters. If a tab character is written to the Screen, it would
* cause issues because we don't know how the terminal emulator would render it and we wouldn't know what state the
* front-buffer is in. Because of this, we convert tabs to a determined number of spaces depending on different
* rules that are available.
*
* @param tabBehaviour Tab behaviour to use when converting a \t character to a spaces
* @see TabBehaviour
*/
void setTabBehaviour(TabBehaviour tabBehaviour);
/**
* Returns the size of the screen. This call is not blocking but should return the size of the screen as it is
* represented by the buffer at the time this method is called.
*
* @return Size of the screen, in columns and rows
*/
TerminalSize getTerminalSize();
/**
* Sets a character in the back-buffer to a specified value with specified colors and modifiers.
* @param column Column of the character to modify (x coordinate)
* @param row Row of the character to modify (y coordinate)
* @param screenCharacter New data to put at the specified position
*/
void setCharacter(int column, int row, TextCharacter screenCharacter);
/**
* Sets a character in the back-buffer to a specified value with specified colors and modifiers.
* @param position Which position in the terminal to modify
* @param screenCharacter New data to put at the specified position
*/
void setCharacter(TerminalPosition position, TextCharacter screenCharacter);
/**
* Creates a new TextGraphics objects that is targeting this Screen for writing to. Any operations done on this
* TextGraphics will be affecting this screen. Remember to call {@code refresh()} on the screen to see your changes.
*
* @return New TextGraphic object targeting this Screen
*/
TextGraphics newTextGraphics();
/**
* Reads a character and its associated meta-data from the front-buffer and returns it encapsulated as a
* ScreenCharacter.
* @param column Which column to get the character from
* @param row Which row to get the character from
* @return A {@code ScreenCharacter} representation of the character in the front-buffer at the specified location
*/
TextCharacter getFrontCharacter(int column, int row);
/**
* Reads a character and its associated meta-data from the front-buffer and returns it encapsulated as a
* ScreenCharacter.
* @param position What position to read the character from
* @return A {@code ScreenCharacter} representation of the character in the front-buffer at the specified location
*/
TextCharacter getFrontCharacter(TerminalPosition position);
/**
* Reads a character and its associated meta-data from the back-buffer and returns it encapsulated as a
* ScreenCharacter.
* @param column Which column to get the character from
* @param row Which row to get the character from
* @return A {@code ScreenCharacter} representation of the character in the back-buffer at the specified location
*/
TextCharacter getBackCharacter(int column, int row);
/**
* Reads a character and its associated meta-data from the back-buffer and returns it encapsulated as a
* ScreenCharacter.
* @param position What position to read the character from
* @return A {@code ScreenCharacter} representation of the character in the back-buffer at the specified location
*/
TextCharacter getBackCharacter(TerminalPosition position);
/**
* This method will take the content from the back-buffer and move it into the front-buffer, making the changes
* visible to the terminal in the process. The graphics workflow with Screen would involve drawing text and text-like
* graphics on the back buffer and then finally calling refresh(..) to make it visible to the user.
* @throws java.io.IOException If there was an underlying I/O error
* @see RefreshType
*/
void refresh() throws IOException;
/**
* This method will take the content from the back-buffer and move it into the front-buffer, making the changes
* visible to the terminal in the process. The graphics workflow with Screen would involve drawing text and text-like
* graphics on the back buffer and then finally calling refresh(..) to make it visible to the user.
* <p>
* Using this method call instead of {@code refresh()} gives you a little bit more control over how the screen will
* be refreshed.
* @param refreshType What type of refresh to do
* @throws java.io.IOException If there was an underlying I/O error
* @see RefreshType
*/
void refresh(RefreshType refreshType) throws IOException;
/**
* One problem working with Screens is that whenever the terminal is resized, the front and back buffers needs to be
* adjusted accordingly and the program should have a chance to figure out what to do with this extra space (or less
* space). The solution is to call, at the start of your rendering code, this method, which will check if the
* terminal has been resized and in that case update the internals of the Screen. After this call finishes, the
* screen's internal buffers will match the most recent size report from the underlying terminal.
*
* @return If the terminal has been resized since this method was last called, it will return the new size of the
* terminal. If not, it will return null.
*/
TerminalSize doResizeIfNecessary();
/**
* Scroll a range of lines of this Screen according to given distance.
*
* Screen implementations of this method do <b>not</b> throw IOException.
*/
@Override
void scrollLines(int firstLine, int lastLine, int distance);
/**
* This enum represents the different ways a Screen can refresh the screen, moving the back-buffer data into the
* front-buffer that is being displayed.
*/
enum RefreshType {
/**
* Using automatic mode, the Screen will make a guess at which refresh type would be the fastest and use this one.
*/
AUTOMATIC,
/**
* In {@code RefreshType.DELTA} mode, the Screen will calculate a diff between the back-buffer and the
* front-buffer, then figure out the set of terminal commands that is required to make the front-buffer exactly
* like the back-buffer. This normally works well when you have modified only parts of the screen, but if you
* have modified almost everything it will cause a lot of overhead and you should use
* {@code RefreshType.COMPLETE} instead.
*/
DELTA,
/**
* In {@code RefreshType.COMPLETE} mode, the screen will send a clear command to the terminal, then redraw the
* whole back-buffer line by line. This is more expensive than {@code RefreshType.COMPLETE}, especially when you
* have only touched smaller parts of the screen, but can be faster if you have modified most of the content,
* as well as if you suspect the screen's internal front buffer is out-of-sync with what's really showing on the
* terminal (you didn't go and call methods on the underlying Terminal while in screen mode, did you?)
*/
COMPLETE,
;
}
}
| mabe02/lanterna | src/main/java/com/googlecode/lanterna/screen/Screen.java |
179,985 | package org.osmdroid.views.overlay;
import android.graphics.Color;
import android.graphics.Paint;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import java.util.ArrayList;
import java.util.List;
/**
* A polygon on the earth's surface that can have a
* popup-{@link org.osmdroid.views.overlay.infowindow.InfoWindow} (a bubble).
* <p>
* Mimics the Polygon class from Google Maps Android API v2 as much as possible. Main differences:<br>
* - Doesn't support: Z-Index, Geodesic mode<br>
* - Supports InfoWindow.
*
* <img alt="Class diagram around Marker class" width="686" height="413" src='src='./doc-files/marker-infowindow-classes.png' />
*
* @author Viesturs Zarins, Martin Pearman for efficient PathOverlay.draw method
* @author M.Kergall: transformation from PathOverlay to Polygon
* @see <a href="http://developer.android.com/reference/com/google/android/gms/maps/model/Polygon.html">Google Maps Polygon</a>
*/
public class Polygon extends PolyOverlayWithIW {
protected OnClickListener mOnClickListener;
// ===========================================================
// Constructors
// ===========================================================
public Polygon() {
this(null);
}
public Polygon(MapView mapView) {
super(mapView, true, true);
mFillPaint = new Paint();
mFillPaint.setColor(Color.TRANSPARENT);
mFillPaint.setStyle(Paint.Style.FILL);
mOutlinePaint.setColor(Color.BLACK);
mOutlinePaint.setStrokeWidth(10.0f);
mOutlinePaint.setStyle(Paint.Style.STROKE);
mOutlinePaint.setAntiAlias(true);
}
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* @deprecated Use {@link #getFillPaint()} instead
*/
@Deprecated
public int getFillColor() {
return mFillPaint.getColor();
}
/**
* @deprecated Use {@link #getOutlinePaint()} instead
*/
@Deprecated
public int getStrokeColor() {
return mOutlinePaint.getColor();
}
/**
* @deprecated Use {@link #getOutlinePaint()} instead
*/
@Deprecated
public float getStrokeWidth() {
return mOutlinePaint.getStrokeWidth();
}
/**
* @return the Paint used for the filling. This allows to set advanced Paint settings.
* @since 6.0.2
*/
public Paint getFillPaint() {
return super.getFillPaint(); // public instead of protected
}
/**
* @return the list of polygon's vertices.
* Warning: changes on this list may cause strange results on the polygon display.
* @deprecated Use {@link PolyOverlayWithIW#getActualPoints()} instead
*/
@Deprecated
public List<GeoPoint> getPoints() {
return getActualPoints();
}
/**
* @deprecated Use {@link #getFillPaint()} instead
*/
@Deprecated
public void setFillColor(final int fillColor) {
mFillPaint.setColor(fillColor);
}
/**
* @deprecated Use {@link #getOutlinePaint()} instead
*/
@Deprecated
public void setStrokeColor(final int color) {
mOutlinePaint.setColor(color);
}
/**
* @deprecated Use {@link #getOutlinePaint()} instead
*/
@Deprecated
public void setStrokeWidth(final float width) {
mOutlinePaint.setStrokeWidth(width);
}
public void setHoles(List<? extends List<GeoPoint>> holes) {
mHoles = new ArrayList<>(holes.size());
for (List<GeoPoint> sourceHole : holes) {
LinearRing newHole = new LinearRing(mPath);
newHole.setGeodesic(mOutline.isGeodesic());
newHole.setPoints(sourceHole);
mHoles.add(newHole);
}
}
/**
* returns a copy of the holes this polygon contains
*
* @return never null
*/
public List<List<GeoPoint>> getHoles() {
List<List<GeoPoint>> result = new ArrayList<>(mHoles.size());
for (LinearRing hole : mHoles) {
result.add(hole.getPoints());
//TODO: completely wrong:
// hole.getPoints() doesn't return a copy but a direct handler to the internal list.
// - if geodesic, this is not the same points as the original list.
}
return result;
}
/**
* Build a list of GeoPoint as a circle.
*
* @param center center of the circle
* @param radiusInMeters
* @return the list of GeoPoint
*/
public static ArrayList<GeoPoint> pointsAsCircle(GeoPoint center, double radiusInMeters) {
ArrayList<GeoPoint> circlePoints = new ArrayList<GeoPoint>(360 / 6);
for (int f = 0; f < 360; f += 6) {
GeoPoint onCircle = center.destinationPoint(radiusInMeters, f);
circlePoints.add(onCircle);
}
return circlePoints;
}
/**
* Build a list of GeoPoint as a rectangle.
*
* @param rectangle defined as a BoundingBox
* @return the list of 4 GeoPoint
*/
public static ArrayList<IGeoPoint> pointsAsRect(BoundingBox rectangle) {
ArrayList<IGeoPoint> points = new ArrayList<IGeoPoint>(4);
points.add(new GeoPoint(rectangle.getLatNorth(), rectangle.getLonWest()));
points.add(new GeoPoint(rectangle.getLatNorth(), rectangle.getLonEast()));
points.add(new GeoPoint(rectangle.getLatSouth(), rectangle.getLonEast()));
points.add(new GeoPoint(rectangle.getLatSouth(), rectangle.getLonWest()));
return points;
}
/**
* Build a list of GeoPoint as a rectangle.
*
* @param center of the rectangle
* @param lengthInMeters on longitude
* @param widthInMeters on latitude
* @return the list of 4 GeoPoint
*/
public static ArrayList<IGeoPoint> pointsAsRect(GeoPoint center, double lengthInMeters, double widthInMeters) {
ArrayList<IGeoPoint> points = new ArrayList<IGeoPoint>(4);
GeoPoint east = center.destinationPoint(lengthInMeters * 0.5, 90.0f);
GeoPoint south = center.destinationPoint(widthInMeters * 0.5, 180.0f);
double westLon = center.getLongitude() * 2 - east.getLongitude();
double northLat = center.getLatitude() * 2 - south.getLatitude();
points.add(new GeoPoint(south.getLatitude(), east.getLongitude()));
points.add(new GeoPoint(south.getLatitude(), westLon));
points.add(new GeoPoint(northLat, westLon));
points.add(new GeoPoint(northLat, east.getLongitude()));
return points;
}
@Override
public void onDetach(MapView mapView) {
super.onDetach(mapView);
mOnClickListener = null;
}
//-- Polygon events listener interfaces ------------------------------------
public interface OnClickListener {
boolean onClick(Polygon polygon, MapView mapView, GeoPoint eventPos);
}
/**
* default behaviour when no click listener is set
*/
public boolean onClickDefault(Polygon polygon, MapView mapView, GeoPoint eventPos) {
polygon.setInfoWindowLocation(eventPos);
polygon.showInfoWindow();
return true;
}
/**
* @param listener
* @since 6.0.2
*/
public void setOnClickListener(OnClickListener listener) {
mOnClickListener = listener;
}
/**
* @since 6.2.0
*/
@Override
protected boolean click(final MapView pMapView, final GeoPoint pEventPos) {
if (mOnClickListener == null) {
return onClickDefault(this, pMapView, pEventPos);
} else {
return mOnClickListener.onClick(this, pMapView, pEventPos);
}
}
}
| osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/views/overlay/Polygon.java |
179,986 | package soot.options;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
/* THIS FILE IS AUTO-GENERATED FROM soot_options.xml. DO NOT MODIFY. */
import soot.*;
import java.util.*;
/**
* Soot command-line options parser.
*
* @author Ondrej Lhotak
*/
@jakarta.annotation.Generated(value = "Saxonica v3.0", comments = "from soot_options.xml")
public class Options extends OptionsBase {
public Options(Singletons.Global g) {
}
public static Options v() {
return G.v().soot_options_Options();
}
public static final int src_prec_c = 1;
public static final int src_prec_class = 1;
public static final int src_prec_only_class = 2;
public static final int src_prec_J = 3;
public static final int src_prec_jimple = 3;
public static final int src_prec_java = 4;
public static final int src_prec_apk = 5;
public static final int src_prec_apk_class_jimple = 6;
public static final int src_prec_apk_c_j = 6;
public static final int src_prec_dotnet = 7;
public static final int output_format_J = 1;
public static final int output_format_jimple = 1;
public static final int output_format_j = 2;
public static final int output_format_jimp = 2;
public static final int output_format_S = 3;
public static final int output_format_shimple = 3;
public static final int output_format_s = 4;
public static final int output_format_shimp = 4;
public static final int output_format_B = 5;
public static final int output_format_baf = 5;
public static final int output_format_b = 6;
public static final int output_format_G = 7;
public static final int output_format_grimple = 7;
public static final int output_format_g = 8;
public static final int output_format_grimp = 8;
public static final int output_format_X = 9;
public static final int output_format_xml = 9;
public static final int output_format_dex = 10;
public static final int output_format_force_dex = 11;
public static final int output_format_n = 12;
public static final int output_format_none = 12;
public static final int output_format_jasmin = 13;
public static final int output_format_c = 14;
public static final int output_format_class = 14;
public static final int output_format_d = 15;
public static final int output_format_dava = 15;
public static final int output_format_t = 16;
public static final int output_format_template = 16;
public static final int output_format_a = 17;
public static final int output_format_asm = 17;
public static final int java_version_default = 1;
public static final int java_version_1_1 = 2;
public static final int java_version_1 = 2;
public static final int java_version_1_2 = 3;
public static final int java_version_2 = 3;
public static final int java_version_1_3 = 4;
public static final int java_version_3 = 4;
public static final int java_version_1_4 = 5;
public static final int java_version_4 = 5;
public static final int java_version_1_5 = 6;
public static final int java_version_5 = 6;
public static final int java_version_1_6 = 7;
public static final int java_version_6 = 7;
public static final int java_version_1_7 = 8;
public static final int java_version_7 = 8;
public static final int java_version_1_8 = 9;
public static final int java_version_8 = 9;
public static final int java_version_1_9 = 10;
public static final int java_version_9 = 10;
public static final int java_version_1_10 = 11;
public static final int java_version_10 = 11;
public static final int java_version_1_11 = 12;
public static final int java_version_11 = 12;
public static final int java_version_1_12 = 13;
public static final int java_version_12 = 13;
public static final int wrong_staticness_fail = 1;
public static final int wrong_staticness_ignore = 2;
public static final int wrong_staticness_fix = 3;
public static final int wrong_staticness_fixstrict = 4;
public static final int field_type_mismatches_fail = 1;
public static final int field_type_mismatches_ignore = 2;
public static final int field_type_mismatches_null = 3;
public static final int throw_analysis_pedantic = 1;
public static final int throw_analysis_unit = 2;
public static final int throw_analysis_dalvik = 3;
public static final int throw_analysis_dotnet = 4;
public static final int throw_analysis_auto_select = 5;
public static final int check_init_throw_analysis_auto = 1;
public static final int check_init_throw_analysis_pedantic = 2;
public static final int check_init_throw_analysis_unit = 3;
public static final int check_init_throw_analysis_dalvik = 4;
public static final int check_init_throw_analysis_dotnet = 5;
@SuppressWarnings("unused")
public boolean parse(String[] argv) {
List<String> phaseOptions = new LinkedList<>();
for(int i = argv.length; i > 0; i--) {
pushOption(argv[i-1]);
}
while(hasMoreOptions()) {
String option = nextOption();
if(option.charAt(0) != '-') {
classes.add(option);
continue;
}
while(option.charAt(0) == '-') {
option = option.substring(1);
}
if (false);
else if (false
|| option.equals("jasmin-backend")
)
jasmin_backend = true;
else if (false
|| option.equals("h")
|| option.equals("help")
)
help = true;
else if (false
|| option.equals("pl")
|| option.equals("phase-list")
)
phase_list = true;
else if (false
|| option.equals("ph")
|| option.equals("phase-help")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (phase_help == null)
phase_help = new LinkedList<>();
phase_help.add(value);
}
else if (false
|| option.equals("version")
)
version = true;
else if (false
|| option.equals("v")
|| option.equals("verbose")
)
verbose = true;
else if (false
|| option.equals("interactive-mode")
)
interactive_mode = true;
else if (false
|| option.equals("unfriendly-mode")
)
unfriendly_mode = true;
else if (false
|| option.equals("app")
)
app = true;
else if (false
|| option.equals("w")
|| option.equals("whole-program")
)
whole_program = true;
else if (false
|| option.equals("ws")
|| option.equals("whole-shimple")
)
whole_shimple = true;
else if (false
|| option.equals("fly")
|| option.equals("on-the-fly")
)
on_the_fly = true;
else if (false
|| option.equals("validate")
)
validate = true;
else if (false
|| option.equals("debug")
)
debug = true;
else if (false
|| option.equals("debug-resolver")
)
debug_resolver = true;
else if (false
|| option.equals("ignore-resolving-levels")
)
ignore_resolving_levels = true;
else if (false
|| option.equals("weak-map-structures")
)
weak_map_structures = true;
else if (false
|| option.equals("cp")
|| option.equals("soot-class-path")
|| option.equals("soot-classpath")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (soot_classpath.isEmpty())
soot_classpath = value;
else {
G.v().out.println("Duplicate values " + soot_classpath + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("soot-modulepath")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (soot_modulepath.isEmpty())
soot_modulepath = value;
else {
G.v().out.println("Duplicate values " + soot_modulepath + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("dotnet-nativehost-path")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (dotnet_nativehost_path.isEmpty())
dotnet_nativehost_path = value;
else {
G.v().out.println("Duplicate values " + dotnet_nativehost_path + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("pp")
|| option.equals("prepend-classpath")
)
prepend_classpath = true;
else if (false
|| option.equals("ice")
|| option.equals("ignore-classpath-errors")
)
ignore_classpath_errors = true;
else if (false
|| option.equals("process-multiple-dex")
)
process_multiple_dex = true;
else if (false
|| option.equals("search-dex-in-archives")
)
search_dex_in_archives = true;
else if (false
|| option.equals("process-path")
|| option.equals("process-dir")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (process_dir == null)
process_dir = new LinkedList<>();
process_dir.add(value);
}
else if (false
|| option.equals("process-jar-dir")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (process_jar_dir == null)
process_jar_dir = new LinkedList<>();
process_jar_dir.add(value);
}
else if (false
|| option.equals("virtualedges-path")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (virtualedges_path.isEmpty())
virtualedges_path = value;
else {
G.v().out.println("Duplicate values " + virtualedges_path + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("no-derive-java-version")
)
derive_java_version = false;
else if (false
|| option.equals("oaat")
)
oaat = true;
else if (false
|| option.equals("android-jars")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (android_jars.isEmpty())
android_jars = value;
else {
G.v().out.println("Duplicate values " + android_jars + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("force-android-jar")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (force_android_jar.isEmpty())
force_android_jar = value;
else {
G.v().out.println("Duplicate values " + force_android_jar + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("android-api-version")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if(android_api_version == -1)
android_api_version = Integer.valueOf(value);
else {
G.v().out.println("Duplicate values " + android_api_version + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("ast-metrics")
)
ast_metrics = true;
else if (false
|| option.equals("src-prec")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (false);
else if (false
|| value.equals("c")
|| value.equals("class")
) {
if (src_prec != 0 && src_prec != src_prec_class) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
src_prec = src_prec_class;
}
else if (false
|| value.equals("only-class")
) {
if (src_prec != 0 && src_prec != src_prec_only_class) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
src_prec = src_prec_only_class;
}
else if (false
|| value.equals("J")
|| value.equals("jimple")
) {
if (src_prec != 0 && src_prec != src_prec_jimple) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
src_prec = src_prec_jimple;
}
else if (false
|| value.equals("java")
) {
if (src_prec != 0 && src_prec != src_prec_java) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
src_prec = src_prec_java;
}
else if (false
|| value.equals("apk")
) {
if (src_prec != 0 && src_prec != src_prec_apk) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
src_prec = src_prec_apk;
}
else if (false
|| value.equals("apk-class-jimple")
|| value.equals("apk-c-j")
) {
if (src_prec != 0 && src_prec != src_prec_apk_c_j) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
src_prec = src_prec_apk_c_j;
}
else if (false
|| value.equals("dotnet")
) {
if (src_prec != 0 && src_prec != src_prec_dotnet) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
src_prec = src_prec_dotnet;
}
else {
G.v().out.println(String.format("Invalid value %s given for option -%s", value, option));
return false;
}
}
else if (false
|| option.equals("full-resolver")
)
full_resolver = true;
else if (false
|| option.equals("ignore-methodsource-error")
)
ignore_methodsource_error = true;
else if (false
|| option.equals("no-resolve-all-dotnet-methods")
)
resolve_all_dotnet_methods = false;
else if (false
|| option.equals("allow-phantom-refs")
)
allow_phantom_refs = true;
else if (false
|| option.equals("allow-phantom-elms")
)
allow_phantom_elms = true;
else if (false
|| option.equals("allow-cg-errors")
)
allow_cg_errors = true;
else if (false
|| option.equals("no-bodies-for-excluded")
)
no_bodies_for_excluded = true;
else if (false
|| option.equals("j2me")
)
j2me = true;
else if (false
|| option.equals("main-class")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (main_class.isEmpty())
main_class = value;
else {
G.v().out.println("Duplicate values " + main_class + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("polyglot")
)
polyglot = true;
else if (false
|| option.equals("permissive-resolving")
)
permissive_resolving = true;
else if (false
|| option.equals("no-drop-bodies-after-load")
)
drop_bodies_after_load = false;
else if (false
|| option.equals("nc")
|| option.equals("native-code")
)
native_code = true;
else if (false
|| option.equals("d")
|| option.equals("output-dir")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (output_dir.isEmpty())
output_dir = value;
else {
G.v().out.println("Duplicate values " + output_dir + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("f")
|| option.equals("output-format")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (false);
else if (false
|| value.equals("J")
|| value.equals("jimple")
) {
if (output_format != 0 && output_format != output_format_jimple) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_jimple;
}
else if (false
|| value.equals("j")
|| value.equals("jimp")
) {
if (output_format != 0 && output_format != output_format_jimp) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_jimp;
}
else if (false
|| value.equals("S")
|| value.equals("shimple")
) {
if (output_format != 0 && output_format != output_format_shimple) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_shimple;
}
else if (false
|| value.equals("s")
|| value.equals("shimp")
) {
if (output_format != 0 && output_format != output_format_shimp) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_shimp;
}
else if (false
|| value.equals("B")
|| value.equals("baf")
) {
if (output_format != 0 && output_format != output_format_baf) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_baf;
}
else if (false
|| value.equals("b")
) {
if (output_format != 0 && output_format != output_format_b) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_b;
}
else if (false
|| value.equals("G")
|| value.equals("grimple")
) {
if (output_format != 0 && output_format != output_format_grimple) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_grimple;
}
else if (false
|| value.equals("g")
|| value.equals("grimp")
) {
if (output_format != 0 && output_format != output_format_grimp) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_grimp;
}
else if (false
|| value.equals("X")
|| value.equals("xml")
) {
if (output_format != 0 && output_format != output_format_xml) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_xml;
}
else if (false
|| value.equals("dex")
) {
if (output_format != 0 && output_format != output_format_dex) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_dex;
}
else if (false
|| value.equals("force-dex")
) {
if (output_format != 0 && output_format != output_format_force_dex) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_force_dex;
}
else if (false
|| value.equals("n")
|| value.equals("none")
) {
if (output_format != 0 && output_format != output_format_none) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_none;
}
else if (false
|| value.equals("jasmin")
) {
if (output_format != 0 && output_format != output_format_jasmin) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_jasmin;
}
else if (false
|| value.equals("c")
|| value.equals("class")
) {
if (output_format != 0 && output_format != output_format_class) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_class;
}
else if (false
|| value.equals("d")
|| value.equals("dava")
) {
if (output_format != 0 && output_format != output_format_dava) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_dava;
}
else if (false
|| value.equals("t")
|| value.equals("template")
) {
if (output_format != 0 && output_format != output_format_template) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_template;
}
else if (false
|| value.equals("a")
|| value.equals("asm")
) {
if (output_format != 0 && output_format != output_format_asm) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
output_format = output_format_asm;
}
else {
G.v().out.println(String.format("Invalid value %s given for option -%s", value, option));
return false;
}
}
else if (false
|| option.equals("java-version")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (false);
else if (false
|| value.equals("default")
) {
if (java_version != 0 && java_version != java_version_default) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_default;
}
else if (false
|| value.equals("1.1")
|| value.equals("1")
) {
if (java_version != 0 && java_version != java_version_1) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_1;
}
else if (false
|| value.equals("1.2")
|| value.equals("2")
) {
if (java_version != 0 && java_version != java_version_2) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_2;
}
else if (false
|| value.equals("1.3")
|| value.equals("3")
) {
if (java_version != 0 && java_version != java_version_3) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_3;
}
else if (false
|| value.equals("1.4")
|| value.equals("4")
) {
if (java_version != 0 && java_version != java_version_4) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_4;
}
else if (false
|| value.equals("1.5")
|| value.equals("5")
) {
if (java_version != 0 && java_version != java_version_5) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_5;
}
else if (false
|| value.equals("1.6")
|| value.equals("6")
) {
if (java_version != 0 && java_version != java_version_6) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_6;
}
else if (false
|| value.equals("1.7")
|| value.equals("7")
) {
if (java_version != 0 && java_version != java_version_7) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_7;
}
else if (false
|| value.equals("1.8")
|| value.equals("8")
) {
if (java_version != 0 && java_version != java_version_8) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_8;
}
else if (false
|| value.equals("1.9")
|| value.equals("9")
) {
if (java_version != 0 && java_version != java_version_9) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_9;
}
else if (false
|| value.equals("1.10")
|| value.equals("10")
) {
if (java_version != 0 && java_version != java_version_10) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_10;
}
else if (false
|| value.equals("1.11")
|| value.equals("11")
) {
if (java_version != 0 && java_version != java_version_11) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_11;
}
else if (false
|| value.equals("1.12")
|| value.equals("12")
) {
if (java_version != 0 && java_version != java_version_12) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
java_version = java_version_12;
}
else {
G.v().out.println(String.format("Invalid value %s given for option -%s", value, option));
return false;
}
}
else if (false
|| option.equals("outjar")
|| option.equals("output-jar")
)
output_jar = true;
else if (false
|| option.equals("hierarchy-dirs")
)
hierarchy_dirs = true;
else if (false
|| option.equals("xml-attributes")
)
xml_attributes = true;
else if (false
|| option.equals("print-tags")
|| option.equals("print-tags-in-output")
)
print_tags_in_output = true;
else if (false
|| option.equals("no-output-source-file-attribute")
)
no_output_source_file_attribute = true;
else if (false
|| option.equals("no-output-inner-classes-attribute")
)
no_output_inner_classes_attribute = true;
else if (false
|| option.equals("dump-body")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (dump_body == null)
dump_body = new LinkedList<>();
dump_body.add(value);
}
else if (false
|| option.equals("dump-cfg")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (dump_cfg == null)
dump_cfg = new LinkedList<>();
dump_cfg.add(value);
}
else if (false
|| option.equals("no-show-exception-dests")
)
show_exception_dests = false;
else if (false
|| option.equals("gzip")
)
gzip = true;
else if (false
|| option.equals("force-overwrite")
)
force_overwrite = true;
else if (false
|| option.equals("plugin")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (plugin == null)
plugin = new LinkedList<>();
plugin.add(value);
if (!loadPluginConfiguration(value)) {
G.v().out.println("Failed to load plugin " + value);
return false;
}
}
else if (false
|| option.equals("wrong-staticness")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (false);
else if (false
|| value.equals("fail")
) {
if (wrong_staticness != 0 && wrong_staticness != wrong_staticness_fail) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
wrong_staticness = wrong_staticness_fail;
}
else if (false
|| value.equals("ignore")
) {
if (wrong_staticness != 0 && wrong_staticness != wrong_staticness_ignore) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
wrong_staticness = wrong_staticness_ignore;
}
else if (false
|| value.equals("fix")
) {
if (wrong_staticness != 0 && wrong_staticness != wrong_staticness_fix) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
wrong_staticness = wrong_staticness_fix;
}
else if (false
|| value.equals("fixstrict")
) {
if (wrong_staticness != 0 && wrong_staticness != wrong_staticness_fixstrict) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
wrong_staticness = wrong_staticness_fixstrict;
}
else {
G.v().out.println(String.format("Invalid value %s given for option -%s", value, option));
return false;
}
}
else if (false
|| option.equals("field-type-mismatches")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (false);
else if (false
|| value.equals("fail")
) {
if (field_type_mismatches != 0 && field_type_mismatches != field_type_mismatches_fail) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
field_type_mismatches = field_type_mismatches_fail;
}
else if (false
|| value.equals("ignore")
) {
if (field_type_mismatches != 0 && field_type_mismatches != field_type_mismatches_ignore) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
field_type_mismatches = field_type_mismatches_ignore;
}
else if (false
|| value.equals("null")
) {
if (field_type_mismatches != 0 && field_type_mismatches != field_type_mismatches_null) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
field_type_mismatches = field_type_mismatches_null;
}
else {
G.v().out.println(String.format("Invalid value %s given for option -%s", value, option));
return false;
}
}
else if (false
|| option.equals("p")
|| option.equals("phase-option")
) {
if (!hasMoreOptions()) {
G.v().out.println("No phase name given for option -" + option);
return false;
}
String phaseName = nextOption();
if (!hasMoreOptions()) {
G.v().out.println("No phase option given for option -" + option + " " + phaseName);
return false;
}
String phaseOption = nextOption();
phaseOptions.add(phaseName);
phaseOptions.add(phaseOption);
}
else if (false
|| option.equals("t")
|| option.equals("num-threads")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if(num_threads == -1)
num_threads = Integer.valueOf(value);
else {
G.v().out.println("Duplicate values " + num_threads + " and " + value + " for option -" + option);
return false;
}
}
else if (false
|| option.equals("O")
|| option.equals("optimize")
) {
pushOption("enabled:true");
pushOption("sop");
pushOption("-p");
pushOption("enabled:true");
pushOption("jop");
pushOption("-p");
pushOption("enabled:true");
pushOption("gop");
pushOption("-p");
pushOption("enabled:true");
pushOption("bop");
pushOption("-p");
pushOption("only-stack-locals:false");
pushOption("gb.a2");
pushOption("-p");
pushOption("only-stack-locals:false");
pushOption("gb.a1");
pushOption("-p");
}
else if (false
|| option.equals("W")
|| option.equals("whole-optimize")
) {
pushOption("-O");
pushOption("-w");
pushOption("enabled:true");
pushOption("wsop");
pushOption("-p");
pushOption("enabled:true");
pushOption("wjop");
pushOption("-p");
}
else if (false
|| option.equals("via-grimp")
)
via_grimp = true;
else if (false
|| option.equals("via-shimple")
)
via_shimple = true;
else if (false
|| option.equals("throw-analysis")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (false);
else if (false
|| value.equals("pedantic")
) {
if (throw_analysis != 0 && throw_analysis != throw_analysis_pedantic) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
throw_analysis = throw_analysis_pedantic;
}
else if (false
|| value.equals("unit")
) {
if (throw_analysis != 0 && throw_analysis != throw_analysis_unit) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
throw_analysis = throw_analysis_unit;
}
else if (false
|| value.equals("dalvik")
) {
if (throw_analysis != 0 && throw_analysis != throw_analysis_dalvik) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
throw_analysis = throw_analysis_dalvik;
}
else if (false
|| value.equals("dotnet")
) {
if (throw_analysis != 0 && throw_analysis != throw_analysis_dotnet) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
throw_analysis = throw_analysis_dotnet;
}
else if (false
|| value.equals("auto-select")
) {
if (throw_analysis != 0 && throw_analysis != throw_analysis_auto_select) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
throw_analysis = throw_analysis_auto_select;
}
else {
G.v().out.println(String.format("Invalid value %s given for option -%s", value, option));
return false;
}
}
else if (false
|| option.equals("check-init-ta")
|| option.equals("check-init-throw-analysis")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (false);
else if (false
|| value.equals("auto")
) {
if (check_init_throw_analysis != 0 && check_init_throw_analysis != check_init_throw_analysis_auto) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
check_init_throw_analysis = check_init_throw_analysis_auto;
}
else if (false
|| value.equals("pedantic")
) {
if (check_init_throw_analysis != 0 && check_init_throw_analysis != check_init_throw_analysis_pedantic) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
check_init_throw_analysis = check_init_throw_analysis_pedantic;
}
else if (false
|| value.equals("unit")
) {
if (check_init_throw_analysis != 0 && check_init_throw_analysis != check_init_throw_analysis_unit) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
check_init_throw_analysis = check_init_throw_analysis_unit;
}
else if (false
|| value.equals("dalvik")
) {
if (check_init_throw_analysis != 0 && check_init_throw_analysis != check_init_throw_analysis_dalvik) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
check_init_throw_analysis = check_init_throw_analysis_dalvik;
}
else if (false
|| value.equals("dotnet")
) {
if (check_init_throw_analysis != 0 && check_init_throw_analysis != check_init_throw_analysis_dotnet) {
G.v().out.println("Multiple values given for option " + option);
return false;
}
check_init_throw_analysis = check_init_throw_analysis_dotnet;
}
else {
G.v().out.println(String.format("Invalid value %s given for option -%s", value, option));
return false;
}
}
else if (false
|| option.equals("omit-excepting-unit-edges")
)
omit_excepting_unit_edges = true;
else if (false
|| option.equals("trim-cfgs")
) {
pushOption("enabled:true");
pushOption("jb.tt");
pushOption("-p");
pushOption("-omit-excepting-unit-edges");
pushOption("unit");
pushOption("-throw-analysis");
}
else if (false
|| option.equals("ire")
|| option.equals("ignore-resolution-errors")
)
ignore_resolution_errors = true;
else if (false
|| option.equals("i")
|| option.equals("include")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (include == null)
include = new LinkedList<>();
include.add(value);
}
else if (false
|| option.equals("x")
|| option.equals("exclude")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (exclude == null)
exclude = new LinkedList<>();
exclude.add(value);
}
else if (false
|| option.equals("include-all")
)
include_all = true;
else if (false
|| option.equals("dynamic-class")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (dynamic_class == null)
dynamic_class = new LinkedList<>();
dynamic_class.add(value);
}
else if (false
|| option.equals("dynamic-dir")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (dynamic_dir == null)
dynamic_dir = new LinkedList<>();
dynamic_dir.add(value);
}
else if (false
|| option.equals("dynamic-package")
) {
if (!hasMoreOptions()) {
G.v().out.println("No value given for option -" + option);
return false;
}
String value = nextOption();
if (dynamic_package == null)
dynamic_package = new LinkedList<>();
dynamic_package.add(value);
}
else if (false
|| option.equals("keep-line-number")
)
keep_line_number = true;
else if (false
|| option.equals("keep-bytecode-offset")
|| option.equals("keep-offset")
)
keep_offset = true;
else if (false
|| option.equals("write-local-annotations")
)
write_local_annotations = true;
else if (false
|| option.equals("annot-purity")
) {
pushOption("enabled:true");
pushOption("wjap.purity");
pushOption("-p");
pushOption("enabled:true");
pushOption("cg.spark");
pushOption("-p");
pushOption("-w");
}
else if (false
|| option.equals("annot-nullpointer")
) {
pushOption("enabled:true");
pushOption("tag.an");
pushOption("-p");
pushOption("enabled:true");
pushOption("jap.npc");
pushOption("-p");
}
else if (false
|| option.equals("annot-arraybounds")
) {
pushOption("enabled:true");
pushOption("tag.an");
pushOption("-p");
pushOption("enabled:true");
pushOption("jap.abc");
pushOption("-p");
pushOption("enabled:true");
pushOption("wjap.ra");
pushOption("-p");
}
else if (false
|| option.equals("annot-side-effect")
) {
pushOption("enabled:true");
pushOption("tag.dep");
pushOption("-p");
pushOption("enabled:true");
pushOption("jap.sea");
pushOption("-p");
pushOption("-w");
}
else if (false
|| option.equals("annot-fieldrw")
) {
pushOption("enabled:true");
pushOption("tag.fieldrw");
pushOption("-p");
pushOption("enabled:true");
pushOption("jap.fieldrw");
pushOption("-p");
pushOption("-w");
}
else if (false
|| option.equals("time")
)
time = true;
else if (false
|| option.equals("subtract-gc")
)
subtract_gc = true;
else if (false
|| option.equals("no-writeout-body-releasing")
)
no_writeout_body_releasing = true;
else {
G.v().out.println("Invalid option -" + option);
return false;
}
}
Iterator<String> it = phaseOptions.iterator();
while(it.hasNext()) {
String phaseName = it.next();
String phaseOption = it.next();
if(!setPhaseOption(phaseName, "enabled:true"))
return false;
}
it = phaseOptions.iterator();
while(it.hasNext()) {
String phaseName = it.next();
String phaseOption = it.next();
if(!setPhaseOption(phaseName, phaseOption))
return false;
}
return true;
}
public boolean jasmin_backend() { return jasmin_backend; }
private boolean jasmin_backend = false;
public void set_jasmin_backend(boolean setting) { jasmin_backend = setting; }
public boolean help() { return help; }
private boolean help = false;
public void set_help(boolean setting) { help = setting; }
public boolean phase_list() { return phase_list; }
private boolean phase_list = false;
public void set_phase_list(boolean setting) { phase_list = setting; }
public List<String> phase_help() {
return phase_help == null ? Collections.emptyList() : phase_help;
}
public void set_phase_help(List<String> setting) { phase_help = setting; }
private List<String> phase_help = null;
public boolean version() { return version; }
private boolean version = false;
public void set_version(boolean setting) { version = setting; }
public boolean verbose() { return verbose; }
private boolean verbose = false;
public void set_verbose(boolean setting) { verbose = setting; }
public boolean interactive_mode() { return interactive_mode; }
private boolean interactive_mode = false;
public void set_interactive_mode(boolean setting) { interactive_mode = setting; }
public boolean unfriendly_mode() { return unfriendly_mode; }
private boolean unfriendly_mode = false;
public void set_unfriendly_mode(boolean setting) { unfriendly_mode = setting; }
public boolean app() { return app; }
private boolean app = false;
public void set_app(boolean setting) { app = setting; }
public boolean whole_program() { return whole_program; }
private boolean whole_program = false;
public void set_whole_program(boolean setting) { whole_program = setting; }
public boolean whole_shimple() { return whole_shimple; }
private boolean whole_shimple = false;
public void set_whole_shimple(boolean setting) { whole_shimple = setting; }
public boolean on_the_fly() { return on_the_fly; }
private boolean on_the_fly = false;
public void set_on_the_fly(boolean setting) { on_the_fly = setting; }
public boolean validate() { return validate; }
private boolean validate = false;
public void set_validate(boolean setting) { validate = setting; }
public boolean debug() { return debug; }
private boolean debug = false;
public void set_debug(boolean setting) { debug = setting; }
public boolean debug_resolver() { return debug_resolver; }
private boolean debug_resolver = false;
public void set_debug_resolver(boolean setting) { debug_resolver = setting; }
public boolean ignore_resolving_levels() { return ignore_resolving_levels; }
private boolean ignore_resolving_levels = false;
public void set_ignore_resolving_levels(boolean setting) { ignore_resolving_levels = setting; }
public boolean weak_map_structures() { return weak_map_structures; }
private boolean weak_map_structures = false;
public void set_weak_map_structures(boolean setting) { weak_map_structures = setting; }
public String soot_classpath() { return soot_classpath; }
public void set_soot_classpath(String setting) { soot_classpath = setting; }
private String soot_classpath = "";
public String soot_modulepath() { return soot_modulepath; }
public void set_soot_modulepath(String setting) { soot_modulepath = setting; }
private String soot_modulepath = "";
public String dotnet_nativehost_path() { return dotnet_nativehost_path; }
public void set_dotnet_nativehost_path(String setting) { dotnet_nativehost_path = setting; }
private String dotnet_nativehost_path = "";
public boolean prepend_classpath() { return prepend_classpath; }
private boolean prepend_classpath = false;
public void set_prepend_classpath(boolean setting) { prepend_classpath = setting; }
public boolean ignore_classpath_errors() { return ignore_classpath_errors; }
private boolean ignore_classpath_errors = false;
public void set_ignore_classpath_errors(boolean setting) { ignore_classpath_errors = setting; }
public boolean process_multiple_dex() { return process_multiple_dex; }
private boolean process_multiple_dex = false;
public void set_process_multiple_dex(boolean setting) { process_multiple_dex = setting; }
public boolean search_dex_in_archives() { return search_dex_in_archives; }
private boolean search_dex_in_archives = false;
public void set_search_dex_in_archives(boolean setting) { search_dex_in_archives = setting; }
public List<String> process_dir() {
return process_dir == null ? Collections.emptyList() : process_dir;
}
public void set_process_dir(List<String> setting) { process_dir = setting; }
private List<String> process_dir = null;
public List<String> process_jar_dir() {
return process_jar_dir == null ? Collections.emptyList() : process_jar_dir;
}
public void set_process_jar_dir(List<String> setting) { process_jar_dir = setting; }
private List<String> process_jar_dir = null;
public String virtualedges_path() { return virtualedges_path; }
public void set_virtualedges_path(String setting) { virtualedges_path = setting; }
private String virtualedges_path = "";
public boolean derive_java_version() { return derive_java_version; }
private boolean derive_java_version = true;
public void set_derive_java_version(boolean setting) { derive_java_version = setting; }
public boolean oaat() { return oaat; }
private boolean oaat = false;
public void set_oaat(boolean setting) { oaat = setting; }
public String android_jars() { return android_jars; }
public void set_android_jars(String setting) { android_jars = setting; }
private String android_jars = "";
public String force_android_jar() { return force_android_jar; }
public void set_force_android_jar(String setting) { force_android_jar = setting; }
private String force_android_jar = "";
public int android_api_version() { return android_api_version; }
public void set_android_api_version(int setting) { android_api_version = setting; }
private int android_api_version = -1;
public boolean ast_metrics() { return ast_metrics; }
private boolean ast_metrics = false;
public void set_ast_metrics(boolean setting) { ast_metrics = setting; }
public int src_prec() {
if (src_prec == 0) return src_prec_class;
return src_prec;
}
public void set_src_prec(int setting) { src_prec = setting; }
private int src_prec = 0;
public boolean full_resolver() { return full_resolver; }
private boolean full_resolver = false;
public void set_full_resolver(boolean setting) { full_resolver = setting; }
public boolean ignore_methodsource_error() { return ignore_methodsource_error; }
private boolean ignore_methodsource_error = false;
public void set_ignore_methodsource_error(boolean setting) { ignore_methodsource_error = setting; }
public boolean resolve_all_dotnet_methods() { return resolve_all_dotnet_methods; }
private boolean resolve_all_dotnet_methods = true;
public void set_resolve_all_dotnet_methods(boolean setting) { resolve_all_dotnet_methods = setting; }
public boolean allow_phantom_refs() { return allow_phantom_refs; }
private boolean allow_phantom_refs = false;
public void set_allow_phantom_refs(boolean setting) { allow_phantom_refs = setting; }
public boolean allow_phantom_elms() { return allow_phantom_elms; }
private boolean allow_phantom_elms = false;
public void set_allow_phantom_elms(boolean setting) { allow_phantom_elms = setting; }
public boolean allow_cg_errors() { return allow_cg_errors; }
private boolean allow_cg_errors = false;
public void set_allow_cg_errors(boolean setting) { allow_cg_errors = setting; }
public boolean no_bodies_for_excluded() { return no_bodies_for_excluded; }
private boolean no_bodies_for_excluded = false;
public void set_no_bodies_for_excluded(boolean setting) { no_bodies_for_excluded = setting; }
public boolean j2me() { return j2me; }
private boolean j2me = false;
public void set_j2me(boolean setting) { j2me = setting; }
public String main_class() { return main_class; }
public void set_main_class(String setting) { main_class = setting; }
private String main_class = "";
public boolean polyglot() { return polyglot; }
private boolean polyglot = false;
public void set_polyglot(boolean setting) { polyglot = setting; }
public boolean permissive_resolving() { return permissive_resolving; }
private boolean permissive_resolving = false;
public void set_permissive_resolving(boolean setting) { permissive_resolving = setting; }
public boolean drop_bodies_after_load() { return drop_bodies_after_load; }
private boolean drop_bodies_after_load = true;
public void set_drop_bodies_after_load(boolean setting) { drop_bodies_after_load = setting; }
public boolean native_code() { return native_code; }
private boolean native_code = false;
public void set_native_code(boolean setting) { native_code = setting; }
public String output_dir() { return output_dir; }
public void set_output_dir(String setting) { output_dir = setting; }
private String output_dir = "";
public int output_format() {
if (output_format == 0) return output_format_class;
return output_format;
}
public void set_output_format(int setting) { output_format = setting; }
private int output_format = 0;
public int java_version() {
return java_version;
}
public void set_java_version(int setting) { java_version = setting; }
private int java_version = 0;
public boolean output_jar() { return output_jar; }
private boolean output_jar = false;
public void set_output_jar(boolean setting) { output_jar = setting; }
public boolean hierarchy_dirs() { return hierarchy_dirs; }
private boolean hierarchy_dirs = false;
public void set_hierarchy_dirs(boolean setting) { hierarchy_dirs = setting; }
public boolean xml_attributes() { return xml_attributes; }
private boolean xml_attributes = false;
public void set_xml_attributes(boolean setting) { xml_attributes = setting; }
public boolean print_tags_in_output() { return print_tags_in_output; }
private boolean print_tags_in_output = false;
public void set_print_tags_in_output(boolean setting) { print_tags_in_output = setting; }
public boolean no_output_source_file_attribute() { return no_output_source_file_attribute; }
private boolean no_output_source_file_attribute = false;
public void set_no_output_source_file_attribute(boolean setting) { no_output_source_file_attribute = setting; }
public boolean no_output_inner_classes_attribute() { return no_output_inner_classes_attribute; }
private boolean no_output_inner_classes_attribute = false;
public void set_no_output_inner_classes_attribute(boolean setting) { no_output_inner_classes_attribute = setting; }
public List<String> dump_body() {
return dump_body == null ? Collections.emptyList() : dump_body;
}
public void set_dump_body(List<String> setting) { dump_body = setting; }
private List<String> dump_body = null;
public List<String> dump_cfg() {
return dump_cfg == null ? Collections.emptyList() : dump_cfg;
}
public void set_dump_cfg(List<String> setting) { dump_cfg = setting; }
private List<String> dump_cfg = null;
public boolean show_exception_dests() { return show_exception_dests; }
private boolean show_exception_dests = true;
public void set_show_exception_dests(boolean setting) { show_exception_dests = setting; }
public boolean gzip() { return gzip; }
private boolean gzip = false;
public void set_gzip(boolean setting) { gzip = setting; }
public boolean force_overwrite() { return force_overwrite; }
private boolean force_overwrite = false;
public void set_force_overwrite(boolean setting) { force_overwrite = setting; }
public List<String> plugin() {
return plugin == null ? Collections.emptyList() : plugin;
}
public void set_plugin(List<String> setting) { plugin = setting; }
private List<String> plugin = null;
public int wrong_staticness() {
if (wrong_staticness == 0) return wrong_staticness_fixstrict;
return wrong_staticness;
}
public void set_wrong_staticness(int setting) { wrong_staticness = setting; }
private int wrong_staticness = 0;
public int field_type_mismatches() {
if (field_type_mismatches == 0) return field_type_mismatches_null;
return field_type_mismatches;
}
public void set_field_type_mismatches(int setting) { field_type_mismatches = setting; }
private int field_type_mismatches = 0;
public int num_threads() { return num_threads; }
public void set_num_threads(int setting) { num_threads = setting; }
private int num_threads = -1;
public boolean via_grimp() { return via_grimp; }
private boolean via_grimp = false;
public void set_via_grimp(boolean setting) { via_grimp = setting; }
public boolean via_shimple() { return via_shimple; }
private boolean via_shimple = false;
public void set_via_shimple(boolean setting) { via_shimple = setting; }
public int throw_analysis() {
if (throw_analysis == 0) return throw_analysis_auto_select;
return throw_analysis;
}
public void set_throw_analysis(int setting) { throw_analysis = setting; }
private int throw_analysis = 0;
public int check_init_throw_analysis() {
if (check_init_throw_analysis == 0) return check_init_throw_analysis_auto;
return check_init_throw_analysis;
}
public void set_check_init_throw_analysis(int setting) { check_init_throw_analysis = setting; }
private int check_init_throw_analysis = 0;
public boolean omit_excepting_unit_edges() { return omit_excepting_unit_edges; }
private boolean omit_excepting_unit_edges = false;
public void set_omit_excepting_unit_edges(boolean setting) { omit_excepting_unit_edges = setting; }
public boolean ignore_resolution_errors() { return ignore_resolution_errors; }
private boolean ignore_resolution_errors = false;
public void set_ignore_resolution_errors(boolean setting) { ignore_resolution_errors = setting; }
public List<String> include() {
return include == null ? Collections.emptyList() : include;
}
public void set_include(List<String> setting) { include = setting; }
private List<String> include = null;
public List<String> exclude() {
return exclude == null ? Collections.emptyList() : exclude;
}
public void set_exclude(List<String> setting) { exclude = setting; }
private List<String> exclude = null;
public boolean include_all() { return include_all; }
private boolean include_all = false;
public void set_include_all(boolean setting) { include_all = setting; }
public List<String> dynamic_class() {
return dynamic_class == null ? Collections.emptyList() : dynamic_class;
}
public void set_dynamic_class(List<String> setting) { dynamic_class = setting; }
private List<String> dynamic_class = null;
public List<String> dynamic_dir() {
return dynamic_dir == null ? Collections.emptyList() : dynamic_dir;
}
public void set_dynamic_dir(List<String> setting) { dynamic_dir = setting; }
private List<String> dynamic_dir = null;
public List<String> dynamic_package() {
return dynamic_package == null ? Collections.emptyList() : dynamic_package;
}
public void set_dynamic_package(List<String> setting) { dynamic_package = setting; }
private List<String> dynamic_package = null;
public boolean keep_line_number() { return keep_line_number; }
private boolean keep_line_number = false;
public void set_keep_line_number(boolean setting) { keep_line_number = setting; }
public boolean keep_offset() { return keep_offset; }
private boolean keep_offset = false;
public void set_keep_offset(boolean setting) { keep_offset = setting; }
public boolean write_local_annotations() { return write_local_annotations; }
private boolean write_local_annotations = false;
public void set_write_local_annotations(boolean setting) { write_local_annotations = setting; }
public boolean time() { return time; }
private boolean time = false;
public void set_time(boolean setting) { time = setting; }
public boolean subtract_gc() { return subtract_gc; }
private boolean subtract_gc = false;
public void set_subtract_gc(boolean setting) { subtract_gc = setting; }
public boolean no_writeout_body_releasing() { return no_writeout_body_releasing; }
private boolean no_writeout_body_releasing = false;
public void set_no_writeout_body_releasing(boolean setting) { no_writeout_body_releasing = setting; }
public String getUsage() {
return ""
+ "\nGeneral Options:\n"
+ padOpt("-jasmin-backend", "Use the Jasmin back end for generating Java bytecode (instead of using ASM).")
+ padOpt("-h, -help", "Display help and exit")
+ padOpt("-pl, -phase-list", "Print list of available phases")
+ padOpt("-ph ARG -phase-help ARG", "Print help for specified ARG")
+ padOpt("-version", "Display version information and exit")
+ padOpt("-v, -verbose", "Verbose mode")
+ padOpt("-interactive-mode", "Run in interactive mode")
+ padOpt("-unfriendly-mode", "Allow Soot to run with no command-line options")
+ padOpt("-app", "Run in application mode")
+ padOpt("-w, -whole-program", "Run in whole-program mode")
+ padOpt("-ws, -whole-shimple", "Run in whole-shimple mode")
+ padOpt("-fly, -on-the-fly", "Run in on-the-fly mode")
+ padOpt("-validate", "Run internal validation on bodies")
+ padOpt("-debug", "Print various Soot debugging info")
+ padOpt("-debug-resolver", "Print debugging info from SootResolver")
+ padOpt("-ignore-resolving-levels", "Ignore mismatching resolving levels")
+ padOpt("-weak-map-structures", "Use weak references in Scene to prevent memory leakage when removing many classes/methods/locals")
+ "\nInput Options:\n"
+ padOpt("-cp ARG -soot-class-path ARG -soot-classpath ARG", "Use ARG as the classpath for finding classes.")
+ padOpt("-soot-modulepath ARG", "Use ARG as the modulepath for finding classes.")
+ padOpt("-dotnet-nativehost-path ARG", "Use to locate your NativeHost Java JNI library.")
+ padOpt("-pp, -prepend-classpath", "Prepend the given soot classpath to the default classpath.")
+ padOpt("-ice, -ignore-classpath-errors", "Ignores invalid entries on the Soot classpath.")
+ padOpt("-process-multiple-dex", "Process all DEX files found in APK.")
+ padOpt("-search-dex-in-archives", "Also includes Jar and Zip files when searching for DEX files under the provided classpath.")
+ padOpt("-process-path ARG -process-dir ARG", "Process all classes found in ARG (but not classes within JAR files in ARG , use process-jar-dir for that)")
+ padOpt("-process-jar-dir ARG", "Process all classes found in JAR files found in ARG")
+ padOpt("-virtualedges-path ARG", "Path to virtual edges configuration used in call graphs")
+ padOpt("-derive-java-version", "Java version for output and internal processing will be derived from the given input classes")
+ padOpt("-oaat", "From the process-dir, processes one class at a time.")
+ padOpt("-android-jars ARG", "Use ARG as the path for finding the android.jar file")
+ padOpt("-force-android-jar ARG", "Force Soot to use ARG as the path for the android.jar file.")
+ padOpt("-ast-metrics", "Compute AST Metrics if performing java to jimple")
+ padOpt("-src-prec ARG", "Sets source precedence to ARG files")
+ padVal("c class (default)", "Favour class files as Soot source")
+ padVal("only-class", "Use only class files as Soot source")
+ padVal("J jimple", "Favour Jimple files as Soot source")
+ padVal("java", "Favour Java files as Soot source")
+ padVal("apk", "Favour APK files as Soot source")
+ padVal("apk-class-jimple apk-c-j", "Favour APK files as Soot source, disregard Java files")
+ padVal("dotnet", "Favour .NET assemblies files as Soot source")
+ padOpt("-full-resolver", "Force transitive resolving of referenced classes")
+ padOpt("-ignore-methodsource-error", "Ignore errors from method source and return empty jimple body")
+ padOpt("-resolve-all-dotnet-methods", "Resolve all dotnet methods, such as unsafe methods")
+ padOpt("-allow-phantom-refs", "Allow unresolved classes; may cause errors")
+ padOpt("-allow-phantom-elms", "Allow phantom methods and fields in non-phantom classes")
+ padOpt("-allow-cg-errors", "Allow Errors during callgraph construction")
+ padOpt("-no-bodies-for-excluded", "Do not load bodies for excluded classes")
+ padOpt("-j2me", "Use J2ME mode; changes assignment of types")
+ padOpt("-main-class ARG", "Sets the main class for whole-program analysis.")
+ padOpt("-polyglot", "Use Java 1.4 Polyglot frontend instead of JastAdd")
+ padOpt("-permissive-resolving", "Use alternative sources when classes cannot be found using the normal resolving strategy")
+ padOpt("-drop-bodies-after-load", "Drop the method source after it has served its purpose of loading the method body")
+ padOpt("-nc, -native-code", "Enables native methods to be concrete. Needed for analyzing the Java Native Interface.")
+ "\nOutput Options:\n"
+ padOpt("-d ARG -output-dir ARG", "Store output files in ARG")
+ padOpt("-f ARG -output-format ARG", "Set output format for Soot")
+ padVal("J jimple", "Produce .jimple Files")
+ padVal("j jimp", "Produce .jimp (abbreviated Jimple) files")
+ padVal("S shimple", "Produce .shimple files")
+ padVal("s shimp", "Produce .shimp (abbreviated Shimple) files")
+ padVal("B baf", "Produce .baf files")
+ padVal("b", "Produce .b (abbreviated Baf) files")
+ padVal("G grimple", "Produce .grimple files")
+ padVal("g grimp", "Produce .grimp (abbreviated Grimp) files")
+ padVal("X xml", "Produce .xml Files")
+ padVal("dex", "Produce Dalvik Virtual Machine files")
+ padVal("force-dex", "Produce Dalvik DEX files")
+ padVal("n none", "Produce no output")
+ padVal("jasmin", "Produce .jasmin files")
+ padVal("c class (default)", "Produce .class Files")
+ padVal("d dava", "Produce dava-decompiled .java files")
+ padVal("t template", "Produce .java files with Jimple templates.")
+ padVal("a asm", "Produce .asm files as textual bytecode representation generated with the ASM back end.")
+ padOpt("-java-version ARG", "Force Java version of bytecode generated by Soot.")
+ padVal("default", "Let Soot determine Java version of generated bytecode.")
+ padVal("1.1 1", "Force Java 1.1 as output version.")
+ padVal("1.2 2", "Force Java 1.2 as output version.")
+ padVal("1.3 3", "Force Java 1.3 as output version.")
+ padVal("1.4 4", "Force Java 1.4 as output version.")
+ padVal("1.5 5", "Force Java 1.5 as output version.")
+ padVal("1.6 6", "Force Java 1.6 as output version.")
+ padVal("1.7 7", "Force Java 1.7 as output version.")
+ padVal("1.8 8", "Force Java 1.8 as output version.")
+ padVal("1.9 9", "Force Java 1.9 as output version (Experimental).")
+ padVal("1.10 10", "Force Java 1.10 as output version (Experimental).")
+ padVal("1.11 11", "Force Java 1.11 as output version (Experimental).")
+ padVal("1.12 12", "Force Java 1.12 as output version (Experimental).")
+ padOpt("-outjar, -output-jar", "Make output dir a Jar file instead of dir")
+ padOpt("-hierarchy-dirs", "Generate class hierarchy directories for Jimple/Shimple")
+ padOpt("-xml-attributes", "Save tags to XML attributes for Eclipse")
+ padOpt("-print-tags, -print-tags-in-output", "Print tags in output files after stmt")
+ padOpt("-no-output-source-file-attribute", "Don't output Source File Attribute when producing class files")
+ padOpt("-no-output-inner-classes-attribute", "Don't output inner classes attribute in class files")
+ padOpt("-dump-body ARG", "Dump the internal representation of each method before and after phase ARG")
+ padOpt("-dump-cfg ARG", "Dump the internal representation of each CFG constructed during phase ARG")
+ padOpt("-show-exception-dests", "Include exception destination edges as well as CFG edges in dumped CFGs")
+ padOpt("-gzip", "GZip IR output files")
+ padOpt("-force-overwrite", "Force Overwrite Output Files")
+ "\nProcessing Options:\n"
+ padOpt("-plugin ARG", "Load all plugins found in ARG")
+ padOpt("-wrong-staticness ARG", "Ignores or fixes errors due to wrong staticness")
+ padVal("fail", "Raise an error when wrong staticness is detected")
+ padVal("ignore", "Ignore errors caused by wrong staticness")
+ padVal("fix", "Transparently fix staticness errors")
+ padVal("fixstrict (default)", "Transparently fix staticness errors, but do not ignore remaining errors")
+ padOpt("-field-type-mismatches ARG", "Specifies how errors shall be handled when resolving field references with mismatching types")
+ padVal("fail", "Raise an error when a field type mismatch is detected")
+ padVal("ignore", "Ignore field type mismatches")
+ padVal("null (default)", "Return null in case of type mismatch")
+ padOpt("-p ARG -phase-option ARG", "Set PHASE 's OPT option to VALUE")
+ padOpt("-O, -optimize", "Perform intraprocedural optimizations")
+ padOpt("-W, -whole-optimize", "Perform whole program optimizations")
+ padOpt("-via-grimp", "Convert to bytecode via Grimp instead of via Baf")
+ padOpt("-via-shimple", "Enable Shimple SSA representation")
+ padOpt("-throw-analysis ARG", "")
+ padVal("pedantic", "Pedantically conservative throw analysis")
+ padVal("unit", "Unit Throw Analysis")
+ padVal("dalvik", "Dalvik Throw Analysis")
+ padVal("dotnet", "Dotnet Throw Analysis")
+ padVal("auto-select (default)", "Automatically Select Throw Analysis")
+ padOpt("-check-init-ta ARG -check-init-throw-analysis ARG", "")
+ padVal("auto (default)", "Automatically select a throw analysis")
+ padVal("pedantic", "Pedantically conservative throw analysis")
+ padVal("unit", "Unit Throw Analysis")
+ padVal("dalvik", "Dalvik Throw Analysis")
+ padVal("dotnet", "Dotnet Throw Analysis")
+ padOpt("-omit-excepting-unit-edges", "Omit CFG edges to handlers from excepting units which lack side effects")
+ padOpt("-trim-cfgs", "Trim unrealizable exceptional edges from CFGs")
+ padOpt("-ire, -ignore-resolution-errors", "Does not throw an exception when a program references an undeclared field or method.")
+ "\nApplication Mode Options:\n"
+ padOpt("-i ARG -include ARG", "Include classes in ARG as application classes")
+ padOpt("-x ARG -exclude ARG", "Exclude classes in ARG from application classes")
+ padOpt("-include-all", "Set default excluded packages to empty list")
+ padOpt("-dynamic-class ARG", "Note that ARG may be loaded dynamically")
+ padOpt("-dynamic-dir ARG", "Mark all classes in ARG as potentially dynamic")
+ padOpt("-dynamic-package ARG", "Marks classes in ARG as potentially dynamic")
+ "\nInput Attribute Options:\n"
+ padOpt("-keep-line-number", "Keep line number tables")
+ padOpt("-keep-bytecode-offset, -keep-offset", "Attach bytecode offset to IR")
+ "\nOutput Attribute Options:\n"
+ padOpt("-write-local-annotations", "Write out debug annotations on local names")
+ "\nAnnotation Options:\n"
+ padOpt("-annot-purity", "Emit purity attributes")
+ padOpt("-annot-nullpointer", "Emit null pointer attributes")
+ padOpt("-annot-arraybounds", "Emit array bounds check attributes")
+ padOpt("-annot-side-effect", "Emit side-effect attributes")
+ padOpt("-annot-fieldrw", "Emit field read/write attributes")
+ "\nMiscellaneous Options:\n"
+ padOpt("-time", "Report time required for transformations")
+ padOpt("-subtract-gc", "Subtract gc from time")
+ padOpt("-no-writeout-body-releasing", "Disables the release of method bodies after writeout. This flag is used internally.");
}
public String getPhaseList() {
return ""
+ padOpt("jb", "Creates a JimpleBody for each method")
+ padVal("jb.dtr", "Reduces chains of catch-all traps")
+ padVal("jb.ese", "Removes empty switch statements")
+ padVal("jb.ls", "Local splitter: one local per DU-UD web")
+ padVal("jb.sils", "Splits primitive locals used as different types")
+ padVal("jb.a", "Aggregator: removes some unnecessary copies")
+ padVal("jb.ule", "Unused local eliminator")
+ padVal("jb.tr", "Assigns types to locals")
+ padVal("jb.ulp", "Local packer: minimizes number of locals")
+ padVal("jb.lns", "Local name standardizer")
+ padVal("jb.cp", "Copy propagator")
+ padVal("jb.dae", "Dead assignment eliminator")
+ padVal("jb.cp-ule", "Post-copy propagation unused local eliminator")
+ padVal("jb.lp", "Local packer: minimizes number of locals")
+ padVal("jb.ne", "Nop eliminator")
+ padVal("jb.uce", "Unreachable code eliminator")
+ padVal("jb.tt", "Trap Tightener")
+ padVal("jb.cbf", "Conditional branch folder")
+ padOpt("jj", "Creates a JimpleBody for each method directly from source")
+ padVal("jj.ls", "Local splitter: one local per DU-UD web")
+ padVal("jj.sils", "Splits primitive locals used as different types")
+ padVal("jj.a", "Aggregator: removes some unnecessary copies")
+ padVal("jj.ule", "Unused local eliminator")
+ padVal("jj.tr", "Assigns types to locals")
+ padVal("jj.ulp", "Local packer: minimizes number of locals")
+ padVal("jj.lns", "Local name standardizer")
+ padVal("jj.cp", "Copy propagator")
+ padVal("jj.dae", "Dead assignment eliminator")
+ padVal("jj.cp-ule", "Post-copy propagation unused local eliminator")
+ padVal("jj.lp", "Local packer: minimizes number of locals")
+ padVal("jj.ne", "Nop eliminator")
+ padVal("jj.uce", "Unreachable code eliminator")
+ padOpt("wjpp", "Whole Jimple Pre-processing Pack")
+ padVal("wjpp.cimbt", "Replaces base objects of calls to Method.invoke() that are string constants by locals")
+ padOpt("wspp", "Whole Shimple Pre-processing Pack")
+ padOpt("cg", "Call graph constructor")
+ padVal("cg.cha", "Builds call graph using Class Hierarchy Analysis")
+ padVal("cg.spark", "Spark points-to analysis framework")
+ padVal("cg.paddle", "Paddle points-to analysis framework")
+ padOpt("wstp", "Whole-shimple transformation pack")
+ padOpt("wsop", "Whole-shimple optimization pack")
+ padOpt("wjtp", "Whole-jimple transformation pack")
+ padVal("wjtp.mhp", "Determines what statements may be run concurrently")
+ padVal("wjtp.tn", "Finds critical sections, allocates locks")
+ padVal("wjtp.rdc", "Rename duplicated classes when the file system is not case sensitive")
+ padOpt("wjop", "Whole-jimple optimization pack")
+ padVal("wjop.smb", "Static method binder: Devirtualizes monomorphic calls")
+ padVal("wjop.si", "Static inliner: inlines monomorphic calls")
+ padOpt("wjap", "Whole-jimple annotation pack: adds interprocedural tags")
+ padVal("wjap.ra", "Rectangular array finder")
+ padVal("wjap.umt", "Tags all unreachable methods")
+ padVal("wjap.uft", "Tags all unreachable fields")
+ padVal("wjap.tqt", "Tags all qualifiers that could be tighter")
+ padVal("wjap.cgg", "Creates graphical call graph.")
+ padVal("wjap.purity", "Emit purity attributes")
+ padOpt("shimple", "Sets parameters for Shimple SSA form")
+ padOpt("stp", "Shimple transformation pack")
+ padOpt("sop", "Shimple optimization pack")
+ padVal("sop.cpf", "Shimple constant propagator and folder")
+ padOpt("jtp", "Jimple transformation pack: intraprocedural analyses added to Soot")
+ padOpt("jop", "Jimple optimization pack (intraprocedural)")
+ padVal("jop.cse", "Common subexpression eliminator")
+ padVal("jop.bcm", "Busy code motion: unaggressive partial redundancy elimination")
+ padVal("jop.lcm", "Lazy code motion: aggressive partial redundancy elimination")
+ padVal("jop.cp", "Copy propagator")
+ padVal("jop.cpf", "Constant propagator and folder")
+ padVal("jop.cbf", "Conditional branch folder")
+ padVal("jop.dae", "Dead assignment eliminator")
+ padVal("jop.nce", "Null Check Eliminator")
+ padVal("jop.uce1", "Unreachable code eliminator, pass 1")
+ padVal("jop.ubf1", "Unconditional branch folder, pass 1")
+ padVal("jop.uce2", "Unreachable code eliminator, pass 2")
+ padVal("jop.ubf2", "Unconditional branch folder, pass 2")
+ padVal("jop.ule", "Unused local eliminator")
+ padOpt("jap", "Jimple annotation pack: adds intraprocedural tags")
+ padVal("jap.npc", "Null pointer checker")
+ padVal("jap.npcolorer", "Null pointer colourer: tags references for eclipse")
+ padVal("jap.abc", "Array bound checker")
+ padVal("jap.profiling", "Instruments null pointer and array checks")
+ padVal("jap.sea", "Side effect tagger")
+ padVal("jap.fieldrw", "Field read/write tagger")
+ padVal("jap.cgtagger", "Call graph tagger")
+ padVal("jap.parity", "Parity tagger")
+ padVal("jap.pat", "Colour-codes method parameters that may be aliased")
+ padVal("jap.lvtagger", "Creates color tags for live variables")
+ padVal("jap.rdtagger", "Creates link tags for reaching defs")
+ padVal("jap.che", "Indicates whether cast checks can be eliminated")
+ padVal("jap.umt", "Inserts assertions into unreachable methods")
+ padVal("jap.lit", "Tags loop invariants")
+ padVal("jap.aet", "Tags statements with sets of available expressions")
+ padVal("jap.dmt", "Tags dominators of statement")
+ padOpt("gb", "Creates a GrimpBody for each method")
+ padVal("gb.a1", "Aggregator: removes some copies, pre-folding")
+ padVal("gb.cf", "Constructor folder")
+ padVal("gb.a2", "Aggregator: removes some copies, post-folding")
+ padVal("gb.ule", "Unused local eliminator")
+ padOpt("gop", "Grimp optimization pack")
+ padOpt("bb", "Creates Baf bodies")
+ padVal("bb.lso", "Load store optimizer")
+ padVal("bb.sco", "Store chain optimizer")
+ padVal("bb.pho", "Peephole optimizer")
+ padVal("bb.ule", "Unused local eliminator")
+ padVal("bb.lp", "Local packer: minimizes number of locals")
+ padVal("bb.ne", "Nop eliminator")
+ padOpt("bop", "Baf optimization pack")
+ padOpt("tag", "Tag aggregator: turns tags into attributes")
+ padVal("tag.ln", "Line number aggregator")
+ padVal("tag.an", "Array bounds and null pointer check aggregator")
+ padVal("tag.dep", "Dependence aggregator")
+ padVal("tag.fieldrw", "Field read/write aggregator")
+ padOpt("db", "Dummy phase to store options for Dava")
+ padVal("db.transformations", "The Dava back-end with all its transformations")
+ padVal("db.renamer", "Apply heuristics based naming of local variables")
+ padVal("db.deobfuscate", "Apply de-obfuscation analyses")
+ padVal("db.force-recompile", "Try to get recompilable code.");
}
public String getPhaseHelp(String phaseName) {
if (phaseName.equals("jb"))
return "Phase " + phaseName + ":\n"
+ "\nJimple Body Creation creates a JimpleBody for each input method, \nusing either asm, to read .class files, or the jimple parser, to \nread .jimple files."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("use-original-names (false)", "")
+ padOpt("preserve-source-annotations (false)", "")
+ padOpt("stabilize-local-names (false)", "")
+ padOpt("model-lambdametafactory (true)", "Replace dynamic invoke instructions to the LambdaMetafactory by static invokes to a synthetic LambdaMetafactory implementation.");
if (phaseName.equals("jb.dtr"))
return "Phase " + phaseName + ":\n"
+ "\nThis transformer detects cases in which the same code block is \ncovered by two different catch all traps with different \nexception handlers (A and B), and if there is at the same time a \nthird catch all trap that covers the second handler B and jumps \nto A, then the second trap is unnecessary, because it is already \ncovered by a combination of the other two traps. This \ntransformer removes the unnecessary trap."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jb.ese"))
return "Phase " + phaseName + ":\n"
+ "\nThe Empty Switch Eliminator detects and removes switch \nstatements that have no data labels. Instead, the code is \ntransformed to contain a single jump statement to the default \nlabel."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jb.ls"))
return "Phase " + phaseName + ":\n"
+ "\nThe Local Splitter identifies DU-UD webs for local variables and \nintroduces new variables so that each disjoint web is associated \nwith a single local."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jb.sils"))
return "Phase " + phaseName + ":\n"
+ "\n"
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jb.a"))
return "Phase " + phaseName + ":\n"
+ "\nThe Jimple Local Aggregator removes some unnecessary copies by \ncombining local variables. Essentially, it finds definitions \nwhich have only a single use and, if it is safe to do so, \nremoves the original definition after replacing the use with the \ndefinition's right-hand side. At this stage in JimpleBody \nconstruction, local aggregation serves largely to remove the \ncopies to and from stack variables which simulate load and store \ninstructions in the original bytecode."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("jb.ule"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unused Local Eliminator removes any unused locals from the \nmethod."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jb.tr"))
return "Phase " + phaseName + ":\n"
+ "\nThe Type Assigner gives local variables types which will \naccommodate the values stored in them over the course of the \nmethod."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("use-older-type-assigner (false)", "Enables the older type assigner")
+ padOpt("compare-type-assigners (false)", "Compares Ben Bellamy's and the older type assigner")
+ padOpt("ignore-nullpointer-dereferences (false)", "Ignores virtual method calls on base objects that may only be null");
if (phaseName.equals("jb.ulp"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unsplit-originals Local Packer executes only when the \n`use-original-names' option is chosen for the `jb' phase. The \nLocal Packer attempts to minimize the number of local variables \nrequired in a method by reusing the same variable for disjoint \nDU-UD webs. Conceptually, it is the inverse of the Local \nSplitter."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("unsplit-original-locals (true)", "");
if (phaseName.equals("jb.lns"))
return "Phase " + phaseName + ":\n"
+ "\nThe Local Name Standardizer assigns generic names to local \nvariables."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (false)", "")
+ padOpt("sort-locals (false)", "Specifies whether the locals shall be ordered.");
if (phaseName.equals("jb.cp"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase performs cascaded copy propagation. If the propagator \nencounters situations of the form: A: a = ...; ... B: x = a; ... \nC: ... = ... x; where a and x are each defined only once (at A \nand B, respectively), then it can propagate immediately without \nchecking between B and C for redefinitions of a. In this case \nthe propagator is global. Otherwise, if a has multiple \ndefinitions then the propagator checks for redefinitions and \npropagates copies only within extended basic blocks."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-regular-locals (false)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("jb.dae"))
return "Phase " + phaseName + ":\n"
+ "\nThe Dead Assignment Eliminator eliminates assignment statements \nto locals whose values are not subsequently used, unless \nevaluating the right-hand side of the assignment may cause \nside-effects."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("jb.cp-ule"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase removes any locals that are unused after copy \npropagation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jb.lp"))
return "Phase " + phaseName + ":\n"
+ "\nThe Local Packer attempts to minimize the number of local \nvariables required in a method by reusing the same variable for \ndisjoint DU-UD webs. Conceptually, it is the inverse of the \nLocal Splitter."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("unsplit-original-locals (false)", "");
if (phaseName.equals("jb.ne"))
return "Phase " + phaseName + ":\n"
+ "\nThe Nop Eliminator removes nop statements from the method."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jb.uce"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unreachable Code Eliminator removes unreachable code and \ntraps whose catch blocks are empty."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("remove-unreachable-traps (true)", "");
if (phaseName.equals("jb.tt"))
return "Phase " + phaseName + ":\n"
+ "\nThe Trap Tightener changes the area protected by each exception \nhandler, so that it begins with the first instruction in the old \nprotected area which is actually capable of throwing an \nexception caught by the handler, and ends just after the last \ninstruction in the old protected area which can throw an \nexception caught by the handler. This reduces the chance of \nproducing unverifiable code as a byproduct of pruning \nexceptional control flow within CFGs."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jb.cbf"))
return "Phase " + phaseName + ":\n"
+ "\nThe Conditional Branch Folder statically evaluates the \nconditional expression of Jimple if statements. If the condition \nis identically true or false, the Folder replaces the \nconditional branch statement with an unconditional goto \nstatement."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jj"))
return "Phase " + phaseName + ":\n"
+ "\nJimple Body Creation creates a JimpleBody for each input method, \nusing polyglot, to read .java files."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("use-original-names (true)", "");
if (phaseName.equals("jj.ls"))
return "Phase " + phaseName + ":\n"
+ "\nThe Local Splitter identifies DU-UD webs for local variables and \nintroduces new variables so that each disjoint web is associated \nwith a single local."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jj.sils"))
return "Phase " + phaseName + ":\n"
+ "\n"
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jj.a"))
return "Phase " + phaseName + ":\n"
+ "\nThe Jimple Local Aggregator removes some unnecessary copies by \ncombining local variables. Essentially, it finds definitions \nwhich have only a single use and, if it is safe to do so, \nremoves the original definition after replacing the use with the \ndefinition's right-hand side. At this stage in JimpleBody \nconstruction, local aggregation serves largely to remove the \ncopies to and from stack variables which simulate load and store \ninstructions in the original bytecode."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("jj.ule"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unused Local Eliminator removes any unused locals from the \nmethod."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jj.tr"))
return "Phase " + phaseName + ":\n"
+ "\nThe Type Assigner gives local variables types which will \naccommodate the values stored in them over the course of the \nmethod."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jj.ulp"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unsplit-originals Local Packer executes only when the \n`use-original-names' option is chosen for the `jb' phase. The \nLocal Packer attempts to minimize the number of local variables \nrequired in a method by reusing the same variable for disjoint \nDU-UD webs. Conceptually, it is the inverse of the Local \nSplitter."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("unsplit-original-locals (false)", "");
if (phaseName.equals("jj.lns"))
return "Phase " + phaseName + ":\n"
+ "\nThe Local Name Standardizer assigns generic names to local \nvariables."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (false)", "");
if (phaseName.equals("jj.cp"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase performs cascaded copy propagation. If the propagator \nencounters situations of the form: A: a = ...; ... B: x = a; ... \nC: ... = ... x; where a and x are each defined only once (at A \nand B, respectively), then it can propagate immediately without \nchecking between B and C for redefinitions of a. In this case \nthe propagator is global. Otherwise, if a has multiple \ndefinitions then the propagator checks for redefinitions and \npropagates copies only within extended basic blocks."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-regular-locals (false)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("jj.dae"))
return "Phase " + phaseName + ":\n"
+ "\nThe Dead Assignment Eliminator eliminates assignment statements \nto locals whose values are not subsequently used, unless \nevaluating the right-hand side of the assignment may cause \nside-effects."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("jj.cp-ule"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase removes any locals that are unused after copy \npropagation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jj.lp"))
return "Phase " + phaseName + ":\n"
+ "\nThe Local Packer attempts to minimize the number of local \nvariables required in a method by reusing the same variable for \ndisjoint DU-UD webs. Conceptually, it is the inverse of the \nLocal Splitter."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("unsplit-original-locals (false)", "");
if (phaseName.equals("jj.ne"))
return "Phase " + phaseName + ":\n"
+ "\nThe Nop Eliminator removes nop statements from the method."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jj.uce"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unreachable Code Eliminator removes unreachable code and \ntraps whose catch blocks are empty."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("wjpp"))
return "Phase " + phaseName + ":\n"
+ "\nThis pack allows you to insert pre-processors that are run \nbefore call-graph construction. Only enabled in whole-program \nmode."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("wjpp.cimbt"))
return "Phase " + phaseName + ":\n"
+ "\nWhen using the types-for-invoke option of the cg phase, problems \nmight occur if the base object of a call to Method.invoke() (the \nfirst argument) is a string constant. This option replaces all \nstring constants of such calls by locals and, therefore, allows \nthe static resolution of reflective call targets on constant \nstring objects."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("verbose (false)", "");
if (phaseName.equals("wspp"))
return "Phase " + phaseName + ":\n"
+ "\nThis pack allows you to insert pre-processors that are run \nbefore call-graph construction. Only enabled in whole-program \nShimple mode. In an unmodified copy of Soot, this pack is empty."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("cg"))
return "Phase " + phaseName + ":\n"
+ "\nThe Call Graph Constructor computes a call graph for whole \nprogram analysis. When this pack finishes, a call graph is \navailable in the Scene. The different phases in this pack are \ndifferent ways to construct the call graph. Exactly one phase in \nthis pack must be enabled; Soot will raise an error otherwise."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("safe-forname (false)", "Handle Class.forName() calls conservatively")
+ padOpt("safe-newinstance (false)", "Handle Class.newInstance() calls conservatively")
+ padOpt("library", "Specifies whether the target classes should be treated as an application or a library.")
+ padVal("disabled (default)", "Call(and pointer assignment) graph construction treat the target classes as application starting from the entry points.")
+ padVal("any-subtype", "In this mode types of any accessible field, method parameter, this local, or caugth exception is set to any possible sub type according to the class hierarchy of the target library.")
+ padVal("signature-resolution", "In this mode types of any accessible field, method parameter, this local, or caugth exception is set to any possible sub type according to a possible extended class hierarchy of the target library.")
+ padOpt("verbose (false)", "Print warnings about where the call graph may be incomplete")
+ padOpt("jdkver (3)", "JDK version for native methods")
+ padOpt("all-reachable (false)", "Assume all methods of application classes are reachable.")
+ padOpt("implicit-entry (true)", "Include methods called implicitly by the VM as entry points")
+ padOpt("trim-clinit (true)", "Removes redundant static initializer calls")
+ padOpt("reflection-log", "Uses a reflection log to resolve reflective calls.")
+ padOpt("guards (ignore)", "Describes how to guard the program from unsound assumptions.")
+ padOpt("types-for-invoke (false)", "Uses reaching types inferred by the pointer analysis to resolve reflective calls.")
+ padOpt("resolve-all-abstract-invokes (false)", "Causes methods invoked on abstract classes to be resolved even if there are no non-abstract children of the classes in the Scene.");
if (phaseName.equals("cg.cha"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase uses Class Hierarchy Analysis to generate a call \ngraph."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("verbose (false)", "Print statistics about the resulting call graph")
+ padOpt("apponly (false)", "Consider only application classes");
if (phaseName.equals("cg.spark"))
return "Phase " + phaseName + ":\n"
+ "\nSpark is a flexible points-to analysis framework. Aside from \nbuilding a call graph, it also generates information about the \ntargets of pointers. For details about Spark, please see Ondrej \nLhotak's M.Sc. thesis."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("verbose (false)", "Print detailed information about the execution of Spark")
+ padOpt("ignore-types (false)", "Make Spark completely ignore declared types of variables")
+ padOpt("force-gc (false)", "Force garbage collection for measuring memory usage")
+ padOpt("pre-jimplify (false)", "Jimplify all methods before starting Spark")
+ padOpt("apponly (false)", "Consider only application classes")
+ padOpt("vta (false)", "Emulate Variable Type Analysis")
+ padOpt("rta (false)", "Emulate Rapid Type Analysis")
+ padOpt("field-based (false)", "Use a field-based rather than field-sensitive representation")
+ padOpt("types-for-sites (false)", "Represent objects by their actual type rather than allocation site")
+ padOpt("merge-stringbuffer (true)", "Represent all StringBuffers as one object")
+ padOpt("string-constants (false)", "Propagate all string constants, not just class names")
+ padOpt("simulate-natives (true)", "Simulate effects of native methods in standard class library")
+ padOpt("empties-as-allocs (false)", "Treat singletons for empty sets etc. as allocation sites")
+ padOpt("simple-edges-bidirectional (false)", "Equality-based analysis between variable nodes")
+ padOpt("on-fly-cg (true)", "Build call graph as receiver types become known")
+ padOpt("simplify-offline (false)", "Collapse single-entry subgraphs of the PAG")
+ padOpt("simplify-sccs (false)", "Collapse strongly-connected components of the PAG")
+ padOpt("ignore-types-for-sccs (false)", "Ignore declared types when determining node equivalence for SCCs")
+ padOpt("propagator", "Select propagation algorithm")
+ padVal("iter", "Simple iterative algorithm")
+ padVal("worklist (default)", "Fast, worklist-based algorithm")
+ padVal("cycle", "Unfinished on-the-fly cycle detection algorithm")
+ padVal("merge", "Unfinished field reference merging algorithms")
+ padVal("alias", "Alias-edge based algorithm")
+ padVal("none", "Disable propagation")
+ padOpt("set-impl", "Select points-to set implementation")
+ padVal("hash", "Use Java HashSet")
+ padVal("bit", "Bit vector")
+ padVal("hybrid", "Hybrid representation using bit vector for large sets")
+ padVal("array", "Sorted array representation")
+ padVal("heintze", "Heintze's shared bit-vector and overflow list representation")
+ padVal("sharedlist", "Shared list representation")
+ padVal("double (default)", "Double set representation for incremental propagation")
+ padOpt("double-set-old", "Select implementation of points-to set for old part of double set")
+ padVal("hash", "Use Java HashSet")
+ padVal("bit", "Bit vector")
+ padVal("hybrid (default)", "Hybrid representation using bit vector for large sets")
+ padVal("array", "Sorted array representation")
+ padVal("heintze", "Heintze's shared bit-vector and overflow list representation")
+ padVal("sharedlist", "Shared list representation")
+ padOpt("double-set-new", "Select implementation of points-to set for new part of double set")
+ padVal("hash", "Use Java HashSet")
+ padVal("bit", "Bit vector")
+ padVal("hybrid (default)", "Hybrid representation using bit vector for large sets")
+ padVal("array", "Sorted array representation")
+ padVal("heintze", "Heintze's shared bit-vector and overflow list representation")
+ padVal("sharedlist", "Shared list representation")
+ padOpt("dump-html (false)", "Dump pointer assignment graph to HTML for debugging")
+ padOpt("dump-pag (false)", "Dump pointer assignment graph for other solvers")
+ padOpt("dump-solution (false)", "Dump final solution for comparison with other solvers")
+ padOpt("topo-sort (false)", "Sort variable nodes in dump")
+ padOpt("dump-types (true)", "Include declared types in dump")
+ padOpt("class-method-var (true)", "In dump, label variables by class and method")
+ padOpt("dump-answer (false)", "Dump computed reaching types for comparison with other solvers")
+ padOpt("add-tags (false)", "Output points-to results in tags for viewing with the Jimple")
+ padOpt("set-mass (false)", "Calculate statistics about points-to set sizes")
+ padOpt("cs-demand (false)", "After running Spark, refine points-to sets on demand with context information")
+ padOpt("lazy-pts (true)", "Create lazy points-to sets that create context information only when needed.")
+ padOpt("traversal (75000)", "Make the analysis traverse at most this number of nodes per query.")
+ padOpt("passes (10)", "Perform at most this number of refinement iterations.")
+ padOpt("geom-pta (false)", "This switch enables/disables the geometric analysis.")
+ padOpt("geom-encoding (Geom)", "Encoding methodology")
+ padVal("Geom (default)", "Geometric Encoding")
+ padVal("HeapIns", "Heap Insensitive Encoding")
+ padVal("PtIns", "PtIns")
+ padOpt("geom-worklist (PQ)", "Worklist type")
+ padVal("PQ (default)", "Priority Queue")
+ padVal("FIFO", "FIFO Queue")
+ padOpt("geom-dump-verbose ()", "Filename for detailed execution log")
+ padOpt("geom-verify-name ()", "Filename for verification file")
+ padOpt("geom-eval (0)", "Precision evaluation methodologies")
+ padOpt("geom-trans (false)", "Transform to context-insensitive result")
+ padOpt("geom-frac-base (40)", "Fractional parameter for precision/performance trade-off")
+ padOpt("geom-blocking (true)", "Enable blocking strategy for recursive calls")
+ padOpt("geom-runs (1)", "Iterations of analysis")
+ padOpt("geom-app-only (true)", "Processing pointers that impact pointers in application code only");
if (phaseName.equals("cg.paddle"))
return "Phase " + phaseName + ":\n"
+ "\nPaddle is a BDD-based interprocedural analysis framework. It \nincludes points-to analysis, call graph construction, and \nvarious client analyses."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("verbose (false)", "Print detailed information about the execution of Paddle")
+ padOpt("conf", "Select Paddle configuration")
+ padVal("ofcg (default)", "On-the fly call graph")
+ padVal("cha", "CHA only")
+ padVal("cha-aot", "CHA ahead-of-time callgraph")
+ padVal("ofcg-aot", "OFCG-AOT callgraph")
+ padVal("cha-context-aot", "CHA-Context-AOT callgraph")
+ padVal("ofcg-context-aot", "OFCG-Context-AOT callgraph")
+ padVal("cha-context", "CHA-Context callgraph")
+ padVal("ofcg-context", "OFCG-Context callgraph")
+ padOpt("bdd (false)", "Use BDD version of Paddle")
+ padOpt("order (32)", "")
+ padOpt("dynamic-order", "")
+ padOpt("profile (false)", "Profile BDDs using JeddProfiler")
+ padOpt("verbosegc (false)", "Print memory usage at each BDD garbage collection.")
+ padOpt("q", "Select queue implementation")
+ padVal("auto (default)", "Select queue implementation based on bdd option")
+ padVal("trad", "Normal worklist queue implementation")
+ padVal("bdd", "BDD-based queue implementation")
+ padVal("debug", "Debugging queue implementation")
+ padVal("trace", "Tracing queue implementation")
+ padVal("numtrace", "Number-tracing queue implementation")
+ padOpt("backend", "Select BDD backend")
+ padVal("auto (default)", "Select backend based on bdd option")
+ padVal("buddy", "BuDDy backend")
+ padVal("cudd", "CUDD backend")
+ padVal("sable", "SableJBDD backend")
+ padVal("javabdd", "JavaBDD backend")
+ padVal("none", "No BDDs")
+ padOpt("bdd-nodes (0)", "Number of BDD nodes to allocate (0=unlimited)")
+ padOpt("ignore-types (false)", "Make Paddle completely ignore declared types of variables")
+ padOpt("pre-jimplify (false)", "Jimplify all methods before starting Paddle")
+ padOpt("context", "Select context-sensitivity level")
+ padVal("insens (default)", "Builds a context-insensitive call graph")
+ padVal("1cfa", "Builds a 1-CFA call graph")
+ padVal("kcfa", "Builds a k-CFA call graph")
+ padVal("objsens", "Builds an object-sensitive call graph")
+ padVal("kobjsens", "Builds a k-object-sensitive call graph")
+ padVal("uniqkobjsens", "Builds a unique-k-object-sensitive call graph")
+ padVal("threadkobjsens", "Experimental option for thread-entry-point sensitivity")
+ padOpt("k (2)", "")
+ padOpt("context-heap (false)", "Treat allocation sites context-sensitively")
+ padOpt("rta (false)", "Emulate Rapid Type Analysis")
+ padOpt("field-based (false)", "Use a field-based rather than field-sensitive representation")
+ padOpt("types-for-sites (false)", "Represent objects by their actual type rather than allocation site")
+ padOpt("merge-stringbuffer (true)", "Represent all StringBuffers as one object")
+ padOpt("string-constants (false)", "Propagate all string constants, not just class names")
+ padOpt("simulate-natives (true)", "Simulate effects of native methods in standard class library")
+ padOpt("global-nodes-in-natives (false)", "Use global node to model variables in simulations of native methods")
+ padOpt("simple-edges-bidirectional (false)", "Equality-based analysis between variable nodes")
+ padOpt("this-edges (false)", "Use pointer assignment edges to model this parameters")
+ padOpt("precise-newinstance (true)", "Make newInstance only allocate objects of dynamic classes")
+ padOpt("propagator", "Select propagation algorithm")
+ padVal("auto (default)", "Select propagation algorithm based on bdd option")
+ padVal("iter", "Simple iterative algorithm")
+ padVal("worklist", "Fast, worklist-based algorithm")
+ padVal("alias", "Alias-edge based algorithm")
+ padVal("bdd", "BDD-based propagator")
+ padVal("incbdd", "Incrementalized BDD-based propagator")
+ padOpt("set-impl", "Select points-to set implementation")
+ padVal("hash", "Use Java HashSet")
+ padVal("bit", "Bit vector")
+ padVal("hybrid", "Hybrid representation using bit vector for large sets")
+ padVal("array", "Sorted array representation")
+ padVal("heintze", "Heintze's shared bit-vector and overflow list representation")
+ padVal("double (default)", "Double set representation for incremental propagation")
+ padOpt("double-set-old", "Select implementation of points-to set for old part of double set")
+ padVal("hash", "Use Java HashSet")
+ padVal("bit", "Bit vector")
+ padVal("hybrid (default)", "Hybrid representation using bit vector for large sets")
+ padVal("array", "Sorted array representation")
+ padVal("heintze", "Heintze's shared bit-vector and overflow list representation")
+ padOpt("double-set-new", "Select implementation of points-to set for new part of double set")
+ padVal("hash", "Use Java HashSet")
+ padVal("bit", "Bit vector")
+ padVal("hybrid (default)", "Hybrid representation using bit vector for large sets")
+ padVal("array", "Sorted array representation")
+ padVal("heintze", "Heintze's shared bit-vector and overflow list representation")
+ padOpt("context-counts (false)", "Print number of contexts for each method")
+ padOpt("total-context-counts (false)", "Print total number of contexts")
+ padOpt("method-context-counts (false)", "Print number of contexts for each method")
+ padOpt("set-mass (false)", "Calculate statistics about points-to set sizes")
+ padOpt("number-nodes (true)", "Print node numbers in dumps");
if (phaseName.equals("wstp"))
return "Phase " + phaseName + ":\n"
+ "\nSoot can perform whole-program analyses. In whole-shimple mode, \nSoot applies the contents of the Whole-Shimple Transformation \nPack to the scene as a whole after constructing a call graph for \nthe program. In an unmodified copy of Soot the Whole-Shimple \nTransformation Pack is empty."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("wsop"))
return "Phase " + phaseName + ":\n"
+ "\nIf Soot is running in whole shimple mode and the Whole-Shimple \nOptimization Pack is enabled, the pack's transformations are \napplied to the scene as a whole after construction of the call \ngraph and application of any enabled Whole-Shimple \nTransformations. In an unmodified copy of Soot the Whole-Shimple \nOptimization Pack is empty."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("wjtp"))
return "Phase " + phaseName + ":\n"
+ "\nSoot can perform whole-program analyses. In whole-program mode, \nSoot applies the contents of the Whole-Jimple Transformation \nPack to the scene as a whole after constructing a call graph for \nthe program."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("wjtp.mhp"))
return "Phase " + phaseName + ":\n"
+ "\nMay Happen in Parallel (MHP) Analyses determine what program \nstatements may be run by different threads concurrently. This \nphase does not perform any transformation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("wjtp.tn"))
return "Phase " + phaseName + ":\n"
+ "\nThe Lock Allocator finds critical sections (synchronized \nregions) in Java programs and assigns locks for execution on \nboth optimistic and pessimistic JVMs. It can also be used to \nanalyze the existing locks."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("locking-scheme", "Selects the granularity of the generated lock allocation")
+ padVal("medium-grained (default)", "Use a runtime object for synchronization where possible")
+ padVal("coarse-grained", "Use static objects for synchronization")
+ padVal("single-static", "Use just one static synchronization object for all transactional regions")
+ padVal("leave-original", "Analyse the existing lock structure without making changes")
+ padOpt("avoid-deadlock (true)", "Perform Deadlock Avoidance")
+ padOpt("open-nesting (true)", "Use an open nesting model")
+ padOpt("do-mhp (true)", "Perform a May-Happen-in-Parallel analysis")
+ padOpt("do-tlo (true)", "Perform a Local-Objects analysis")
+ padOpt("print-graph (false)", "Print topological graph of transactions")
+ padOpt("print-table (false)", "Print table of transactions")
+ padOpt("print-debug (false)", "Print debugging info");
if (phaseName.equals("wjtp.rdc"))
return "Phase " + phaseName + ":\n"
+ "\nRename duplicated classes when the file system is not case \nsensitive. If the file system is case sensitive, this phase does \nnothing."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("fcn fixed-class-names", "Set ARG for the fixed class names.");
if (phaseName.equals("wjop"))
return "Phase " + phaseName + ":\n"
+ "\nIf Soot is running in whole program mode and the Whole-Jimple \nOptimization Pack is enabled, the pack's transformations are \napplied to the scene as a whole after construction of the call \ngraph and application of any enabled Whole-Jimple \nTransformations."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("wjop.smb"))
return "Phase " + phaseName + ":\n"
+ "\nThe Static Method Binder statically binds monomorphic call \nsites. That is, it searches the call graph for virtual method \ninvocations that can be determined statically to call only a \nsingle implementation of the called method. Then it replaces \nsuch virtual invocations with invocations of a static copy of \nthe single called implementation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("insert-null-checks (true)", "")
+ padOpt("insert-redundant-casts (true)", "")
+ padOpt("allowed-modifier-changes", "")
+ padVal("unsafe (default)", "")
+ padVal("safe", "")
+ padVal("none", "");
if (phaseName.equals("wjop.si"))
return "Phase " + phaseName + ":\n"
+ "\nThe Static Inliner visits all call sites in the call graph in a \nbottom-up fashion, replacing monomorphic calls with inlined \ncopies of the invoked methods."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("rerun-jb (true)", "")
+ padOpt("insert-null-checks (true)", "")
+ padOpt("insert-redundant-casts (true)", "")
+ padOpt("allowed-modifier-changes", "")
+ padVal("unsafe (default)", "")
+ padVal("safe", "")
+ padVal("none", "")
+ padOpt("expansion-factor (3)", "")
+ padOpt("max-container-size (5000)", "")
+ padOpt("max-inlinee-size (20)", "");
if (phaseName.equals("wjap"))
return "Phase " + phaseName + ":\n"
+ "\nSome analyses do not transform Jimple body directly, but \nannotate statements or values with tags. Whole-Jimple annotation \npack provides a place for annotation-oriented analyses in whole \nprogram mode."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("wjap.ra"))
return "Phase " + phaseName + ":\n"
+ "\nThe Rectangular Array Finder traverses Jimple statements based \non the static call graph, and finds array variables which always \nhold rectangular two-dimensional array objects. In Java, a \nmulti-dimensional array is an array of arrays, which means the \nshape of the array can be ragged. Nevertheless, many \napplications use rectangular arrays. Knowing that an array is \nrectangular can be very helpful in proving safe array bounds \nchecks. The Rectangular Array Finder does not change the program \nbeing analyzed. Its results are used by the Array Bound Checker."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("wjap.umt"))
return "Phase " + phaseName + ":\n"
+ "\nUses the call graph to determine which methods are unreachable \nand adds color tags so they can be highlighted in a source \nbrowser."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("wjap.uft"))
return "Phase " + phaseName + ":\n"
+ "\nUses the call graph to determine which fields are unreachable \nand adds color tags so they can be highlighted in a source \nbrowser."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("wjap.tqt"))
return "Phase " + phaseName + ":\n"
+ "\nDetermines which methods and fields have qualifiers that could \nbe tightened. For example: if a field or method has the \nqualifier of public but is only used within the declaring class \nit could be private. This, this field or method is tagged with \ncolor tags so that the results can be highlighted in a source \nbrowser."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("wjap.cgg"))
return "Phase " + phaseName + ":\n"
+ "\nCreates graphical call graph."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("show-lib-meths (false)", "");
if (phaseName.equals("wjap.purity"))
return "Phase " + phaseName + ":\n"
+ "\nPurity anaysis implemented by Antoine Mine and based on the \npaper A Combined Pointer and Purity Analysis for Java Programs \nby Alexandru Salcianu and Martin Rinard."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("dump-summaries (true)", "")
+ padOpt("dump-cg (false)", "")
+ padOpt("dump-intra (false)", "")
+ padOpt("print (true)", "")
+ padOpt("annotate (true)", "Marks pure methods with a purity bytecode attribute")
+ padOpt("verbose (false)", "");
if (phaseName.equals("shimple"))
return "Phase " + phaseName + ":\n"
+ "\nShimple Control sets parameters which apply throughout the \ncreation and manipulation of Shimple bodies. Shimple is Soot's \nSSA representation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("node-elim-opt (true)", "Node elimination optimizations")
+ padOpt("standard-local-names (false)", "Uses naming scheme of the Local Name Standardizer.")
+ padOpt("extended (false)", "Compute extended SSA (SSI) form.")
+ padOpt("debug (false)", "Enables debugging output, if any.");
if (phaseName.equals("stp"))
return "Phase " + phaseName + ":\n"
+ "\nWhen the Shimple representation is produced, Soot applies the \ncontents of the Shimple Transformation Pack to each method under \nanalysis. This pack contains no transformations in an unmodified \nversion of Soot."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("sop"))
return "Phase " + phaseName + ":\n"
+ "\nThe Shimple Optimization Pack contains transformations that \nperform optimizations on Shimple, Soot's SSA representation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("sop.cpf"))
return "Phase " + phaseName + ":\n"
+ "\nA powerful constant propagator and folder based on an algorithm \nsketched by Cytron et al that takes conditional control flow \ninto account. This optimization demonstrates some of the \nbenefits of SSA -- particularly the fact that Phi nodes \nrepresent natural merge points in the control flow."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("prune-cfg (true)", "Take advantage of CFG optimization opportunities.");
if (phaseName.equals("jtp"))
return "Phase " + phaseName + ":\n"
+ "\nSoot applies the contents of the Jimple Transformation Pack to \neach method under analysis. This pack contains no \ntransformations in an unmodified version of Soot."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jop"))
return "Phase " + phaseName + ":\n"
+ "\nWhen Soot's Optimize option is on, Soot applies the Jimple \nOptimization Pack to every JimpleBody in application classes. \nThis section lists the default transformations in the Jimple \nOptimization Pack."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "Eliminates common subexpressions");
if (phaseName.equals("jop.cse"))
return "Phase " + phaseName + ":\n"
+ "\nThe Common Subexpression Eliminator runs an available \nexpressions analysis on the method body, then eliminates common \nsubexpressions. This implementation is especially slow, as it \nruns on individual statements rather than on basic blocks. A \nbetter implementation (which would find most common \nsubexpressions, but not all) would use basic blocks instead. \nThis implementation is also slow because the flow universe is \nexplicitly created; it need not be. A better implementation \nwould implicitly compute the kill sets at every node. Because of \nits current slowness, this transformation is not enabled by \ndefault."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("naive-side-effect (false)", "Use naive side effect analysis even if interprocedural information is available");
if (phaseName.equals("jop.bcm"))
return "Phase " + phaseName + ":\n"
+ "\nBusy Code Motion is a straightforward implementation of Partial \nRedundancy Elimination. This implementation is not very \naggressive. Lazy Code Motion is an improved version which should \nbe used instead of Busy Code Motion."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("naive-side-effect (false)", "Use a naive side effect analysis even if interprocedural information is available");
if (phaseName.equals("jop.lcm"))
return "Phase " + phaseName + ":\n"
+ "\nLazy Code Motion is an enhanced version of Busy Code Motion, a \nPartial Redundancy Eliminator. Before doing Partial Redundancy \nElimination, this optimization performs loop inversion (turning \nwhile loops into do while loops inside an if statement). This \nallows the Partial Redundancy Eliminator to optimize loop \ninvariants of while loops."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("safety", "")
+ padVal("safe (default)", "")
+ padVal("medium", "")
+ padVal("unsafe", "")
+ padOpt("unroll (true)", "")
+ padOpt("naive-side-effect (false)", "Use a naive side effect analysis even if interprocedural information is available");
if (phaseName.equals("jop.cp"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase performs cascaded copy propagation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-regular-locals (false)", "")
+ padOpt("only-stack-locals (false)", "");
if (phaseName.equals("jop.cpf"))
return "Phase " + phaseName + ":\n"
+ "\nThe Jimple Constant Propagator and Folder evaluates any \nexpressions consisting entirely of compile-time constants, for \nexample 2 * 3, and replaces the expression with the constant \nresult, in this case 6."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jop.cbf"))
return "Phase " + phaseName + ":\n"
+ "\nThe Conditional Branch Folder statically evaluates the \nconditional expression of Jimple if statements. If the condition \nis identically true or false, the Folder replaces the \nconditional branch statement with an unconditional goto \nstatement."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jop.dae"))
return "Phase " + phaseName + ":\n"
+ "\nThe Dead Assignment Eliminator eliminates assignment statements \nto locals whose values are not subsequently used, unless \nevaluating the right-hand side of the assignment may cause \nside-effects."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-tag (false)", "")
+ padOpt("only-stack-locals (false)", "");
if (phaseName.equals("jop.nce"))
return "Phase " + phaseName + ":\n"
+ "\nReplaces statements 'if(x!=null) goto y' with 'goto y' if x is \nknown to be non-null or with 'nop' if it is known to be null, \netc. Generates dead code and is hence followed by unreachable \ncode elimination. Disabled by default because it can be \nexpensive on methods with many locals."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jop.uce1"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unreachable Code Eliminator removes unreachable code and \ntraps whose catch blocks are empty."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("remove-unreachable-traps (false)", "");
if (phaseName.equals("jop.ubf1"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unconditional Branch Folder removes unnecessary `goto' \nstatements from a JimpleBody. If a goto statement's target is \nthe next instruction, then the statement is removed. If a goto's \ntarget is another goto, with target y, then the first \nstatement's target is changed to y. If some if statement's \ntarget is a goto statement, then the if's target can be replaced \nwith the goto's target. (These situations can result from other \noptimizations, and branch folding may itself generate more \nunreachable code.)"
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jop.uce2"))
return "Phase " + phaseName + ":\n"
+ "\nAnother iteration of the Unreachable Code Eliminator."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("remove-unreachable-traps (false)", "");
if (phaseName.equals("jop.ubf2"))
return "Phase " + phaseName + ":\n"
+ "\nAnother iteration of the Unconditional Branch Folder."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jop.ule"))
return "Phase " + phaseName + ":\n"
+ "\nThe Unused Local Eliminator phase removes any unused locals from \nthe method."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jap"))
return "Phase " + phaseName + ":\n"
+ "\nThe Jimple Annotation Pack contains phases which add annotations \nto Jimple bodies individually (as opposed to the Whole-Jimple \nAnnotation Pack, which adds annotations based on the analysis of \nthe whole program)."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("jap.npc"))
return "Phase " + phaseName + ":\n"
+ "\nThe Null Pointer Checker finds instruction which have the \npotential to throw NullPointerExceptions and adds annotations \nindicating whether or not the pointer being dereferenced can be \ndetermined statically not to be null."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("only-array-ref (false)", "Annotate only array references")
+ padOpt("profiling (false)", "Insert instructions to count safe pointer accesses");
if (phaseName.equals("jap.npcolorer"))
return "Phase " + phaseName + ":\n"
+ "\nProduce colour tags that the Soot plug-in for Eclipse can use to \nhighlight null and non-null references."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.abc"))
return "Phase " + phaseName + ":\n"
+ "\nThe Array Bound Checker performs a static analysis to determine \nwhich array bounds checks may safely be eliminated and then \nannotates statements with the results of the analysis. If Soot \nis in whole-program mode, the Array Bound Checker can use the \nresults provided by the Rectangular Array Finder."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("with-all (false)", "")
+ padOpt("with-cse (false)", "")
+ padOpt("with-arrayref (false)", "")
+ padOpt("with-fieldref (false)", "")
+ padOpt("with-classfield (false)", "")
+ padOpt("with-rectarray (false)", "")
+ padOpt("profiling (false)", "Profile the results of array bounds check analysis.")
+ padOpt("add-color-tags (false)", "Add color tags to results of array bound check analysis.");
if (phaseName.equals("jap.profiling"))
return "Phase " + phaseName + ":\n"
+ "\nThe Profiling Generator inserts the method invocations required \nto initialize and to report the results of any profiling \nperformed by the Null Pointer Checker and Array Bound Checker. \nUsers of the Profiling Generator must provide a MultiCounter \nclass implementing the methods invoked. For details, see the \nProfilingGenerator source code."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("notmainentry (false)", "Instrument runBenchmark() instead of main()");
if (phaseName.equals("jap.sea"))
return "Phase " + phaseName + ":\n"
+ "\nThe Side Effect Tagger uses the active invoke graph to produce \nside-effect attributes, as described in the Spark thesis, \nchapter 6."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("naive (false)", "");
if (phaseName.equals("jap.fieldrw"))
return "Phase " + phaseName + ":\n"
+ "\nThe Field Read/Write Tagger uses the active invoke graph to \nproduce tags indicating which fields may be read or written by \neach statement, including invoke statements."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("threshold (100)", "");
if (phaseName.equals("jap.cgtagger"))
return "Phase " + phaseName + ":\n"
+ "\nThe Call Graph Tagger produces LinkTags based on the call graph. \nThe Eclipse plugin uses these tags to produce linked popup lists \nwhich indicate the source and target methods of the statement. \nSelecting a link from the list moves the cursor to the indicated \nmethod."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.parity"))
return "Phase " + phaseName + ":\n"
+ "\nThe Parity Tagger produces StringTags and ColorTags indicating \nthe parity of a variable (even, odd, top, or bottom). The \neclipse plugin can use tooltips and variable colouring to \ndisplay the information in these tags. For example, even \nvariables (such as x in x = 2) are coloured yellow."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.pat"))
return "Phase " + phaseName + ":\n"
+ "\nFor each method with parameters of reference type, this tagger \nindicates the aliasing relationships between the parameters \nusing colour tags. Parameters that may be aliased are the same \ncolour. Parameters that may not be aliased are in different \ncolours."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.lvtagger"))
return "Phase " + phaseName + ":\n"
+ "\nColors live variables."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.rdtagger"))
return "Phase " + phaseName + ":\n"
+ "\nFor each use of a local in a stmt creates a link to the reaching \ndef."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.che"))
return "Phase " + phaseName + ":\n"
+ "\nIndicates whether cast checks can be eliminated."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.umt"))
return "Phase " + phaseName + ":\n"
+ "\nWhen the whole-program analysis determines a method to be \nunreachable, this transformer inserts an assertion into the \nmethod to check that it is indeed unreachable."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.lit"))
return "Phase " + phaseName + ":\n"
+ "\nAn expression whose operands are constant or have reaching \ndefinitions from outside the loop body are tagged as loop \ninvariant."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("jap.aet"))
return "Phase " + phaseName + ":\n"
+ "\nA each statement a set of available expressions is after the \nstatement is added as a tag."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "")
+ padOpt("kind", "")
+ padVal("optimistic (default)", "")
+ padVal("pessimistic", "");
if (phaseName.equals("jap.dmt"))
return "Phase " + phaseName + ":\n"
+ "\nProvides link tags at a statement to all of the satements \ndominators."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("gb"))
return "Phase " + phaseName + ":\n"
+ "\nThe Grimp Body Creation phase creates a GrimpBody for each \nsource method. It is run only if the output format is grimp or \ngrimple, or if class files are being output and the Via Grimp \noption has been specified."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("gb.a1"))
return "Phase " + phaseName + ":\n"
+ "\nThe Grimp Pre-folding Aggregator combines some local variables, \nfinding definitions with only a single use and removing the \ndefinition after replacing the use with the definition's \nright-hand side, if it is safe to do so. While the mechanism is \nthe same as that employed by the Jimple Local Aggregator, there \nis more scope for aggregation because of Grimp's more \ncomplicated expressions."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("gb.cf"))
return "Phase " + phaseName + ":\n"
+ "\nThe Grimp Constructor Folder combines new statements with the \nspecialinvoke statement that calls the new object's constructor. \nFor example, it turns r2 = new java.util.ArrayList; r2.init(); \ninto r2 = new java.util.ArrayList();"
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("gb.a2"))
return "Phase " + phaseName + ":\n"
+ "\nThe Grimp Post-folding Aggregator combines local variables after \nconstructors have been folded. Constructor folding typically \nintroduces new opportunities for aggregation, since when a \nsequence of instructions like r2 = new java.util.ArrayList; \nr2.init(); r3 = r2 is replaced by r2 = new \njava.util.ArrayList(); r3 = r2 the invocation of init no longer \nrepresents a potential side-effect separating the two \ndefinitions, so they can be combined into r3 = new \njava.util.ArrayList(); (assuming there are no subsequent uses of \nr2)."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("only-stack-locals (true)", "");
if (phaseName.equals("gb.ule"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase removes any locals that are unused after constructor \nfolding and aggregation."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("gop"))
return "Phase " + phaseName + ":\n"
+ "\nThe Grimp Optimization pack performs optimizations on GrimpBodys \n(currently there are no optimizations performed specifically on \nGrimpBodys, and the pack is empty). It is run only if the output \nformat is grimp or grimple, or if class files are being output \nand the Via Grimp option has been specified."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("bb"))
return "Phase " + phaseName + ":\n"
+ "\nThe Baf Body Creation phase creates a BafBody from each source \nmethod. It is run if the output format is baf or b or asm or a, \nor if class files are being output and the Via Grimp option has \nnot been specified."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("bb.lso"))
return "Phase " + phaseName + ":\n"
+ "\nThe Load Store Optimizer replaces some combinations of loads to \nand stores from local variables with stack instructions. A \nsimple example would be the replacement of store.r $r2; load.r \n$r2; with dup1.r in cases where the value of r2 is not used \nsubsequently."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("debug (false)", "")
+ padOpt("inter (false)", "")
+ padOpt("sl (true)", "")
+ padOpt("sl2 (false)", "")
+ padOpt("sll (true)", "")
+ padOpt("sll2 (false)", "");
if (phaseName.equals("bb.sco"))
return "Phase " + phaseName + ":\n"
+ "\nThe store chain optimizer detects chains of push/store pairs \nthat write to the same variable and only retains the last store. \nIt removes the unnecessary previous push/stores that are \nsubsequently overwritten."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("bb.pho"))
return "Phase " + phaseName + ":\n"
+ "\nApplies peephole optimizations to the Baf intermediate \nrepresentation. Individual optimizations must be implemented by \nclasses implementing the Peephole interface. The Peephole \nOptimizer reads the names of the Peephole classes at runtime \nfrom the file peephole.dat and loads them dynamically. Then it \ncontinues to apply the Peepholes repeatedly until none of them \nare able to perform any further optimizations. Soot provides \nonly one Peephole, named ExamplePeephole, which is not enabled \nby the delivered peephole.dat file. ExamplePeephole removes all \ncheckcast instructions."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("bb.ule"))
return "Phase " + phaseName + ":\n"
+ "\nThis phase removes any locals that are unused after load store \noptimization and peephole optimization."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("bb.lp"))
return "Phase " + phaseName + ":\n"
+ "\nThe Local Packer attempts to minimize the number of local \nvariables required in a method by reusing the same variable for \ndisjoint DU-UD webs. Conceptually, it is the inverse of the \nLocal Splitter."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("unsplit-original-locals (false)", "");
if (phaseName.equals("bb.ne"))
return "Phase " + phaseName + ":\n"
+ "\nThe Nop Eliminator removes nop instructions from the method."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("bop"))
return "Phase " + phaseName + ":\n"
+ "\nThe Baf Optimization pack performs optimizations on BafBodys \n(currently there are no optimizations performed specifically on \nBafBodys, and the pack is empty). It is run only if the output \nformat is baf or b or asm or a, or if class files are being \noutput and the Via Grimp option has not been specified."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("tag"))
return "Phase " + phaseName + ":\n"
+ "\nThe Tag Aggregator pack aggregates tags attached to individual \nunits into a code attribute for each method, so that these \nattributes can be encoded in Java class files."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("tag.ln"))
return "Phase " + phaseName + ":\n"
+ "\nThe Line Number Tag Aggregator aggregates line number tags."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("tag.an"))
return "Phase " + phaseName + ":\n"
+ "\nThe Array Bounds and Null Pointer Tag Aggregator aggregates tags \nproduced by the Array Bound Checker and Null Pointer Checker."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("tag.dep"))
return "Phase " + phaseName + ":\n"
+ "\nThe Dependence Tag Aggregator aggregates tags produced by the \nSide Effect Tagger."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("tag.fieldrw"))
return "Phase " + phaseName + ":\n"
+ "\nThe Field Read/Write Tag Aggregator aggregates field read/write \ntags produced by the Field Read/Write Tagger, phase jap.fieldrw."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("db"))
return "Phase " + phaseName + ":\n"
+ "\nThe decompile (Dava) option is set using the -f dava options in \nSoot. Options provided by Dava are added to this dummy phase so \nas not to clutter the soot general arguments. -p db (option \nname):(value) will be used to set all required values for Dava."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "")
+ padOpt("source-is-javac (true)", "");
if (phaseName.equals("db.transformations"))
return "Phase " + phaseName + ":\n"
+ "\nThe transformations implemented using AST Traversal and \nstructural flow analses on Dava's AST"
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("db.renamer"))
return "Phase " + phaseName + ":\n"
+ "\nIf set, the renaming analyses implemented in Dava are applied to \neach method body being decompiled. The analyses use heuristics \nto choose potentially better names for local variables. (As of \nFebruary 14th 2006, work is still under progress on these \nanalyses (dava.toolkits.base.renamer)."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (false)", "");
if (phaseName.equals("db.deobfuscate"))
return "Phase " + phaseName + ":\n"
+ "\nCertain analyses make sense only when the bytecode is obfuscated \ncode. There are plans to implement such analyses and apply them \non methods only if this flag is set. Dead Code elimination which \nincludes removing code guarded by some condition which is always \nfalse or always true is one such analysis. Another suggested \nanalysis is giving default names to classes and fields. \nOnfuscators love to use weird names for fields and classes and \neven a simple re-naming of these could be a good help to the \nuser. Another more advanced analysis would be to check for \nredundant constant fields added by obfuscators and then remove \nuses of these constant fields from the code."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
if (phaseName.equals("db.force-recompile"))
return "Phase " + phaseName + ":\n"
+ "\nWhile decompiling we have to be clear what our aim is: do we \nwant to convert bytecode to Java syntax and stay as close to the \nactual execution of bytecode or do we want recompilably Java \nsource representing the bytecode. This distinction is important \nbecause some restrictions present in Java source are absent from \nthe bytecode. Examples of this include that fact that in Java a \ncall to a constructor or super needs to be the first statement \nin a constructors body. This restriction is absent from the \nbytecode. Similarly final fields HAVE to be initialized once and \nonly once in either the static initializer (static fields) or \nall the constructors (non-static fields). Additionally the \nfields should be initialized on all possible execution paths. \nThese restrictions are again absent from the bytecode. In doing \na one-one conversion of bytecode to Java source then no attempt \nshould be made to fix any of these and similar problems in the \nJava source. However, if the aim is to get recompilable code \nthen these and similar issues need to be fixed. Setting the \nforce-recompilability flag will ensure that the decompiler tries \nits best to produce recompilable Java source."
+ "\n\nRecognized options (with default values):\n"
+ padOpt("enabled (true)", "");
return "Unrecognized phase: " + phaseName;
}
public static String getDeclaredOptionsForPhase(String phaseName) {
if (phaseName.equals("jb"))
return String.join(" ",
"enabled",
"use-original-names",
"preserve-source-annotations",
"stabilize-local-names",
"model-lambdametafactory"
);
if (phaseName.equals("jb.dtr"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.ese"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.ls"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.sils"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.a"))
return String.join(" ",
"enabled",
"only-stack-locals"
);
if (phaseName.equals("jb.ule"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.tr"))
return String.join(" ",
"enabled",
"use-older-type-assigner",
"compare-type-assigners",
"ignore-nullpointer-dereferences"
);
if (phaseName.equals("jb.ulp"))
return String.join(" ",
"enabled",
"unsplit-original-locals"
);
if (phaseName.equals("jb.lns"))
return String.join(" ",
"enabled",
"only-stack-locals",
"sort-locals"
);
if (phaseName.equals("jb.cp"))
return String.join(" ",
"enabled",
"only-regular-locals",
"only-stack-locals"
);
if (phaseName.equals("jb.dae"))
return String.join(" ",
"enabled",
"only-stack-locals"
);
if (phaseName.equals("jb.cp-ule"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.lp"))
return String.join(" ",
"enabled",
"unsplit-original-locals"
);
if (phaseName.equals("jb.ne"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.uce"))
return String.join(" ",
"enabled",
"remove-unreachable-traps"
);
if (phaseName.equals("jb.tt"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jb.cbf"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jj"))
return String.join(" ",
"enabled",
"use-original-names"
);
if (phaseName.equals("jj.ls"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jj.sils"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jj.a"))
return String.join(" ",
"enabled",
"only-stack-locals"
);
if (phaseName.equals("jj.ule"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jj.tr"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jj.ulp"))
return String.join(" ",
"enabled",
"unsplit-original-locals"
);
if (phaseName.equals("jj.lns"))
return String.join(" ",
"enabled",
"only-stack-locals"
);
if (phaseName.equals("jj.cp"))
return String.join(" ",
"enabled",
"only-regular-locals",
"only-stack-locals"
);
if (phaseName.equals("jj.dae"))
return String.join(" ",
"enabled",
"only-stack-locals"
);
if (phaseName.equals("jj.cp-ule"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jj.lp"))
return String.join(" ",
"enabled",
"unsplit-original-locals"
);
if (phaseName.equals("jj.ne"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jj.uce"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjpp"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjpp.cimbt"))
return String.join(" ",
"enabled",
"verbose"
);
if (phaseName.equals("wspp"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("cg"))
return String.join(" ",
"enabled",
"safe-forname",
"safe-newinstance",
"library",
"verbose",
"jdkver",
"all-reachable",
"implicit-entry",
"trim-clinit",
"reflection-log",
"guards",
"types-for-invoke",
"resolve-all-abstract-invokes"
);
if (phaseName.equals("cg.cha"))
return String.join(" ",
"enabled",
"verbose",
"apponly"
);
if (phaseName.equals("cg.spark"))
return String.join(" ",
"enabled",
"verbose",
"ignore-types",
"force-gc",
"pre-jimplify",
"apponly",
"vta",
"rta",
"field-based",
"types-for-sites",
"merge-stringbuffer",
"string-constants",
"simulate-natives",
"empties-as-allocs",
"simple-edges-bidirectional",
"on-fly-cg",
"simplify-offline",
"simplify-sccs",
"ignore-types-for-sccs",
"propagator",
"set-impl",
"double-set-old",
"double-set-new",
"dump-html",
"dump-pag",
"dump-solution",
"topo-sort",
"dump-types",
"class-method-var",
"dump-answer",
"add-tags",
"set-mass",
"cs-demand",
"lazy-pts",
"traversal",
"passes",
"geom-pta",
"geom-encoding",
"geom-worklist",
"geom-dump-verbose",
"geom-verify-name",
"geom-eval",
"geom-trans",
"geom-frac-base",
"geom-blocking",
"geom-runs",
"geom-app-only"
);
if (phaseName.equals("cg.paddle"))
return String.join(" ",
"enabled",
"verbose",
"conf",
"bdd",
"order",
"dynamic-order",
"profile",
"verbosegc",
"q",
"backend",
"bdd-nodes",
"ignore-types",
"pre-jimplify",
"context",
"k",
"context-heap",
"rta",
"field-based",
"types-for-sites",
"merge-stringbuffer",
"string-constants",
"simulate-natives",
"global-nodes-in-natives",
"simple-edges-bidirectional",
"this-edges",
"precise-newinstance",
"propagator",
"set-impl",
"double-set-old",
"double-set-new",
"context-counts",
"total-context-counts",
"method-context-counts",
"set-mass",
"number-nodes"
);
if (phaseName.equals("wstp"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wsop"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjtp"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjtp.mhp"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjtp.tn"))
return String.join(" ",
"enabled",
"locking-scheme",
"avoid-deadlock",
"open-nesting",
"do-mhp",
"do-tlo",
"print-graph",
"print-table",
"print-debug"
);
if (phaseName.equals("wjtp.rdc"))
return String.join(" ",
"enabled",
"fcn fixed-class-names"
);
if (phaseName.equals("wjop"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjop.smb"))
return String.join(" ",
"enabled",
"insert-null-checks",
"insert-redundant-casts",
"allowed-modifier-changes"
);
if (phaseName.equals("wjop.si"))
return String.join(" ",
"enabled",
"rerun-jb",
"insert-null-checks",
"insert-redundant-casts",
"allowed-modifier-changes",
"expansion-factor",
"max-container-size",
"max-inlinee-size"
);
if (phaseName.equals("wjap"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjap.ra"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjap.umt"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjap.uft"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjap.tqt"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("wjap.cgg"))
return String.join(" ",
"enabled",
"show-lib-meths"
);
if (phaseName.equals("wjap.purity"))
return String.join(" ",
"enabled",
"dump-summaries",
"dump-cg",
"dump-intra",
"print",
"annotate",
"verbose"
);
if (phaseName.equals("shimple"))
return String.join(" ",
"enabled",
"node-elim-opt",
"standard-local-names",
"extended",
"debug"
);
if (phaseName.equals("stp"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("sop"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("sop.cpf"))
return String.join(" ",
"enabled",
"prune-cfg"
);
if (phaseName.equals("jtp"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jop"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jop.cse"))
return String.join(" ",
"enabled",
"naive-side-effect"
);
if (phaseName.equals("jop.bcm"))
return String.join(" ",
"enabled",
"naive-side-effect"
);
if (phaseName.equals("jop.lcm"))
return String.join(" ",
"enabled",
"safety",
"unroll",
"naive-side-effect"
);
if (phaseName.equals("jop.cp"))
return String.join(" ",
"enabled",
"only-regular-locals",
"only-stack-locals"
);
if (phaseName.equals("jop.cpf"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jop.cbf"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jop.dae"))
return String.join(" ",
"enabled",
"only-tag",
"only-stack-locals"
);
if (phaseName.equals("jop.nce"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jop.uce1"))
return String.join(" ",
"enabled",
"remove-unreachable-traps"
);
if (phaseName.equals("jop.ubf1"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jop.uce2"))
return String.join(" ",
"enabled",
"remove-unreachable-traps"
);
if (phaseName.equals("jop.ubf2"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jop.ule"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.npc"))
return String.join(" ",
"enabled",
"only-array-ref",
"profiling"
);
if (phaseName.equals("jap.npcolorer"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.abc"))
return String.join(" ",
"enabled",
"with-all",
"with-cse",
"with-arrayref",
"with-fieldref",
"with-classfield",
"with-rectarray",
"profiling",
"add-color-tags"
);
if (phaseName.equals("jap.profiling"))
return String.join(" ",
"enabled",
"notmainentry"
);
if (phaseName.equals("jap.sea"))
return String.join(" ",
"enabled",
"naive"
);
if (phaseName.equals("jap.fieldrw"))
return String.join(" ",
"enabled",
"threshold"
);
if (phaseName.equals("jap.cgtagger"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.parity"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.pat"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.lvtagger"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.rdtagger"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.che"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.umt"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.lit"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("jap.aet"))
return String.join(" ",
"enabled",
"kind"
);
if (phaseName.equals("jap.dmt"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("gb"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("gb.a1"))
return String.join(" ",
"enabled",
"only-stack-locals"
);
if (phaseName.equals("gb.cf"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("gb.a2"))
return String.join(" ",
"enabled",
"only-stack-locals"
);
if (phaseName.equals("gb.ule"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("gop"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("bb"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("bb.lso"))
return String.join(" ",
"enabled",
"debug",
"inter",
"sl",
"sl2",
"sll",
"sll2"
);
if (phaseName.equals("bb.sco"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("bb.pho"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("bb.ule"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("bb.lp"))
return String.join(" ",
"enabled",
"unsplit-original-locals"
);
if (phaseName.equals("bb.ne"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("bop"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("tag"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("tag.ln"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("tag.an"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("tag.dep"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("tag.fieldrw"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("db"))
return String.join(" ",
"enabled",
"source-is-javac"
);
if (phaseName.equals("db.transformations"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("db.renamer"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("db.deobfuscate"))
return String.join(" ",
"enabled"
);
if (phaseName.equals("db.force-recompile"))
return String.join(" ",
"enabled"
);
// The default set of options is just enabled.
return "enabled";
}
public static String getDefaultOptionsForPhase(String phaseName) {
if (phaseName.equals("jb"))
return ""
+ "enabled:true "
+ "use-original-names:false "
+ "preserve-source-annotations:false "
+ "stabilize-local-names:false "
+ "model-lambdametafactory:true ";
if (phaseName.equals("jb.dtr"))
return ""
+ "enabled:true ";
if (phaseName.equals("jb.ese"))
return ""
+ "enabled:true ";
if (phaseName.equals("jb.ls"))
return ""
+ "enabled:true ";
if (phaseName.equals("jb.sils"))
return ""
+ "enabled:true ";
if (phaseName.equals("jb.a"))
return ""
+ "enabled:true "
+ "only-stack-locals:true ";
if (phaseName.equals("jb.ule"))
return ""
+ "enabled:true ";
if (phaseName.equals("jb.tr"))
return ""
+ "enabled:true "
+ "use-older-type-assigner:false "
+ "compare-type-assigners:false "
+ "ignore-nullpointer-dereferences:false ";
if (phaseName.equals("jb.ulp"))
return ""
+ "enabled:true "
+ "unsplit-original-locals:true ";
if (phaseName.equals("jb.lns"))
return ""
+ "enabled:true "
+ "only-stack-locals:false "
+ "sort-locals:false ";
if (phaseName.equals("jb.cp"))
return ""
+ "enabled:true "
+ "only-regular-locals:false "
+ "only-stack-locals:true ";
if (phaseName.equals("jb.dae"))
return ""
+ "enabled:true "
+ "only-stack-locals:true ";
if (phaseName.equals("jb.cp-ule"))
return ""
+ "enabled:true ";
if (phaseName.equals("jb.lp"))
return ""
+ "enabled:false "
+ "unsplit-original-locals:false ";
if (phaseName.equals("jb.ne"))
return ""
+ "enabled:true ";
if (phaseName.equals("jb.uce"))
return ""
+ "enabled:true "
+ "remove-unreachable-traps:true ";
if (phaseName.equals("jb.tt"))
return ""
+ "enabled:false ";
if (phaseName.equals("jb.cbf"))
return ""
+ "enabled:true ";
if (phaseName.equals("jj"))
return ""
+ "enabled:true "
+ "use-original-names:true ";
if (phaseName.equals("jj.ls"))
return ""
+ "enabled:false ";
if (phaseName.equals("jj.sils"))
return ""
+ "enabled:true ";
if (phaseName.equals("jj.a"))
return ""
+ "enabled:true "
+ "only-stack-locals:true ";
if (phaseName.equals("jj.ule"))
return ""
+ "enabled:true ";
if (phaseName.equals("jj.tr"))
return ""
+ "enabled:false ";
if (phaseName.equals("jj.ulp"))
return ""
+ "enabled:false "
+ "unsplit-original-locals:false ";
if (phaseName.equals("jj.lns"))
return ""
+ "enabled:true "
+ "only-stack-locals:false ";
if (phaseName.equals("jj.cp"))
return ""
+ "enabled:true "
+ "only-regular-locals:false "
+ "only-stack-locals:true ";
if (phaseName.equals("jj.dae"))
return ""
+ "enabled:true "
+ "only-stack-locals:true ";
if (phaseName.equals("jj.cp-ule"))
return ""
+ "enabled:true ";
if (phaseName.equals("jj.lp"))
return ""
+ "enabled:false "
+ "unsplit-original-locals:false ";
if (phaseName.equals("jj.ne"))
return ""
+ "enabled:true ";
if (phaseName.equals("jj.uce"))
return ""
+ "enabled:true ";
if (phaseName.equals("wjpp"))
return ""
+ "enabled:true ";
if (phaseName.equals("wjpp.cimbt"))
return ""
+ "enabled:false "
+ "verbose:false ";
if (phaseName.equals("wspp"))
return ""
+ "enabled:true ";
if (phaseName.equals("cg"))
return ""
+ "enabled:true "
+ "safe-forname:false "
+ "safe-newinstance:false "
+ "library:disabled "
+ "verbose:false "
+ "jdkver:3 "
+ "all-reachable:false "
+ "implicit-entry:true "
+ "trim-clinit:true "
+ "guards:ignore "
+ "types-for-invoke:false "
+ "resolve-all-abstract-invokes:false ";
if (phaseName.equals("cg.cha"))
return ""
+ "enabled:true "
+ "verbose:false "
+ "apponly:false ";
if (phaseName.equals("cg.spark"))
return ""
+ "enabled:false "
+ "verbose:false "
+ "ignore-types:false "
+ "force-gc:false "
+ "pre-jimplify:false "
+ "apponly:false "
+ "vta:false "
+ "rta:false "
+ "field-based:false "
+ "types-for-sites:false "
+ "merge-stringbuffer:true "
+ "string-constants:false "
+ "simulate-natives:true "
+ "empties-as-allocs:false "
+ "simple-edges-bidirectional:false "
+ "on-fly-cg:true "
+ "simplify-offline:false "
+ "simplify-sccs:false "
+ "ignore-types-for-sccs:false "
+ "propagator:worklist "
+ "set-impl:double "
+ "double-set-old:hybrid "
+ "double-set-new:hybrid "
+ "dump-html:false "
+ "dump-pag:false "
+ "dump-solution:false "
+ "topo-sort:false "
+ "dump-types:true "
+ "class-method-var:true "
+ "dump-answer:false "
+ "add-tags:false "
+ "set-mass:false "
+ "cs-demand:false "
+ "lazy-pts:true "
+ "traversal:75000 "
+ "passes:10 "
+ "geom-pta:false "
+ "geom-encoding:Geom "
+ "geom-encoding:Geom "
+ "geom-worklist:PQ "
+ "geom-worklist:PQ "
+ "geom-dump-verbose: "
+ "geom-verify-name: "
+ "geom-eval:0 "
+ "geom-trans:false "
+ "geom-frac-base:40 "
+ "geom-blocking:true "
+ "geom-runs:1 "
+ "geom-app-only:true ";
if (phaseName.equals("cg.paddle"))
return ""
+ "enabled:false "
+ "verbose:false "
+ "conf:ofcg "
+ "bdd:false "
+ "order:32 "
+ "profile:false "
+ "verbosegc:false "
+ "q:auto "
+ "backend:auto "
+ "bdd-nodes:0 "
+ "ignore-types:false "
+ "pre-jimplify:false "
+ "context:insens "
+ "k:2 "
+ "context-heap:false "
+ "rta:false "
+ "field-based:false "
+ "types-for-sites:false "
+ "merge-stringbuffer:true "
+ "string-constants:false "
+ "simulate-natives:true "
+ "global-nodes-in-natives:false "
+ "simple-edges-bidirectional:false "
+ "this-edges:false "
+ "precise-newinstance:true "
+ "propagator:auto "
+ "set-impl:double "
+ "double-set-old:hybrid "
+ "double-set-new:hybrid "
+ "context-counts:false "
+ "total-context-counts:false "
+ "method-context-counts:false "
+ "set-mass:false "
+ "number-nodes:true ";
if (phaseName.equals("wstp"))
return ""
+ "enabled:true ";
if (phaseName.equals("wsop"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjtp"))
return ""
+ "enabled:true ";
if (phaseName.equals("wjtp.mhp"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjtp.tn"))
return ""
+ "enabled:false "
+ "locking-scheme:medium-grained "
+ "avoid-deadlock:true "
+ "open-nesting:true "
+ "do-mhp:true "
+ "do-tlo:true "
+ "print-graph:false "
+ "print-table:false "
+ "print-debug:false ";
if (phaseName.equals("wjtp.rdc"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjop"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjop.smb"))
return ""
+ "enabled:false "
+ "insert-null-checks:true "
+ "insert-redundant-casts:true "
+ "allowed-modifier-changes:unsafe ";
if (phaseName.equals("wjop.si"))
return ""
+ "enabled:true "
+ "rerun-jb:true "
+ "insert-null-checks:true "
+ "insert-redundant-casts:true "
+ "allowed-modifier-changes:unsafe "
+ "expansion-factor:3 "
+ "max-container-size:5000 "
+ "max-inlinee-size:20 ";
if (phaseName.equals("wjap"))
return ""
+ "enabled:true ";
if (phaseName.equals("wjap.ra"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjap.umt"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjap.uft"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjap.tqt"))
return ""
+ "enabled:false ";
if (phaseName.equals("wjap.cgg"))
return ""
+ "enabled:false "
+ "show-lib-meths:false ";
if (phaseName.equals("wjap.purity"))
return ""
+ "enabled:false "
+ "dump-summaries:true "
+ "dump-cg:false "
+ "dump-intra:false "
+ "print:true "
+ "annotate:true "
+ "verbose:false ";
if (phaseName.equals("shimple"))
return ""
+ "enabled:true "
+ "node-elim-opt:true "
+ "standard-local-names:false "
+ "extended:false "
+ "debug:false ";
if (phaseName.equals("stp"))
return ""
+ "enabled:true ";
if (phaseName.equals("sop"))
return ""
+ "enabled:false ";
if (phaseName.equals("sop.cpf"))
return ""
+ "enabled:true "
+ "prune-cfg:true ";
if (phaseName.equals("jtp"))
return ""
+ "enabled:true ";
if (phaseName.equals("jop"))
return ""
+ "enabled:false ";
if (phaseName.equals("jop.cse"))
return ""
+ "enabled:false "
+ "naive-side-effect:false ";
if (phaseName.equals("jop.bcm"))
return ""
+ "enabled:false "
+ "naive-side-effect:false ";
if (phaseName.equals("jop.lcm"))
return ""
+ "enabled:false "
+ "safety:safe "
+ "unroll:true "
+ "naive-side-effect:false ";
if (phaseName.equals("jop.cp"))
return ""
+ "enabled:true "
+ "only-regular-locals:false "
+ "only-stack-locals:false ";
if (phaseName.equals("jop.cpf"))
return ""
+ "enabled:true ";
if (phaseName.equals("jop.cbf"))
return ""
+ "enabled:true ";
if (phaseName.equals("jop.dae"))
return ""
+ "enabled:true "
+ "only-tag:false "
+ "only-stack-locals:false ";
if (phaseName.equals("jop.nce"))
return ""
+ "enabled:false ";
if (phaseName.equals("jop.uce1"))
return ""
+ "enabled:true "
+ "remove-unreachable-traps:false ";
if (phaseName.equals("jop.ubf1"))
return ""
+ "enabled:true ";
if (phaseName.equals("jop.uce2"))
return ""
+ "enabled:true "
+ "remove-unreachable-traps:false ";
if (phaseName.equals("jop.ubf2"))
return ""
+ "enabled:true ";
if (phaseName.equals("jop.ule"))
return ""
+ "enabled:true ";
if (phaseName.equals("jap"))
return ""
+ "enabled:true ";
if (phaseName.equals("jap.npc"))
return ""
+ "enabled:false "
+ "only-array-ref:false "
+ "profiling:false ";
if (phaseName.equals("jap.npcolorer"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.abc"))
return ""
+ "enabled:false "
+ "with-all:false "
+ "with-cse:false "
+ "with-arrayref:false "
+ "with-fieldref:false "
+ "with-classfield:false "
+ "with-rectarray:false "
+ "profiling:false "
+ "add-color-tags:false ";
if (phaseName.equals("jap.profiling"))
return ""
+ "enabled:false "
+ "notmainentry:false ";
if (phaseName.equals("jap.sea"))
return ""
+ "enabled:false "
+ "naive:false ";
if (phaseName.equals("jap.fieldrw"))
return ""
+ "enabled:false "
+ "threshold:100 ";
if (phaseName.equals("jap.cgtagger"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.parity"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.pat"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.lvtagger"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.rdtagger"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.che"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.umt"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.lit"))
return ""
+ "enabled:false ";
if (phaseName.equals("jap.aet"))
return ""
+ "enabled:false "
+ "kind:optimistic ";
if (phaseName.equals("jap.dmt"))
return ""
+ "enabled:false ";
if (phaseName.equals("gb"))
return ""
+ "enabled:true ";
if (phaseName.equals("gb.a1"))
return ""
+ "enabled:true "
+ "only-stack-locals:true ";
if (phaseName.equals("gb.cf"))
return ""
+ "enabled:true ";
if (phaseName.equals("gb.a2"))
return ""
+ "enabled:true "
+ "only-stack-locals:true ";
if (phaseName.equals("gb.ule"))
return ""
+ "enabled:true ";
if (phaseName.equals("gop"))
return ""
+ "enabled:false ";
if (phaseName.equals("bb"))
return ""
+ "enabled:true ";
if (phaseName.equals("bb.lso"))
return ""
+ "enabled:true "
+ "debug:false "
+ "inter:false "
+ "sl:true "
+ "sl2:false "
+ "sll:true "
+ "sll2:false ";
if (phaseName.equals("bb.sco"))
return ""
+ "enabled:true ";
if (phaseName.equals("bb.pho"))
return ""
+ "enabled:true ";
if (phaseName.equals("bb.ule"))
return ""
+ "enabled:true ";
if (phaseName.equals("bb.lp"))
return ""
+ "enabled:true "
+ "unsplit-original-locals:false ";
if (phaseName.equals("bb.ne"))
return ""
+ "enabled:true ";
if (phaseName.equals("bop"))
return ""
+ "enabled:false ";
if (phaseName.equals("tag"))
return ""
+ "enabled:true ";
if (phaseName.equals("tag.ln"))
return ""
+ "enabled:true ";
if (phaseName.equals("tag.an"))
return ""
+ "enabled:false ";
if (phaseName.equals("tag.dep"))
return ""
+ "enabled:false ";
if (phaseName.equals("tag.fieldrw"))
return ""
+ "enabled:false ";
if (phaseName.equals("db"))
return ""
+ "enabled:true "
+ "source-is-javac:true ";
if (phaseName.equals("db.transformations"))
return ""
+ "enabled:true ";
if (phaseName.equals("db.renamer"))
return ""
+ "enabled:false ";
if (phaseName.equals("db.deobfuscate"))
return ""
+ "enabled:true ";
if (phaseName.equals("db.force-recompile"))
return ""
+ "enabled:true ";
// The default default value is enabled.
return "enabled";
}
public void warnForeignPhase(String phaseName) {
if (false
|| phaseName.equals("jb")
|| phaseName.equals("jb.dtr")
|| phaseName.equals("jb.ese")
|| phaseName.equals("jb.ls")
|| phaseName.equals("jb.sils")
|| phaseName.equals("jb.a")
|| phaseName.equals("jb.ule")
|| phaseName.equals("jb.tr")
|| phaseName.equals("jb.ulp")
|| phaseName.equals("jb.lns")
|| phaseName.equals("jb.cp")
|| phaseName.equals("jb.dae")
|| phaseName.equals("jb.cp-ule")
|| phaseName.equals("jb.lp")
|| phaseName.equals("jb.ne")
|| phaseName.equals("jb.uce")
|| phaseName.equals("jb.tt")
|| phaseName.equals("jb.cbf")
|| phaseName.equals("jj")
|| phaseName.equals("jj.ls")
|| phaseName.equals("jj.sils")
|| phaseName.equals("jj.a")
|| phaseName.equals("jj.ule")
|| phaseName.equals("jj.tr")
|| phaseName.equals("jj.ulp")
|| phaseName.equals("jj.lns")
|| phaseName.equals("jj.cp")
|| phaseName.equals("jj.dae")
|| phaseName.equals("jj.cp-ule")
|| phaseName.equals("jj.lp")
|| phaseName.equals("jj.ne")
|| phaseName.equals("jj.uce")
|| phaseName.equals("wjpp")
|| phaseName.equals("wjpp.cimbt")
|| phaseName.equals("wspp")
|| phaseName.equals("cg")
|| phaseName.equals("cg.cha")
|| phaseName.equals("cg.spark")
|| phaseName.equals("cg.paddle")
|| phaseName.equals("wstp")
|| phaseName.equals("wsop")
|| phaseName.equals("wjtp")
|| phaseName.equals("wjtp.mhp")
|| phaseName.equals("wjtp.tn")
|| phaseName.equals("wjtp.rdc")
|| phaseName.equals("wjop")
|| phaseName.equals("wjop.smb")
|| phaseName.equals("wjop.si")
|| phaseName.equals("wjap")
|| phaseName.equals("wjap.ra")
|| phaseName.equals("wjap.umt")
|| phaseName.equals("wjap.uft")
|| phaseName.equals("wjap.tqt")
|| phaseName.equals("wjap.cgg")
|| phaseName.equals("wjap.purity")
|| phaseName.equals("shimple")
|| phaseName.equals("stp")
|| phaseName.equals("sop")
|| phaseName.equals("sop.cpf")
|| phaseName.equals("jtp")
|| phaseName.equals("jop")
|| phaseName.equals("jop.cse")
|| phaseName.equals("jop.bcm")
|| phaseName.equals("jop.lcm")
|| phaseName.equals("jop.cp")
|| phaseName.equals("jop.cpf")
|| phaseName.equals("jop.cbf")
|| phaseName.equals("jop.dae")
|| phaseName.equals("jop.nce")
|| phaseName.equals("jop.uce1")
|| phaseName.equals("jop.ubf1")
|| phaseName.equals("jop.uce2")
|| phaseName.equals("jop.ubf2")
|| phaseName.equals("jop.ule")
|| phaseName.equals("jap")
|| phaseName.equals("jap.npc")
|| phaseName.equals("jap.npcolorer")
|| phaseName.equals("jap.abc")
|| phaseName.equals("jap.profiling")
|| phaseName.equals("jap.sea")
|| phaseName.equals("jap.fieldrw")
|| phaseName.equals("jap.cgtagger")
|| phaseName.equals("jap.parity")
|| phaseName.equals("jap.pat")
|| phaseName.equals("jap.lvtagger")
|| phaseName.equals("jap.rdtagger")
|| phaseName.equals("jap.che")
|| phaseName.equals("jap.umt")
|| phaseName.equals("jap.lit")
|| phaseName.equals("jap.aet")
|| phaseName.equals("jap.dmt")
|| phaseName.equals("gb")
|| phaseName.equals("gb.a1")
|| phaseName.equals("gb.cf")
|| phaseName.equals("gb.a2")
|| phaseName.equals("gb.ule")
|| phaseName.equals("gop")
|| phaseName.equals("bb")
|| phaseName.equals("bb.lso")
|| phaseName.equals("bb.sco")
|| phaseName.equals("bb.pho")
|| phaseName.equals("bb.ule")
|| phaseName.equals("bb.lp")
|| phaseName.equals("bb.ne")
|| phaseName.equals("bop")
|| phaseName.equals("tag")
|| phaseName.equals("tag.ln")
|| phaseName.equals("tag.an")
|| phaseName.equals("tag.dep")
|| phaseName.equals("tag.fieldrw")
|| phaseName.equals("db")
|| phaseName.equals("db.transformations")
|| phaseName.equals("db.renamer")
|| phaseName.equals("db.deobfuscate")
|| phaseName.equals("db.force-recompile")
) return;
G.v().out.println("Warning: Phase " + phaseName + " is not a standard Soot phase listed in XML files.");
}
public void warnNonexistentPhase() {
if (!PackManager.v().hasPhase("jb"))
G.v().out.println("Warning: Options exist for non-existent phase jb");
if (!PackManager.v().hasPhase("jb.dtr"))
G.v().out.println("Warning: Options exist for non-existent phase jb.dtr");
if (!PackManager.v().hasPhase("jb.ese"))
G.v().out.println("Warning: Options exist for non-existent phase jb.ese");
if (!PackManager.v().hasPhase("jb.ls"))
G.v().out.println("Warning: Options exist for non-existent phase jb.ls");
if (!PackManager.v().hasPhase("jb.sils"))
G.v().out.println("Warning: Options exist for non-existent phase jb.sils");
if (!PackManager.v().hasPhase("jb.a"))
G.v().out.println("Warning: Options exist for non-existent phase jb.a");
if (!PackManager.v().hasPhase("jb.ule"))
G.v().out.println("Warning: Options exist for non-existent phase jb.ule");
if (!PackManager.v().hasPhase("jb.tr"))
G.v().out.println("Warning: Options exist for non-existent phase jb.tr");
if (!PackManager.v().hasPhase("jb.ulp"))
G.v().out.println("Warning: Options exist for non-existent phase jb.ulp");
if (!PackManager.v().hasPhase("jb.lns"))
G.v().out.println("Warning: Options exist for non-existent phase jb.lns");
if (!PackManager.v().hasPhase("jb.cp"))
G.v().out.println("Warning: Options exist for non-existent phase jb.cp");
if (!PackManager.v().hasPhase("jb.dae"))
G.v().out.println("Warning: Options exist for non-existent phase jb.dae");
if (!PackManager.v().hasPhase("jb.cp-ule"))
G.v().out.println("Warning: Options exist for non-existent phase jb.cp-ule");
if (!PackManager.v().hasPhase("jb.lp"))
G.v().out.println("Warning: Options exist for non-existent phase jb.lp");
if (!PackManager.v().hasPhase("jb.ne"))
G.v().out.println("Warning: Options exist for non-existent phase jb.ne");
if (!PackManager.v().hasPhase("jb.uce"))
G.v().out.println("Warning: Options exist for non-existent phase jb.uce");
if (!PackManager.v().hasPhase("jb.tt"))
G.v().out.println("Warning: Options exist for non-existent phase jb.tt");
if (!PackManager.v().hasPhase("jb.cbf"))
G.v().out.println("Warning: Options exist for non-existent phase jb.cbf");
if (!PackManager.v().hasPhase("jj"))
G.v().out.println("Warning: Options exist for non-existent phase jj");
if (!PackManager.v().hasPhase("jj.ls"))
G.v().out.println("Warning: Options exist for non-existent phase jj.ls");
if (!PackManager.v().hasPhase("jj.sils"))
G.v().out.println("Warning: Options exist for non-existent phase jj.sils");
if (!PackManager.v().hasPhase("jj.a"))
G.v().out.println("Warning: Options exist for non-existent phase jj.a");
if (!PackManager.v().hasPhase("jj.ule"))
G.v().out.println("Warning: Options exist for non-existent phase jj.ule");
if (!PackManager.v().hasPhase("jj.tr"))
G.v().out.println("Warning: Options exist for non-existent phase jj.tr");
if (!PackManager.v().hasPhase("jj.ulp"))
G.v().out.println("Warning: Options exist for non-existent phase jj.ulp");
if (!PackManager.v().hasPhase("jj.lns"))
G.v().out.println("Warning: Options exist for non-existent phase jj.lns");
if (!PackManager.v().hasPhase("jj.cp"))
G.v().out.println("Warning: Options exist for non-existent phase jj.cp");
if (!PackManager.v().hasPhase("jj.dae"))
G.v().out.println("Warning: Options exist for non-existent phase jj.dae");
if (!PackManager.v().hasPhase("jj.cp-ule"))
G.v().out.println("Warning: Options exist for non-existent phase jj.cp-ule");
if (!PackManager.v().hasPhase("jj.lp"))
G.v().out.println("Warning: Options exist for non-existent phase jj.lp");
if (!PackManager.v().hasPhase("jj.ne"))
G.v().out.println("Warning: Options exist for non-existent phase jj.ne");
if (!PackManager.v().hasPhase("jj.uce"))
G.v().out.println("Warning: Options exist for non-existent phase jj.uce");
if (!PackManager.v().hasPhase("wjpp"))
G.v().out.println("Warning: Options exist for non-existent phase wjpp");
if (!PackManager.v().hasPhase("wjpp.cimbt"))
G.v().out.println("Warning: Options exist for non-existent phase wjpp.cimbt");
if (!PackManager.v().hasPhase("wspp"))
G.v().out.println("Warning: Options exist for non-existent phase wspp");
if (!PackManager.v().hasPhase("cg"))
G.v().out.println("Warning: Options exist for non-existent phase cg");
if (!PackManager.v().hasPhase("cg.cha"))
G.v().out.println("Warning: Options exist for non-existent phase cg.cha");
if (!PackManager.v().hasPhase("cg.spark"))
G.v().out.println("Warning: Options exist for non-existent phase cg.spark");
if (!PackManager.v().hasPhase("cg.paddle"))
G.v().out.println("Warning: Options exist for non-existent phase cg.paddle");
if (!PackManager.v().hasPhase("wstp"))
G.v().out.println("Warning: Options exist for non-existent phase wstp");
if (!PackManager.v().hasPhase("wsop"))
G.v().out.println("Warning: Options exist for non-existent phase wsop");
if (!PackManager.v().hasPhase("wjtp"))
G.v().out.println("Warning: Options exist for non-existent phase wjtp");
if (!PackManager.v().hasPhase("wjtp.mhp"))
G.v().out.println("Warning: Options exist for non-existent phase wjtp.mhp");
if (!PackManager.v().hasPhase("wjtp.tn"))
G.v().out.println("Warning: Options exist for non-existent phase wjtp.tn");
if (!PackManager.v().hasPhase("wjtp.rdc"))
G.v().out.println("Warning: Options exist for non-existent phase wjtp.rdc");
if (!PackManager.v().hasPhase("wjop"))
G.v().out.println("Warning: Options exist for non-existent phase wjop");
if (!PackManager.v().hasPhase("wjop.smb"))
G.v().out.println("Warning: Options exist for non-existent phase wjop.smb");
if (!PackManager.v().hasPhase("wjop.si"))
G.v().out.println("Warning: Options exist for non-existent phase wjop.si");
if (!PackManager.v().hasPhase("wjap"))
G.v().out.println("Warning: Options exist for non-existent phase wjap");
if (!PackManager.v().hasPhase("wjap.ra"))
G.v().out.println("Warning: Options exist for non-existent phase wjap.ra");
if (!PackManager.v().hasPhase("wjap.umt"))
G.v().out.println("Warning: Options exist for non-existent phase wjap.umt");
if (!PackManager.v().hasPhase("wjap.uft"))
G.v().out.println("Warning: Options exist for non-existent phase wjap.uft");
if (!PackManager.v().hasPhase("wjap.tqt"))
G.v().out.println("Warning: Options exist for non-existent phase wjap.tqt");
if (!PackManager.v().hasPhase("wjap.cgg"))
G.v().out.println("Warning: Options exist for non-existent phase wjap.cgg");
if (!PackManager.v().hasPhase("wjap.purity"))
G.v().out.println("Warning: Options exist for non-existent phase wjap.purity");
if (!PackManager.v().hasPhase("shimple"))
G.v().out.println("Warning: Options exist for non-existent phase shimple");
if (!PackManager.v().hasPhase("stp"))
G.v().out.println("Warning: Options exist for non-existent phase stp");
if (!PackManager.v().hasPhase("sop"))
G.v().out.println("Warning: Options exist for non-existent phase sop");
if (!PackManager.v().hasPhase("sop.cpf"))
G.v().out.println("Warning: Options exist for non-existent phase sop.cpf");
if (!PackManager.v().hasPhase("jtp"))
G.v().out.println("Warning: Options exist for non-existent phase jtp");
if (!PackManager.v().hasPhase("jop"))
G.v().out.println("Warning: Options exist for non-existent phase jop");
if (!PackManager.v().hasPhase("jop.cse"))
G.v().out.println("Warning: Options exist for non-existent phase jop.cse");
if (!PackManager.v().hasPhase("jop.bcm"))
G.v().out.println("Warning: Options exist for non-existent phase jop.bcm");
if (!PackManager.v().hasPhase("jop.lcm"))
G.v().out.println("Warning: Options exist for non-existent phase jop.lcm");
if (!PackManager.v().hasPhase("jop.cp"))
G.v().out.println("Warning: Options exist for non-existent phase jop.cp");
if (!PackManager.v().hasPhase("jop.cpf"))
G.v().out.println("Warning: Options exist for non-existent phase jop.cpf");
if (!PackManager.v().hasPhase("jop.cbf"))
G.v().out.println("Warning: Options exist for non-existent phase jop.cbf");
if (!PackManager.v().hasPhase("jop.dae"))
G.v().out.println("Warning: Options exist for non-existent phase jop.dae");
if (!PackManager.v().hasPhase("jop.nce"))
G.v().out.println("Warning: Options exist for non-existent phase jop.nce");
if (!PackManager.v().hasPhase("jop.uce1"))
G.v().out.println("Warning: Options exist for non-existent phase jop.uce1");
if (!PackManager.v().hasPhase("jop.ubf1"))
G.v().out.println("Warning: Options exist for non-existent phase jop.ubf1");
if (!PackManager.v().hasPhase("jop.uce2"))
G.v().out.println("Warning: Options exist for non-existent phase jop.uce2");
if (!PackManager.v().hasPhase("jop.ubf2"))
G.v().out.println("Warning: Options exist for non-existent phase jop.ubf2");
if (!PackManager.v().hasPhase("jop.ule"))
G.v().out.println("Warning: Options exist for non-existent phase jop.ule");
if (!PackManager.v().hasPhase("jap"))
G.v().out.println("Warning: Options exist for non-existent phase jap");
if (!PackManager.v().hasPhase("jap.npc"))
G.v().out.println("Warning: Options exist for non-existent phase jap.npc");
if (!PackManager.v().hasPhase("jap.npcolorer"))
G.v().out.println("Warning: Options exist for non-existent phase jap.npcolorer");
if (!PackManager.v().hasPhase("jap.abc"))
G.v().out.println("Warning: Options exist for non-existent phase jap.abc");
if (!PackManager.v().hasPhase("jap.profiling"))
G.v().out.println("Warning: Options exist for non-existent phase jap.profiling");
if (!PackManager.v().hasPhase("jap.sea"))
G.v().out.println("Warning: Options exist for non-existent phase jap.sea");
if (!PackManager.v().hasPhase("jap.fieldrw"))
G.v().out.println("Warning: Options exist for non-existent phase jap.fieldrw");
if (!PackManager.v().hasPhase("jap.cgtagger"))
G.v().out.println("Warning: Options exist for non-existent phase jap.cgtagger");
if (!PackManager.v().hasPhase("jap.parity"))
G.v().out.println("Warning: Options exist for non-existent phase jap.parity");
if (!PackManager.v().hasPhase("jap.pat"))
G.v().out.println("Warning: Options exist for non-existent phase jap.pat");
if (!PackManager.v().hasPhase("jap.lvtagger"))
G.v().out.println("Warning: Options exist for non-existent phase jap.lvtagger");
if (!PackManager.v().hasPhase("jap.rdtagger"))
G.v().out.println("Warning: Options exist for non-existent phase jap.rdtagger");
if (!PackManager.v().hasPhase("jap.che"))
G.v().out.println("Warning: Options exist for non-existent phase jap.che");
if (!PackManager.v().hasPhase("jap.umt"))
G.v().out.println("Warning: Options exist for non-existent phase jap.umt");
if (!PackManager.v().hasPhase("jap.lit"))
G.v().out.println("Warning: Options exist for non-existent phase jap.lit");
if (!PackManager.v().hasPhase("jap.aet"))
G.v().out.println("Warning: Options exist for non-existent phase jap.aet");
if (!PackManager.v().hasPhase("jap.dmt"))
G.v().out.println("Warning: Options exist for non-existent phase jap.dmt");
if (!PackManager.v().hasPhase("gb"))
G.v().out.println("Warning: Options exist for non-existent phase gb");
if (!PackManager.v().hasPhase("gb.a1"))
G.v().out.println("Warning: Options exist for non-existent phase gb.a1");
if (!PackManager.v().hasPhase("gb.cf"))
G.v().out.println("Warning: Options exist for non-existent phase gb.cf");
if (!PackManager.v().hasPhase("gb.a2"))
G.v().out.println("Warning: Options exist for non-existent phase gb.a2");
if (!PackManager.v().hasPhase("gb.ule"))
G.v().out.println("Warning: Options exist for non-existent phase gb.ule");
if (!PackManager.v().hasPhase("gop"))
G.v().out.println("Warning: Options exist for non-existent phase gop");
if (!PackManager.v().hasPhase("bb"))
G.v().out.println("Warning: Options exist for non-existent phase bb");
if (!PackManager.v().hasPhase("bb.lso"))
G.v().out.println("Warning: Options exist for non-existent phase bb.lso");
if (!PackManager.v().hasPhase("bb.sco"))
G.v().out.println("Warning: Options exist for non-existent phase bb.sco");
if (!PackManager.v().hasPhase("bb.pho"))
G.v().out.println("Warning: Options exist for non-existent phase bb.pho");
if (!PackManager.v().hasPhase("bb.ule"))
G.v().out.println("Warning: Options exist for non-existent phase bb.ule");
if (!PackManager.v().hasPhase("bb.lp"))
G.v().out.println("Warning: Options exist for non-existent phase bb.lp");
if (!PackManager.v().hasPhase("bb.ne"))
G.v().out.println("Warning: Options exist for non-existent phase bb.ne");
if (!PackManager.v().hasPhase("bop"))
G.v().out.println("Warning: Options exist for non-existent phase bop");
if (!PackManager.v().hasPhase("tag"))
G.v().out.println("Warning: Options exist for non-existent phase tag");
if (!PackManager.v().hasPhase("tag.ln"))
G.v().out.println("Warning: Options exist for non-existent phase tag.ln");
if (!PackManager.v().hasPhase("tag.an"))
G.v().out.println("Warning: Options exist for non-existent phase tag.an");
if (!PackManager.v().hasPhase("tag.dep"))
G.v().out.println("Warning: Options exist for non-existent phase tag.dep");
if (!PackManager.v().hasPhase("tag.fieldrw"))
G.v().out.println("Warning: Options exist for non-existent phase tag.fieldrw");
if (!PackManager.v().hasPhase("db"))
G.v().out.println("Warning: Options exist for non-existent phase db");
if (!PackManager.v().hasPhase("db.transformations"))
G.v().out.println("Warning: Options exist for non-existent phase db.transformations");
if (!PackManager.v().hasPhase("db.renamer"))
G.v().out.println("Warning: Options exist for non-existent phase db.renamer");
if (!PackManager.v().hasPhase("db.deobfuscate"))
G.v().out.println("Warning: Options exist for non-existent phase db.deobfuscate");
if (!PackManager.v().hasPhase("db.force-recompile"))
G.v().out.println("Warning: Options exist for non-existent phase db.force-recompile");
}
}
| soot-oss/soot | src/main/generated/options/soot/options/Options.java |
179,988 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written by Doug Lea and Martin Buchholz with assistance from members of
* JCP JSR-166 Expert Group and released to the public domain, as explained
* at http://creativecommons.org/publicdomain/zero/1.0/
*/
package io.undertow.util;
import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* A modified version of ConcurrentLinkedDequeue which includes direct
* removal and is portable accorss all JVMs. This is only a fallback if
* the JVM does not offer access to Unsafe.
*
* More specifically, an unbounded concurrent {@linkplain java.util.Deque deque} based on linked nodes.
* Concurrent insertion, removal, and access operations execute safely
* across multiple threads.
* A {@code ConcurrentLinkedDeque} is an appropriate choice when
* many threads will share access to a common collection.
* Like most other concurrent collection implementations, this class
* does not permit the use of {@code null} elements.
*
* <p>Iterators are <i>weakly consistent</i>, returning elements
* reflecting the state of the deque at some point at or since the
* creation of the iterator. They do <em>not</em> throw {@link
* java.util.ConcurrentModificationException
* ConcurrentModificationException}, and may proceed concurrently with
* other operations.
*
* <p>Beware that, unlike in most collections, the {@code size} method
* is <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these deques, determining the current number
* of elements requires a traversal of the elements, and so may report
* inaccurate results if this collection is modified during traversal.
* Additionally, the bulk operations {@code addAll},
* {@code removeAll}, {@code retainAll}, {@code containsAll},
* {@code equals}, and {@code toArray} are <em>not</em> guaranteed
* to be performed atomically. For example, an iterator operating
* concurrently with an {@code addAll} operation might view only some
* of the added elements.
*
* <p>This class and its iterator implement all of the <em>optional</em>
* methods of the {@link java.util.Deque} and {@link java.util.Iterator} interfaces.
*
* <p>Memory consistency effects: As with other concurrent collections,
* actions in a thread prior to placing an object into a
* {@code ConcurrentLinkedDeque}
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
* actions subsequent to the access or removal of that element from
* the {@code ConcurrentLinkedDeque} in another thread.
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.7
* @author Doug Lea
* @author Martin Buchholz
* @author Jason T. Grene
* @param <E> the type of elements held in this collection
*/
public class PortableConcurrentDirectDeque<E>
extends ConcurrentDirectDeque<E> implements Deque<E>, java.io.Serializable {
/*
* This is an implementation of a concurrent lock-free deque
* supporting interior removes but not interior insertions, as
* required to support the entire Deque interface.
*
* We extend the techniques developed for ConcurrentLinkedQueue and
* LinkedTransferQueue (see the internal docs for those classes).
* Understanding the ConcurrentLinkedQueue implementation is a
* prerequisite for understanding the implementation of this class.
*
* The data structure is a symmetrical doubly-linked "GC-robust"
* linked list of nodes. We minimize the number of volatile writes
* using two techniques: advancing multiple hops with a single CAS
* and mixing volatile and non-volatile writes of the same memory
* locations.
*
* A node contains the expected E ("item") and links to predecessor
* ("prev") and successor ("next") nodes:
*
* class Node<E> { volatile Node<E> prev, next; volatile E item; }
*
* A node p is considered "live" if it contains a non-null item
* (p.item != null). When an item is CASed to null, the item is
* atomically logically deleted from the collection.
*
* At any time, there is precisely one "first" node with a null
* prev reference that terminates any chain of prev references
* starting at a live node. Similarly there is precisely one
* "last" node terminating any chain of next references starting at
* a live node. The "first" and "last" nodes may or may not be live.
* The "first" and "last" nodes are always mutually reachable.
*
* A new element is added atomically by CASing the null prev or
* next reference in the first or last node to a fresh node
* containing the element. The element's node atomically becomes
* "live" at that point.
*
* A node is considered "active" if it is a live node, or the
* first or last node. Active nodes cannot be unlinked.
*
* A "self-link" is a next or prev reference that is the same node:
* p.prev == p or p.next == p
* Self-links are used in the node unlinking process. Active nodes
* never have self-links.
*
* A node p is active if and only if:
*
* p.item != null ||
* (p.prev == null && p.next != p) ||
* (p.next == null && p.prev != p)
*
* The deque object has two node references, "head" and "tail".
* The head and tail are only approximations to the first and last
* nodes of the deque. The first node can always be found by
* following prev pointers from head; likewise for tail. However,
* it is permissible for head and tail to be referring to deleted
* nodes that have been unlinked and so may not be reachable from
* any live node.
*
* There are 3 stages of node deletion;
* "logical deletion", "unlinking", and "gc-unlinking".
*
* 1. "logical deletion" by CASing item to null atomically removes
* the element from the collection, and makes the containing node
* eligible for unlinking.
*
* 2. "unlinking" makes a deleted node unreachable from active
* nodes, and thus eventually reclaimable by GC. Unlinked nodes
* may remain reachable indefinitely from an iterator.
*
* Physical node unlinking is merely an optimization (albeit a
* critical one), and so can be performed at our convenience. At
* any time, the set of live nodes maintained by prev and next
* links are identical, that is, the live nodes found via next
* links from the first node is equal to the elements found via
* prev links from the last node. However, this is not true for
* nodes that have already been logically deleted - such nodes may
* be reachable in one direction only.
*
* 3. "gc-unlinking" takes unlinking further by making active
* nodes unreachable from deleted nodes, making it easier for the
* GC to reclaim future deleted nodes. This step makes the data
* structure "gc-robust", as first described in detail by Boehm
* (http://portal.acm.org/citation.cfm?doid=503272.503282).
*
* GC-unlinked nodes may remain reachable indefinitely from an
* iterator, but unlike unlinked nodes, are never reachable from
* head or tail.
*
* Making the data structure GC-robust will eliminate the risk of
* unbounded memory retention with conservative GCs and is likely
* to improve performance with generational GCs.
*
* When a node is dequeued at either end, e.g. via poll(), we would
* like to break any references from the node to active nodes. We
* develop further the use of self-links that was very effective in
* other concurrent collection classes. The idea is to replace
* prev and next pointers with special values that are interpreted
* to mean off-the-list-at-one-end. These are approximations, but
* good enough to preserve the properties we want in our
* traversals, e.g. we guarantee that a traversal will never visit
* the same element twice, but we don't guarantee whether a
* traversal that runs out of elements will be able to see more
* elements later after enqueues at that end. Doing gc-unlinking
* safely is particularly tricky, since any node can be in use
* indefinitely (for example by an iterator). We must ensure that
* the nodes pointed at by head/tail never get gc-unlinked, since
* head/tail are needed to get "back on track" by other nodes that
* are gc-unlinked. gc-unlinking accounts for much of the
* implementation complexity.
*
* Since neither unlinking nor gc-unlinking are necessary for
* correctness, there are many implementation choices regarding
* frequency (eagerness) of these operations. Since volatile
* reads are likely to be much cheaper than CASes, saving CASes by
* unlinking multiple adjacent nodes at a time may be a win.
* gc-unlinking can be performed rarely and still be effective,
* since it is most important that long chains of deleted nodes
* are occasionally broken.
*
* The actual representation we use is that p.next == p means to
* goto the first node (which in turn is reached by following prev
* pointers from head), and p.next == null && p.prev == p means
* that the iteration is at an end and that p is a (static final)
* dummy node, NEXT_TERMINATOR, and not the last active node.
* Finishing the iteration when encountering such a TERMINATOR is
* good enough for read-only traversals, so such traversals can use
* p.next == null as the termination condition. When we need to
* find the last (active) node, for enqueueing a new node, we need
* to check whether we have reached a TERMINATOR node; if so,
* restart traversal from tail.
*
* The implementation is completely directionally symmetrical,
* except that most public methods that iterate through the list
* follow next pointers ("forward" direction).
*
* We believe (without full proof) that all single-element deque
* operations (e.g., addFirst, peekLast, pollLast) are linearizable
* (see Herlihy and Shavit's book). However, some combinations of
* operations are known not to be linearizable. In particular,
* when an addFirst(A) is racing with pollFirst() removing B, it is
* possible for an observer iterating over the elements to observe
* A B C and subsequently observe A C, even though no interior
* removes are ever performed. Nevertheless, iterators behave
* reasonably, providing the "weakly consistent" guarantees.
*
* Empirically, microbenchmarks suggest that this class adds about
* 40% overhead relative to ConcurrentLinkedQueue, which feels as
* good as we can hope for.
*/
private static final long serialVersionUID = 876323262645176354L;
/**
* A node from which the first node on list (that is, the unique node p
* with p.prev == null && p.next != p) can be reached in O(1) time.
* Invariants:
* - the first node is always O(1) reachable from head via prev links
* - all live nodes are reachable from the first node via succ()
* - head != null
* - (tmp = head).next != tmp || tmp != head
* - head is never gc-unlinked (but may be unlinked)
* Non-invariants:
* - head.item may or may not be null
* - head may not be reachable from the first or last node, or from tail
*/
private transient volatile Node<E> head;
/**
* A node from which the last node on list (that is, the unique node p
* with p.next == null && p.prev != p) can be reached in O(1) time.
* Invariants:
* - the last node is always O(1) reachable from tail via next links
* - all live nodes are reachable from the last node via pred()
* - tail != null
* - tail is never gc-unlinked (but may be unlinked)
* Non-invariants:
* - tail.item may or may not be null
* - tail may not be reachable from the first or last node, or from head
*/
private transient volatile Node<E> tail;
private static final AtomicReferenceFieldUpdater<PortableConcurrentDirectDeque, Node> headUpdater = AtomicReferenceFieldUpdater.newUpdater(PortableConcurrentDirectDeque.class, Node.class, "head");
private static final AtomicReferenceFieldUpdater<PortableConcurrentDirectDeque, Node> tailUpdater = AtomicReferenceFieldUpdater.newUpdater(PortableConcurrentDirectDeque.class, Node.class, "tail");
private static final Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR;
@SuppressWarnings("unchecked")
Node<E> prevTerminator() {
return (Node<E>) PREV_TERMINATOR;
}
@SuppressWarnings("unchecked")
Node<E> nextTerminator() {
return (Node<E>) NEXT_TERMINATOR;
}
static final class Node<E> {
private static final AtomicReferenceFieldUpdater<Node, Node> prevUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "prev");
private static final AtomicReferenceFieldUpdater<Node, Node> nextUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "next");
private static final AtomicReferenceFieldUpdater<Node, Object> itemUpdater = AtomicReferenceFieldUpdater.newUpdater(Node.class, Object.class, "item");
volatile Node<E> prev;
volatile E item;
volatile Node<E> next;
Node() { // default constructor for NEXT_TERMINATOR, PREV_TERMINATOR
}
/**
* Constructs a new node. Uses relaxed write because item can
* only be seen after publication via casNext or casPrev.
*/
Node(E item) {
this.item = item;
}
boolean casItem(E cmp, E val) {
return itemUpdater.compareAndSet(this, cmp, val);
}
void lazySetNext(Node<E> val) {
next = val;
}
boolean casNext(Node<E> cmp, Node<E> val) {
return nextUpdater.compareAndSet(this, cmp, val);
}
void lazySetPrev(Node<E> val) {
prev = val;
}
boolean casPrev(Node<E> cmp, Node<E> val) {
return prevUpdater.compareAndSet(this, cmp, val);
}
}
/**
* Links e as first element.
*/
private Node linkFirst(E e) {
checkNotNullParamWithNullPointerException("e", e);
final Node<E> newNode = new Node<>(e);
restartFromHead:
for (;;)
for (Node<E> h = head, p = h, q;;) {
if ((q = p.prev) != null &&
(q = (p = q).prev) != null)
// Check for head updates every other hop.
// If p == q, we are sure to follow head instead.
p = (h != (h = head)) ? h : q;
else if (p.next == p) // PREV_TERMINATOR
continue restartFromHead;
else {
// p is first node
newNode.lazySetNext(p); // CAS piggyback
if (p.casPrev(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this deque,
// and for newNode to become "live".
if (p != h) // hop two nodes at a time
casHead(h, newNode); // Failure is OK.
return newNode;
}
// Lost CAS race to another thread; re-read prev
}
}
}
/**
* Links e as last element.
*/
private Node linkLast(E e) {
checkNotNullParamWithNullPointerException("e", e);
final Node<E> newNode = new Node<>(e);
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p.prev == p) // NEXT_TERMINATOR
continue restartFromTail;
else {
// p is last node
newNode.lazySetPrev(p); // CAS piggyback
if (p.casNext(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this deque,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time
casTail(t, newNode); // Failure is OK.
return newNode;
}
// Lost CAS race to another thread; re-read next
}
}
}
private static final int HOPS = 2;
/**
* Unlinks non-null node x.
*/
void unlink(Node<E> x) {
final Node<E> prev = x.prev;
final Node<E> next = x.next;
if (prev == null) {
unlinkFirst(x, next);
} else if (next == null) {
unlinkLast(x, prev);
} else {
// Unlink interior node.
//
// This is the common case, since a series of polls at the
// same end will be "interior" removes, except perhaps for
// the first one, since end nodes cannot be unlinked.
//
// At any time, all active nodes are mutually reachable by
// following a sequence of either next or prev pointers.
//
// Our strategy is to find the unique active predecessor
// and successor of x. Try to fix up their links so that
// they point to each other, leaving x unreachable from
// active nodes. If successful, and if x has no live
// predecessor/successor, we additionally try to gc-unlink,
// leaving active nodes unreachable from x, by rechecking
// that the status of predecessor and successor are
// unchanged and ensuring that x is not reachable from
// tail/head, before setting x's prev/next links to their
// logical approximate replacements, self/TERMINATOR.
Node<E> activePred, activeSucc;
boolean isFirst, isLast;
int hops = 1;
// Find active predecessor
for (Node<E> p = prev; ; ++hops) {
if (p.item != null) {
activePred = p;
isFirst = false;
break;
}
Node<E> q = p.prev;
if (q == null) {
if (p.next == p)
return;
activePred = p;
isFirst = true;
break;
}
else if (p == q)
return;
else
p = q;
}
// Find active successor
for (Node<E> p = next; ; ++hops) {
if (p.item != null) {
activeSucc = p;
isLast = false;
break;
}
Node<E> q = p.next;
if (q == null) {
if (p.prev == p)
return;
activeSucc = p;
isLast = true;
break;
}
else if (p == q)
return;
else
p = q;
}
// TODO: better HOP heuristics
if (hops < HOPS
// always squeeze out interior deleted nodes
&& (isFirst || isLast))
return;
// Squeeze out deleted nodes between activePred and
// activeSucc, including x.
skipDeletedSuccessors(activePred);
skipDeletedPredecessors(activeSucc);
// Try to gc-unlink, if possible
if ((isFirst || isLast) &&
// Recheck expected state of predecessor and successor
(activePred.next == activeSucc) &&
(activeSucc.prev == activePred) &&
(isFirst ? activePred.prev == null : activePred.item != null) &&
(isLast ? activeSucc.next == null : activeSucc.item != null)) {
updateHead(); // Ensure x is not reachable from head
updateTail(); // Ensure x is not reachable from tail
// Finally, actually gc-unlink
x.lazySetPrev(isFirst ? prevTerminator() : x);
x.lazySetNext(isLast ? nextTerminator() : x);
}
}
}
/**
* Unlinks non-null first node.
*/
private void unlinkFirst(Node<E> first, Node<E> next) {
for (Node<E> o = null, p = next, q;;) {
if (p.item != null || (q = p.next) == null) {
if (o != null && p.prev != p && first.casNext(next, p)) {
skipDeletedPredecessors(p);
if (first.prev == null &&
(p.next == null || p.item != null) &&
p.prev == first) {
updateHead(); // Ensure o is not reachable from head
updateTail(); // Ensure o is not reachable from tail
// Finally, actually gc-unlink
o.lazySetNext(o);
o.lazySetPrev(prevTerminator());
}
}
return;
}
else if (p == q)
return;
else {
o = p;
p = q;
}
}
}
/**
* Unlinks non-null last node.
*/
private void unlinkLast(Node<E> last, Node<E> prev) {
for (Node<E> o = null, p = prev, q;;) {
if (p.item != null || (q = p.prev) == null) {
if (o != null && p.next != p && last.casPrev(prev, p)) {
skipDeletedSuccessors(p);
if (last.next == null &&
(p.prev == null || p.item != null) &&
p.next == last) {
updateHead(); // Ensure o is not reachable from head
updateTail(); // Ensure o is not reachable from tail
// Finally, actually gc-unlink
o.lazySetPrev(o);
o.lazySetNext(nextTerminator());
}
}
return;
}
else if (p == q)
return;
else {
o = p;
p = q;
}
}
}
/**
* Guarantees that any node which was unlinked before a call to
* this method will be unreachable from head after it returns.
* Does not guarantee to eliminate slack, only that head will
* point to a node that was active while this method was running.
*/
private void updateHead() {
// Either head already points to an active node, or we keep
// trying to cas it to the first node until it does.
Node<E> h, p, q;
restartFromHead:
while ((h = head).item == null && (p = h.prev) != null) {
for (;;) {
if ((q = p.prev) == null ||
(q = (p = q).prev) == null) {
// It is possible that p is PREV_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
if (casHead(h, p))
return;
else
continue restartFromHead;
}
else if (h != head)
continue restartFromHead;
else
p = q;
}
}
}
/**
* Guarantees that any node which was unlinked before a call to
* this method will be unreachable from tail after it returns.
* Does not guarantee to eliminate slack, only that tail will
* point to a node that was active while this method was running.
*/
private void updateTail() {
// Either tail already points to an active node, or we keep
// trying to cas it to the last node until it does.
Node<E> t, p, q;
restartFromTail:
while ((t = tail).item == null && (p = t.next) != null) {
for (;;) {
if ((q = p.next) == null ||
(q = (p = q).next) == null) {
// It is possible that p is NEXT_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
if (casTail(t, p))
return;
else
continue restartFromTail;
}
else if (t != tail)
continue restartFromTail;
else
p = q;
}
}
}
private void skipDeletedPredecessors(Node<E> x) {
whileActive:
do {
Node<E> prev = x.prev;
Node<E> p = prev;
findActive:
for (;;) {
if (p.item != null)
break findActive;
Node<E> q = p.prev;
if (q == null) {
if (p.next == p)
continue whileActive;
break findActive;
}
else if (p == q)
continue whileActive;
else
p = q;
}
// found active CAS target
if (prev == p || x.casPrev(prev, p))
return;
} while (x.item != null || x.next == null);
}
private void skipDeletedSuccessors(Node<E> x) {
whileActive:
do {
Node<E> next = x.next;
Node<E> p = next;
findActive:
for (;;) {
if (p.item != null)
break findActive;
Node<E> q = p.next;
if (q == null) {
if (p.prev == p)
continue whileActive;
break findActive;
}
else if (p == q)
continue whileActive;
else
p = q;
}
// found active CAS target
if (next == p || x.casNext(next, p))
return;
} while (x.item != null || x.prev == null);
}
/**
* Returns the successor of p, or the first node if p.next has been
* linked to self, which will only be true if traversing with a
* stale pointer that is now off the list.
*/
final Node<E> succ(Node<E> p) {
// TODO: should we skip deleted nodes here?
Node<E> q = p.next;
return (p == q) ? first() : q;
}
/**
* Returns the predecessor of p, or the last node if p.prev has been
* linked to self, which will only be true if traversing with a
* stale pointer that is now off the list.
*/
final Node<E> pred(Node<E> p) {
Node<E> q = p.prev;
return (p == q) ? last() : q;
}
/**
* Returns the first node, the unique node p for which:
* p.prev == null && p.next != p
* The returned node may or may not be logically deleted.
* Guarantees that head is set to the returned node.
*/
Node<E> first() {
restartFromHead:
for (;;)
for (Node<E> h = head, p = h, q;;) {
if ((q = p.prev) != null &&
(q = (p = q).prev) != null)
// Check for head updates every other hop.
// If p == q, we are sure to follow head instead.
p = (h != (h = head)) ? h : q;
else if (p == h
// It is possible that p is PREV_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
|| casHead(h, p))
return p;
else
continue restartFromHead;
}
}
/**
* Returns the last node, the unique node p for which:
* p.next == null && p.prev != p
* The returned node may or may not be logically deleted.
* Guarantees that tail is set to the returned node.
*/
Node<E> last() {
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p == t
// It is possible that p is NEXT_TERMINATOR,
// but if so, the CAS is guaranteed to fail.
|| casTail(t, p))
return p;
else
continue restartFromTail;
}
}
// Minor convenience utilities
/**
* Returns element unless it is null, in which case throws
* NoSuchElementException.
*
* @param v the element
* @return the element
*/
private E screenNullResult(E v) {
if (v == null)
throw new NoSuchElementException();
return v;
}
/**
* Creates an array list and fills it with elements of this list.
* Used by toArray.
*
* @return the arrayList
*/
private ArrayList<E> toArrayList() {
ArrayList<E> list = new ArrayList<>();
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null)
list.add(item);
}
return list;
}
/**
* Constructs an empty deque.
*/
public PortableConcurrentDirectDeque() {
head = tail = new Node<>(null);
}
/**
* Constructs a deque initially containing the elements of
* the given collection, added in traversal order of the
* collection's iterator.
*
* @param c the collection of elements to initially contain
* @throws NullPointerException if the specified collection or any
* of its elements are null
*/
public PortableConcurrentDirectDeque(Collection<? extends E> c) {
// Copy c into a private chain of Nodes
Node<E> h = null, t = null;
for (E e : c) {
checkNotNullParamWithNullPointerException("e", e);
Node<E> newNode = new Node<>(e);
if (h == null)
h = t = newNode;
else {
t.lazySetNext(newNode);
newNode.lazySetPrev(t);
t = newNode;
}
}
initHeadTail(h, t);
}
/**
* Initializes head and tail, ensuring invariants hold.
*/
private void initHeadTail(Node<E> h, Node<E> t) {
if (h == t) {
if (h == null)
h = t = new Node<>(null);
else {
// Avoid edge case of a single Node with non-null item.
Node<E> newNode = new Node<>(null);
t.lazySetNext(newNode);
newNode.lazySetPrev(t);
t = newNode;
}
}
head = h;
tail = t;
}
/**
* Inserts the specified element at the front of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException}.
*
* @throws NullPointerException if the specified element is null
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Inserts the specified element at the end of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException}.
*
* <p>This method is equivalent to {@link #add}.
*
* @throws NullPointerException if the specified element is null
*/
public void addLast(E e) {
linkLast(e);
}
/**
* Inserts the specified element at the front of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* @return {@code true} (as specified by {@link java.util.Deque#offerFirst})
* @throws NullPointerException if the specified element is null
*/
public boolean offerFirst(E e) {
linkFirst(e);
return true;
}
public Object offerFirstAndReturnToken(E e) {
return linkFirst(e);
}
public Object offerLastAndReturnToken(E e) {
return linkLast(e);
}
public void removeToken(Object token) {
if (!(token instanceof Node)) {
throw new IllegalArgumentException();
}
Node node = (Node) (token);
while (! node.casItem(node.item, null)) {}
unlink(node);
}
/**
* Inserts the specified element at the end of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* <p>This method is equivalent to {@link #add}.
*
* @return {@code true} (as specified by {@link java.util.Deque#offerLast})
* @throws NullPointerException if the specified element is null
*/
public boolean offerLast(E e) {
linkLast(e);
return true;
}
public E peekFirst() {
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null)
return item;
}
return null;
}
public E peekLast() {
for (Node<E> p = last(); p != null; p = pred(p)) {
E item = p.item;
if (item != null)
return item;
}
return null;
}
/**
* @throws java.util.NoSuchElementException {@inheritDoc}
*/
public E getFirst() {
return screenNullResult(peekFirst());
}
/**
* @throws java.util.NoSuchElementException {@inheritDoc}
*/
public E getLast() {
return screenNullResult(peekLast());
}
public E pollFirst() {
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null && p.casItem(item, null)) {
unlink(p);
return item;
}
}
return null;
}
public E pollLast() {
for (Node<E> p = last(); p != null; p = pred(p)) {
E item = p.item;
if (item != null && p.casItem(item, null)) {
unlink(p);
return item;
}
}
return null;
}
/**
* @throws java.util.NoSuchElementException {@inheritDoc}
*/
public E removeFirst() {
return screenNullResult(pollFirst());
}
/**
* @throws java.util.NoSuchElementException {@inheritDoc}
*/
public E removeLast() {
return screenNullResult(pollLast());
}
// *** Queue and stack methods ***
/**
* Inserts the specified element at the tail of this deque.
* As the deque is unbounded, this method will never return {@code false}.
*
* @return {@code true} (as specified by {@link java.util.Queue#offer})
* @throws NullPointerException if the specified element is null
*/
public boolean offer(E e) {
return offerLast(e);
}
/**
* Inserts the specified element at the tail of this deque.
* As the deque is unbounded, this method will never throw
* {@link IllegalStateException} or return {@code false}.
*
* @return {@code true} (as specified by {@link java.util.Collection#add})
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
return offerLast(e);
}
public E poll() {
return pollFirst();
}
public E remove() {
return removeFirst();
}
public E peek() {
return peekFirst();
}
public E element() {
return getFirst();
}
public void push(E e) {
addFirst(e);
}
public E pop() {
return removeFirst();
}
/**
* Removes the first element {@code e} such that
* {@code o.equals(e)}, if such an element exists in this deque.
* If the deque does not contain the element, it is unchanged.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean removeFirstOccurrence(Object o) {
checkNotNullParamWithNullPointerException("o", o);
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null && o.equals(item) && p.casItem(item, null)) {
unlink(p);
return true;
}
}
return false;
}
/**
* Removes the last element {@code e} such that
* {@code o.equals(e)}, if such an element exists in this deque.
* If the deque does not contain the element, it is unchanged.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean removeLastOccurrence(Object o) {
checkNotNullParamWithNullPointerException("o", o);
for (Node<E> p = last(); p != null; p = pred(p)) {
E item = p.item;
if (item != null && o.equals(item) && p.casItem(item, null)) {
unlink(p);
return true;
}
}
return false;
}
/**
* Returns {@code true} if this deque contains at least one
* element {@code e} such that {@code o.equals(e)}.
*
* @param o element whose presence in this deque is to be tested
* @return {@code true} if this deque contains the specified element
*/
public boolean contains(Object o) {
if (o == null) return false;
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null && o.equals(item))
return true;
}
return false;
}
/**
* Returns {@code true} if this collection contains no elements.
*
* @return {@code true} if this collection contains no elements
*/
public boolean isEmpty() {
return peekFirst() == null;
}
/**
* Returns the number of elements in this deque. If this deque
* contains more than {@code Integer.MAX_VALUE} elements, it
* returns {@code Integer.MAX_VALUE}.
*
* <p>Beware that, unlike in most collections, this method is
* <em>NOT</em> a constant-time operation. Because of the
* asynchronous nature of these deques, determining the current
* number of elements requires traversing them all to count them.
* Additionally, it is possible for the size to change during
* execution of this method, in which case the returned result
* will be inaccurate. Thus, this method is typically not very
* useful in concurrent applications.
*
* @return the number of elements in this deque
*/
public int size() {
int count = 0;
for (Node<E> p = first(); p != null; p = succ(p))
if (p.item != null)
// Collection.size() spec says to max out
if (++count == Integer.MAX_VALUE)
break;
return count;
}
/**
* Removes the first element {@code e} such that
* {@code o.equals(e)}, if such an element exists in this deque.
* If the deque does not contain the element, it is unchanged.
*
* @param o element to be removed from this deque, if present
* @return {@code true} if the deque contained the specified element
* @throws NullPointerException if the specified element is null
*/
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
/**
* Appends all of the elements in the specified collection to the end of
* this deque, in the order that they are returned by the specified
* collection's iterator. Attempts to {@code addAll} of a deque to
* itself result in {@code IllegalArgumentException}.
*
* @param c the elements to be inserted into this deque
* @return {@code true} if this deque changed as a result of the call
* @throws NullPointerException if the specified collection or any
* of its elements are null
* @throws IllegalArgumentException if the collection is this deque
*/
public boolean addAll(Collection<? extends E> c) {
if (c == this)
// As historically specified in AbstractQueue#addAll
throw new IllegalArgumentException();
// Copy c into a private chain of Nodes
Node<E> beginningOfTheEnd = null, last = null;
for (E e : c) {
checkNotNullParamWithNullPointerException("e", e);
Node<E> newNode = new Node<>(e);
if (beginningOfTheEnd == null)
beginningOfTheEnd = last = newNode;
else {
last.lazySetNext(newNode);
newNode.lazySetPrev(last);
last = newNode;
}
}
if (beginningOfTheEnd == null)
return false;
// Atomically append the chain at the tail of this collection
restartFromTail:
for (;;)
for (Node<E> t = tail, p = t, q;;) {
if ((q = p.next) != null &&
(q = (p = q).next) != null)
// Check for tail updates every other hop.
// If p == q, we are sure to follow tail instead.
p = (t != (t = tail)) ? t : q;
else if (p.prev == p) // NEXT_TERMINATOR
continue restartFromTail;
else {
// p is last node
beginningOfTheEnd.lazySetPrev(p); // CAS piggyback
if (p.casNext(null, beginningOfTheEnd)) {
// Successful CAS is the linearization point
// for all elements to be added to this deque.
if (!casTail(t, last)) {
// Try a little harder to update tail,
// since we may be adding many elements.
t = tail;
if (last.next == null)
casTail(t, last);
}
return true;
}
// Lost CAS race to another thread; re-read next
}
}
}
/**
* Removes all of the elements from this deque.
*/
public void clear() {
while (pollFirst() != null) { }
}
/**
* Returns an array containing all of the elements in this deque, in
* proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this deque. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this deque
*/
public Object[] toArray() {
return toArrayList().toArray();
}
/**
* Returns an array containing all of the elements in this deque,
* in proper sequence (from first to last element); the runtime
* type of the returned array is that of the specified array. If
* the deque fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of
* the specified array and the size of this deque.
*
* <p>If this deque fits in the specified array with room to spare
* (i.e., the array has more elements than this deque), the element in
* the array immediately following the end of the deque is set to
* {@code null}.
*
* <p>Like the {@link #toArray()} method, this method acts as
* bridge between array-based and collection-based APIs. Further,
* this method allows precise control over the runtime type of the
* output array, and may, under certain circumstances, be used to
* save allocation costs.
*
* <p>Suppose {@code x} is a deque known to contain only strings.
* The following code can be used to dump the deque into a newly
* allocated array of {@code String}:
*
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
*
* Note that {@code toArray(new Object[0])} is identical in function to
* {@code toArray()}.
*
* @param a the array into which the elements of the deque are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose
* @return an array containing all of the elements in this deque
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this deque
* @throws NullPointerException if the specified array is null
*/
public <T> T[] toArray(T[] a) {
return toArrayList().toArray(a);
}
/**
* Returns an iterator over the elements in this deque in proper sequence.
* The elements will be returned in order from first (head) to last (tail).
*
* <p>The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
* ConcurrentModificationException}, and guarantees to traverse
* elements as they existed upon construction of the iterator, and
* may (but is not guaranteed to) reflect any modifications
* subsequent to construction.
*
* @return an iterator over the elements in this deque in proper sequence
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* Returns an iterator over the elements in this deque in reverse
* sequential order. The elements will be returned in order from
* last (tail) to first (head).
*
* <p>The returned iterator is a "weakly consistent" iterator that
* will never throw {@link java.util.ConcurrentModificationException
* ConcurrentModificationException}, and guarantees to traverse
* elements as they existed upon construction of the iterator, and
* may (but is not guaranteed to) reflect any modifications
* subsequent to construction.
*
* @return an iterator over the elements in this deque in reverse order
*/
public Iterator<E> descendingIterator() {
return new DescendingItr();
}
private abstract class AbstractItr implements Iterator<E> {
/**
* Next node to return item for.
*/
private Node<E> nextNode;
/**
* nextItem holds on to item fields because once we claim
* that an element exists in hasNext(), we must return it in
* the following next() call even if it was in the process of
* being removed when hasNext() was called.
*/
private E nextItem;
/**
* Node returned by most recent call to next. Needed by remove.
* Reset to null if this element is deleted by a call to remove.
*/
private Node<E> lastRet;
abstract Node<E> startNode();
abstract Node<E> nextNode(Node<E> p);
AbstractItr() {
advance();
}
/**
* Sets nextNode and nextItem to next valid node, or to null
* if no such.
*/
private void advance() {
lastRet = nextNode;
Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode);
for (;; p = nextNode(p)) {
if (p == null) {
// p might be active end or TERMINATOR node; both are OK
nextNode = null;
nextItem = null;
break;
}
E item = p.item;
if (item != null) {
nextNode = p;
nextItem = item;
break;
}
}
}
public boolean hasNext() {
return nextItem != null;
}
public E next() {
E item = nextItem;
if (item == null) throw new NoSuchElementException();
advance();
return item;
}
public void remove() {
Node<E> l = lastRet;
if (l == null) throw new IllegalStateException();
l.item = null;
unlink(l);
lastRet = null;
}
}
/** Forward iterator */
private class Itr extends AbstractItr {
Node<E> startNode() {
return first();
}
Node<E> nextNode(Node<E> p) {
return succ(p);
}
}
/**
* Descending iterator
*/
private class DescendingItr extends AbstractItr {
Node<E> startNode() {
return last();
}
Node<E> nextNode(Node<E> p) {
return pred(p);
}
}
/**
* Saves this deque to a stream (that is, serializes it).
*
* @serialData All of the elements (each an {@code E}) in
* the proper order, followed by a null
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden stuff
s.defaultWriteObject();
// Write out all elements in the proper order.
for (Node<E> p = first(); p != null; p = succ(p)) {
E item = p.item;
if (item != null)
s.writeObject(item);
}
// Use trailing null as sentinel
s.writeObject(null);
}
/**
* Reconstitutes this deque from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in elements until trailing null sentinel found
Node<E> h = null, t = null;
Object item;
while ((item = s.readObject()) != null) {
@SuppressWarnings("unchecked")
Node<E> newNode = new Node<>((E) item);
if (h == null)
h = t = newNode;
else {
t.lazySetNext(newNode);
newNode.lazySetPrev(t);
t = newNode;
}
}
initHeadTail(h, t);
}
private boolean casHead(Node<E> cmp, Node<E> val) {
return headUpdater.compareAndSet(this, cmp, val);
}
private boolean casTail(Node<E> cmp, Node<E> val) {
return tailUpdater.compareAndSet(this, cmp, val);
}
// Unsafe mechanics
static {
PREV_TERMINATOR = new Node<>();
PREV_TERMINATOR.next = PREV_TERMINATOR;
NEXT_TERMINATOR = new Node<>();
NEXT_TERMINATOR.prev = NEXT_TERMINATOR;
}
}
| undertow-io/undertow | core/src/main/java/io/undertow/util/PortableConcurrentDirectDeque.java |
180,000 | package zti.projekt_zti.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import zti.projekt_zti.service.StatisticsService;
/**
* Klasa kontrolera obsługującego żądania związane ze statystykami.
*/
@RequiredArgsConstructor
@RestController
public class StatisticsController {
@Autowired
private StatisticsService statisticsService;
/**
* Obsługuje żądanie pobrania statystyk dla dobrostanu (WellBeeing).
*
* @param period okres czasu
* @param userId identyfikator użytkownika
* @return ResponseEntity zwracający statystyki w formacie WellBeeingParameterStatisticsDto lub wiadomość o błędzie
*/
@GetMapping("/wellBeeing")
public ResponseEntity<?> getWellBeeing(@RequestParam(name = "period", required = false) String period,
@RequestParam(name = "userId", required = false) Integer userId) {
if (period == null || userId == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Wymagane parametry nie zostały podane.");
}
return ResponseEntity.ok(statisticsService.getWellBeeing(period, userId));
}
/**
* Obsługuje żądanie pobrania statystyk dla konkretnego parametru dobrostanu (WellBeeingParameter).
*
* @param period okres czasu
* @param userId identyfikator użytkownika
* @param wellBeeing rodzaj samopoczucia
* @param parameter parametr od którego uzależniamy samopoczucie
* @param name nazwa suplementu lub używki
* @return ResponseEntity zwracający statystyki w formacie WellBeeingParameterStatisticsDto lub wiadomość o błędzie
*/
@GetMapping("/wellBeeingParameter")
public ResponseEntity<?> getWellBeeingParameter(@RequestParam(name = "period", required = false) String period,
@RequestParam(name = "userId", required = false) Integer userId,
@RequestParam(name = "wellBeeing", required = false) String wellBeeing,
@RequestParam(name = "parameter", required = false) String parameter,
@RequestParam(name = "name", required = false) String name) {
if (period == null || userId == null || wellBeeing == null || parameter == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Wymagane parametry nie zostały podane.");
}
return ResponseEntity.ok(statisticsService.getWellBeeingParameter(period, userId, wellBeeing, parameter, name));
}
/**
* Obsługuje żądanie pobrania statystyk dla konkretnego parametru.
*
* @param period okres czasu
* @param userId identyfikator użytkownika
* @param parameter parametr
* @param name nazwa suplemetu lub używki
* @return ResponseEntity zwracający statystyki dla konkretnego parametru w formacie ParameterStatisticsDto lub wiadomość o błędzie
*/
@GetMapping("/parameter")
public ResponseEntity<?> getWellBeeingParameter(@RequestParam(name = "period", required = false) String period,
@RequestParam(name = "userId", required = false) Integer userId,
@RequestParam(name = "parameter", required = false) String parameter,
@RequestParam(name = "name", required = false) String name) {
if (period == null || userId == null || parameter == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Wymagane parametry nie zostały podane.");
}
return ResponseEntity.ok(statisticsService.getParameter(period, userId, parameter, name));
}
/**
* Obsługuje żądanie pobrania ogólnych statystyk.
*
* @param period okres czasu
* @param userId identyfikator użytkownika
* @param parameter parametr
* @param name nazwa suplementu lub używki
* @return ResponseEntity zwracający ogólne statystyki w formacie StatisticsDto lub wiadomość o błędzie
*/
@GetMapping("/statistics")
public ResponseEntity<?> getStatistics(@RequestParam(name = "period", required = false) String period,
@RequestParam(name = "userId", required = false) Integer userId,
@RequestParam(name = "parameter", required = false) String parameter,
@RequestParam(name = "name", required = false) String name) {
if (period == null || userId == null || parameter == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Wymagane parametry nie zostały podane.");
}
return ResponseEntity.ok(statisticsService.getStatistics(period, userId, parameter, name));
}
} | kinan11/ZTI_Projekt | projekt_ZTI/src/main/java/zti/projekt_zti/controller/StatisticsController.java |
180,001 | package zti.projekt_zti.service;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import zti.projekt_zti.dto.ParameterStatisticsDto;
import zti.projekt_zti.dto.StatisticsDto;
import zti.projekt_zti.dto.WellBeeingParameterStatisticsDto;
import zti.projekt_zti.dto.WellBeeingStatisticsDto;
import zti.projekt_zti.entity.Day;
import zti.projekt_zti.repository.DayRepository;
import zti.projekt_zti.repository.DrugRepository;
import zti.projekt_zti.repository.MeetingRepository;
import zti.projekt_zti.repository.SupplementRepository;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
/**
* Ta klasa zawiera testy jednostkowe dla klasy StatisticsService w pakiecie {@code zti.projekt_zti.service}.
* Testy te weryfikują poprawność działania serwisu w obsłudze operacji dotyczących dni.
*/
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class StatisticsServiceTest {
@Mock
private DayRepository dayRepository;
@InjectMocks
private StatisticsService statisticsService;
@BeforeEach
public void setup() {
MockitoAnnotations.openMocks(this);
}
/**
* Przypadek testowy pobierania statystyk dobre samopoczucie - tydzień.
* Test sprawdza, czy metoda statisticsService.getWellBeeing() poprawnie zwraca statystyki dotyczące dobre samopoczucie na przestrzeni tygodnia.
*/
@Test
public void testGetWellBeeing_Week() {
Integer userId = 1;
String period = "week";
LocalDate endDate = LocalDate.now();
LocalDateTime localDateTimeWithMidnightEnd = endDate.atStartOfDay();
Timestamp timestampEnd = Timestamp.valueOf(localDateTimeWithMidnightEnd);
LocalDate startDate = endDate.minusDays(7);
LocalDateTime localDateTimeWithMidnightStart = startDate.atStartOfDay();
Timestamp timestampStart = Timestamp.valueOf(localDateTimeWithMidnightStart);
List<Day> days = new ArrayList<>();
Day day1 = new Day();
day1.setPhysicalWellBeeing(5);
day1.setMentalWellBeeing(4);
days.add(day1);
Day day2 = new Day();
day2.setPhysicalWellBeeing(3);
day2.setMentalWellBeeing(2);
days.add(day2);
when(dayRepository.findAllByDateBetweenAndUserId(timestampStart, timestampEnd, userId)).thenReturn(days);
WellBeeingStatisticsDto result = statisticsService.getWellBeeing(period, userId);
assertEquals(2, result.getStatistics().size());
assertEquals(5, result.getStatistics().get(0).getX());
assertEquals(4, result.getStatistics().get(0).getY());
assertEquals(3, result.getStatistics().get(1).getX());
assertEquals(2, result.getStatistics().get(1).getY());
}
/**
* Przypadek testowy pobierania statystyk określonego parametru dobre samopoczucie - miesiąc.
* Test sprawdza, czy metoda statisticsService.getWellBeeingParameter() poprawnie zwraca statystyki określonego parametru dobre samopoczucie na przestrzeni miesiąca.
*/
@Test
public void testGetWellBeeingParameter_Month() {
Integer userId = 1;
String period = "month";
String wellBeeing = "physical";
String parameter = "workH";
String name = "";
LocalDate endDate = LocalDate.now();
LocalDateTime localDateTimeWithMidnightEnd = endDate.atStartOfDay();
Timestamp timestampEnd = Timestamp.valueOf(localDateTimeWithMidnightEnd);
LocalDate startDate = endDate.minusDays(30);
LocalDateTime localDateTimeWithMidnightStart = startDate.atStartOfDay();
Timestamp timestampStart = Timestamp.valueOf(localDateTimeWithMidnightStart);
List<Day> days = new ArrayList<>();
Day day1 = new Day();
day1.setWorkH(8.0);
day1.setPhysicalWellBeeing(5);
days.add(day1);
Day day2 = new Day();
day2.setWorkH(7.5);
day2.setPhysicalWellBeeing(4);
days.add(day2);
when(dayRepository.findAllByDateBetweenAndUserId(timestampStart, timestampEnd, userId)).thenReturn(days);
WellBeeingParameterStatisticsDto result = statisticsService.getWellBeeingParameter(period, userId, wellBeeing, parameter, name);
assertEquals(2, result.getStatistics().size());
assertEquals(8.0, result.getStatistics().get(0).getX());
assertEquals(5, result.getStatistics().get(0).getY());
assertEquals(7.5, result.getStatistics().get(1).getX());
assertEquals(4, result.getStatistics().get(1).getY());
}
/**
* Przypadek testowy pobierania statystyk określonego parametru.
* Test sprawdza, czy metoda statisticsService.getParameter() poprawnie zwraca statystyki określonego parametru na przestrzeni tygodnia.
*/
@Test
public void testGetParameter() {
String period = "week";
Integer userId = 1;
String parameter = "workH";
LocalDate endDate = LocalDate.now();
LocalDateTime localDateTimeWithMidnightEnd = endDate.atStartOfDay();
Timestamp timestampEnd = Timestamp.valueOf(localDateTimeWithMidnightEnd);
LocalDate startDate = endDate.minusDays(7);
LocalDateTime localDateTimeWithMidnightStart = startDate.atStartOfDay();
Timestamp timestampStart = Timestamp.valueOf(localDateTimeWithMidnightStart);
List<Day> days = new ArrayList<>();
days.add(new Day());
when(dayRepository.findAllByDateBetweenAndUserId(timestampStart, timestampEnd, userId)).thenReturn(days);
ParameterStatisticsDto result = statisticsService.getParameter(period, userId, parameter, null);
Assertions.assertNotNull(result);
verify(dayRepository, times(1)).findAllByDateBetweenAndUserId(timestampStart, timestampEnd, userId);
}
/**
* Przypadek testowy pobierania ogólnych statystyk.
* Test sprawdza, czy metoda statisticsService.getStatistics() poprawnie zwraca ogólne statystyki na przestrzeni tygodnia.
*/
@Test
public void testGetStatistics() {
String period = "week";
Integer userId = 1;
String parameter = "workH";
String name = "Work";
LocalDate endDate = LocalDate.now();
LocalDateTime localDateTimeWithMidnightEnd = endDate.atStartOfDay();
Timestamp timestampEnd = Timestamp.valueOf(localDateTimeWithMidnightEnd);
LocalDate startDate = endDate.minusDays(7);
LocalDateTime localDateTimeWithMidnightStart = startDate.atStartOfDay();
Timestamp timestampStart = Timestamp.valueOf(localDateTimeWithMidnightStart);
List<Day> days = new ArrayList<>();
days.add(new Day());
when(dayRepository.findAllByDateBetweenAndUserId(timestampStart, timestampEnd, userId)).thenReturn(days);
StatisticsDto result = statisticsService.getStatistics(period, userId, parameter, name);
Assertions.assertNotNull(result);
verify(dayRepository, times(1)).findAllByDateBetweenAndUserId(timestampStart, timestampEnd, userId);
}
}
| kinan11/ZTI_Projekt | projekt_ZTI/src/test/java/zti/projekt_zti/service/StatisticsServiceTest.java |
180,003 | import java.util.Arrays;
public class PD6_18 {
public static void main(String[] args) {
int[] firstArray ={23,45,12,3,78,98,15,-3};
int[] secondArray ={2,12,24,15,48,64,-5,65};
int [] arrayTemp = new int [firstArray.length + secondArray.length];
int arrayLenght = 0;
for (int i = 0; i < secondArray.length; i++) {
int count = 0;
for (int j = 0; j < firstArray.length; j++) {
if (firstArray[j] == secondArray[i]) {
count++;
}
}
if (count == 0) {
arrayTemp[arrayLenght] = secondArray[i];
arrayLenght++;
}
}
int [] newArray = new int [arrayLenght];
for (int i = 0; i < arrayLenght; i++) {
newArray[i]=arrayTemp[i];
}
System.out.println(Arrays.toString(firstArray));
System.out.println(Arrays.toString(secondArray));
System.out.println(Arrays.toString(newArray));
}
}
//Yra duoti du sveikųjų skaičių masyvai. Parašykite programą, kuri atrenka visus antro masyvo
//elementus, kurie nepasikartoja pirmame masyve. Rezultatą įrašykite į trečia masyvą.
| EmilijaCer/E_Cerniauskaite-Exercises | PD6/src/PD6_18.java |
180,004 | 404: Not Found | TomSabMGTfan/T_Sabaliauskas-Exercises | PD4/src/lt/techin/PD4_2.java |
180,005 | package Darbas;
import javax.swing.JButton;
public class SkaicBud1 extends javax.swing.JFrame {
public SkaicBud1() {
initComponents();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
Result1 = new javax.swing.JLabel();
Result2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
ResultButton = new javax.swing.JButton();
Close = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel2.setText("Įveskite sekantį skirtumą:");
jLabel1.setText("Įveskite pradinį skirtumą:");
jLabel3.setText("cm");
jLabel4.setText("cm");
Result1.setText("Rezultatas gaunasi:");
Result2.setText(" ");
Close.setBackground(new java.awt.Color(0, 102, 102));
Close.setText("Uždaryti langą");
Close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CloseActionPerformed(evt);
}
});
ResultButton.setBackground(new java.awt.Color(0, 102, 102));
ResultButton.setText("Gauti skaičiavimo rezultatą");
ResultButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
ResultButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResultButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)))
.addContainerGap())
.addComponent(Result1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Close, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ResultButton, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(130, 130, 130)))));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)))
.addComponent(Result1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ResultButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Close, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(17, Short.MAX_VALUE)));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)));
pack();
}
public void ResultButtonActionPerformed(java.awt.event.ActionEvent evt) {
float a = Float.parseFloat(jTextField1.getText());
float b = Float.parseFloat(jTextField2.getText());
float c = a/(a-b);
Result2.setText(Float.toString(c));}
private void CloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseActionPerformed
this.dispose();}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}}
catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SkaicBud1().setVisible(true);
}});
}
private javax.swing.JPanel jPanel1;
private javax.swing.JButton Close;
private javax.swing.JButton ResultButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel Result1;
private javax.swing.JLabel Result2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
}
| rutaladygaite/Java-implementation-with-Physics-calculation- | src/Darbas/SkaicBud1.java |
180,007 | package lt.techin.exam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Tasks {
public static void main(String[] args) {
ArrayList<Element> list = new ArrayList<>();
Element e1 = new Element("$10.0", true);
Element e2 = new Element("$5.4", true);
Element e3 = new Element("$1.2", true);
Element e4 = new Element("$5.5", true);
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);
System.out.println(findSumOfPrices(list));
}
/* Paduotus duomenis kilometrais ir metrais konvertuoja į metrus ir rezultatą išveda į ekraną
* pvz. kilometers = 4, meters = 67 =>
* Atspausdina:
* 4067 metrų
*/
public static void convertToMeters(int kilometers, int meters) {
System.out.println(kilometers * 1000 + meters + " metrų");
}
/*Kasininkė grąžą pirkėjui pabėrė centais ct. Reikia apskaičiuoti kiek tai yra eurų ir centų .
* pvz. 234 ct => atspausdina:
* Gauta: 2 Eur ir 34 ct
*/
public static void convertCentsToEuros(int cents) {
int euros = cents / 100;
cents = cents % 100;
System.out.println("Gauta: " + euros + " Eur ir " + cents + " ct");
}
/* Raskite skaičių a, b ir c vidurkį
*/
public static double averageOf(int a, int b, int c) {
return (a + b + c) / 3.0;
}
/* Duoti trys skaičiai. Parašykite metodą, kuris nustatytų, ar bent vienas iš jų yra lyginis.
Pvz.:
a = 1, b = 3, c = 5 => false
a = 1, b = 3, c = 6 => true
* */
public static boolean isEven(int a, int b, int c) {
if (a % 2 == 0 || b % 2 == 0 || c % 2 == 0) {
return true;
}
return false;
}
/*
* Metodas parodo ar iš duotų trijų atkarpų (įvedami jų ilgiai) galima sudaryti trikampį.
*/
public static boolean isTriangleValid(int a, int b, int c) {
return a + b > c && a + c > b && b + c > a;
}
/* Metodas spausdina nelyginius skaičius nuo pateikto skaičiaus 'number' iki 1
* pvz. number = 8 =>
* 7
* 5
* 3
* 1
* */
public static void printOddNumbers(int number) {
for (int i = number; i > 0; i--) {
if (i % 2 != 0) {
System.out.println(i);
}
}
}
/* Paskaičiuoti kiek masyve yra skaičių didesnių nei skaičius 'number'
* Pvz. array = {5, 2, 4, 1} number = 3 => 2
*/
public static int countLargerThanNumber(int[] array, int number) {
return (int) Arrays.stream(array).filter(s -> s > number).count();
}
/* Surasti mažiausią skaičių ArrayListe
* Pvz {6.7, 3.5, 8.2, 4.3} => 8.2
*/
public static double findSmallest(ArrayList<Double> numbers) {
Optional<Double> answer = numbers.stream().min(Double::compare);
return answer.isPresent() ? answer.get() : -9999;
}
/*
* Paskaičiuokite kiek simbolių yra String'ų List'e
*/
public static int countLettersInList(List<String> words) {
return words.stream().mapToInt(String::length).sum();
}
/* Paskaičiuoti kiek ArrayListe yra stringų, kuriuose yra žodis word
pvz: {"iphone 12", "IPHONE 12", "samsung s23"} word = "iphone" => 2
*/
public static int countStringsContainingWord(ArrayList<String> strings, String word) {
return (int) strings.stream().filter(s -> s.toLowerCase().contains(word.toLowerCase())).count();
}
/*
* Paskaičiuokite kiek liste elementų, kur savybė displayed yra true
*/
public static int countDisplayedElements(List<Element> elements) {
return (int) elements.stream().filter(Element::isDisplayed).count();
}
/*
* Grąžinkite listą elementų kurių tekstas nėra tuščias arba sudarytas tik iš tarpų
*/
public static List<Element> findElementsWithNonEmptyTexts(List<Element> elements) {
return elements.stream().filter(s -> !s.getText().isEmpty() && !s.getText().isBlank()).collect(Collectors.toList());
}
/*
* Elementų tekste užrašytos prekių kainos, pvz. "$10.52"
* Raskite didžiausią kainą
*/
public static double findSumOfPrices(List<Element> elements) {
// double sum = 0;
// for (Element e : elements) {
// String[] arr = (e.getText().split("\\$"));
// sum += Double.parseDouble(arr[1]);
// }
// return sum;
return elements.stream().map(s -> s.getText().split("\\$")).mapToDouble(s -> Double.parseDouble(s[1])).sum();
}
}
| andzej123/Techin_Java_Andzej | java-exam-part1-andzej/src/main/java/lt/techin/exam/Tasks.java |
180,008 | package skaitiniaimetodai;
//nr 44 x=2exp(-3x)+1 (2 - Paprastųjų iteracijų metodas; 4 - Niutono metodas;)
/**
Nustatykite intervalą [a,b], kuriame yra tik vienas netiesinės lygties sprendinys ir išspręskite
netiesinę lygtį nurodytais metodais. Palyginkite gautą rezultatą su tiksliu sprendiniu.
Atsiskaitant reikia suformuluoti uždavinį, pateikti skaičiavimo rezultatų lentelę, nubrėžti grafikus,
padaryti išvadas. Taip pat reikia turėti veikiančią programą. Šį darbą reikia apginti iki 2011-04-07
d. Varianto numeris sutampa su numeriu grupės sąraše.
**/
public class Uzd2 {
/**
public static void main(String[] args) {
System.out.println("Funkcija: F(x) = 2 * exp(-3 * x) + 1 - x");
int N = 25; // į kiek intervalas skaidomas
Double from = 0.0; // pradinio intervalo pradžia
Double to = 1.0; // pradinio intervalo pradžia
System.out.println("\n**************** Intervalo paieška ****************");
System.out.printf("N = %d, nuo %f iki %f\n", N, from, to);
IntervalFinder finder = new IntervalFinder(N, from, to);
Interval interval = finder.getFirstInterval();
if (interval != null)
System.out.printf("Intervalas yra [%f %f]\n", interval.getFrom(), interval.getTo());
System.out.println("\n**************** Iteracijų metodas ****************");
IterationMethod iteration = new IterationMethod();
Double e = 0.001; // tikslumas
//from = interval.getFrom(); // intervalo pradžia
//to = interval.getTo(); // intervalo pabaiga
from = 0.0;
to = 1.0;
System.out.printf("e = %f, nuo %f iki %f\n", e, from, to);
iteration.solve(e, from, to);
System.out.printf("q = %.17f, (1-q)/q = %.17f, ((1-q)/q)*e = %.17f\n", iteration.q, iteration.Q, iteration.Q * e);
iteration.outputResult();
System.out.println("\n**************** Niutono metodas ****************");
NewtonMethod newton = new NewtonMethod();
Double x0 = to; // pradinė x reikšmė
System.out.printf("e = %f, x0 = %f\n", e, x0);
newton.solve(e, x0);
newton.outputResult();
}
**/
}
| MikeMwambia-TrojanSystem/Numerical-methods | src/skaitiniaimetodai/Uzd2.java |
180,009 | 404: Not Found | TomSabMGTfan/T_Sabaliauskas-Exercises | PD4/src/lt/techin/PD4_6.java |
180,010 | package lt.techin.exam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tasks {
/* Paduotus duomenis kilometrais ir metrais konvertuoja į metrus ir rezultatą išveda į ekraną
* pvz. kilometers = 4, meters = 67 =>
* Atspausdina:
* 4067 metrų
*/
public static void convertToMeters(int kilometers, int meters) {
System.out.println(kilometers * 1000 + meters + " metrų");
}
/*Kasininkė grąžą pirkėjui pabėrė centais ct. Reikia apskaičiuoti kiek tai yra eurų ir centų .
* pvz. 234 ct => atspausdina:
* Gauta: 2 Eur ir 34 ct
*/
public static void convertCentsToEuros(int cents) {
int eur = 0;
int ct = 0;
if (cents > 99) {
eur = cents / 100;
ct = cents % 100;
} else {
ct = cents;
}
System.out.println("Gauta: " + eur + " Eur ir " + ct + " ct");
}
/* Raskite skaičių a, b ir c vidurkį
*/
public static double averageOf(int a, int b, int c) {
return (a + b + c) / 3.0;
}
/* Duoti trys skaičiai. Parašykite metodą, kuris nustatytų, ar bent vienas iš jų yra lyginis.
Pvz.:
a = 1, b = 3, c = 5 => false
a = 1, b = 3, c = 6 => true
* */
public static boolean isEven(int a, int b, int c) {
return (a % 2 == 0 || b % 2 == 0 || c % 2 == 0);
}
/*
* Metodas parodo ar iš duotų trijų atkarpų (įvedami jų ilgiai) galima sudaryti trikampį.
*/
public static boolean isTriangleValid(int a, int b, int c) {
return (a + b > c && a + c > b && b + c > a);
}
/* Metodas spausdina nelyginius skaičius nuo pateikto skaičiaus 'number' iki 1
* pvz. number = 8 =>
* 7
* 5
* 3
* 1
* */
public static void printOddNumbers(int number) {
for (int i = number; i > 0; i--) {
if (i % 2 != 0) {
System.out.println(i);
}
}
}
/* Paskaičiuoti kiek masyve yra skaičių didesnių nei skaičius 'number'
* Pvz. array = {5, 2, 4, 1} number = 3 => 2
*/
public static int countLargerThanNumber(int[] array, int number) {
return (int) Arrays.stream(array).filter(x -> x > number).count();
}
/* Surasti mažiausią skaičių ArrayListe
* Pvz {6.7, 3.5, 8.2, 4.3} => 8.2
*/
public static double findSmallest(ArrayList<Double> numbers) {
return numbers.stream().min(Comparator.comparingDouble(Double::doubleValue)).get();
}
/*
* Paskaičiuokite kiek simbolių yra String'ų List'e
*/
public static int countLettersInList(List<String> words) {
int count = 0;
for (String word : words) {
count += word.length();
}
return count;
}
/* Paskaičiuoti kiek ArrayListe yra stringų, kuriuose yra žodis word
pvz: {"iphone 12", "IPHONE 12", "samsung s23"} word = "iphone" => 2
*/
public static int countStringsContainingWord(ArrayList<String> strings, String word) {
return (int) strings.stream().filter(x -> x.toLowerCase().contains(word)).count();
}
/*
* Paskaičiuokite kiek liste elementų, kur savybė displayed yra true
*/
public static int countDisplayedElements(List<Element> elements) {
return (int) elements.stream().filter(Element::isDisplayed).count();
}
/*
* Grąžinkite listą elementų kurių tekstas nėra tuščias arba sudarytas tik iš tarpų
*/
public static List<Element> findElementsWithNonEmptyTexts(List<Element> elements) {
return elements.stream().filter(x -> !x.getText().isBlank()).toList();
}
/*
* Elementų tekste užrašytos prekių kainos, pvz. "$10.52"
* Raskite didžiausią kainą
*/
public static double findSumOfPrices(List<Element> elements) {
return elements.stream().map(x -> x.getText().replaceAll("[^\\d.]", ""))
.mapToDouble(Double::parseDouble)
.sum();
}
}
| Pavelslc/Techin_JAVA | java-exam-part1-pavel-salc/src/main/java/lt/techin/exam/Tasks.java |
180,011 | package Darbas;
import javax.swing.JButton;
public class SkaicBud2 extends javax.swing.JFrame {
public SkaicBud2() {
initComponents();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
Result1 = new javax.swing.JLabel();
Result2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
Close = new javax.swing.JButton();
Result = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Įveskite pradinį dažnį:");
jLabel2.setText("Įveskite molio masę:");
jLabel3.setText("Įveskite kitą dažnį:");
jLabel4.setText("Įveskite aplinkos temperatūrą:");
jLabel5.setText("Įveskite ilgį:");
jLabel6.setText("Hz");
jLabel7.setText("Hz");
jLabel8.setText("K");
jLabel9.setText("m");
jLabel10.setText("kg/mol");
Result1.setText("Rezultatas gaunasi:");
Result2.setText(" ");
Close.setBackground(new java.awt.Color(0, 102, 102));
Close.setText("Uždaryti langą");
Close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CloseActionPerformed(evt);
}
});
Result.setBackground(new java.awt.Color(0, 102, 102));
Result.setText("Gauti skaičiavimo rezultatą");
Result.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
Result.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResultActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)))
.addContainerGap())
.addComponent(Result1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Close, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(130, 130, 130)))));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(10, 10, 10)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel5)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabel9))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(Result1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Close, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(17, Short.MAX_VALUE)));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)));
pack();
}
public void ResultActionPerformed(java.awt.event.ActionEvent evt) {
float a = Float.parseFloat(jTextField1.getText());
float b = Float.parseFloat(jTextField2.getText());
float c = Float.parseFloat(jTextField3.getText());
float d = Float.parseFloat(jTextField4.getText());
float e = Float.parseFloat(jTextField5.getText());
float f = (b/(e*d))*a*c;
Result2.setText(Float.toString(f));
}
private void CloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseActionPerformed
this.dispose();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}}}
catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SkaicBud2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SkaicBud2().setVisible(true);
}});
}
private javax.swing.JButton Close;
private javax.swing.JButton Result;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel Result1;
private javax.swing.JLabel Result2;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
}
| rutaladygaite/Java-implementation-with-Physics-calculation- | src/Darbas/SkaicBud2.java |
180,012 | /*
* Main.java
* @author R.Vaicekauskas
* Pirmosios užduoties sprendimo java šablonas
*/
// Irašyti reikiamą paketo vardą
//package pirmoji;
/**
* Dirbant NetBeans aplinkoje klasė "Main" sugeneruojama automatiškai
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Programa pradeda darba");
TestThread.pradeti();
System.out.println("Programa baigia darba.");
}
}
/*
Naujai sukurta klase.
Gijos klasė, turi būti išvesta iš Thread
*/
class TestThread extends Thread
{
// Gijos objekto specifiniai duomenys
BendroNaudojimoObjektas bendras;
// Konstruktorius, skirtas perduoti duomenis gijos objektui
public TestThread(BendroNaudojimoObjektas bendras)
{
this.bendras = bendras;
}
// Metodas, vykdomas paleidus giją
// Thread.run()
public void run()
{
System.out.println("Gija " + this + " paleista");
// Ciklas (didesnis iteracijų skaičius padidina duomenų skaitymo
// atnaujinimo konflikto galimybę
for (int i = 0; i < 100; i++)
{
// Sinchronizuoto bloko pradžia
// Bloko viduje galima saugiai skaityti/modifikuoti
// Objekto bendras laukus
// *** Užkomentavus turėtų atsirasti duomenų atnaujinimo konfliktai ***
synchronized(bendras)
{
// Kontrolinis spausdinimas, kad įsitikinti vienalaikiu gijų veikimu
System.out.println("Gija " + this + " pries atnaujinant bendra kintamaji");
// Kviečiame metodą, kuris modifikuoja objekto lauko reikšmę
// *** Konkrečiam taikymui metodo kvietinys/iai turi būti pakeistas/i***
bendras.padidinti();
// Kontrolinis spausdinimas, kad įsitikinti vienalaikiu gijų veikimu
System.out.println("Gija " + this + " atnaujino bendra kintamaji");
}
}
System.out.println("Gija " + this + " baigia darbą");
}
// Metodas paleidžiantis gijas darbui ir išvedantis rezultatą
public static void pradeti()
{
// Sukuriame objektą, kurį bendrai naudos kelios gijos
BendroNaudojimoObjektas bendras = new BendroNaudojimoObjektas();
bendras.n = 0; // Pradinė reikšmė
try
{
// Sukuriame ir startuojame pirmąją giją
// perduodami kaip parametrą objektą "bendras"
Thread t1 = new TestThread(bendras);
t1.start();
// Sukuriame ir startuojame pirmąją giją
Thread t2 = new TestThread(bendras);
t2.start();
// Laukiame, kol abi gijos baigs darbą
t1.join(); t2.join();
// Išvedame galutinį rezultatą
System.out.println("Rezultatas n = " + bendras.n + ". Turi buti 10");
}
catch (InterruptedException exc)
{
System.out.println("Ivyko klaida "+exc);
}
}
}
/*
Klasė, aprašanti bendrai gijų naudojamą objektą
*** Konkrečiam taikymui turi būti pakeistas***
*/
class BendroNaudojimoObjektas
{
// Laukas, kurį skaitys modifikuos kelios gijos
int n;
// Metodas modifikuojantis objekto turinį
public void padidinti()
{
int nn = n; // Nuskaityti
nn++; // Apskaiciuoti
n = nn; // Isiminti objekto lauke
System.out.println(n);
}
} | Dizgog/UNI_CODE | 3_kursas/Lygiagretieji skaičiavimai/1_lab/Main.java |
180,014 | package Darbas;
import javax.swing.JButton;
public class SkaicBud3 extends javax.swing.JFrame {
public SkaicBud3() {
initComponents();
}
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
jTextField6 = new javax.swing.JTextField();
jTextField7 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
Result = new javax.swing.JButton();
Close = new javax.swing.JButton();
Result1 = new javax.swing.JLabel();
Result2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Įveskite molio masę:");
jLabel2.setText("Įveskite aplinkos temperatūrą:");
jLabel3.setText("Įveskite pradinį atstumą:");
jLabel4.setText("Įveskite kitą atstumą:");
jLabel5.setText("Įveskite susitiprėjimų skaičių:");
jLabel6.setText("Įveskite generatoriaus įtampos dažnį:");
jLabel7.setText("kg/mol");
jLabel8.setText("K");
jLabel9.setText("m");
jLabel10.setText("m");
jLabel11.setText("vnt");
jLabel12.setText("Hz");
Result1.setText("Rezultatas gaunasi:");
Result2.setText(" ");
Result.setBackground(new java.awt.Color(0, 102, 102));
Result.setText("Gauti skaičiavimo rezultatą");
Result.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
Result.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ResultActionPerformed(evt);
}});
Close.setBackground(new java.awt.Color(0, 102, 102));
Close.setText("Uždaryti langą");
Close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CloseActionPerformed(evt);
}});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel9))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel10))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel8))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 360, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel12))
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Result1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap())
.addComponent(Result1, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Result, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Close, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(130, 130, 130)));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(10, 10, 10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(5, 5, 5)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addGap(4, 4, 4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addGap(4, 4, 4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11))
.addGap(4, 4, 4)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12))
.addComponent(Result1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Result, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Close, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap()));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
pack();
}
private void ResultActionPerformed(java.awt.event.ActionEvent evt) {
float molmas = Float.parseFloat(jTextField1.getText());
float T = Float.parseFloat(jTextField2.getText());
float x1 = Float.parseFloat(jTextField3.getText());
float x2 = Float.parseFloat(jTextField4.getText());
float n = Float.parseFloat(jTextField5.getText());
float f = Float.parseFloat(jTextField6.getText());
double x = Math.pow(x2-x1,2);
double result = (4*f*(x*molmas)/(n*T));
Result2.setText(Double.toString(result));
}
private void CloseActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}}}
catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SkaicBud3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SkaicBud3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SkaicBud3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SkaicBud3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SkaicBud3().setVisible(true);
}});
}
private javax.swing.JButton Close;
private javax.swing.JButton Result;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel Result1;
private javax.swing.JLabel Result2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField jTextField7;
}
| rutaladygaite/Java-implementation-with-Physics-calculation- | src/Darbas/SkaicBud3.java |
180,015 | 404: Not Found | TomSabMGTfan/T_Sabaliauskas-Exercises | PD4/src/lt/techin/PD4_12.java |
180,016 | package lt.techin.exam;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
public class Tasks {
/* Paduotus duomenis kilometrais ir metrais konvertuoja į metrus ir rezultatą išveda į ekraną
* pvz. kilometers = 4, meters = 67 =>
* Atspausdina:
* 4067 metrų
*/
public static void convertToMeters(int kilometers, int meters) {
System.out.println(kilometers * 1000 + meters + " metrų");
}
/*Kasininkė grąžą pirkėjui pabėrė centais ct. Reikia apskaičiuoti kiek tai yra eurų ir centų .
* pvz. 234 ct => atspausdina:
* Gauta: 2 Eur ir 34 ct
*/
public static void convertCentsToEuros(int cents) {
System.out.println("Gauta: " + cents / 100 + " Eur ir " + cents % 100 + " ct");
}
/* Raskite skaičių a, b ir c vidurkį
*/
public static double averageOf(int a, int b, int c) {
return (1.0 * (a + b + c) / 3);
//throw new UnsupportedOperationException("Parašykite implementaciją");
}
/* Duoti trys skaičiai. Parašykite metodą, kuris nustatytų, ar bent vienas iš jų yra lyginis.
Pvz.:
a = 1, b = 3, c = 5 => false
a = 1, b = 3, c = 6 => true
* */
public static boolean isEven(int a, int b, int c) {
if (a % 2 == 0 || b % 2 == 0 || c % 2 == 0) return true;
return false;
//throw new UnsupportedOperationException("Parašykite implementaciją");
}
/*
* Metodas parodo ar iš duotų trijų atkarpų (įvedami jų ilgiai) galima sudaryti trikampį.
*/
public static boolean isTriangleValid(int a, int b, int c) {
if (a + b > c && b + c > a && a + c > b) return true;
return false;
}
/* Metodas spausdina nelyginius skaičius nuo pateikto skaičiaus 'number' iki 1
* pvz. number = 8 =>
* 7
* 5
* 3
* 1
* */
public static void printOddNumbers(int number) {
for (int i = number; i >= 1; i--) {
if (i % 2 != 0) System.out.println(i);
}
}
/* Paskaičiuoti kiek masyve yra skaičių didesnių nei skaičius 'number'
* Pvz. array = {5, 2, 4, 1} number = 3 => 2
*/
public static int countLargerThanNumber(int[] array, int number) {
int count = 0;
for (int num : array) {
if (num > number) count++;
}
return count;
}
/* Surasti mažiausią skaičių ArrayListe
* Pvz {6.7, 3.5, 8.2, 4.3} => 8.2
*/
public static double findSmallest(ArrayList<Double> numbers) {
double min = numbers.getFirst();
for (Double number : numbers) {
if (number < min) min = number;
}
return min;
}
/*
* Paskaičiuokite kiek simbolių yra String'ų List'e
*/
public static int countLettersInList(List<String> words) {
int counter = 0;
for (String word : words) {
counter += word.length();
}
return counter;
}
/* Paskaičiuoti kiek ArrayListe yra stringų, kuriuose yra žodis word
pvz: {"iphone 12", "IPHONE 12", "samsung s23"} word = "iphone" => 2
*/
public static int countStringsContainingWord(ArrayList<String> strings, String word) {
int counter = 0;
for (String string : strings) {
if (string.toLowerCase().contains(word.toLowerCase())) {
counter++;
}
}
return counter;
//return strings.stream().filter(Cont)
}
/*
* Paskaičiuokite kiek liste elementų, kur savybė displayed yra true
*/
public static int countDisplayedElements(List<Element> elements) {
int count = 0;
for (Element element : elements) {
if (element.isDisplayed()) {
count++;
}
}
return count;
}
/*
* Grąžinkite listą elementų kurių tekstas nėra tuščias arba sudarytas tik iš tarpų
*/
public static List<Element> findElementsWithNonEmptyTexts(List<Element> elements) {
List<Element> myElements = new ArrayList<>();
for (Element element : elements) {
if (element != null && !element.getText().trim().isEmpty()) {
myElements.add(element);
}
}
return myElements;
}
/*
* Elementų tekste užrašytos prekių kainos, pvz. "$10.52"
* Raskite suma
*/
public static double findSumOfPrices(List<Element> elements) {
return elements.stream().map(e->e.getText().split("\\$")).mapToDouble(e-> Double.parseDouble(e[1])).sum();
}
}
| TechinDarius/JAVA_techin | java-exam-part1/src/main/java/lt/techin/exam/Tasks.java |
180,018 | 404: Not Found | TomSabMGTfan/T_Sabaliauskas-Exercises | PD3/src/lt/techin/PD3_8.java |