file_id
int64 1
215k
| content
stringlengths 7
454k
| repo
stringlengths 6
113
| path
stringlengths 6
251
|
---|---|---|---|
101 | //You're given strings J representing the types of stones that are jewels, and S representing the stones you have.
//Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
//The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive,
//so "a" is considered a different type of stone from "A".
class JewelsAndStones {
public int numJewelsInStones(String J, String S) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(char c: J.toCharArray()) {
map.put(c, 1);
}
int numberOfJewels = 0;
for(char c: S.toCharArray()) {
if(map.containsKey(c)) {
numberOfJewels++;
}
}
return numberOfJewels;
}
}
| kdn251/interviews | leetcode/hash-table/JewelsAndStones.java |
102 |
class Solution {
public int numJewelsInStones(String J, String S) {
Set<Character> Jset = new HashSet();
for (char j: J.toCharArray())
Jset.add(j);
int ans = 0;
for (char s: S.toCharArray())
if (Jset.contains(s))
ans++;
return ans;
}
} | MisterBooo/LeetCodeAnimation | 0771-Jewels-Stones/Code/1.java |
103 | /*
* Copyright (C) 2014 The Guava 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.
*/
package com.google.common.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import javax.annotation.CheckForNull;
/**
* Helper functions that operate on any {@code Object}, and are not already provided in {@link
* java.util.Objects}.
*
* <p>See the Guava User Guide on <a
* href="https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained">writing {@code Object}
* methods with {@code MoreObjects}</a>.
*
* @author Laurence Gonsalves
* @since 18.0 (since 2.0 as {@code Objects})
*/
@GwtCompatible
@ElementTypesAreNonnullByDefault
public final class MoreObjects {
/**
* Returns the first of two given parameters that is not {@code null}, if either is, or otherwise
* throws a {@link NullPointerException}.
*
* <p>To find the first non-null element in an iterable, use {@code Iterables.find(iterable,
* Predicates.notNull())}. For varargs, use {@code Iterables.find(Arrays.asList(a, b, c, ...),
* Predicates.notNull())}, static importing as necessary.
*
* <p><b>Note:</b> if {@code first} is represented as an {@link Optional}, this can be
* accomplished with {@link Optional#or(Object) first.or(second)}. That approach also allows for
* lazy evaluation of the fallback instance, using {@link Optional#or(Supplier)
* first.or(supplier)}.
*
* <p><b>Java 9 users:</b> use {@code java.util.Objects.requireNonNullElse(first, second)}
* instead.
*
* @return {@code first} if it is non-null; otherwise {@code second} if it is non-null
* @throws NullPointerException if both {@code first} and {@code second} are null
* @since 18.0 (since 3.0 as {@code Objects.firstNonNull()}).
*/
public static <T> T firstNonNull(@CheckForNull T first, @CheckForNull T second) {
if (first != null) {
return first;
}
if (second != null) {
return second;
}
throw new NullPointerException("Both parameters are null");
}
/**
* Creates an instance of {@link ToStringHelper}.
*
* <p>This is helpful for implementing {@link Object#toString()}. Specification by example:
*
* <pre>{@code
* // Returns "ClassName{}"
* MoreObjects.toStringHelper(this)
* .toString();
*
* // Returns "ClassName{x=1}"
* MoreObjects.toStringHelper(this)
* .add("x", 1)
* .toString();
*
* // Returns "MyObject{x=1}"
* MoreObjects.toStringHelper("MyObject")
* .add("x", 1)
* .toString();
*
* // Returns "ClassName{x=1, y=foo}"
* MoreObjects.toStringHelper(this)
* .add("x", 1)
* .add("y", "foo")
* .toString();
*
* // Returns "ClassName{x=1}"
* MoreObjects.toStringHelper(this)
* .omitNullValues()
* .add("x", 1)
* .add("y", null)
* .toString();
* }</pre>
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param self the object to generate the string for (typically {@code this}), used only for its
* class name
* @since 18.0 (since 2.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(Object self) {
return new ToStringHelper(self.getClass().getSimpleName());
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as {@link
* #toStringHelper(Object)}, but using the simple name of {@code clazz} instead of using an
* instance's {@link Object#getClass()}.
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param clazz the {@link Class} of the instance
* @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(Class<?> clazz) {
return new ToStringHelper(clazz.getSimpleName());
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as {@link
* #toStringHelper(Object)}, but using {@code className} instead of using an instance's {@link
* Object#getClass()}.
*
* @param className the name of the instance type
* @since 18.0 (since 7.0 as {@code Objects.toStringHelper()}).
*/
public static ToStringHelper toStringHelper(String className) {
return new ToStringHelper(className);
}
/**
* Support class for {@link MoreObjects#toStringHelper}.
*
* @author Jason Lee
* @since 18.0 (since 2.0 as {@code Objects.ToStringHelper}).
*/
public static final class ToStringHelper {
private final String className;
private final ValueHolder holderHead = new ValueHolder();
private ValueHolder holderTail = holderHead;
private boolean omitNullValues = false;
private boolean omitEmptyValues = false;
/** Use {@link MoreObjects#toStringHelper(Object)} to create an instance. */
private ToStringHelper(String className) {
this.className = checkNotNull(className);
}
/**
* Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null
* value. The order of calling this method, relative to the {@code add()}/{@code addValue()}
* methods, is not significant.
*
* @since 18.0 (since 12.0 as {@code Objects.ToStringHelper.omitNullValues()}).
*/
@CanIgnoreReturnValue
public ToStringHelper omitNullValues() {
omitNullValues = true;
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format. If {@code value}
* is {@code null}, the string {@code "null"} is used, unless {@link #omitNullValues()} is
* called, in which case this name/value pair will not be added.
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, @CheckForNull Object value) {
return addHolder(name, value);
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, boolean value) {
return addUnconditionalHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, char value) {
return addUnconditionalHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, double value) {
return addUnconditionalHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, float value) {
return addUnconditionalHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, int value) {
return addUnconditionalHolder(name, String.valueOf(value));
}
/**
* Adds a name/value pair to the formatted output in {@code name=value} format.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.add()}).
*/
@CanIgnoreReturnValue
public ToStringHelper add(String name, long value) {
return addUnconditionalHolder(name, String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, Object)} instead and give value a
* readable name.
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(@CheckForNull Object value) {
return addHolder(value);
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, boolean)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(boolean value) {
return addUnconditionalHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, char)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(char value) {
return addUnconditionalHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, double)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(double value) {
return addUnconditionalHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, float)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(float value) {
return addUnconditionalHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, int)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(int value) {
return addUnconditionalHolder(String.valueOf(value));
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, long)} instead and give value a
* readable name.
*
* @since 18.0 (since 11.0 as {@code Objects.ToStringHelper.addValue()}).
*/
@CanIgnoreReturnValue
public ToStringHelper addValue(long value) {
return addUnconditionalHolder(String.valueOf(value));
}
private static boolean isEmpty(Object value) {
// Put types estimated to be the most frequent first.
if (value instanceof CharSequence) {
return ((CharSequence) value).length() == 0;
} else if (value instanceof Collection) {
return ((Collection<?>) value).isEmpty();
} else if (value instanceof Map) {
return ((Map<?, ?>) value).isEmpty();
} else if (value instanceof java.util.Optional) {
return !((java.util.Optional<?>) value).isPresent();
} else if (value instanceof OptionalInt) {
return !((OptionalInt) value).isPresent();
} else if (value instanceof OptionalLong) {
return !((OptionalLong) value).isPresent();
} else if (value instanceof OptionalDouble) {
return !((OptionalDouble) value).isPresent();
} else if (value instanceof Optional) {
return !((Optional) value).isPresent();
} else if (value.getClass().isArray()) {
return Array.getLength(value) == 0;
}
return false;
}
/**
* Returns a string in the format specified by {@link MoreObjects#toStringHelper(Object)}.
*
* <p>After calling this method, you can keep adding more properties to later call toString()
* again and get a more complete representation of the same object; but properties cannot be
* removed, so this only allows limited reuse of the helper instance. The helper allows
* duplication of properties (multiple name/value pairs with the same name can be added).
*/
@Override
public String toString() {
// create a copy to keep it consistent in case value changes
boolean omitNullValuesSnapshot = omitNullValues;
boolean omitEmptyValuesSnapshot = omitEmptyValues;
String nextSeparator = "";
StringBuilder builder = new StringBuilder(32).append(className).append('{');
for (ValueHolder valueHolder = holderHead.next;
valueHolder != null;
valueHolder = valueHolder.next) {
Object value = valueHolder.value;
if (valueHolder instanceof UnconditionalValueHolder
|| (value == null
? !omitNullValuesSnapshot
: (!omitEmptyValuesSnapshot || !isEmpty(value)))) {
builder.append(nextSeparator);
nextSeparator = ", ";
if (valueHolder.name != null) {
builder.append(valueHolder.name).append('=');
}
if (value != null && value.getClass().isArray()) {
Object[] objectArray = {value};
String arrayString = Arrays.deepToString(objectArray);
builder.append(arrayString, 1, arrayString.length() - 1);
} else {
builder.append(value);
}
}
}
return builder.append('}').toString();
}
private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
}
@CanIgnoreReturnValue
private ToStringHelper addHolder(@CheckForNull Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
return this;
}
@CanIgnoreReturnValue
private ToStringHelper addHolder(String name, @CheckForNull Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.value = value;
valueHolder.name = checkNotNull(name);
return this;
}
private UnconditionalValueHolder addUnconditionalHolder() {
UnconditionalValueHolder valueHolder = new UnconditionalValueHolder();
holderTail = holderTail.next = valueHolder;
return valueHolder;
}
@CanIgnoreReturnValue
private ToStringHelper addUnconditionalHolder(Object value) {
UnconditionalValueHolder valueHolder = addUnconditionalHolder();
valueHolder.value = value;
return this;
}
@CanIgnoreReturnValue
private ToStringHelper addUnconditionalHolder(String name, Object value) {
UnconditionalValueHolder valueHolder = addUnconditionalHolder();
valueHolder.value = value;
valueHolder.name = checkNotNull(name);
return this;
}
// Holder object for values that might be null and/or empty.
static class ValueHolder {
@CheckForNull String name;
@CheckForNull Object value;
@CheckForNull ValueHolder next;
}
/**
* Holder object for values that cannot be null or empty (will be printed unconditionally). This
* helps to shortcut most calls to isEmpty(), which is important because the check for emptiness
* is relatively expensive. Use a subtype so this also doesn't need any extra storage.
*/
private static final class UnconditionalValueHolder extends ValueHolder {}
}
private MoreObjects() {}
}
| google/guava | guava/src/com/google/common/base/MoreObjects.java |
104 | package com.genymobile.scrcpy;
import com.genymobile.scrcpy.wrappers.ClipboardManager;
import com.genymobile.scrcpy.wrappers.DisplayControl;
import com.genymobile.scrcpy.wrappers.InputManager;
import com.genymobile.scrcpy.wrappers.ServiceManager;
import com.genymobile.scrcpy.wrappers.SurfaceControl;
import com.genymobile.scrcpy.wrappers.WindowManager;
import android.content.IOnPrimaryClipChangedListener;
import android.graphics.Rect;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.view.IDisplayFoldListener;
import android.view.IRotationWatcher;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import java.util.concurrent.atomic.AtomicBoolean;
public final class Device {
public static final int POWER_MODE_OFF = SurfaceControl.POWER_MODE_OFF;
public static final int POWER_MODE_NORMAL = SurfaceControl.POWER_MODE_NORMAL;
public static final int INJECT_MODE_ASYNC = InputManager.INJECT_INPUT_EVENT_MODE_ASYNC;
public static final int INJECT_MODE_WAIT_FOR_RESULT = InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT;
public static final int INJECT_MODE_WAIT_FOR_FINISH = InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH;
public static final int LOCK_VIDEO_ORIENTATION_UNLOCKED = -1;
public static final int LOCK_VIDEO_ORIENTATION_INITIAL = -2;
public interface RotationListener {
void onRotationChanged(int rotation);
}
public interface FoldListener {
void onFoldChanged(int displayId, boolean folded);
}
public interface ClipboardListener {
void onClipboardTextChanged(String text);
}
private final Rect crop;
private int maxSize;
private final int lockVideoOrientation;
private Size deviceSize;
private ScreenInfo screenInfo;
private RotationListener rotationListener;
private FoldListener foldListener;
private ClipboardListener clipboardListener;
private final AtomicBoolean isSettingClipboard = new AtomicBoolean();
/**
* Logical display identifier
*/
private final int displayId;
/**
* The surface flinger layer stack associated with this logical display
*/
private final int layerStack;
private final boolean supportsInputEvents;
public Device(Options options) throws ConfigurationException {
displayId = options.getDisplayId();
DisplayInfo displayInfo = ServiceManager.getDisplayManager().getDisplayInfo(displayId);
if (displayInfo == null) {
Ln.e("Display " + displayId + " not found\n" + LogUtils.buildDisplayListMessage());
throw new ConfigurationException("Unknown display id: " + displayId);
}
int displayInfoFlags = displayInfo.getFlags();
deviceSize = displayInfo.getSize();
crop = options.getCrop();
maxSize = options.getMaxSize();
lockVideoOrientation = options.getLockVideoOrientation();
screenInfo = ScreenInfo.computeScreenInfo(displayInfo.getRotation(), deviceSize, crop, maxSize, lockVideoOrientation);
layerStack = displayInfo.getLayerStack();
ServiceManager.getWindowManager().registerRotationWatcher(new IRotationWatcher.Stub() {
@Override
public void onRotationChanged(int rotation) {
synchronized (Device.this) {
screenInfo = screenInfo.withDeviceRotation(rotation);
// notify
if (rotationListener != null) {
rotationListener.onRotationChanged(rotation);
}
}
}
}, displayId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceManager.getWindowManager().registerDisplayFoldListener(new IDisplayFoldListener.Stub() {
@Override
public void onDisplayFoldChanged(int displayId, boolean folded) {
if (Device.this.displayId != displayId) {
// Ignore events related to other display ids
return;
}
synchronized (Device.this) {
DisplayInfo displayInfo = ServiceManager.getDisplayManager().getDisplayInfo(displayId);
if (displayInfo == null) {
Ln.e("Display " + displayId + " not found\n" + LogUtils.buildDisplayListMessage());
return;
}
deviceSize = displayInfo.getSize();
screenInfo = ScreenInfo.computeScreenInfo(displayInfo.getRotation(), deviceSize, crop, maxSize, lockVideoOrientation);
// notify
if (foldListener != null) {
foldListener.onFoldChanged(displayId, folded);
}
}
}
});
}
if (options.getControl() && options.getClipboardAutosync()) {
// If control and autosync are enabled, synchronize Android clipboard to the computer automatically
ClipboardManager clipboardManager = ServiceManager.getClipboardManager();
if (clipboardManager != null) {
clipboardManager.addPrimaryClipChangedListener(new IOnPrimaryClipChangedListener.Stub() {
@Override
public void dispatchPrimaryClipChanged() {
if (isSettingClipboard.get()) {
// This is a notification for the change we are currently applying, ignore it
return;
}
synchronized (Device.this) {
if (clipboardListener != null) {
String text = getClipboardText();
if (text != null) {
clipboardListener.onClipboardTextChanged(text);
}
}
}
}
});
} else {
Ln.w("No clipboard manager, copy-paste between device and computer will not work");
}
}
if ((displayInfoFlags & DisplayInfo.FLAG_SUPPORTS_PROTECTED_BUFFERS) == 0) {
Ln.w("Display doesn't have FLAG_SUPPORTS_PROTECTED_BUFFERS flag, mirroring can be restricted");
}
// main display or any display on Android >= Q
supportsInputEvents = displayId == 0 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
if (!supportsInputEvents) {
Ln.w("Input events are not supported for secondary displays before Android 10");
}
}
public int getDisplayId() {
return displayId;
}
public synchronized void setMaxSize(int newMaxSize) {
maxSize = newMaxSize;
screenInfo = ScreenInfo.computeScreenInfo(screenInfo.getReverseVideoRotation(), deviceSize, crop, newMaxSize, lockVideoOrientation);
}
public synchronized ScreenInfo getScreenInfo() {
return screenInfo;
}
public int getLayerStack() {
return layerStack;
}
public Point getPhysicalPoint(Position position) {
// it hides the field on purpose, to read it with a lock
@SuppressWarnings("checkstyle:HiddenField")
ScreenInfo screenInfo = getScreenInfo(); // read with synchronization
// ignore the locked video orientation, the events will apply in coordinates considered in the physical device orientation
Size unlockedVideoSize = screenInfo.getUnlockedVideoSize();
int reverseVideoRotation = screenInfo.getReverseVideoRotation();
// reverse the video rotation to apply the events
Position devicePosition = position.rotate(reverseVideoRotation);
Size clientVideoSize = devicePosition.getScreenSize();
if (!unlockedVideoSize.equals(clientVideoSize)) {
// The client sends a click relative to a video with wrong dimensions,
// the device may have been rotated since the event was generated, so ignore the event
return null;
}
Rect contentRect = screenInfo.getContentRect();
Point point = devicePosition.getPoint();
int convertedX = contentRect.left + point.getX() * contentRect.width() / unlockedVideoSize.getWidth();
int convertedY = contentRect.top + point.getY() * contentRect.height() / unlockedVideoSize.getHeight();
return new Point(convertedX, convertedY);
}
public static String getDeviceName() {
return Build.MODEL;
}
public static boolean supportsInputEvents(int displayId) {
return displayId == 0 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
}
public boolean supportsInputEvents() {
return supportsInputEvents;
}
public static boolean injectEvent(InputEvent inputEvent, int displayId, int injectMode) {
if (!supportsInputEvents(displayId)) {
throw new AssertionError("Could not inject input event if !supportsInputEvents()");
}
if (displayId != 0 && !InputManager.setDisplayId(inputEvent, displayId)) {
return false;
}
return ServiceManager.getInputManager().injectInputEvent(inputEvent, injectMode);
}
public boolean injectEvent(InputEvent event, int injectMode) {
return injectEvent(event, displayId, injectMode);
}
public static boolean injectKeyEvent(int action, int keyCode, int repeat, int metaState, int displayId, int injectMode) {
long now = SystemClock.uptimeMillis();
KeyEvent event = new KeyEvent(now, now, action, keyCode, repeat, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD);
return injectEvent(event, displayId, injectMode);
}
public boolean injectKeyEvent(int action, int keyCode, int repeat, int metaState, int injectMode) {
return injectKeyEvent(action, keyCode, repeat, metaState, displayId, injectMode);
}
public static boolean pressReleaseKeycode(int keyCode, int displayId, int injectMode) {
return injectKeyEvent(KeyEvent.ACTION_DOWN, keyCode, 0, 0, displayId, injectMode)
&& injectKeyEvent(KeyEvent.ACTION_UP, keyCode, 0, 0, displayId, injectMode);
}
public boolean pressReleaseKeycode(int keyCode, int injectMode) {
return pressReleaseKeycode(keyCode, displayId, injectMode);
}
public static boolean isScreenOn() {
return ServiceManager.getPowerManager().isScreenOn();
}
public synchronized void setRotationListener(RotationListener rotationListener) {
this.rotationListener = rotationListener;
}
public synchronized void setFoldListener(FoldListener foldlistener) {
this.foldListener = foldlistener;
}
public synchronized void setClipboardListener(ClipboardListener clipboardListener) {
this.clipboardListener = clipboardListener;
}
public static void expandNotificationPanel() {
ServiceManager.getStatusBarManager().expandNotificationsPanel();
}
public static void expandSettingsPanel() {
ServiceManager.getStatusBarManager().expandSettingsPanel();
}
public static void collapsePanels() {
ServiceManager.getStatusBarManager().collapsePanels();
}
public static String getClipboardText() {
ClipboardManager clipboardManager = ServiceManager.getClipboardManager();
if (clipboardManager == null) {
return null;
}
CharSequence s = clipboardManager.getText();
if (s == null) {
return null;
}
return s.toString();
}
public boolean setClipboardText(String text) {
ClipboardManager clipboardManager = ServiceManager.getClipboardManager();
if (clipboardManager == null) {
return false;
}
String currentClipboard = getClipboardText();
if (currentClipboard != null && currentClipboard.equals(text)) {
// The clipboard already contains the requested text.
// Since pasting text from the computer involves setting the device clipboard, it could be set twice on a copy-paste. This would cause
// the clipboard listeners to be notified twice, and that would flood the Android keyboard clipboard history. To workaround this
// problem, do not explicitly set the clipboard text if it already contains the expected content.
return false;
}
isSettingClipboard.set(true);
boolean ok = clipboardManager.setText(text);
isSettingClipboard.set(false);
return ok;
}
/**
* @param mode one of the {@code POWER_MODE_*} constants
*/
public static boolean setScreenPowerMode(int mode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// On Android 14, these internal methods have been moved to DisplayControl
boolean useDisplayControl =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !SurfaceControl.hasPhysicalDisplayIdsMethod();
// Change the power mode for all physical displays
long[] physicalDisplayIds = useDisplayControl ? DisplayControl.getPhysicalDisplayIds() : SurfaceControl.getPhysicalDisplayIds();
if (physicalDisplayIds == null) {
Ln.e("Could not get physical display ids");
return false;
}
boolean allOk = true;
for (long physicalDisplayId : physicalDisplayIds) {
IBinder binder = useDisplayControl ? DisplayControl.getPhysicalDisplayToken(
physicalDisplayId) : SurfaceControl.getPhysicalDisplayToken(physicalDisplayId);
allOk &= SurfaceControl.setDisplayPowerMode(binder, mode);
}
return allOk;
}
// Older Android versions, only 1 display
IBinder d = SurfaceControl.getBuiltInDisplay();
if (d == null) {
Ln.e("Could not get built-in display");
return false;
}
return SurfaceControl.setDisplayPowerMode(d, mode);
}
public static boolean powerOffScreen(int displayId) {
if (!isScreenOn()) {
return true;
}
return pressReleaseKeycode(KeyEvent.KEYCODE_POWER, displayId, Device.INJECT_MODE_ASYNC);
}
/**
* Disable auto-rotation (if enabled), set the screen rotation and re-enable auto-rotation (if it was enabled).
*/
public void rotateDevice() {
WindowManager wm = ServiceManager.getWindowManager();
boolean accelerometerRotation = !wm.isRotationFrozen(displayId);
int currentRotation = getCurrentRotation(displayId);
int newRotation = (currentRotation & 1) ^ 1; // 0->1, 1->0, 2->1, 3->0
String newRotationString = newRotation == 0 ? "portrait" : "landscape";
Ln.i("Device rotation requested: " + newRotationString);
wm.freezeRotation(displayId, newRotation);
// restore auto-rotate if necessary
if (accelerometerRotation) {
wm.thawRotation(displayId);
}
}
private static int getCurrentRotation(int displayId) {
if (displayId == 0) {
return ServiceManager.getWindowManager().getRotation();
}
DisplayInfo displayInfo = ServiceManager.getDisplayManager().getDisplayInfo(displayId);
return displayInfo.getRotation();
}
}
| Genymobile/scrcpy | server/src/main/java/com/genymobile/scrcpy/Device.java |
105 | /*
* Copyright 2002-2023 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.util;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.TimeZone;
import org.springframework.lang.Contract;
import org.springframework.lang.Nullable;
/**
* Miscellaneous object utility methods.
*
* <p>Mainly for internal use within the framework.
*
* <p>Thanks to Alex Ruiz for contributing several enhancements to this class!
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Chris Beams
* @author Sam Brannen
* @since 19.03.2004
* @see ClassUtils
* @see CollectionUtils
* @see StringUtils
*/
public abstract class ObjectUtils {
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
private static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
private static final String NON_EMPTY_ARRAY = ARRAY_START + "..." + ARRAY_END;
private static final String COLLECTION = "[...]";
private static final String MAP = NON_EMPTY_ARRAY;
/**
* Return whether the given throwable is a checked exception:
* that is, neither a RuntimeException nor an Error.
* @param ex the throwable to check
* @return whether the throwable is a checked exception
* @see java.lang.Exception
* @see java.lang.RuntimeException
* @see java.lang.Error
*/
public static boolean isCheckedException(Throwable ex) {
return !(ex instanceof RuntimeException || ex instanceof Error);
}
/**
* Check whether the given exception is compatible with the specified
* exception types, as declared in a {@code throws} clause.
* @param ex the exception to check
* @param declaredExceptions the exception types declared in the throws clause
* @return whether the given exception is compatible
*/
public static boolean isCompatibleWithThrowsClause(Throwable ex, @Nullable Class<?>... declaredExceptions) {
if (!isCheckedException(ex)) {
return true;
}
if (declaredExceptions != null) {
for (Class<?> declaredException : declaredExceptions) {
if (declaredException.isInstance(ex)) {
return true;
}
}
}
return false;
}
/**
* Determine whether the given object is an array:
* either an Object array or a primitive array.
* @param obj the object to check
*/
@Contract("null -> false")
public static boolean isArray(@Nullable Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* Determine whether the given array is empty:
* i.e. {@code null} or of zero length.
* @param array the array to check
* @see #isEmpty(Object)
*/
@Contract("null -> true")
public static boolean isEmpty(@Nullable Object[] array) {
return (array == null || array.length == 0);
}
/**
* Determine whether the given object is empty.
* <p>This method supports the following object types.
* <ul>
* <li>{@code Optional}: considered empty if not {@link Optional#isPresent()}</li>
* <li>{@code Array}: considered empty if its length is zero</li>
* <li>{@link CharSequence}: considered empty if its length is zero</li>
* <li>{@link Collection}: delegates to {@link Collection#isEmpty()}</li>
* <li>{@link Map}: delegates to {@link Map#isEmpty()}</li>
* </ul>
* <p>If the given object is non-null and not one of the aforementioned
* supported types, this method returns {@code false}.
* @param obj the object to check
* @return {@code true} if the object is {@code null} or <em>empty</em>
* @since 4.2
* @see Optional#isPresent()
* @see ObjectUtils#isEmpty(Object[])
* @see StringUtils#hasLength(CharSequence)
* @see CollectionUtils#isEmpty(java.util.Collection)
* @see CollectionUtils#isEmpty(java.util.Map)
*/
public static boolean isEmpty(@Nullable Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof Optional<?> optional) {
return optional.isEmpty();
}
if (obj instanceof CharSequence charSequence) {
return charSequence.isEmpty();
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof Collection<?> collection) {
return collection.isEmpty();
}
if (obj instanceof Map<?, ?> map) {
return map.isEmpty();
}
// else
return false;
}
/**
* Unwrap the given object which is potentially a {@link java.util.Optional}.
* @param obj the candidate object
* @return either the value held within the {@code Optional}, {@code null}
* if the {@code Optional} is empty, or simply the given object as-is
* @since 5.0
*/
@Nullable
public static Object unwrapOptional(@Nullable Object obj) {
if (obj instanceof Optional<?> optional) {
if (optional.isEmpty()) {
return null;
}
Object result = optional.get();
Assert.isTrue(!(result instanceof Optional), "Multi-level Optional usage not supported");
return result;
}
return obj;
}
/**
* Check whether the given array contains the given element.
* @param array the array to check (may be {@code null},
* in which case the return value will always be {@code false})
* @param element the element to check for
* @return whether the element has been found in the given array
*/
public static boolean containsElement(@Nullable Object[] array, Object element) {
if (array == null) {
return false;
}
for (Object arrayEle : array) {
if (nullSafeEquals(arrayEle, element)) {
return true;
}
}
return false;
}
/**
* Check whether the given array of enum constants contains a constant with the given name,
* ignoring case when determining a match.
* @param enumValues the enum values to check, typically obtained via {@code MyEnum.values()}
* @param constant the constant name to find (must not be null or empty string)
* @return whether the constant has been found in the given array
*/
public static boolean containsConstant(Enum<?>[] enumValues, String constant) {
return containsConstant(enumValues, constant, false);
}
/**
* Check whether the given array of enum constants contains a constant with the given name.
* @param enumValues the enum values to check, typically obtained via {@code MyEnum.values()}
* @param constant the constant name to find (must not be null or empty string)
* @param caseSensitive whether case is significant in determining a match
* @return whether the constant has been found in the given array
*/
public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) {
for (Enum<?> candidate : enumValues) {
if (caseSensitive ? candidate.toString().equals(constant) :
candidate.toString().equalsIgnoreCase(constant)) {
return true;
}
}
return false;
}
/**
* Case insensitive alternative to {@link Enum#valueOf(Class, String)}.
* @param <E> the concrete Enum type
* @param enumValues the array of all Enum constants in question, usually per {@code Enum.values()}
* @param constant the constant to get the enum value of
* @throws IllegalArgumentException if the given constant is not found in the given array
* of enum values. Use {@link #containsConstant(Enum[], String)} as a guard to avoid this exception.
*/
public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) {
for (E candidate : enumValues) {
if (candidate.toString().equalsIgnoreCase(constant)) {
return candidate;
}
}
throw new IllegalArgumentException("Constant [" + constant + "] does not exist in enum type " +
enumValues.getClass().componentType().getName());
}
/**
* Append the given object to the given array, returning a new array
* consisting of the input array contents plus the given object.
* @param array the array to append to (can be {@code null})
* @param obj the object to append
* @return the new array (of the same component type; never {@code null})
*/
public static <A, O extends A> A[] addObjectToArray(@Nullable A[] array, @Nullable O obj) {
return addObjectToArray(array, obj, (array != null ? array.length : 0));
}
/**
* Add the given object to the given array at the specified position, returning
* a new array consisting of the input array contents plus the given object.
* @param array the array to add to (can be {@code null})
* @param obj the object to append
* @param position the position at which to add the object
* @return the new array (of the same component type; never {@code null})
* @since 6.0
*/
public static <A, O extends A> A[] addObjectToArray(@Nullable A[] array, @Nullable O obj, int position) {
Class<?> componentType = Object.class;
if (array != null) {
componentType = array.getClass().componentType();
}
else if (obj != null) {
componentType = obj.getClass();
}
int newArrayLength = (array != null ? array.length + 1 : 1);
@SuppressWarnings("unchecked")
A[] newArray = (A[]) Array.newInstance(componentType, newArrayLength);
if (array != null) {
System.arraycopy(array, 0, newArray, 0, position);
System.arraycopy(array, position, newArray, position + 1, array.length - position);
}
newArray[position] = obj;
return newArray;
}
/**
* Convert the given array (which may be a primitive array) to an
* object array (if necessary of primitive wrapper objects).
* <p>A {@code null} source value will be converted to an
* empty Object array.
* @param source the (potentially primitive) array
* @return the corresponding object array (never {@code null})
* @throws IllegalArgumentException if the parameter is not an array
*/
public static Object[] toObjectArray(@Nullable Object source) {
if (source instanceof Object[] objects) {
return objects;
}
if (source == null) {
return EMPTY_OBJECT_ARRAY;
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return EMPTY_OBJECT_ARRAY;
}
Class<?> wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
//---------------------------------------------------------------------
// Convenience methods for content-based equality/hash-code handling
//---------------------------------------------------------------------
/**
* Determine if the given objects are equal, returning {@code true} if
* both are {@code null} or {@code false} if only one is {@code null}.
* <p>Compares arrays with {@code Arrays.equals}, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first Object to compare
* @param o2 second Object to compare
* @return whether the given objects are equal
* @see Object#equals(Object)
* @see java.util.Arrays#equals
*/
@Contract("null, null -> true; null, _ -> false; _, null -> false")
public static boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
return arrayEquals(o1, o2);
}
return false;
}
/**
* Compare the given arrays with {@code Arrays.equals}, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first array to compare
* @param o2 second array to compare
* @return whether the given objects are equal
* @see #nullSafeEquals(Object, Object)
* @see java.util.Arrays#equals
*/
private static boolean arrayEquals(Object o1, Object o2) {
if (o1 instanceof Object[] objects1 && o2 instanceof Object[] objects2) {
return Arrays.equals(objects1, objects2);
}
if (o1 instanceof boolean[] booleans1 && o2 instanceof boolean[] booleans2) {
return Arrays.equals(booleans1, booleans2);
}
if (o1 instanceof byte[] bytes1 && o2 instanceof byte[] bytes2) {
return Arrays.equals(bytes1, bytes2);
}
if (o1 instanceof char[] chars1 && o2 instanceof char[] chars2) {
return Arrays.equals(chars1, chars2);
}
if (o1 instanceof double[] doubles1 && o2 instanceof double[] doubles2) {
return Arrays.equals(doubles1, doubles2);
}
if (o1 instanceof float[] floats1 && o2 instanceof float[] floats2) {
return Arrays.equals(floats1, floats2);
}
if (o1 instanceof int[] ints1 && o2 instanceof int[] ints2) {
return Arrays.equals(ints1, ints2);
}
if (o1 instanceof long[] longs1 && o2 instanceof long[] longs2) {
return Arrays.equals(longs1, longs2);
}
if (o1 instanceof short[] shorts1 && o2 instanceof short[] shorts2) {
return Arrays.equals(shorts1, shorts2);
}
return false;
}
/**
* Return a hash code for the given elements, delegating to
* {@link #nullSafeHashCode(Object)} for each element. Contrary
* to {@link Objects#hash(Object...)}, this method can handle an
* element that is an array.
* @param elements the elements to be hashed
* @return a hash value of the elements
* @since 6.1
*/
public static int nullSafeHash(@Nullable Object... elements) {
if (elements == null) {
return 0;
}
int result = 1;
for (Object element : elements) {
result = 31 * result + nullSafeHashCode(element);
}
return result;
}
/**
* Return a hash code for the given object; typically the value of
* {@code Object#hashCode()}}. If the object is an array,
* this method will delegate to any of the {@code Arrays.hashCode}
* methods. If the object is {@code null}, this method returns 0.
* @see Object#hashCode()
* @see Arrays
*/
public static int nullSafeHashCode(@Nullable Object obj) {
if (obj == null) {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[] objects) {
return Arrays.hashCode(objects);
}
if (obj instanceof boolean[] booleans) {
return Arrays.hashCode(booleans);
}
if (obj instanceof byte[] bytes) {
return Arrays.hashCode(bytes);
}
if (obj instanceof char[] chars) {
return Arrays.hashCode(chars);
}
if (obj instanceof double[] doubles) {
return Arrays.hashCode(doubles);
}
if (obj instanceof float[] floats) {
return Arrays.hashCode(floats);
}
if (obj instanceof int[] ints) {
return Arrays.hashCode(ints);
}
if (obj instanceof long[] longs) {
return Arrays.hashCode(longs);
}
if (obj instanceof short[] shorts) {
return Arrays.hashCode(shorts);
}
}
return obj.hashCode();
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(Object[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable Object[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(boolean[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable boolean[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(byte[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable byte[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(char[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable char[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(double[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable double[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(float[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable float[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(int[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable int[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(long[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable long[] array) {
return Arrays.hashCode(array);
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
* @deprecated as of 6.1 in favor of {@link Arrays#hashCode(short[])}
*/
@Deprecated(since = "6.1")
public static int nullSafeHashCode(@Nullable short[] array) {
return Arrays.hashCode(array);
}
//---------------------------------------------------------------------
// Convenience methods for toString output
//---------------------------------------------------------------------
/**
* Return a String representation of an object's overall identity.
* @param obj the object (may be {@code null})
* @return the object's identity as String representation,
* or an empty String if the object was {@code null}
*/
public static String identityToString(@Nullable Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return obj.getClass().getName() + "@" + getIdentityHexString(obj);
}
/**
* Return a hex String form of an object's identity hash code.
* @param obj the object
* @return the object's identity code in hex notation
*/
public static String getIdentityHexString(Object obj) {
return Integer.toHexString(System.identityHashCode(obj));
}
/**
* Return a content-based String representation if {@code obj} is
* not {@code null}; otherwise returns an empty String.
* <p>Differs from {@link #nullSafeToString(Object)} in that it returns
* an empty String rather than "null" for a {@code null} value.
* @param obj the object to build a display String for
* @return a display String representation of {@code obj}
* @see #nullSafeToString(Object)
*/
public static String getDisplayString(@Nullable Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return nullSafeToString(obj);
}
/**
* Determine the class name for the given object.
* <p>Returns a {@code "null"} String if {@code obj} is {@code null}.
* @param obj the object to introspect (may be {@code null})
* @return the corresponding class name
*/
public static String nullSafeClassName(@Nullable Object obj) {
return (obj != null ? obj.getClass().getName() : NULL_STRING);
}
/**
* Return a String representation of the specified Object.
* <p>Builds a String representation of the contents in case of an array.
* Returns a {@code "null"} String if {@code obj} is {@code null}.
* @param obj the object to build a String representation for
* @return a String representation of {@code obj}
* @see #nullSafeConciseToString(Object)
*/
public static String nullSafeToString(@Nullable Object obj) {
if (obj == null) {
return NULL_STRING;
}
if (obj instanceof String string) {
return string;
}
if (obj instanceof Object[] objects) {
return nullSafeToString(objects);
}
if (obj instanceof boolean[] booleans) {
return nullSafeToString(booleans);
}
if (obj instanceof byte[] bytes) {
return nullSafeToString(bytes);
}
if (obj instanceof char[] chars) {
return nullSafeToString(chars);
}
if (obj instanceof double[] doubles) {
return nullSafeToString(doubles);
}
if (obj instanceof float[] floats) {
return nullSafeToString(floats);
}
if (obj instanceof int[] ints) {
return nullSafeToString(ints);
}
if (obj instanceof long[] longs) {
return nullSafeToString(longs);
}
if (obj instanceof short[] shorts) {
return nullSafeToString(shorts);
}
String str = obj.toString();
return (str != null ? str : EMPTY_STRING);
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable Object[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (Object o : array) {
stringJoiner.add(String.valueOf(o));
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable boolean[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (boolean b : array) {
stringJoiner.add(String.valueOf(b));
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable byte[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (byte b : array) {
stringJoiner.add(String.valueOf(b));
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable char[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (char c : array) {
stringJoiner.add('\'' + String.valueOf(c) + '\'');
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable double[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (double d : array) {
stringJoiner.add(String.valueOf(d));
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable float[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (float f : array) {
stringJoiner.add(String.valueOf(f));
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable int[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (int i : array) {
stringJoiner.add(String.valueOf(i));
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable long[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (long l : array) {
stringJoiner.add(String.valueOf(l));
}
return stringJoiner.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space).
* Returns a {@code "null"} String if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(@Nullable short[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringJoiner stringJoiner = new StringJoiner(ARRAY_ELEMENT_SEPARATOR, ARRAY_START, ARRAY_END);
for (short s : array) {
stringJoiner.add(String.valueOf(s));
}
return stringJoiner.toString();
}
/**
* Generate a null-safe, concise string representation of the supplied object
* as described below.
* <p>Favor this method over {@link #nullSafeToString(Object)} when you need
* the length of the generated string to be limited.
* <p>Returns:
* <ul>
* <li>{@code "null"} if {@code obj} is {@code null}</li>
* <li>{@code "Optional.empty"} if {@code obj} is an empty {@link Optional}</li>
* <li>{@code "Optional[<concise-string>]"} if {@code obj} is a non-empty {@code Optional},
* where {@code <concise-string>} is the result of invoking this method on the object
* contained in the {@code Optional}</li>
* <li>{@code "{}"} if {@code obj} is an empty array</li>
* <li>{@code "{...}"} if {@code obj} is a {@link Map} or a non-empty array</li>
* <li>{@code "[...]"} if {@code obj} is a {@link Collection}</li>
* <li>{@linkplain Class#getName() Class name} if {@code obj} is a {@link Class}</li>
* <li>{@linkplain Charset#name() Charset name} if {@code obj} is a {@link Charset}</li>
* <li>{@linkplain TimeZone#getID() TimeZone ID} if {@code obj} is a {@link TimeZone}</li>
* <li>{@linkplain ZoneId#getId() Zone ID} if {@code obj} is a {@link ZoneId}</li>
* <li>Potentially {@linkplain StringUtils#truncate(CharSequence) truncated string}
* if {@code obj} is a {@link String} or {@link CharSequence}</li>
* <li>Potentially {@linkplain StringUtils#truncate(CharSequence) truncated string}
* if {@code obj} is a <em>simple value type</em> whose {@code toString()} method
* returns a non-null value</li>
* <li>Otherwise, a string representation of the object's type name concatenated
* with {@code "@"} and a hex string form of the object's identity hash code</li>
* </ul>
* <p>In the context of this method, a <em>simple value type</em> is any of the following:
* primitive wrapper (excluding {@link Void}), {@link Enum}, {@link Number},
* {@link java.util.Date Date}, {@link java.time.temporal.Temporal Temporal},
* {@link java.io.File File}, {@link java.nio.file.Path Path},
* {@link java.net.URI URI}, {@link java.net.URL URL},
* {@link java.net.InetAddress InetAddress}, {@link java.util.Currency Currency},
* {@link java.util.Locale Locale}, {@link java.util.UUID UUID},
* {@link java.util.regex.Pattern Pattern}.
* @param obj the object to build a string representation for
* @return a concise string representation of the supplied object
* @since 5.3.27
* @see #nullSafeToString(Object)
* @see StringUtils#truncate(CharSequence)
* @see ClassUtils#isSimpleValueType(Class)
*/
public static String nullSafeConciseToString(@Nullable Object obj) {
if (obj == null) {
return "null";
}
if (obj instanceof Optional<?> optional) {
return (optional.isEmpty() ? "Optional.empty" :
"Optional[%s]".formatted(nullSafeConciseToString(optional.get())));
}
if (obj.getClass().isArray()) {
return (Array.getLength(obj) == 0 ? EMPTY_ARRAY : NON_EMPTY_ARRAY);
}
if (obj instanceof Collection) {
return COLLECTION;
}
if (obj instanceof Map) {
return MAP;
}
if (obj instanceof Class<?> clazz) {
return clazz.getName();
}
if (obj instanceof Charset charset) {
return charset.name();
}
if (obj instanceof TimeZone timeZone) {
return timeZone.getID();
}
if (obj instanceof ZoneId zoneId) {
return zoneId.getId();
}
if (obj instanceof CharSequence charSequence) {
return StringUtils.truncate(charSequence);
}
Class<?> type = obj.getClass();
if (ClassUtils.isSimpleValueType(type)) {
String str = obj.toString();
if (str != null) {
return StringUtils.truncate(str);
}
}
return type.getTypeName() + "@" + getIdentityHexString(obj);
}
}
| spring-projects/spring-framework | spring-core/src/main/java/org/springframework/util/ObjectUtils.java |
106 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.threadpool;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
import org.elasticsearch.common.util.concurrent.EsAbortPolicy;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.core.TimeValue;
import java.util.concurrent.Delayed;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Scheduler that allows to schedule one-shot and periodic commands.
*/
public interface Scheduler {
/**
* Create a scheduler that can be used client side. Server side, please use <code>ThreadPool.schedule</code> instead.
*
* Notice that if any scheduled jobs fail with an exception, these will bubble up to the uncaught exception handler where they will
* be logged as a warning. This includes jobs started using execute, submit and schedule.
* @param settings the settings to use
* @param schedulerName a string that identifies the threads belonging to this scheduler
* @return executor
*/
static ScheduledThreadPoolExecutor initScheduler(Settings settings, String schedulerName) {
final ScheduledThreadPoolExecutor scheduler = new SafeScheduledThreadPoolExecutor(
1,
EsExecutors.daemonThreadFactory(settings, schedulerName),
new EsAbortPolicy()
);
scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
scheduler.setRemoveOnCancelPolicy(true);
return scheduler;
}
static boolean terminate(ScheduledThreadPoolExecutor scheduledThreadPoolExecutor, long timeout, TimeUnit timeUnit) {
scheduledThreadPoolExecutor.shutdown();
if (awaitTermination(scheduledThreadPoolExecutor, timeout, timeUnit)) {
return true;
}
// last resort
scheduledThreadPoolExecutor.shutdownNow();
return awaitTermination(scheduledThreadPoolExecutor, timeout, timeUnit);
}
static boolean awaitTermination(
final ScheduledThreadPoolExecutor scheduledThreadPoolExecutor,
final long timeout,
final TimeUnit timeUnit
) {
try {
if (scheduledThreadPoolExecutor.awaitTermination(timeout, timeUnit)) {
return true;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return false;
}
/**
* Schedules a one-shot command to be run after a given delay. The command is run in the context of the calling thread.
* Implementations may choose to run the command on the given {@code executor} or on the scheduler thread. If {@code executor} is {@link
* EsExecutors#DIRECT_EXECUTOR_SERVICE} then the command runs on the scheduler thread in all cases. Do not run blocking calls on the
* scheduler thread.
*
* @param command the command to run
* @param delay delay before the task executes
* @param executor the executor that has to execute this task.
* @return a ScheduledFuture whose {@link ScheduledFuture#get()} will return when the task has been added to its target thread pool and
* throws an exception if the task is canceled before it was added to its target thread pool. Once the task has been added to
* its target thread pool the ScheduledFuture cannot interact with it.
* @throws EsRejectedExecutionException if the task cannot be scheduled for execution
*/
ScheduledCancellable schedule(Runnable command, TimeValue delay, Executor executor);
/**
* Schedules a periodic action that runs on scheduler thread. Do not run blocking calls on the scheduler thread. Subclasses may allow
* to execute on a different executor, in which case blocking calls are allowed.
*
* @param command the action to take
* @param interval the delay interval
* @param executor the name of the executor that has to execute this task. Ignored in the default implementation but can be used
* by subclasses that support multiple executors.
* @return a {@link Cancellable} that can be used to cancel the subsequent runs of the command. If the command is running, it will
* not be interrupted.
*/
default Cancellable scheduleWithFixedDelay(Runnable command, TimeValue interval, Executor executor) {
var runnable = new ReschedulingRunnable(command, interval, executor, this, e -> {}, e -> {});
runnable.start();
return runnable;
}
/**
* Utility method to wrap a <code>Future</code> as a <code>Cancellable</code>
* @param future the future to wrap
* @return a cancellable delegating to the future
*/
static Cancellable wrapAsCancellable(Future<?> future) {
return new CancellableAdapter(future);
}
/**
* Utility method to wrap a <code>ScheduledFuture</code> as a <code>ScheduledCancellable</code>
* @param scheduledFuture the scheduled future to wrap
* @return a SchedulecCancellable delegating to the scheduledFuture
*/
static ScheduledCancellable wrapAsScheduledCancellable(ScheduledFuture<?> scheduledFuture) {
return new ScheduledCancellableAdapter(scheduledFuture);
}
/**
* This interface represents an object whose execution may be cancelled during runtime.
*/
interface Cancellable {
/**
* Cancel the execution of this object. This method is idempotent.
*/
boolean cancel();
/**
* Check if the execution has been cancelled
* @return true if cancelled
*/
boolean isCancelled();
}
/**
* A scheduled cancellable allow cancelling and reading the remaining delay of a scheduled task.
*/
interface ScheduledCancellable extends Delayed, Cancellable {}
/**
* This class encapsulates the scheduling of a {@link Runnable} that needs to be repeated on a interval. For example, checking a value
* for cleanup every second could be done by passing in a Runnable that can perform the check and the specified interval between
* executions of this runnable. <em>NOTE:</em> the runnable is only rescheduled to run again after completion of the runnable.
*
* For this class, <i>completion</i> means that the call to {@link Runnable#run()} returned or an exception was thrown and caught. In
* case of an exception, this class will log the exception and reschedule the runnable for its next execution. This differs from the
* {@link ScheduledThreadPoolExecutor#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)} semantics as an exception there would
* terminate the rescheduling of the runnable.
*/
final class ReschedulingRunnable extends AbstractRunnable implements Cancellable {
private final Runnable runnable;
private final TimeValue interval;
private final Executor executor;
private final Scheduler scheduler;
private final Consumer<Exception> rejectionConsumer;
private final Consumer<Exception> failureConsumer;
private volatile boolean run = true;
/**
* Creates a new rescheduling runnable
*
* @param runnable the {@link Runnable} that should be executed periodically
* @param interval the time interval between executions
* @param executor the executor where this runnable should be scheduled to run
* @param scheduler the {@link Scheduler} instance to use for scheduling
*/
ReschedulingRunnable(
Runnable runnable,
TimeValue interval,
Executor executor,
Scheduler scheduler,
Consumer<Exception> rejectionConsumer,
Consumer<Exception> failureConsumer
) {
this.runnable = runnable;
this.interval = interval;
this.executor = executor;
this.scheduler = scheduler;
this.rejectionConsumer = rejectionConsumer;
this.failureConsumer = failureConsumer;
}
/**
* Schedules the first execution of this runnable
*/
void start() {
scheduler.schedule(this, interval, executor);
}
@Override
public boolean cancel() {
final boolean result = run;
run = false;
return result;
}
@Override
public boolean isCancelled() {
return run == false;
}
@Override
public void doRun() {
// always check run here since this may have been cancelled since the last execution and we do not want to run
if (run) {
runnable.run();
}
}
@Override
public void onFailure(Exception e) {
try {
if (runnable instanceof AbstractRunnable abstractRunnable) {
abstractRunnable.onFailure(e);
}
} finally {
failureConsumer.accept(e);
}
}
@Override
public void onRejection(Exception e) {
run = false;
try {
if (runnable instanceof AbstractRunnable abstractRunnable) {
abstractRunnable.onRejection(e);
}
} finally {
rejectionConsumer.accept(e);
}
}
@Override
public void onAfter() {
// if this has not been cancelled reschedule it to run again
if (run) {
try {
scheduler.schedule(this, interval, executor);
} catch (final EsRejectedExecutionException e) {
onRejection(e);
}
}
}
@Override
public boolean isForceExecution() {
return runnable instanceof AbstractRunnable abstractRunnable && abstractRunnable.isForceExecution();
}
@Override
public String toString() {
return "ReschedulingRunnable{" + "runnable=" + runnable + ", interval=" + interval + '}';
}
}
/**
* This subclass ensures to properly bubble up Throwable instances of both type Error and Exception thrown in submitted/scheduled
* tasks to the uncaught exception handler
*/
class SafeScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
@SuppressForbidden(reason = "properly rethrowing errors, see EsExecutors.rethrowErrors")
public SafeScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, threadFactory, handler);
}
@SuppressForbidden(reason = "properly rethrowing errors, see EsExecutors.rethrowErrors")
public SafeScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize, threadFactory);
}
@SuppressForbidden(reason = "properly rethrowing errors, see EsExecutors.rethrowErrors")
public SafeScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
if (t != null) return;
// Scheduler only allows Runnable's so we expect no checked exceptions here. If anyone uses submit directly on `this`, we
// accept the wrapped exception in the output.
if (r instanceof RunnableFuture && ((RunnableFuture<?>) r).isDone()) {
// only check this if task is done, which it always is except for periodic tasks. Periodic tasks will hang on
// RunnableFuture.get()
ExceptionsHelper.reThrowIfNotNull(EsExecutors.rethrowErrors(r));
}
}
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/threadpool/Scheduler.java |
107 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.virtual.proxy;
/**
* Interface for expensive object and proxy object.
*/
public interface ExpensiveObject {
void process();
} | iluwatar/java-design-patterns | virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/ExpensiveObject.java |
108 | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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.tensorflow;
import java.util.Iterator;
/**
* A data flow graph representing a TensorFlow computation.
*
* <p>Instances of a Graph are thread-safe.
*
* <p><b>WARNING:</b> Resources consumed by the Graph object must be explicitly freed by invoking
* the {@link #close()} method then the Graph object is no longer needed.
*/
public final class Graph implements ExecutionEnvironment, AutoCloseable {
/** Create an empty Graph. */
public Graph() {
nativeHandle = allocate();
}
/** Create a Graph from an existing handle (takes ownership). */
Graph(long nativeHandle) {
this.nativeHandle = nativeHandle;
}
/**
* Release resources associated with the Graph.
*
* <p>Blocks until there are no active {@link Session} instances referring to this Graph. A Graph
* is not usable after close returns.
*/
@Override
public void close() {
synchronized (nativeHandleLock) {
if (nativeHandle == 0) {
return;
}
while (refcount > 0) {
try {
nativeHandleLock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// Possible leak of the graph in this case?
return;
}
}
delete(nativeHandle);
nativeHandle = 0;
}
}
/**
* Returns the operation (node in the Graph) with the provided name.
*
* <p>Or {@code null} if no such operation exists in the Graph.
*/
public GraphOperation operation(String name) {
synchronized (nativeHandleLock) {
long oph = operation(nativeHandle, name);
if (oph == 0) {
return null;
}
return new GraphOperation(this, oph);
}
}
/**
* Iterator over all the {@link Operation}s in the graph.
*
* <p>The order of iteration is unspecified. Consumers of the iterator will receive no
* notification should the underlying graph change during iteration.
*/
public Iterator<Operation> operations() {
return new OperationIterator(this);
}
/**
* Returns a builder to add {@link Operation}s to the Graph.
*
* @param type of the Operation (i.e., identifies the computation to be performed)
* @param name to refer to the created Operation in the graph.
* @return an {@link OperationBuilder}, which will add the Operation to the graph when {@link
* OperationBuilder#build()} is invoked. If {@link OperationBuilder#build()} is not invoked,
* then some resources may leak.
*/
@Override
public GraphOperationBuilder opBuilder(String type, String name) {
return new GraphOperationBuilder(this, type, name);
}
/**
* Import a serialized representation of a TensorFlow graph.
*
* <p>The serialized representation of the graph, often referred to as a <i>GraphDef</i>, can be
* generated by {@link #toGraphDef()} and equivalents in other language APIs.
*
* @throws IllegalArgumentException if graphDef is not a recognized serialization of a graph.
* @see #importGraphDef(byte[], String)
*/
public void importGraphDef(byte[] graphDef) throws IllegalArgumentException {
importGraphDef(graphDef, "");
}
/**
* Import a serialized representation of a TensorFlow graph.
*
* @param graphDef the serialized representation of a TensorFlow graph.
* @param prefix a prefix that will be prepended to names in graphDef
* @throws IllegalArgumentException if graphDef is not a recognized serialization of a graph.
* @see #importGraphDef(byte[])
*/
public void importGraphDef(byte[] graphDef, String prefix) throws IllegalArgumentException {
if (graphDef == null || prefix == null) {
throw new IllegalArgumentException("graphDef and prefix cannot be null");
}
synchronized (nativeHandleLock) {
importGraphDef(nativeHandle, graphDef, prefix);
}
}
/**
* Generate a serialized representation of the Graph.
*
* @see #importGraphDef(byte[])
* @see #importGraphDef(byte[], String)
*/
public byte[] toGraphDef() {
synchronized (nativeHandleLock) {
return toGraphDef(nativeHandle);
}
}
/**
* Adds operations to compute the partial derivatives of sum of {@code y}s w.r.t {@code x}s, i.e.,
* {@code d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2...}
*
* <p>{@code dx} are used as initial gradients (which represent the symbolic partial derivatives
* of some loss function {@code L} w.r.t. {@code y}). {@code dx} must be null or have size of
* {@code y}.
*
* <p>If {@code dx} is null, the implementation will use dx of {@link
* org.tensorflow.op.core.OnesLike OnesLike} for all shapes in {@code y}.
*
* <p>{@code prefix} is used as the name prefix applied to all nodes added to the graph to compute
* gradients. It must be unique within the provided graph or the operation will fail.
*
* <p>If {@code prefix} is null, then one will be chosen automatically.
*
* @param prefix unique string prefix applied before the names of nodes added to the graph to
* compute gradients. If null, a default one will be chosen.
* @param y output of the function to derive
* @param x inputs of the function for which partial derivatives are computed
* @param dx if not null, the partial derivatives of some loss function {@code L} w.r.t. {@code y}
* @return the partial derivatives {@code dy} with the size of {@code x}
*/
public Output<?>[] addGradients(String prefix, Output<?>[] y, Output<?>[] x, Output<?>[] dx) {
Output<?>[] dy = new Output<?>[x.length];
final long[] yHandles = new long[y.length];
final int[] yIndices = new int[y.length];
final long[] xHandles = new long[x.length];
final int[] xIndices = new int[x.length];
long[] dxHandles = null;
int[] dxIndices = null;
try (Reference ref = ref()) {
for (int i = 0; i < y.length; ++i) {
yHandles[i] = y[i].getUnsafeNativeHandle();
yIndices[i] = y[i].index();
}
for (int i = 0; i < x.length; ++i) {
xHandles[i] = x[i].getUnsafeNativeHandle();
xIndices[i] = x[i].index();
}
if (dx != null && dx.length > 0) {
dxHandles = new long[dx.length];
dxIndices = new int[dx.length];
for (int i = 0; i < dx.length; ++i) {
dxHandles[i] = dx[i].getUnsafeNativeHandle();
dxIndices[i] = dx[i].index();
}
}
// Gradient outputs are returned in two continuous arrays concatenated into one. The first
// holds the native handles of the gradient operations while the second holds the index of
// their output e.g. given
// xHandles = [x0Handle, x1Handle, ...] and xIndices = [x0Index, x1Index, ..], we obtain
// dy = [dy0Handle, dy1Handle, ..., dy0Index, dy1Index, ...]
long[] dyHandlesAndIndices =
addGradients(
ref.nativeHandle(),
prefix,
yHandles,
yIndices,
xHandles,
xIndices,
dxHandles,
dxIndices);
int ndy = dyHandlesAndIndices.length >> 1;
if (ndy != dy.length) {
throw new IllegalStateException(String.valueOf(ndy) + " gradients were added to the graph when " + dy.length
+ " were expected");
}
for (int i = 0, j = ndy; i < ndy; ++i, ++j) {
GraphOperation op = new GraphOperation(this, dyHandlesAndIndices[i]);
dy[i] = new Output<>(op, (int) dyHandlesAndIndices[j]);
}
}
return dy;
}
/**
* Adds operations to compute the partial derivatives of sum of {@code y}s w.r.t {@code x}s,
* i.e., {@code dy/dx_1, dy/dx_2...}
* <p>
* This is a simplified version of {@link #addGradients(String, Output[], Output[], Output[])}
* where {@code y} is a single output, {@code dx} is null and {@code prefix} is null.
*
* @param y output of the function to derive
* @param x inputs of the function for which partial derivatives are computed
* @return the partial derivatives {@code dy} with the size of {@code x}
*/
public Output<?>[] addGradients(Output<?> y, Output<?>[] x) {
return addGradients(null, new Output<?>[] {y}, x, null);
}
/**
* Used to instantiate an abstract class which overrides the buildSubgraph method to build a
* conditional or body subgraph for a while loop. After Java 8, this can alternatively be used to
* create a lambda for the same purpose.
*
* <p>To be used when calling {@link #whileLoop(Output[],
* org.tensorflow.Graph.WhileSubgraphBuilder, org.tensorflow.Graph.WhileSubgraphBuilder, String)}
*
* <p>Example usage (prior to Java 8):
*
* <p>{@code WhileSubgraphBuilder bodyGraphBuilder = new WhileSubgraphBuilder() { @Override public
* void buildSubgraph(Graph bodyGraph, Output<?>[] bodyInputs, Output<?>[] bodyOutputs) { // build
* body subgraph } }; }
*
* <p>Example usage (after Java 8):
*
* <p>{@code WhileSubgraphBuilder bodyGraphBuilder = (bodyGraph, bodyInputs, bodyOutputs) -> { //
* build body subgraph };}
*/
public interface WhileSubgraphBuilder {
/**
* To be overridden by user with code to build conditional or body subgraph for a while loop
*
* @param g the subgraph
* @param inputs subgraph inputs
* @param outputs subgraph outputs
*/
public void buildSubgraph(Graph g, Output<?>[] inputs, Output<?>[] outputs);
}
// called by while loop code in graph_jni.cc to construct conditional/body subgraphs
private static long[] buildSubgraph(
WhileSubgraphBuilder subgraphBuilder,
long subgraphHandle,
long[] inputHandles,
int[] inputIndices,
long[] outputHandles,
int[] outputIndices) {
Graph subgraph = new Graph(subgraphHandle);
int ninputs = inputHandles.length;
int noutputs = outputHandles.length;
Output<?>[] inputs = new Output<?>[ninputs];
Output<?>[] outputs = new Output<?>[noutputs];
long[] outputHandlesAndIndices = new long[noutputs * 2];
synchronized (subgraph.nativeHandleLock) {
try (Reference ref = subgraph.ref()) {
for (int i = 0; i < ninputs; i++) {
Operation op = new GraphOperation(subgraph, inputHandles[i]);
inputs[i] = op.output(inputIndices[i]);
}
for (int i = 0; i < noutputs; i++) {
Operation op = new GraphOperation(subgraph, outputHandles[i]);
outputs[i] = op.output(outputIndices[i]);
}
subgraphBuilder.buildSubgraph(subgraph, inputs, outputs);
for (int i = 0, j = noutputs; i < noutputs; i++, j++) {
outputHandlesAndIndices[i] = outputs[i].getUnsafeNativeHandle();
outputHandlesAndIndices[j] = (long) outputs[i].index();
}
}
return outputHandlesAndIndices;
}
}
/**
* Builds a while loop.
*
* @param inputs the loop inputs
* @param cgBuilder WhileSubgraphBuilder to build the conditional subgraph
* @param bgBuilder WhileSubgraphBuilder to build the body subgraph
* @param name name for the loop
* @return list of loop outputs, of the same length as {@code inputs}
*/
public Output<?>[] whileLoop(
Output<?>[] inputs,
WhileSubgraphBuilder cgBuilder,
WhileSubgraphBuilder bgBuilder,
String name) {
int ninputs = inputs.length;
long[] inputHandles = new long[ninputs];
int[] inputIndices = new int[ninputs];
Output<?>[] outputs = new Output<?>[ninputs];
synchronized (nativeHandleLock) {
try (Reference ref = ref()) {
for (int i = 0; i < ninputs; i++) {
inputHandles[i] = inputs[i].getUnsafeNativeHandle();
inputIndices[i] = inputs[i].index();
}
long[] outputHandlesAndIndices =
whileLoop(nativeHandle, inputHandles, inputIndices, name, cgBuilder, bgBuilder);
for (int i = 0, j = ninputs; i < ninputs; ++i, ++j) {
Operation op = new GraphOperation(this, outputHandlesAndIndices[i]);
outputs[i] = op.output((int) outputHandlesAndIndices[j]);
}
}
return outputs;
}
}
private final Object nativeHandleLock = new Object();
private long nativeHandle;
private int refcount = 0;
// Related native objects (such as the TF_Operation object backing an Operation instance)
// have a validity tied to that of the Graph. The handles to those native objects are not
// valid after Graph.close() has been invoked.
//
// Instances of the Reference class should be used to ensure the Graph has not been closed
// while dependent handles are in use.
class Reference implements AutoCloseable {
private Reference() {
synchronized (Graph.this.nativeHandleLock) {
active = Graph.this.nativeHandle != 0;
if (!active) {
throw new IllegalStateException("close() has been called on the Graph");
}
active = true;
Graph.this.refcount++;
}
}
@Override
public void close() {
synchronized (Graph.this.nativeHandleLock) {
if (!active) {
return;
}
active = false;
if (--Graph.this.refcount == 0) {
Graph.this.nativeHandleLock.notifyAll();
}
}
}
public long nativeHandle() {
synchronized (Graph.this.nativeHandleLock) {
return active ? Graph.this.nativeHandle : 0;
}
}
private boolean active;
}
Reference ref() {
return new Reference();
}
private static final class OperationIterator implements Iterator<Operation> {
OperationIterator(Graph g) {
this.graph = g;
this.operation = null;
this.position = 0;
this.advance();
}
private final void advance() {
Graph.Reference reference = this.graph.ref();
this.operation = null;
try {
long[] nativeReturn = nextOperation(reference.nativeHandle(), this.position);
if ((nativeReturn != null) && (nativeReturn[0] != 0)) {
this.operation = new GraphOperation(this.graph, nativeReturn[0]);
this.position = (int) nativeReturn[1];
}
} finally {
reference.close();
}
}
@Override
public boolean hasNext() {
return (this.operation != null);
}
@Override
public Operation next() {
Operation rhett = this.operation;
this.advance();
return rhett;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove() is unsupported.");
}
private final Graph graph;
private Operation operation;
private int position;
}
private static native long allocate();
private static native void delete(long handle);
private static native long operation(long handle, String name);
// This method returns the Operation native handle at index 0 and the new value for pos at index 1
// (see TF_GraphNextOperation)
private static native long[] nextOperation(long handle, int position);
private static native void importGraphDef(long handle, byte[] graphDef, String prefix)
throws IllegalArgumentException;
private static native byte[] toGraphDef(long handle);
private static native long[] addGradients(
long handle,
String prefix,
long[] inputHandles,
int[] inputIndices,
long[] outputHandles,
int[] outputIndices,
long[] gradInputHandles,
int[] gradInputIndices);
private static native long[] whileLoop(
long handle,
long[] inputHandles,
int[] inputIndices,
String name,
WhileSubgraphBuilder condGraphBuilder,
WhileSubgraphBuilder bodyGraphBuilder);
static {
TensorFlow.init();
}
}
| tensorflow/tensorflow | tensorflow/java/src/main/java/org/tensorflow/Graph.java |
110 | import java.io.File;
import java.io.FileInputStream;
import java.util.*;
import java.util.regex.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.FlagTerm;
//Dependencies- Java mail API
public class KumarAsshole {
public static void main(String[] args) {
KumarAsshole asshole = new KumarAsshole();
asshole.read();
}
public void read() {
Properties props = new Properties();
//modify below properties to your details
String host = "smtp.gmail.com";
String username = "[email protected] goes here";
String password = "your password goes here ";
String Kumar_mail = "the mail address to be replied to !";
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect(host, username, password);
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
for (int i = 0; i < messages.length; i++) {
if (messages[i].getFrom()[0].toString().contains(Kumar_mail)) {
String bodytext = null;
Object content = messages[i].getContent();
if (content instanceof String) {
bodytext = (String) content;
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
BodyPart bp = mp.getBodyPart(mp.getCount() - 1);
bodytext = (String) bp.getContent();
}
Pattern pattern = Pattern.compile("sorry|help|wrong", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(bodytext);
// check all occurance
if (matcher.find()) {
Properties props1 = new Properties();
Address[] tomail;
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(username));
tomail = messages[i].getFrom();
String t1 = tomail[0].toString();
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(t1));
msg.setSubject("Database fixes");
msg.setText("No problem. I've fixed it. \n\n Please be careful next time.");
Transport t = null;
t = session.getTransport("smtps");
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
}
}
}
inbox.close(true);
store.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
| NARKOZ/hacker-scripts | java/KumarAsshole.java |
111 | /*
* Protocol Buffers - Google's data interchange format
* Copyright 2014 Google Inc. All rights reserved.
* https://developers.google.com/protocol-buffers/
*
* 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 Google Inc. 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
* OWNER 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.google.protobuf.jruby;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.DynamicMessage;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jruby.*;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.Helpers;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
@JRubyClass(name = "Map", include = "Enumerable")
public class RubyMap extends RubyObject {
public static void createRubyMap(Ruby runtime) {
RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf");
RubyClass cMap =
protobuf.defineClassUnder(
"Map",
runtime.getObject(),
new ObjectAllocator() {
@Override
public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) {
return new RubyMap(ruby, rubyClass);
}
});
cMap.includeModule(runtime.getEnumerable());
cMap.defineAnnotatedMethods(RubyMap.class);
}
public RubyMap(Ruby ruby, RubyClass rubyClass) {
super(ruby, rubyClass);
}
/*
* call-seq:
* Map.new(key_type, value_type, value_typeclass = nil, init_hashmap = {})
* => new map
*
* Allocates a new Map container. This constructor may be called with 2, 3, or 4
* arguments. The first two arguments are always present and are symbols (taking
* on the same values as field-type symbols in message descriptors) that
* indicate the type of the map key and value fields.
*
* The supported key types are: :int32, :int64, :uint32, :uint64, :fixed32,
* :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes.
*
* The supported value types are: :int32, :int64, :uint32, :uint64, :fixed32,
* :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes,
* :enum, :message.
*
* The third argument, value_typeclass, must be present if value_type is :enum
* or :message. As in RepeatedField#new, this argument must be a message class
* (for :message) or enum module (for :enum).
*
* The last argument, if present, provides initial content for map. Note that
* this may be an ordinary Ruby hashmap or another Map instance with identical
* key and value types. Also note that this argument may be present whether or
* not value_typeclass is present (and it is unambiguously separate from
* value_typeclass because value_typeclass's presence is strictly determined by
* value_type). The contents of this initial hashmap or Map instance are
* shallow-copied into the new Map: the original map is unmodified, but
* references to underlying objects will be shared if the value type is a
* message type.
*/
@JRubyMethod(required = 2, optional = 2)
public IRubyObject initialize(ThreadContext context, IRubyObject[] args) {
this.table = new HashMap<IRubyObject, IRubyObject>();
this.keyType = Utils.rubyToFieldType(args[0]);
this.valueType = Utils.rubyToFieldType(args[1]);
switch (keyType) {
case STRING:
case BYTES:
this.keyTypeIsString = true;
break;
case INT32:
case INT64:
case SINT32:
case SINT64:
case UINT32:
case UINT64:
case FIXED32:
case FIXED64:
case SFIXED32:
case SFIXED64:
case BOOL:
// These are OK.
break;
default:
throw context.runtime.newArgumentError("Invalid key type for map.");
}
int initValueArg = 2;
if (needTypeclass(this.valueType) && args.length > 2) {
this.valueTypeClass = args[2];
Utils.validateTypeClass(context, this.valueType, this.valueTypeClass);
initValueArg = 3;
} else {
this.valueTypeClass = context.runtime.getNilClass();
}
if (args.length > initValueArg) {
mergeIntoSelf(context, args[initValueArg]);
}
return this;
}
/*
* call-seq:
* Map.[]=(key, value) => value
*
* Inserts or overwrites the value at the given key with the given new value.
* Throws an exception if the key type is incorrect. Returns the new value that
* was just inserted.
*/
@JRubyMethod(name = "[]=")
public IRubyObject indexSet(ThreadContext context, IRubyObject key, IRubyObject value) {
checkFrozen();
/*
* String types for keys return a different error than
* other types for keys, so deal with them specifically first
*/
if (keyTypeIsString && !(key instanceof RubySymbol || key instanceof RubyString)) {
throw Utils.createTypeError(context, "Expected string for map key");
}
key = Utils.checkType(context, keyType, "key", key, (RubyModule) valueTypeClass);
value = Utils.checkType(context, valueType, "value", value, (RubyModule) valueTypeClass);
IRubyObject symbol;
if (valueType == FieldDescriptor.Type.ENUM
&& Utils.isRubyNum(value)
&& !(symbol = RubyEnum.lookup(context, valueTypeClass, value)).isNil()) {
value = symbol;
}
this.table.put(key, value);
return value;
}
/*
* call-seq:
* Map.[](key) => value
*
* Accesses the element at the given key. Throws an exception if the key type is
* incorrect. Returns nil when the key is not present in the map.
*/
@JRubyMethod(name = "[]")
public IRubyObject index(ThreadContext context, IRubyObject key) {
key = Utils.symToString(key);
return Helpers.nullToNil(table.get(key), context.nil);
}
/*
* call-seq:
* Map.==(other) => boolean
*
* Compares this map to another. Maps are equal if they have identical key sets,
* and for each key, the values in both maps compare equal. Elements are
* compared as per normal Ruby semantics, by calling their :== methods (or
* performing a more efficient comparison for primitive types).
*
* Maps with dissimilar key types or value types/typeclasses are never equal,
* even if value comparison (for example, between integers and floats) would
* have otherwise indicated that every element has equal value.
*/
@JRubyMethod(name = "==")
public IRubyObject eq(ThreadContext context, IRubyObject _other) {
if (_other instanceof RubyHash) return singleLevelHash(context).op_equal(context, _other);
RubyMap other = (RubyMap) _other;
if (this == other) return context.runtime.getTrue();
if (!typeCompatible(other) || this.table.size() != other.table.size())
return context.runtime.getFalse();
for (IRubyObject key : table.keySet()) {
if (!other.table.containsKey(key)) return context.runtime.getFalse();
if (!other.table.get(key).equals(table.get(key))) return context.runtime.getFalse();
}
return context.runtime.getTrue();
}
/*
* call-seq:
* Map.inspect => string
*
* Returns a string representing this map's elements. It will be formatted as
* "{key => value, key => value, ...}", with each key and value string
* representation computed by its own #inspect method.
*/
@JRubyMethod
public IRubyObject inspect() {
return singleLevelHash(getRuntime().getCurrentContext()).inspect();
}
/*
* call-seq:
* Map.hash => hash_value
*
* Returns a hash value based on this map's contents.
*/
@JRubyMethod
public IRubyObject hash(ThreadContext context) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
for (IRubyObject key : table.keySet()) {
digest.update((byte) key.hashCode());
digest.update((byte) table.get(key).hashCode());
}
return context.runtime.newFixnum(ByteBuffer.wrap(digest.digest()).getLong());
} catch (NoSuchAlgorithmException ignore) {
return context.runtime.newFixnum(System.identityHashCode(table));
}
}
/*
* call-seq:
* Map.keys => [list_of_keys]
*
* Returns the list of keys contained in the map, in unspecified order.
*/
@JRubyMethod
public IRubyObject keys(ThreadContext context) {
return RubyArray.newArray(context.runtime, table.keySet());
}
/*
* call-seq:
* Map.values => [list_of_values]
*
* Returns the list of values contained in the map, in unspecified order.
*/
@JRubyMethod
public IRubyObject values(ThreadContext context) {
return RubyArray.newArray(context.runtime, table.values());
}
/*
* call-seq:
* Map.clear
*
* Removes all entries from the map.
*/
@JRubyMethod
public IRubyObject clear(ThreadContext context) {
checkFrozen();
table.clear();
return context.nil;
}
/*
* call-seq:
* Map.each(&block)
*
* Invokes &block on each |key, value| pair in the map, in unspecified order.
* Note that Map also includes Enumerable; map thus acts like a normal Ruby
* sequence.
*/
@JRubyMethod
public IRubyObject each(ThreadContext context, Block block) {
for (IRubyObject key : table.keySet()) {
block.yieldSpecific(context, key, table.get(key));
}
return context.nil;
}
/*
* call-seq:
* Map.delete(key) => old_value
*
* Deletes the value at the given key, if any, returning either the old value or
* nil if none was present. Throws an exception if the key is of the wrong type.
*/
@JRubyMethod
public IRubyObject delete(ThreadContext context, IRubyObject key) {
checkFrozen();
return table.remove(key);
}
/*
* call-seq:
* Map.has_key?(key) => bool
*
* Returns true if the given key is present in the map. Throws an exception if
* the key has the wrong type.
*/
@JRubyMethod(name = "has_key?")
public IRubyObject hasKey(ThreadContext context, IRubyObject key) {
return this.table.containsKey(key) ? context.runtime.getTrue() : context.runtime.getFalse();
}
/*
* call-seq:
* Map.length
*
* Returns the number of entries (key-value pairs) in the map.
*/
@JRubyMethod(name = {"length", "size"})
public IRubyObject length(ThreadContext context) {
return context.runtime.newFixnum(this.table.size());
}
/*
* call-seq:
* Map.dup => new_map
*
* Duplicates this map with a shallow copy. References to all non-primitive
* element objects (e.g., submessages) are shared.
*/
@JRubyMethod
public IRubyObject dup(ThreadContext context) {
RubyMap newMap = newThisType(context);
for (Map.Entry<IRubyObject, IRubyObject> entry : table.entrySet()) {
newMap.table.put(entry.getKey(), entry.getValue());
}
return newMap;
}
@JRubyMethod(name = "to_h")
public RubyHash toHash(ThreadContext context) {
Map<IRubyObject, IRubyObject> mapForHash = new HashMap();
table.forEach(
(key, value) -> {
if (!value.isNil()) {
if (value.respondsTo("to_h")) {
value = Helpers.invoke(context, value, "to_h");
} else if (value.respondsTo("to_a")) {
value = Helpers.invoke(context, value, "to_a");
}
mapForHash.put(key, value);
}
});
return RubyHash.newHash(context.runtime, mapForHash, context.nil);
}
@JRubyMethod
public IRubyObject freeze(ThreadContext context) {
if (isFrozen()) {
return this;
}
setFrozen(true);
if (valueType == FieldDescriptor.Type.MESSAGE) {
for (IRubyObject key : table.keySet()) {
((RubyMessage) table.get(key)).freeze(context);
}
}
return this;
}
// Used by Google::Protobuf.deep_copy but not exposed directly.
protected IRubyObject deepCopy(ThreadContext context) {
RubyMap newMap = newThisType(context);
switch (valueType) {
case MESSAGE:
for (IRubyObject key : table.keySet()) {
RubyMessage message = (RubyMessage) table.get(key);
newMap.table.put(key.dup(), message.deepCopy(context));
}
break;
default:
for (IRubyObject key : table.keySet()) {
newMap.table.put(key.dup(), table.get(key).dup());
}
}
return newMap;
}
protected List<DynamicMessage> build(
ThreadContext context, RubyDescriptor descriptor, int depth, int recursionLimit) {
List<DynamicMessage> list = new ArrayList<DynamicMessage>();
RubyClass rubyClass = (RubyClass) descriptor.msgclass(context);
FieldDescriptor keyField = descriptor.getField("key");
FieldDescriptor valueField = descriptor.getField("value");
for (IRubyObject key : table.keySet()) {
RubyMessage mapMessage = (RubyMessage) rubyClass.newInstance(context, Block.NULL_BLOCK);
mapMessage.setField(context, keyField, key);
mapMessage.setField(context, valueField, table.get(key));
list.add(mapMessage.build(context, depth + 1, recursionLimit));
}
return list;
}
protected RubyMap mergeIntoSelf(final ThreadContext context, IRubyObject hashmap) {
if (hashmap instanceof RubyHash) {
((RubyHash) hashmap)
.visitAll(
context,
new RubyHash.Visitor() {
@Override
public void visit(IRubyObject key, IRubyObject val) {
if (val instanceof RubyHash && !valueTypeClass.isNil()) {
val = ((RubyClass) valueTypeClass).newInstance(context, val, Block.NULL_BLOCK);
}
indexSet(context, key, val);
}
},
null);
} else if (hashmap instanceof RubyMap) {
RubyMap other = (RubyMap) hashmap;
if (!typeCompatible(other)) {
throw Utils.createTypeError(context, "Attempt to merge Map with mismatching types");
}
} else {
throw Utils.createTypeError(context, "Unknown type merging into Map");
}
return this;
}
protected boolean typeCompatible(RubyMap other) {
return this.keyType == other.keyType
&& this.valueType == other.valueType
&& this.valueTypeClass == other.valueTypeClass;
}
private RubyMap newThisType(ThreadContext context) {
RubyMap newMap;
if (needTypeclass(valueType)) {
newMap =
(RubyMap)
metaClass.newInstance(
context,
Utils.fieldTypeToRuby(context, keyType),
Utils.fieldTypeToRuby(context, valueType),
valueTypeClass,
Block.NULL_BLOCK);
} else {
newMap =
(RubyMap)
metaClass.newInstance(
context,
Utils.fieldTypeToRuby(context, keyType),
Utils.fieldTypeToRuby(context, valueType),
Block.NULL_BLOCK);
}
newMap.table = new HashMap<IRubyObject, IRubyObject>();
return newMap;
}
/*
* toHash calls toHash on values, for some camparisons we only need
* a hash with the original objects still as values
*/
private RubyHash singleLevelHash(ThreadContext context) {
return RubyHash.newHash(context.runtime, table, context.nil);
}
private boolean needTypeclass(FieldDescriptor.Type type) {
switch (type) {
case MESSAGE:
case ENUM:
return true;
default:
return false;
}
}
private FieldDescriptor.Type keyType;
private FieldDescriptor.Type valueType;
private IRubyObject valueTypeClass;
private Map<IRubyObject, IRubyObject> table;
private boolean keyTypeIsString = false;
}
| protocolbuffers/protobuf | ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java |
112 | /*
* Copyright (C) 2015 Square, 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.
*/
package retrofit2;
import static retrofit2.Utils.throwIfFatal;
import java.io.IOException;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Timeout;
final class OkHttpCall<T> implements Call<T> {
private final RequestFactory requestFactory;
private final Object instance;
private final Object[] args;
private final okhttp3.Call.Factory callFactory;
private final Converter<ResponseBody, T> responseConverter;
private volatile boolean canceled;
@GuardedBy("this")
private @Nullable okhttp3.Call rawCall;
@GuardedBy("this") // Either a RuntimeException, non-fatal Error, or IOException.
private @Nullable Throwable creationFailure;
@GuardedBy("this")
private boolean executed;
OkHttpCall(
RequestFactory requestFactory,
Object instance,
Object[] args,
okhttp3.Call.Factory callFactory,
Converter<ResponseBody, T> responseConverter) {
this.requestFactory = requestFactory;
this.instance = instance;
this.args = args;
this.callFactory = callFactory;
this.responseConverter = responseConverter;
}
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
@Override
public OkHttpCall<T> clone() {
return new OkHttpCall<>(requestFactory, instance, args, callFactory, responseConverter);
}
@Override
public synchronized Request request() {
try {
return getRawCall().request();
} catch (IOException e) {
throw new RuntimeException("Unable to create request.", e);
}
}
@Override
public synchronized Timeout timeout() {
try {
return getRawCall().timeout();
} catch (IOException e) {
throw new RuntimeException("Unable to create call.", e);
}
}
/**
* Returns the raw call, initializing it if necessary. Throws if initializing the raw call throws,
* or has thrown in previous attempts to create it.
*/
@GuardedBy("this")
private okhttp3.Call getRawCall() throws IOException {
okhttp3.Call call = rawCall;
if (call != null) return call;
// Re-throw previous failures if this isn't the first attempt.
if (creationFailure != null) {
if (creationFailure instanceof IOException) {
throw (IOException) creationFailure;
} else if (creationFailure instanceof RuntimeException) {
throw (RuntimeException) creationFailure;
} else {
throw (Error) creationFailure;
}
}
// Create and remember either the success or the failure.
try {
return rawCall = createRawCall();
} catch (RuntimeException | Error | IOException e) {
throwIfFatal(e); // Do not assign a fatal error to creationFailure.
creationFailure = e;
throw e;
}
}
@Override
public void enqueue(final Callback<T> callback) {
Objects.requireNonNull(callback, "callback == null");
okhttp3.Call call;
Throwable failure;
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
call = rawCall;
failure = creationFailure;
if (call == null && failure == null) {
try {
call = rawCall = createRawCall();
} catch (Throwable t) {
throwIfFatal(t);
failure = creationFailure = t;
}
}
}
if (failure != null) {
callback.onFailure(this, failure);
return;
}
if (canceled) {
call.cancel();
}
call.enqueue(
new okhttp3.Callback() {
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
Response<T> response;
try {
response = parseResponse(rawResponse);
} catch (Throwable e) {
throwIfFatal(e);
callFailure(e);
return;
}
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
throwIfFatal(t);
t.printStackTrace(); // TODO this is not great
}
}
@Override
public void onFailure(okhttp3.Call call, IOException e) {
callFailure(e);
}
private void callFailure(Throwable e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
throwIfFatal(t);
t.printStackTrace(); // TODO this is not great
}
}
});
}
@Override
public synchronized boolean isExecuted() {
return executed;
}
@Override
public Response<T> execute() throws IOException {
okhttp3.Call call;
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
call = getRawCall();
}
if (canceled) {
call.cancel();
}
return parseResponse(call.execute());
}
private okhttp3.Call createRawCall() throws IOException {
okhttp3.Call call = callFactory.newCall(requestFactory.create(instance, args));
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
ResponseBody rawBody = rawResponse.body();
// Remove the body's source (the only stateful object) so we can pass the response along.
rawResponse =
rawResponse
.newBuilder()
.body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
.build();
int code = rawResponse.code();
if (code < 200 || code >= 300) {
try {
// Buffer the entire body to avoid future I/O.
ResponseBody bufferedBody = Utils.buffer(rawBody);
return Response.error(bufferedBody, rawResponse);
} finally {
rawBody.close();
}
}
if (code == 204 || code == 205) {
rawBody.close();
return Response.success(null, rawResponse);
}
ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
try {
T body = responseConverter.convert(catchingBody);
return Response.success(body, rawResponse);
} catch (RuntimeException e) {
// If the underlying source threw an exception, propagate that rather than indicating it was
// a runtime exception.
catchingBody.throwIfCaught();
throw e;
}
}
@Override
public void cancel() {
canceled = true;
okhttp3.Call call;
synchronized (this) {
call = rawCall;
}
if (call != null) {
call.cancel();
}
}
@Override
public boolean isCanceled() {
if (canceled) {
return true;
}
synchronized (this) {
return rawCall != null && rawCall.isCanceled();
}
}
static final class NoContentResponseBody extends ResponseBody {
private final @Nullable MediaType contentType;
private final long contentLength;
NoContentResponseBody(@Nullable MediaType contentType, long contentLength) {
this.contentType = contentType;
this.contentLength = contentLength;
}
@Override
public MediaType contentType() {
return contentType;
}
@Override
public long contentLength() {
return contentLength;
}
@Override
public BufferedSource source() {
throw new IllegalStateException("Cannot read raw response body of a converted body.");
}
}
static final class ExceptionCatchingResponseBody extends ResponseBody {
private final ResponseBody delegate;
private final BufferedSource delegateSource;
@Nullable IOException thrownException;
ExceptionCatchingResponseBody(ResponseBody delegate) {
this.delegate = delegate;
this.delegateSource =
Okio.buffer(
new ForwardingSource(delegate.source()) {
@Override
public long read(Buffer sink, long byteCount) throws IOException {
try {
return super.read(sink, byteCount);
} catch (IOException e) {
thrownException = e;
throw e;
}
}
});
}
@Override
public MediaType contentType() {
return delegate.contentType();
}
@Override
public long contentLength() {
return delegate.contentLength();
}
@Override
public BufferedSource source() {
return delegateSource;
}
@Override
public void close() {
delegate.close();
}
void throwIfCaught() throws IOException {
if (thrownException != null) {
throw thrownException;
}
}
}
}
| square/retrofit | retrofit/src/main/java/retrofit2/OkHttpCall.java |
113 | /*
* Copyright (C) 2007 The Guava 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.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Platform.getDeclaringClassOrObjectForJ2cl;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.EnumMap;
import java.util.Map;
/**
* A {@code BiMap} backed by two {@code EnumMap} instances. Null keys and values are not permitted.
* An {@code EnumBiMap} and its inverse are both serializable.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap">{@code BiMap}</a>.
*
* @author Mike Bostock
* @since 2.0
*/
@GwtCompatible(emulated = true)
@J2ktIncompatible
@ElementTypesAreNonnullByDefault
public final class EnumBiMap<K extends Enum<K>, V extends Enum<V>> extends AbstractBiMap<K, V> {
/*
* J2CL's EnumMap does not need the Class instance, so we can use Object.class instead. (Or we
* could use null, but that messes with our nullness checking, including under J2KT. We could
* probably work around it by changing how we annotate the J2CL EnumMap, but that's probably more
* trouble than just using Object.class.)
*
* Then we declare the getters for these fields as @GwtIncompatible so that no one can try to use
* them under J2CL—or, as an unfortunate side effect, under GWT. We do still give the fields
* themselves their proper values under GWT, since GWT's EnumMap does need the Class instance.
*
* Note that sometimes these fields *do* have correct values under J2CL: They will if the caller
* calls `create(Foo.class)`, rather than `create(map)`. That's fine; we just shouldn't rely on
* it.
*/
transient Class<K> keyTypeOrObjectUnderJ2cl;
transient Class<V> valueTypeOrObjectUnderJ2cl;
/**
* Returns a new, empty {@code EnumBiMap} using the specified key and value types.
*
* @param keyType the key type
* @param valueType the value type
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(
Class<K> keyType, Class<V> valueType) {
return new EnumBiMap<>(keyType, valueType);
}
/**
* Returns a new bimap with the same mappings as the specified map. If the specified map is an
* {@code EnumBiMap}, the new bimap has the same types as the provided map. Otherwise, the
* specified map must contain at least one mapping, in order to determine the key and value types.
*
* @param map the map whose mappings are to be placed in this map
* @throws IllegalArgumentException if map is not an {@code EnumBiMap} instance and contains no
* mappings
*/
public static <K extends Enum<K>, V extends Enum<V>> EnumBiMap<K, V> create(Map<K, V> map) {
EnumBiMap<K, V> bimap =
create(inferKeyTypeOrObjectUnderJ2cl(map), inferValueTypeOrObjectUnderJ2cl(map));
bimap.putAll(map);
return bimap;
}
private EnumBiMap(Class<K> keyTypeOrObjectUnderJ2cl, Class<V> valueTypeOrObjectUnderJ2cl) {
super(
new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
this.keyTypeOrObjectUnderJ2cl = keyTypeOrObjectUnderJ2cl;
this.valueTypeOrObjectUnderJ2cl = valueTypeOrObjectUnderJ2cl;
}
static <K extends Enum<K>> Class<K> inferKeyTypeOrObjectUnderJ2cl(Map<K, ?> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
}
if (map instanceof EnumHashBiMap) {
return ((EnumHashBiMap<K, ?>) map).keyTypeOrObjectUnderJ2cl;
}
checkArgument(!map.isEmpty());
return getDeclaringClassOrObjectForJ2cl(map.keySet().iterator().next());
}
private static <V extends Enum<V>> Class<V> inferValueTypeOrObjectUnderJ2cl(Map<?, V> map) {
if (map instanceof EnumBiMap) {
return ((EnumBiMap<?, V>) map).valueTypeOrObjectUnderJ2cl;
}
checkArgument(!map.isEmpty());
return getDeclaringClassOrObjectForJ2cl(map.values().iterator().next());
}
/** Returns the associated key type. */
@GwtIncompatible
public Class<K> keyType() {
return keyTypeOrObjectUnderJ2cl;
}
/** Returns the associated value type. */
@GwtIncompatible
public Class<V> valueType() {
return valueTypeOrObjectUnderJ2cl;
}
@Override
K checkKey(K key) {
return checkNotNull(key);
}
@Override
V checkValue(V value) {
return checkNotNull(value);
}
/**
* @serialData the key class, value class, number of entries, first key, first value, second key,
* second value, and so on.
*/
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(keyTypeOrObjectUnderJ2cl);
stream.writeObject(valueTypeOrObjectUnderJ2cl);
Serialization.writeMap(this, stream);
}
@SuppressWarnings("unchecked") // reading fields populated by writeObject
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
keyTypeOrObjectUnderJ2cl = (Class<K>) requireNonNull(stream.readObject());
valueTypeOrObjectUnderJ2cl = (Class<V>) requireNonNull(stream.readObject());
setDelegates(
new EnumMap<K, V>(keyTypeOrObjectUnderJ2cl), new EnumMap<V, K>(valueTypeOrObjectUnderJ2cl));
Serialization.populateMap(this, stream);
}
@GwtIncompatible // not needed in emulated source.
private static final long serialVersionUID = 0;
}
| google/guava | android/guava/src/com/google/common/collect/EnumBiMap.java |
114 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import org.openqa.selenium.internal.Require;
/**
* Mechanism used to locate elements within a document. In order to create your own locating
* mechanisms, it is possible to subclass this class and override the protected methods as required,
* though it is expected that all subclasses rely on the basic finding mechanisms provided through
* static methods of this class:
*
* <pre><code>
* public WebElement findElement(WebDriver driver) {
* WebElement element = driver.findElement(By.id(getSelector()));
* if (element == null)
* element = driver.findElement(By.name(getSelector());
* return element;
* }
* </code></pre>
*/
public abstract class By {
/**
* @param id The value of the "id" attribute to search for.
* @return A By which locates elements by the value of the "id" attribute.
*/
public static By id(String id) {
return new ById(id);
}
/**
* @param linkText The exact text to match against.
* @return A By which locates A elements by the exact text it displays.
*/
public static By linkText(String linkText) {
return new ByLinkText(linkText);
}
/**
* @param partialLinkText The partial text to match against
* @return a By which locates elements that contain the given link text.
*/
public static By partialLinkText(String partialLinkText) {
return new ByPartialLinkText(partialLinkText);
}
/**
* @param name The value of the "name" attribute to search for.
* @return A By which locates elements by the value of the "name" attribute.
*/
public static By name(String name) {
return new ByName(name);
}
/**
* @param tagName The element's tag name.
* @return A By which locates elements by their tag name.
*/
public static By tagName(String tagName) {
return new ByTagName(tagName);
}
/**
* @param xpathExpression The XPath to use.
* @return A By which locates elements via XPath.
*/
public static By xpath(String xpathExpression) {
return new ByXPath(xpathExpression);
}
/**
* Find elements based on the value of the "class" attribute. Only one class name should be used.
* If an element has multiple classes, please use {@link By#cssSelector(String)}.
*
* @param className The value of the "class" attribute to search for.
* @return A By which locates elements by the value of the "class" attribute.
*/
public static By className(String className) {
return new ByClassName(className);
}
/**
* Find elements via the driver's underlying W3C Selector engine. If the browser does not
* implement the Selector API, the best effort is made to emulate the API. In this case, we strive
* for at least CSS2 support, but offer no guarantees.
*
* @param cssSelector CSS expression.
* @return A By which locates elements by CSS.
*/
public static By cssSelector(String cssSelector) {
return new ByCssSelector(cssSelector);
}
/**
* Find a single element. Override this method if necessary.
*
* @param context A context to use to find the element.
* @return The WebElement that matches the selector.
*/
public WebElement findElement(SearchContext context) {
List<WebElement> allElements = findElements(context);
if (allElements == null || allElements.isEmpty()) {
throw new NoSuchElementException("Cannot locate an element using " + toString());
}
return allElements.get(0);
}
/**
* Find many elements.
*
* @param context A context to use to find the elements.
* @return A list of WebElements matching the selector.
*/
public abstract List<WebElement> findElements(SearchContext context);
protected WebDriver getWebDriver(SearchContext context) {
if (context instanceof WebDriver) {
return (WebDriver) context;
}
if (!(context instanceof WrapsDriver)) {
throw new IllegalArgumentException("Context does not wrap a webdriver: " + context);
}
return ((WrapsDriver) context).getWrappedDriver();
}
protected JavascriptExecutor getJavascriptExecutor(SearchContext context) {
WebDriver driver = getWebDriver(context);
if (!(context instanceof JavascriptExecutor)) {
throw new IllegalArgumentException(
"Context does not provide a mechanism to execute JS: " + context);
}
return (JavascriptExecutor) driver;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof By)) {
return false;
}
By that = (By) o;
return this.toString().equals(that.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
// A stub to prevent endless recursion in hashCode()
return "[unknown locator]";
}
public static class ById extends PreW3CLocator {
private final String id;
public ById(String id) {
super(
"id", Require.argument("Id", id).nonNull("Cannot find elements when id is null."), "#%s");
this.id = id;
}
@Override
public String toString() {
return "By.id: " + id;
}
}
public static class ByLinkText extends BaseW3CLocator {
private final String linkText;
public ByLinkText(String linkText) {
super(
"link text",
Require.argument("Link text", linkText)
.nonNull("Cannot find elements when the link text is null."));
this.linkText = linkText;
}
@Override
public String toString() {
return "By.linkText: " + linkText;
}
}
public static class ByPartialLinkText extends BaseW3CLocator {
private final String partialLinkText;
public ByPartialLinkText(String partialLinkText) {
super(
"partial link text",
Require.argument("Partial link text", partialLinkText)
.nonNull("Cannot find elements when the link text is null."));
this.partialLinkText = partialLinkText;
}
@Override
public String toString() {
return "By.partialLinkText: " + partialLinkText;
}
}
public static class ByName extends PreW3CLocator {
private final String name;
public ByName(String name) {
super(
"name",
Require.argument("Name", name).nonNull("Cannot find elements when name text is null."),
String.format("*[name='%s']", name.replace("'", "\\'")));
this.name = name;
}
@Override
public String toString() {
return "By.name: " + name;
}
}
public static class ByTagName extends BaseW3CLocator {
private final String tagName;
public ByTagName(String tagName) {
super(
"tag name",
Require.argument("Tag name", tagName)
.nonNull("Cannot find elements when the tag name is null."));
if (tagName.isEmpty()) {
throw new InvalidSelectorException("Tag name must not be blank");
}
this.tagName = tagName;
}
@Override
public String toString() {
return "By.tagName: " + tagName;
}
}
public static class ByXPath extends BaseW3CLocator {
private final String xpathExpression;
public ByXPath(String xpathExpression) {
super(
"xpath",
Require.argument("XPath", xpathExpression)
.nonNull("Cannot find elements when the XPath is null."));
this.xpathExpression = xpathExpression;
}
@Override
public String toString() {
return "By.xpath: " + xpathExpression;
}
}
public static class ByClassName extends PreW3CLocator {
private final String className;
public ByClassName(String className) {
super(
"class name",
Require.argument("Class name", className)
.nonNull("Cannot find elements when the class name expression is null."),
".%s");
if (className.matches(".*\\s.*")) {
throw new InvalidSelectorException("Compound class names not permitted");
}
this.className = className;
}
@Override
public String toString() {
return "By.className: " + className;
}
}
public static class ByCssSelector extends BaseW3CLocator {
private final String cssSelector;
public ByCssSelector(String cssSelector) {
super(
"css selector",
Require.argument("CSS selector", cssSelector)
.nonNull("Cannot find elements when the selector is null"));
this.cssSelector = cssSelector;
}
@Override
public String toString() {
return "By.cssSelector: " + cssSelector;
}
}
public interface Remotable {
Parameters getRemoteParameters();
class Parameters {
private final String using;
private final Object value;
public Parameters(String using, Object value) {
this.using = Require.nonNull("Search mechanism", using);
// There may be subclasses where the value is optional. Allow for this.
this.value = value;
}
public String using() {
return using;
}
public Object value() {
return value;
}
@Override
public String toString() {
return "[" + using + ": " + value + "]";
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Parameters)) {
return false;
}
Parameters that = (Parameters) o;
return using.equals(that.using) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(using, value);
}
private Map<String, Object> toJson() {
Map<String, Object> params = new HashMap<>();
params.put("using", using);
params.put("value", value);
return Collections.unmodifiableMap(params);
}
}
}
private abstract static class BaseW3CLocator extends By implements Remotable {
private final Parameters params;
protected BaseW3CLocator(String using, String value) {
this.params = new Parameters(using, value);
}
@Override
public WebElement findElement(SearchContext context) {
Require.nonNull("Search Context", context);
return context.findElement(this);
}
@Override
public List<WebElement> findElements(SearchContext context) {
Require.nonNull("Search Context", context);
return context.findElements(this);
}
@Override
public final Parameters getRemoteParameters() {
return params;
}
protected final Map<String, Object> toJson() {
return getRemoteParameters().toJson();
}
}
private abstract static class PreW3CLocator extends By implements Remotable {
private static final Pattern CSS_ESCAPE =
Pattern.compile("([\\s'\"\\\\#.:;,!?+<>=~*^$|%&@`{}\\-\\/\\[\\]\\(\\)])");
private final Parameters remoteParams;
private final ByCssSelector fallback;
private PreW3CLocator(String using, String value, String formatString) {
this.remoteParams = new Remotable.Parameters(using, value);
this.fallback = new ByCssSelector(String.format(formatString, cssEscape(value)));
}
@Override
public WebElement findElement(SearchContext context) {
return context.findElement(fallback);
}
@Override
public List<WebElement> findElements(SearchContext context) {
return context.findElements(fallback);
}
@Override
public final Parameters getRemoteParameters() {
return remoteParams;
}
protected final Map<String, Object> toJson() {
return fallback.toJson();
}
private String cssEscape(String using) {
using = CSS_ESCAPE.matcher(using).replaceAll("\\\\$1");
if (!using.isEmpty() && Character.isDigit(using.charAt(0))) {
using = "\\" + (30 + Integer.parseInt(using.substring(0, 1))) + " " + using.substring(1);
}
return using;
}
}
}
| SeleniumHQ/selenium | java/src/org/openqa/selenium/By.java |
115 | // Companion Code to the paper "Generative Forests" by R. Nock and M. Guillame-Bert.
import java.io.*;
import java.util.*;
class Wrapper implements Debuggable {
public static boolean FAST_SPLITTING = true;
public static String BOTH_IMPUTE_FILES = "BOTH_IMPUTE_FILES",
IMPUTE_CSV = "IMPUTE_CSV",
IMPUTE_TXT = "IMPUTE_TXT";
public static String DATASET = "--dataset=",
DATASET_SPEC = "--dataset_spec=",
DATASET_TEST = "--dataset_test=",
NUM_SAMPLES = "--num_samples=",
WORK_DIR = "--work_dir=",
OUTPUT_SAMPLES = "--output_samples=",
OUTPUT_STATS = "--output_stats=",
FLAGS = "--flags",
HELP = "--help",
IMPUTE_MISSING = "--impute_missing=",
DENSITY_ESTIMATION = "--density_estimation=",
PLOT_LABELS = "--plot_labels=";
public static String ALGORITHM_CATEGORY = "--algorithm_category=";
public static String[] ALL_FLAGS = {
"iterations",
"unknown_value_coding",
"force_integer_coding",
"force_binary_coding",
"initial_number_of_trees",
"splitting_method",
"type_of_generative_model",
"plot_type",
"imputation_method"
};
public static String GENERATIVE_FOREST = "generative_forest",
ENSEMBLE_OF_GENERATIVE_TREES = "ensemble_of_generative_trees",
TRY_THEM_ALL = "try_all";
public static String PLOT_TYPE_ALL = "all", PLOT_TYPE_DATA = "data";
public static String BOOSTING = "boosting";
public static String IMPUTATION_AT_THE_MAX = "at_max_density",
IMPUTATION_SAMPLING_DENSITY = "sampling_density";
public static String[] TYPE_OF_GENERATIVE_MODEL = {
GENERATIVE_FOREST, ENSEMBLE_OF_GENERATIVE_TREES, TRY_THEM_ALL
};
public static String[] TYPE_OF_SPLITTING_METHOD = {BOOSTING};
public static String[] TYPE_OF_IMPUTATION = {
IMPUTATION_AT_THE_MAX, IMPUTATION_SAMPLING_DENSITY, TRY_THEM_ALL
};
public static void CHECK_IMPUTATION_METHOD(String s) {
int i = 0;
do {
if (TYPE_OF_IMPUTATION[i].equals(s)) return;
else i++;
} while (i < TYPE_OF_IMPUTATION.length);
Dataset.perror("Wrapper.class :: no imputation method named " + s);
}
public static void CHECK_SPLITTING_METHOD(String s) {
int i = 0;
do {
if (TYPE_OF_SPLITTING_METHOD[i].equals(s)) return;
else i++;
} while (i < TYPE_OF_SPLITTING_METHOD.length);
Dataset.perror("Wrapper.class :: no splitting method named " + s);
}
public static void CHECK_GENERATIVE_MODEL(String s) {
int i = 0;
do {
if (TYPE_OF_GENERATIVE_MODEL[i].equals(s)) return;
else i++;
} while (i < TYPE_OF_GENERATIVE_MODEL.length);
Dataset.perror("Wrapper.class :: no generative model named " + s);
}
public int INDEX_OF(String s) {
int i = 0;
do {
if (s.equals(TYPE_OF_GENERATIVE_MODEL[i])) return i;
else i++;
} while (i < TYPE_OF_GENERATIVE_MODEL.length);
Dataset.perror("Wrapper.class :: no such use of generative model as " + s);
return -1;
}
// all flag names recognized in command line in --flags = {"name" : value, ...}
// unknown_value_coding: String = enforces an "unknown value" different from default
// force_integer_coding: boolean = if true, enforce integer coding of observation variables
// recognizable as integers ("cleaner" GT)
// generative_forest = if true, the set of trees is used as generative_forest, otherwise as
// ensemble_of_generative_trees
public static int ALL_FLAGS_INDEX_ITERATIONS = 0,
ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING = 1,
ALL_FLAGS_FORCE_INTEGER_CODING = 2,
ALL_FLAGS_FORCE_BINARY_CODING = 3,
ALL_FLAGS_INDEX_INITIAL_NUMBER_OF_TREES = 4,
ALL_FLAGS_SPLITTING_METHOD = 5,
ALL_FLAGS_TYPE_OF_GENERATIVE_MODEL = 6,
ALL_FLAGS_PLOT_TYPE = 7,
ALL_FLAGS_IMPUTATION_METHOD = 8;
public static String[] DATASET_TOKENS = {
"\"name\":", "\"path\":", "\"label\":", "\"task\":"
}; // spec_name, spec_path, spec_label, spec_task
public static String PREFIX_GENERATOR = "generator_";
public String path_and_name_of_domain_dataset,
path_and_name_of_test_dataset = null,
path_name_test = null,
path_to_generated_samples,
working_directory,
blueprint_save_name,
spec_name,
prefix_domain,
spec_path,
spec_label,
spec_task,
output_stats_file,
output_stats_directory,
generator_filename,
token_save_string,
type_of_generative_model = Wrapper.GENERATIVE_FOREST,
splitting_method = Wrapper.BOOSTING,
plot_type = Wrapper.PLOT_TYPE_DATA,
imputation_type = Wrapper.IMPUTATION_AT_THE_MAX;
// spec_name = prefix name
public String[] flags_values;
int size_generated, number_iterations; // was nums
// int index_x_name, index_y_name;
int[] plot_labels_indexes;
String[] plot_labels_names;
String[][] densityplot_filename,
frontierplot_filename,
jointdensityplot_filename,
domaindensityplot_filename,
generateddatadensityplot_filename,
imputeddataplot_token;
int algorithm_category, initial_nb_of_trees;
Algorithm myAlgos;
Domain myDomain;
boolean force_integer_coding = false,
force_binary_coding = true,
impute_missing = false,
density_estimation = false,
has_missing_values,
generative_forest = true;
long loading_time,
gt_computation_time,
marginal_computation_time,
saving_generator_time,
saving_stats_time,
generate_observations_time,
saving_generated_sample_time,
saving_density_plot_generated_sample_time,
imputation_time,
density_estimation_time;
Wrapper() {
flags_values = new String[ALL_FLAGS.length];
size_generated = number_iterations = algorithm_category = -1;
densityplot_filename =
frontierplot_filename =
jointdensityplot_filename =
domaindensityplot_filename = generateddatadensityplot_filename = null;
token_save_string = null;
plot_labels_names = null;
plot_labels_indexes = null;
path_and_name_of_domain_dataset = spec_path = null;
loading_time =
gt_computation_time =
marginal_computation_time =
saving_generator_time =
saving_stats_time =
generate_observations_time =
saving_generated_sample_time =
saving_density_plot_generated_sample_time = 0;
has_missing_values = false;
}
public static String help() {
String ret = "";
ret += "Example run\n";
ret += "Java Wrapper --dataset=${ANYDIR}/Datasets/iris/iris.csv\n";
ret +=
" '--dataset_spec={\"name\": \"iris\", \"path\":"
+ " \"${ANYDIR}/Datasets/iris/iris.csv\", \"label\": \"class\", \"task\":"
+ " \"BINARY_CLASSIFICATION\"}'\n";
ret += " --num_samples=1000 \n";
ret += " --work_dir=${ANYDIR}/Datasets/iris/working_dir \n";
ret +=
" "
+ " --output_samples=${ANYDIR}/Datasets/iris/output_samples/iris_geot_generated.csv\n";
ret +=
" --output_stats=${ANYDIR}/Datasets/iris/results/generated_observations.stats"
+ " \n";
ret += " '--plot_labels={\"Sepal.Length\",\"Sepal.Width\"}' \n";
ret +=
" '--flags={\"iterations\" : \"10\", \"force_integer_coding\" : \"true\","
+ " \"force_binary_coding\" : \"true\", \"unknown_value_coding\" : \"NA\","
+ " \"initial_number_of_trees\" : \"2\", \"splitting_method\" : \"boosting\","
+ " \"type_of_generative_model\" : \"try_all\"}'\n";
ret += " --impute_missing=true\n\n";
ret += " --dataset: path to access the.csv data file containing variable names in first line\n";
ret +=
" --dataset_test: path to access the.csv data file containing the test dataset (for density"
+ " estimation)\n";
ret += " --dataset_spec: self explanatory\n";
ret += " --num_samples: number of generated observations\n";
ret += " --work_dir: directory where the generative models and density plots are saved\n";
ret += " --output_samples: generated samples filename\n";
ret +=
" --output_stats: file to store all data related to run (execution times, node stats in"
+ " tree(s), etc)\n";
ret +=
" --plot_labels: (optional) variables used to save 2D plots of (i) frontiers, (ii) density"
+ " learned, (iii) domain density\n";
ret +=
" use >= 2 features, CONTINUOUS only & small dims / domain size for"
+ " efficient computation (otherwise, can be very long)\n";
ret += " --flags: flags...\n";
ret += " iterations (mandatory): integer; number of *global* boosting iterations\n";
ret +=
" force_integer_coding (optional): boolean; if true, recognizes integer variables"
+ " and codes them as such (otherwise, codes them as doubles) -- default: false\n";
ret +=
" force_binary_coding (optional): boolean; if true, recognizes 0/1/unknown"
+ " variables and codes them as nominal, otherwise treat them as integers or doubles --"
+ " default: true\n";
ret +=
" unknown_value_coding (optional): String; representation of 'unknown' value in"
+ " dataset -- default: \"-1\"\n";
ret += " initial_number_of_trees (mandatory): integer; number of trees in the model\n";
ret += " splitting_method (mandatory): String in {\"boosting\", \"random\"}\n";
ret +=
" method used to split nodes among two possible:\n";
ret +=
" boosting : use boost using methods described"
+ " in the draft\n";
ret += " random : random splits\n";
ret +=
" type_of_generative_model (mandatory): String in {\"generative_forest\","
+ " \"ensemble_of_generative_trees\", \"try_all\"}\n";
ret +=
" what kind of generative model learned /"
+ " used among three possible:\n";
ret +=
" generative_forest : generative ensemble"
+ " of trees (uses training sample to compute probabilities)\n";
ret +=
" ensemble_of_generative_trees : ensemble"
+ " of generative trees (uses only generative trees w/ probabilities at the arcs)\n";
ret += " try_all : loop over both types\n";
ret += " plot_type (optional): String in {\"all\", \"data\"}\n";
ret +=
" plotting types (if variables specified with"
+ " plot_labels):\n";
ret +=
" all : maximum # of plots (domain, generated,"
+ " frontiers of density learned, density learned) -- can be time consuming\n";
ret +=
" data : only domain and generated data plots (if"
+ " available)\n";
ret +=
" imputation_method (optional): String in {\"at_max_density\","
+ " \"using_distribution\"}\n";
ret +=
" method used to impute data based on generative"
+ " model\n";
ret +=
" at_max_density : imputes at peak density"
+ " conditioned to missing features\n";
ret +=
" sampling_density : imputes by sampling"
+ " density conditioned to missing features\n";
ret += " try_all : loop over both types\n";
ret +=
" --impute_missing: if true, uses the generated tree to impute the missing values in the"
+ " training data\n\n";
ret +=
" --density_estimation: if true, performs density estimation at each step of training,"
+ " using the dataset dataset_test.csv \n\n";
ret +=
" * warning * : parameters may be included in file names to facilitate identification of"
+ " training parameters, on the form of a token SW_IX_TY_GEOTZ\n";
ret +=
" W in {0,1} = 1 iff split type is boosting, X = # iterations, Y = # trees, Z"
+ " in {0,1} = 1 iff generative ensemble of trees learned / used\n";
return ret;
}
public static String DUMS =
"////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////";
public static String FILL(String s) {
String basics = "// Training GF / EOGT () //";
int i;
String ret = "";
for (i = 0; i < s.length() - basics.length() - History.CURRENT_HISTORY().length() - 1; i++)
ret += " ";
return ret;
}
public static void main(String[] arg) {
int i, j;
Wrapper w = new Wrapper();
System.out.println("");
System.out.println(Wrapper.DUMS);
System.out.println(
"// Training GF / EOGT (" + History.CURRENT_HISTORY() + ") " + FILL(Wrapper.DUMS) + " //");
System.out.println(
"// "
+ " //");
if (arg.length == 0) {
System.out.println("// *No parameters*. Run 'java Wrapper --help' for more");
System.exit(0);
}
System.out.println(
"// Help & observation run: 'java Wrapper --help' "
+ " //");
System.out.println(
"////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////");
for (i = 0; i < arg.length; i++) {
if (arg[i].equals(HELP)) {
System.out.println(help());
System.exit(0);
}
w.fit_vars(arg[i]);
}
w.summary();
w.simple_go();
}
public void simple_go() {
long b, e;
int i;
Vector<Observation> v_gen = null;
GenerativeModelBasedOnEnsembleOfTrees geot;
boolean try_model;
String which_model = "dummy", prefix_output_stats_file = output_stats_file;
System.out.print("Loading stuff start... ");
b = System.currentTimeMillis();
myDomain = new Domain(this);
e = System.currentTimeMillis();
loading_time = e - b;
System.out.println("Loading stuff ok (time elapsed: " + loading_time + " ms).\n");
if ((density_estimation)
&& ((path_and_name_of_test_dataset == null) || (path_and_name_of_test_dataset.equals(""))))
Dataset.perror("Wrapper.class :: density estimation but no test dataset");
for (i = 0; i <= 1; i++) {
try_model = false;
if ((i == 0)
&& ((type_of_generative_model.equals(Wrapper.GENERATIVE_FOREST))
|| (type_of_generative_model.equals(Wrapper.TRY_THEM_ALL)))) {
myAlgos =
new Algorithm(
myDomain.myDS, 0, number_iterations, initial_nb_of_trees, splitting_method, true);
which_model = "GF";
try_model = true;
} else if ((i == 1)
&& ((type_of_generative_model.equals(Wrapper.ENSEMBLE_OF_GENERATIVE_TREES))
|| (type_of_generative_model.equals(Wrapper.TRY_THEM_ALL)))) {
myAlgos =
new Algorithm(
myDomain.myDS, 0, number_iterations, initial_nb_of_trees, splitting_method, false);
which_model = "EOGT";
try_model = true;
}
if (try_model) {
System.out.print("Learning the generator... ");
b = System.currentTimeMillis();
geot = myAlgos.learn_geot();
e = System.currentTimeMillis();
gt_computation_time = e - b;
System.out.println("ok (time elapsed: " + gt_computation_time + " ms).\n\n");
System.out.println(which_model + " used:\n " + geot);
token_save_string =
"_S"
+ ((splitting_method.equals(Wrapper.BOOSTING)) ? 1 : 0)
+ "_I"
+ number_iterations
+ "_T"
+ initial_nb_of_trees
+ "_GEOT"
+ ((geot.generative_forest) ? 1 : 0)
+ "_";
output_stats_file = prefix_output_stats_file + token_save_string;
compute_filenames();
save_model(geot);
if (size_generated > 0) {
System.out.print(
"Generating " + size_generated + " observations using the " + which_model + "... ");
b = System.currentTimeMillis();
v_gen = geot.generate_sample_with_density(size_generated);
e = System.currentTimeMillis();
generate_observations_time = e - b;
System.out.println("ok (time elapsed: " + generate_observations_time + " ms).");
}
if (plot_labels_names != null) {
System.out.print("Saving projected frontiers & density plots... ");
b = System.currentTimeMillis();
save_frontier_and_density_plot(geot, v_gen);
e = System.currentTimeMillis();
System.out.println("ok (time elapsed: " + (e - b) + " ms).");
}
if ((has_missing_values) && (impute_missing)) {
System.out.print("Imputing observations using the " + which_model + "... ");
b = System.currentTimeMillis();
// impute_and_save(geot, true);
impute_and_save(geot, Wrapper.BOTH_IMPUTE_FILES);
e = System.currentTimeMillis();
imputation_time = e - b;
System.out.println("ok (time elapsed: " + imputation_time + " ms).");
}
if (density_estimation) {
System.out.print("Density estimation using the " + which_model + "... ");
density_estimation_save(myAlgos);
System.out.println("ok.");
}
System.out.print("Saving generated sample... ");
b = System.currentTimeMillis();
save_sample(v_gen);
e = System.currentTimeMillis();
saving_generated_sample_time = e - b;
System.out.println("ok (time elapsed: " + saving_generated_sample_time + " ms).");
System.out.print("Saving stats file... ");
b = System.currentTimeMillis();
save_stats(geot);
e = System.currentTimeMillis();
saving_stats_time = e - b;
System.out.println("ok (time elapsed: " + saving_stats_time + " ms).");
}
}
System.out.println("All finished. Stopping...");
myDomain.myMemoryMonitor.stop();
}
public void save_sample(Vector<Observation> v_gen) {
FileWriter f;
int i;
String save_name;
if (blueprint_save_name.contains(".csv"))
save_name =
blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf(".csv"))
+ token_save_string
+ ".csv";
else save_name = blueprint_save_name + token_save_string + ".csv";
String nameFile = path_to_generated_samples + "/" + save_name;
try {
f = new FileWriter(nameFile);
for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) {
f.write(myDomain.myDS.features_names_from_file[i]);
if (i < myDomain.myDS.features_names_from_file.length - 1)
f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]);
}
f.write("\n");
for (i = 0; i < v_gen.size(); i++)
f.write(((Observation) v_gen.elementAt(i)).toStringSave(true) + "\n");
f.close();
} catch (IOException e) {
Dataset.perror("Experiments.class :: Saving results error in file " + nameFile);
}
}
public void save_density_plot_sample(Vector<Observation> v_gen, boolean in_csv) {
FileWriter f;
int i, j, k;
String nameFile;
for (i = 0; i < plot_labels_names.length - 1; i++) {
for (j = i + 1; j < plot_labels_names.length; j++) {
nameFile = working_directory + "/" + densityplot_filename[i][j];
if (!in_csv) nameFile += ".txt";
try {
f = new FileWriter(nameFile);
if (in_csv)
f.write("//" + plot_labels_names[i] + "," + plot_labels_names[j] + ",density_value\n");
for (k = 0; k < v_gen.size(); k++)
f.write(
((Observation) v_gen.elementAt(k))
.toStringSaveDensity(plot_labels_indexes[i], plot_labels_indexes[j], in_csv)
+ "\n");
f.close();
} catch (IOException e) {
Dataset.perror("Experiments.class :: Saving results error in file " + nameFile);
}
}
}
}
public void save_model(GenerativeModelBasedOnEnsembleOfTrees geot) {
FileWriter f;
String nameFile;
nameFile = working_directory + "/" + spec_name + token_save_string + "_generative_model.txt";
try {
f = new FileWriter(nameFile);
f.write(geot.toString());
f.close();
} catch (IOException e) {
Dataset.perror("Experiments.class :: Saving results error in file " + nameFile);
}
}
public void impute_and_save(GenerativeModelBasedOnEnsembleOfTrees geot, String which_file) {
FileWriter f;
int i, j, k;
Vector<Observation> imputed_observations_at_the_max = null;
Vector<Observation> imputed_observations_sampling_density = null;
Vector<Observation> imputed_observations_target;
if ((imputation_type.equals(Wrapper.TRY_THEM_ALL))
|| (imputation_type.equals(Wrapper.IMPUTATION_AT_THE_MAX)))
imputed_observations_at_the_max = new Vector<>();
if ((imputation_type.equals(Wrapper.TRY_THEM_ALL))
|| (imputation_type.equals(Wrapper.IMPUTATION_SAMPLING_DENSITY)))
imputed_observations_sampling_density = new Vector<>();
String nameFile, token_imputation_type;
Observation ee, ee_cop_at_the_max, ee_cop_sampling_density;
for (i = 0; i < myDomain.myDS.observations_from_file.size(); i++) {
ee_cop_at_the_max = ee_cop_sampling_density = null;
if ((i % (myDomain.myDS.observations_from_file.size() / 100) == 0)
&& ((i / (myDomain.myDS.observations_from_file.size() / 100)) <= 100))
System.out.print((i / (myDomain.myDS.observations_from_file.size() / 100)) + "% ");
ee = (Observation) myDomain.myDS.observations_from_file.elementAt(i);
if ((imputation_type.equals(Wrapper.TRY_THEM_ALL))
|| (imputation_type.equals(Wrapper.IMPUTATION_AT_THE_MAX)))
ee_cop_at_the_max = Observation.copyOf(ee);
if ((imputation_type.equals(Wrapper.TRY_THEM_ALL))
|| (imputation_type.equals(Wrapper.IMPUTATION_SAMPLING_DENSITY)))
ee_cop_sampling_density = Observation.copyOf(ee);
if (ee.contains_unknown_values()) {
geot.impute(ee_cop_at_the_max, ee_cop_sampling_density, i);
}
if ((imputation_type.equals(Wrapper.TRY_THEM_ALL))
|| (imputation_type.equals(Wrapper.IMPUTATION_AT_THE_MAX)))
imputed_observations_at_the_max.addElement(ee_cop_at_the_max);
if ((imputation_type.equals(Wrapper.TRY_THEM_ALL))
|| (imputation_type.equals(Wrapper.IMPUTATION_SAMPLING_DENSITY)))
imputed_observations_sampling_density.addElement(ee_cop_sampling_density);
}
if (plot_labels_names != null) {
Plotting my_plot;
System.out.print(" (Imputed data plots");
for (k = 0; k < 2; k++) {
imputed_observations_target = null;
token_imputation_type = null;
if ((k == 0)
&& ((imputation_type.equals(Wrapper.IMPUTATION_AT_THE_MAX))
|| (imputation_type.equals(Wrapper.TRY_THEM_ALL)))) {
imputed_observations_target = imputed_observations_at_the_max;
token_imputation_type = Wrapper.IMPUTATION_AT_THE_MAX;
} else if ((k == 1)
&& ((imputation_type.equals(Wrapper.IMPUTATION_SAMPLING_DENSITY))
|| (imputation_type.equals(Wrapper.TRY_THEM_ALL)))) {
imputed_observations_target = imputed_observations_sampling_density;
token_imputation_type = Wrapper.IMPUTATION_SAMPLING_DENSITY;
}
if (imputed_observations_target != null) {
for (i = 0; i < plot_labels_names.length; i++) {
for (j = 0; j < plot_labels_names.length; j++) {
if (j != i) {
System.out.print(" [" + plot_labels_names[i] + ":" + plot_labels_names[j] + "]");
nameFile =
working_directory
+ "/"
+ imputeddataplot_token[i][j]
+ "_"
+ token_imputation_type
+ ".png";
my_plot = new Plotting();
my_plot.init(geot, plot_labels_indexes[i], plot_labels_indexes[j]);
my_plot.compute_and_store_x_y_densities_dataset(
geot, imputed_observations_target, nameFile);
}
}
}
}
}
System.out.print(") ");
}
if ((which_file.equals(Wrapper.BOTH_IMPUTE_FILES)) || (which_file.equals(Wrapper.IMPUTE_CSV))) {
for (k = 0; k < 2; k++) {
imputed_observations_target = null;
token_imputation_type = null;
if ((k == 0)
&& ((imputation_type.equals(Wrapper.IMPUTATION_AT_THE_MAX))
|| (imputation_type.equals(Wrapper.TRY_THEM_ALL)))) {
imputed_observations_target = imputed_observations_at_the_max;
token_imputation_type = Wrapper.IMPUTATION_AT_THE_MAX;
} else if ((k == 1)
&& ((imputation_type.equals(Wrapper.IMPUTATION_SAMPLING_DENSITY))
|| (imputation_type.equals(Wrapper.TRY_THEM_ALL)))) {
imputed_observations_target = imputed_observations_sampling_density;
token_imputation_type = Wrapper.IMPUTATION_SAMPLING_DENSITY;
}
if (imputed_observations_target != null) {
nameFile =
working_directory
+ "/"
+ spec_name
+ token_save_string
+ "_"
+ token_imputation_type
+ "_imputed.csv";
try {
f = new FileWriter(nameFile);
for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) {
f.write(myDomain.myDS.features_names_from_file[i]);
if (i < myDomain.myDS.features_names_from_file.length - 1)
f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]);
}
f.write("\n");
for (i = 0; i < imputed_observations_target.size(); i++)
f.write(imputed_observations_target.elementAt(i).toStringSave(true) + "\n");
f.close();
} catch (IOException e) {
Dataset.perror("Experiments.class :: Saving results error in file " + nameFile);
}
}
}
}
if ((which_file.equals(Wrapper.BOTH_IMPUTE_FILES)) || (which_file.equals(Wrapper.IMPUTE_TXT))) {
for (k = 0; k < 2; k++) {
imputed_observations_target = null;
token_imputation_type = null;
if ((k == 0)
&& ((imputation_type.equals(Wrapper.IMPUTATION_AT_THE_MAX))
|| (imputation_type.equals(Wrapper.TRY_THEM_ALL)))) {
imputed_observations_target = imputed_observations_at_the_max;
token_imputation_type = Wrapper.IMPUTATION_AT_THE_MAX;
} else if ((k == 1)
&& ((imputation_type.equals(Wrapper.IMPUTATION_SAMPLING_DENSITY))
|| (imputation_type.equals(Wrapper.TRY_THEM_ALL)))) {
imputed_observations_target = imputed_observations_sampling_density;
token_imputation_type = Wrapper.IMPUTATION_SAMPLING_DENSITY;
}
if (imputed_observations_target != null) {
nameFile =
working_directory
+ "/"
+ spec_name
+ token_save_string
+ "_"
+ token_imputation_type
+ "_imputed.csv.txt";
try {
f = new FileWriter(nameFile);
f.write("#");
for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++) {
f.write(myDomain.myDS.features_names_from_file[i]);
if (i < myDomain.myDS.features_names_from_file.length - 1)
f.write(Dataset.KEY_SEPARATION_STRING[Dataset.SEPARATION_INDEX]);
}
f.write("\n");
for (i = 0; i < imputed_observations_target.size(); i++)
f.write(imputed_observations_target.elementAt(i).toStringSave(false) + "\n");
f.close();
} catch (IOException e) {
Dataset.perror("Experiments.class :: Saving results error in file " + nameFile);
}
}
}
}
}
public void save_frontier_and_density_plot(
GenerativeModelBasedOnEnsembleOfTrees geot, Vector<Observation> v_gen) {
String fpname;
String dpname;
String domain_dpname;
String generated_dpname;
int i, j;
Plotting my_plot;
if (plot_labels_names != null) {
for (i = 0; i < plot_labels_names.length; i++) {
for (j = 0; j < plot_labels_names.length; j++) {
if (j != i) {
System.out.print("[" + plot_labels_names[i] + ":" + plot_labels_names[j] + "]");
fpname = working_directory + "/" + frontierplot_filename[i][j];
dpname = working_directory + "/" + jointdensityplot_filename[i][j];
domain_dpname = working_directory + "/" + domaindensityplot_filename[i][j];
if (plot_type.equals(Wrapper.PLOT_TYPE_ALL)) {
System.out.print("(frontiers)");
my_plot = new Plotting();
my_plot.init(geot, plot_labels_indexes[i], plot_labels_indexes[j]);
my_plot.compute_and_store_x_y_frontiers(geot, fpname);
if (geot.generative_forest) {
System.out.print("(densities)");
my_plot = new Plotting();
my_plot.init(geot, plot_labels_indexes[i], plot_labels_indexes[j]);
my_plot.compute_and_store_x_y_densities(geot, dpname);
}
}
if ((plot_type.equals(Wrapper.PLOT_TYPE_ALL))
|| (plot_type.equals(Wrapper.PLOT_TYPE_DATA))) {
System.out.print("(domain)");
my_plot = new Plotting();
my_plot.init(geot, plot_labels_indexes[i], plot_labels_indexes[j]);
my_plot.compute_and_store_x_y_densities_dataset(
geot, geot.myDS.observations_from_file, domain_dpname);
if (v_gen != null) {
generated_dpname =
working_directory
+ "/"
+ generateddatadensityplot_filename[i][j]
+ "_"
+ v_gen.size()
+ ".png";
System.out.print("(generated)");
my_plot.init(geot, plot_labels_indexes[i], plot_labels_indexes[j]);
my_plot.compute_and_store_x_y_densities_dataset(geot, v_gen, generated_dpname);
}
}
}
}
}
}
}
public void save_stats(GenerativeModelBasedOnEnsembleOfTrees geot) {
int i, j;
FileWriter f = null;
int[] node_counts = new int[myDomain.myDS.features_names_from_file.length];
String output_stats_additional = output_stats_file + "_more.txt";
long time_gt_plus_generation = gt_computation_time + generate_observations_time;
long time_gt_plus_imputation = -1;
if ((has_missing_values) && (impute_missing))
time_gt_plus_imputation = gt_computation_time + imputation_time;
String all_depths = "{";
String all_number_nodes = "{";
for (i = 0; i < geot.trees.size(); i++) {
all_depths += geot.trees.elementAt(i).depth + "";
all_number_nodes += geot.trees.elementAt(i).number_nodes + "";
if (i < geot.trees.size() - 1) {
all_depths += ",";
all_number_nodes += ",";
}
geot.trees.elementAt(i).root.recursive_fill_node_counts(node_counts);
}
all_depths += "}";
all_number_nodes += "}";
try {
f = new FileWriter(output_stats_file + ".txt");
f.write("{\n");
f.write(
" \"running_time_seconds\": "
+ DF8.format(((double) gt_computation_time + generate_observations_time) / 1000)
+ ",\n");
f.write(" \"geot_eogt_number_trees\": " + geot.trees.size() + ",\n");
f.write(" \"geot_eogt_nodes_per_tree\": " + all_number_nodes + ",\n");
f.write(" \"geot_eogt_depth_per_tree\": " + all_depths + ",\n");
f.write(
" \"running_time_training_plus_exemple_generation\": "
+ DF8.format(((double) time_gt_plus_generation / 1000))
+ ",\n");
if ((has_missing_values) && (impute_missing))
f.write(
" \"running_time_training_plus_imputation\": "
+ DF8.format(((double) time_gt_plus_imputation / 1000))
+ "\n");
f.write("}\n");
f.close();
} catch (IOException e) {
Dataset.perror("Wrapper.class :: Saving results error in file " + output_stats_file);
}
try {
f = new FileWriter(output_stats_additional);
f.write("// flag values used: ");
for (i = 0; i < flags_values.length; i++)
f.write(" [" + ALL_FLAGS[i] + ":" + flags_values[i] + "] ");
f.write("\n\n");
f.write("// Time to learn the generator: " + gt_computation_time + " ms.\n");
f.write("// Time to generate sample: " + generate_observations_time + " ms.\n");
f.write("\n// Generator: overall node counts per feature name (w/ interpreted type)\n");
for (i = 0; i < myDomain.myDS.features_names_from_file.length; i++)
f.write(
"// "
+ myDomain.myDS.features.elementAt(i).name
+ " ("
+ myDomain.myDS.features.elementAt(i).type
+ ") : "
+ node_counts[i]
+ "\n");
f.write("\n// Generator: per-tree node counts per feature name\n");
for (i = 0; i < geot.trees.size(); i++) {
f.write("// Tree# " + i + " :\t");
for (j = 0;
j < geot.trees.elementAt(i).statistics_number_of_nodes_for_each_feature.length;
j++)
f.write(geot.trees.elementAt(i).statistics_number_of_nodes_for_each_feature[j] + "\t");
f.write("\n");
}
f.close();
} catch (IOException e) {
Dataset.perror("Wrapper.class :: Saving results error in file " + output_stats_additional);
}
}
public void compute_filenames() {
int i, j;
if (plot_labels_names != null) {
densityplot_filename = new String[plot_labels_names.length][];
frontierplot_filename = new String[plot_labels_names.length][];
jointdensityplot_filename = new String[plot_labels_names.length][];
domaindensityplot_filename = new String[plot_labels_names.length][];
generateddatadensityplot_filename = new String[plot_labels_names.length][];
imputeddataplot_token = new String[plot_labels_names.length][];
for (i = 0; i < plot_labels_names.length; i++) {
densityplot_filename[i] = new String[plot_labels_names.length];
frontierplot_filename[i] = new String[plot_labels_names.length];
jointdensityplot_filename[i] = new String[plot_labels_names.length];
domaindensityplot_filename[i] = new String[plot_labels_names.length];
generateddatadensityplot_filename[i] = new String[plot_labels_names.length];
imputeddataplot_token[i] = new String[plot_labels_names.length];
for (j = 0; j < plot_labels_names.length; j++) {
if (j != i) {
densityplot_filename[i][j] =
blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.'))
+ token_save_string
+ "_X_"
+ plot_labels_names[i]
+ "_Y_"
+ plot_labels_names[j]
+ blueprint_save_name.substring(
blueprint_save_name.lastIndexOf('.'), blueprint_save_name.length())
+ "_2DDensity_plot";
frontierplot_filename[i][j] =
blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.'))
+ token_save_string
+ "_X_"
+ plot_labels_names[i]
+ "_Y_"
+ plot_labels_names[j]
+ "_projectedfrontiers_plot.png";
jointdensityplot_filename[i][j] =
blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.'))
+ token_save_string
+ "_X_"
+ plot_labels_names[i]
+ "_Y_"
+ plot_labels_names[j]
+ "_jointdensity_plot.png";
domaindensityplot_filename[i][j] =
blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.'))
+ token_save_string
+ "_X_"
+ plot_labels_names[i]
+ "_Y_"
+ plot_labels_names[j]
+ "_jointdensity_plot_domaindensity.png";
generateddatadensityplot_filename[i][j] =
blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.'))
+ token_save_string
+ "_X_"
+ plot_labels_names[i]
+ "_Y_"
+ plot_labels_names[j]
+ "_jointdensity_plot_generated";
imputeddataplot_token[i][j] =
blueprint_save_name.substring(0, blueprint_save_name.lastIndexOf('.'))
+ token_save_string
+ "_X_"
+ plot_labels_names[i]
+ "_Y_"
+ plot_labels_names[j]
+ "_jointdensity_plot_imputed";
}
}
}
}
}
public void summary() {
int i, j;
System.out.println("\nRunning copycat generator training with the following inputs:");
System.out.println(" * dataset path to train generator:" + path_and_name_of_domain_dataset);
System.out.println(" * working directory:" + working_directory);
System.out.println(
" * generated samples ("
+ size_generated
+ " observations) stored in directory "
+ path_to_generated_samples
+ " with filename "
+ blueprint_save_name);
System.out.println(
" * generator (gt) stored in working directory with filename " + generator_filename);
System.out.println(" * stats file at " + output_stats_file);
if (spec_path == null) Dataset.warning(" No path information in --dataset_spec");
else if (!path_and_name_of_domain_dataset.equals(spec_path))
Dataset.warning(
" Non identical information in --dataset_spec path vs --dataset"
+ " (path_and_name_of_domain_dataset = "
+ path_and_name_of_domain_dataset
+ ", spec_path = "
+ spec_path
+ ")\n");
if (impute_missing)
System.out.println(
" * imputed sample saved at filename "
+ working_directory
+ "/"
+ spec_name
+ "_imputed.csv");
System.out.print(" * flags (non null): ");
for (i = 0; i < flags_values.length; i++)
if (flags_values[i] != null)
System.out.print("[" + ALL_FLAGS[i] + ":" + flags_values[i] + "] ");
System.out.println("");
if (flags_values[ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING] != null)
FeatureValue.S_UNKNOWN = flags_values[ALL_FLAGS_INDEX_UNKNOWN_VALUE_CODING];
if (flags_values[ALL_FLAGS_FORCE_INTEGER_CODING] != null)
force_integer_coding = Boolean.parseBoolean(flags_values[ALL_FLAGS_FORCE_INTEGER_CODING]);
if (flags_values[ALL_FLAGS_FORCE_BINARY_CODING] != null)
force_binary_coding = Boolean.parseBoolean(flags_values[ALL_FLAGS_FORCE_BINARY_CODING]);
if (flags_values[ALL_FLAGS_INDEX_ITERATIONS] != null)
number_iterations = Integer.parseInt(flags_values[ALL_FLAGS_INDEX_ITERATIONS]);
if (flags_values[ALL_FLAGS_INDEX_INITIAL_NUMBER_OF_TREES] != null)
initial_nb_of_trees = Integer.parseInt(flags_values[ALL_FLAGS_INDEX_INITIAL_NUMBER_OF_TREES]);
if (flags_values[ALL_FLAGS_SPLITTING_METHOD] != null)
splitting_method = new String(flags_values[ALL_FLAGS_SPLITTING_METHOD]);
Wrapper.CHECK_SPLITTING_METHOD(splitting_method);
if (flags_values[ALL_FLAGS_TYPE_OF_GENERATIVE_MODEL] != null)
type_of_generative_model = new String(flags_values[ALL_FLAGS_TYPE_OF_GENERATIVE_MODEL]);
Wrapper.CHECK_GENERATIVE_MODEL(type_of_generative_model);
if (flags_values[ALL_FLAGS_PLOT_TYPE] != null)
plot_type = new String(flags_values[ALL_FLAGS_PLOT_TYPE]);
if (flags_values[ALL_FLAGS_IMPUTATION_METHOD] != null)
imputation_type = new String(flags_values[ALL_FLAGS_IMPUTATION_METHOD]);
// token_save_string = "_A" + algorithm_category + "_I" + number_iterations + "_T" +
// initial_nb_of_trees + "_GEOT" + ((generative_forest) ? 1 : 0) + "_";
// output_stats_file += token_save_string;
if (plot_labels_names != null) {
System.out.print(
" * 2D density plots, frontier plots, joint density plots and / or domain density plots"
+ " to be recorded on couples of features in (");
for (j = 0; j < plot_labels_names.length; j++) {
System.out.print(plot_labels_names[j]);
if (j < plot_labels_names.length - 1) System.out.print(",");
}
System.out.println(")");
}
System.out.println("");
}
public void fit_vars(String s) {
String dummys;
if (s.contains(DATASET)) {
path_and_name_of_domain_dataset = s.substring(DATASET.length(), s.length());
spec_name =
path_and_name_of_domain_dataset.substring(
path_and_name_of_domain_dataset.lastIndexOf('/') + 1,
path_and_name_of_domain_dataset.lastIndexOf('.'));
} else if (s.contains(DATASET_TEST)) {
path_and_name_of_test_dataset = s.substring(DATASET_TEST.length(), s.length());
path_name_test =
path_and_name_of_test_dataset.substring(
0, path_and_name_of_test_dataset.lastIndexOf('/') + 1);
} else if (s.contains(DATASET_SPEC)) {
spec_path = spec_label = spec_task = null;
int i, begin_ind, end_ind;
String[] values = new String[4];
int[] index_tokens = {0, 0, 0, 0};
for (i = 0; i < DATASET_TOKENS.length; i++) {
if (s.indexOf(DATASET_TOKENS[i]) != s.lastIndexOf(DATASET_TOKENS[i]))
Dataset.perror(
"Wrapper.class :: more than one occurrence of "
+ DATASET_TOKENS[i]
+ " in string"
+ s);
if (s.indexOf(DATASET_TOKENS[i]) == -1)
Dataset.perror(
"Wrapper.class :: zero occurrence of " + DATASET_TOKENS[i] + " in string" + s);
else index_tokens[i] = s.indexOf(DATASET_TOKENS[i]);
}
for (i = 0; i < DATASET_TOKENS.length - 1; i++)
if (index_tokens[i] > index_tokens[i + 1])
Dataset.perror(
"Wrapper.class :: token "
+ DATASET_TOKENS[i]
+ " should appear before token "
+ DATASET_TOKENS[i + 1]
+ " in string"
+ s);
for (i = 0; i < DATASET_TOKENS.length; i++) {
begin_ind = index_tokens[i] + DATASET_TOKENS[i].length();
if (i == DATASET_TOKENS.length - 1) end_ind = s.length();
else end_ind = index_tokens[i + 1] - 1;
dummys = s.substring(begin_ind, end_ind);
values[i] = dummys.substring(dummys.indexOf('\"') + 1, dummys.lastIndexOf('\"'));
}
prefix_domain = spec_name;
spec_path = values[1];
spec_label = values[2];
spec_task = values[3];
} else if (s.contains(NUM_SAMPLES)) {
size_generated = Integer.parseInt(s.substring(NUM_SAMPLES.length(), s.length()));
} else if (s.contains(ALGORITHM_CATEGORY)) {
algorithm_category = Integer.parseInt(s.substring(ALGORITHM_CATEGORY.length(), s.length()));
} else if (s.contains(WORK_DIR)) {
working_directory = s.substring(WORK_DIR.length(), s.length());
} else if (s.contains(OUTPUT_SAMPLES)) {
dummys = s.substring(OUTPUT_SAMPLES.length(), s.length());
path_to_generated_samples = dummys.substring(0, dummys.lastIndexOf('/'));
blueprint_save_name = dummys.substring(dummys.lastIndexOf('/') + 1, dummys.length());
generator_filename = PREFIX_GENERATOR + blueprint_save_name;
} else if (s.contains(OUTPUT_STATS)) {
output_stats_file = s.substring(OUTPUT_STATS.length(), s.length());
output_stats_directory = s.substring(OUTPUT_STATS.length(), s.lastIndexOf('/'));
} else if (s.contains(PLOT_LABELS)) {
String all_labels = s.substring(PLOT_LABELS.length(), s.length()), dums;
Vector<String> all_strings = new Vector<>();
boolean in_s = false, word_ok = false;
int i = 0, i_b = -1, i_e = -1, j;
do {
if (all_labels.charAt(i) == '"') {
if (in_s) {
i_e = i;
word_ok = true;
in_s = false;
} else {
i_b = i + 1;
i_e = -1;
in_s = true;
}
if (word_ok) {
if (i_b == i_e) Dataset.perror("Wrapper.class :: empty string in --plot_labels");
dums = all_labels.substring(i_b, i_e);
all_strings.addElement(dums);
i_b = i_e = -1;
word_ok = false;
}
}
i++;
} while (i < all_labels.length());
if (all_strings.size() <= 1)
Dataset.perror("Wrapper.class :: <= 1 label only in --plot_labels");
plot_labels_names = new String[all_strings.size()];
for (i = 0; i < all_strings.size(); i++) plot_labels_names[i] = all_strings.elementAt(i);
for (i = 0; i < all_strings.size() - 1; i++)
for (j = i + 1; j < all_strings.size(); j++)
if (plot_labels_names[i].equals(plot_labels_names[j]))
Dataset.perror(
"Wrapper.class :: same label ("
+ plot_labels_names[i]
+ ") repeated in --plot_labels");
} else if (s.contains(FLAGS)) {
dummys = ((s.substring(FLAGS.length(), s.length())).replaceAll(" ", "")).replaceAll("=", "");
if (!dummys.substring(0, 1).equals("{"))
Dataset.perror("Wrapper.class :: FLAGS flags does not begin with '{'");
if (!dummys.substring(dummys.length() - 1, dummys.length()).equals("}"))
Dataset.perror("Wrapper.class :: FLAGS flags does not end with '}'");
dummys = (dummys.substring(1, dummys.length() - 1)).replace("\"", "");
int b = 0, e = -1, i;
String subs, tags, vals;
while (e < dummys.length()) {
b = e + 1;
do {
e++;
} while ((e < dummys.length()) && (!dummys.substring(e, e + 1).equals(",")));
subs = dummys.substring(b, e);
if (!subs.contains(":"))
Dataset.perror("Wrapper.class :: flags string " + subs + " not of the syntax tag:value");
tags = subs.substring(0, subs.lastIndexOf(':'));
vals = subs.substring(subs.lastIndexOf(':') + 1, subs.length());
i = 0;
do {
if (!ALL_FLAGS[i].equals(tags)) i++;
} while ((i < ALL_FLAGS.length) && (!ALL_FLAGS[i].equals(tags)));
if (i == ALL_FLAGS.length)
Dataset.perror("Wrapper.class :: flags string " + tags + " not in authorized tags");
flags_values[i] = vals;
}
} else if (s.contains(IMPUTE_MISSING)) {
impute_missing = Boolean.parseBoolean(s.substring(IMPUTE_MISSING.length(), s.length()));
} else if (s.contains(DENSITY_ESTIMATION)) {
density_estimation =
Boolean.parseBoolean(s.substring(DENSITY_ESTIMATION.length(), s.length()));
if (path_and_name_of_test_dataset == null)
Dataset.perror("Wrapper.class :: density_estimation performed but no test set provided");
}
}
public void density_estimation_save(Algorithm algo) {
String nameFile_likelihoods =
path_name_test + "density_estimation_likelihoods" + token_save_string + ".txt";
String nameFile_log_likelihoods =
path_name_test + "density_estimation_log_likelihoods" + token_save_string + ".txt";
FileWriter f;
int i;
try {
f = new FileWriter(nameFile_likelihoods);
for (i = 0; i < algo.density_estimation_outputs_likelihoods.size(); i++) {
f.write(
((int)
algo.density_estimation_outputs_likelihoods
.elementAt(i)
.elementAt(0)
.doubleValue())
+ "\t"
+ (algo.density_estimation_outputs_likelihoods
.elementAt(i)
.elementAt(1)
.doubleValue())
+ "\t"
+ (algo.density_estimation_outputs_likelihoods
.elementAt(i)
.elementAt(2)
.doubleValue())
+ "\n");
}
f.close();
} catch (IOException e) {
Dataset.perror("Experiments.class :: Saving results error in file " + nameFile_likelihoods);
}
try {
f = new FileWriter(nameFile_log_likelihoods);
for (i = 0; i < algo.density_estimation_outputs_log_likelihoods.size(); i++) {
f.write(
((int)
algo.density_estimation_outputs_log_likelihoods
.elementAt(i)
.elementAt(0)
.doubleValue())
+ "\t"
+ DF6.format(
algo.density_estimation_outputs_log_likelihoods
.elementAt(i)
.elementAt(1)
.doubleValue())
+ "\t"
+ DF6.format(
algo.density_estimation_outputs_log_likelihoods
.elementAt(i)
.elementAt(2)
.doubleValue())
+ "\n");
}
f.close();
} catch (IOException e) {
Dataset.perror(
"Experiments.class :: Saving results error in file " + nameFile_log_likelihoods);
}
}
}
| google-research/google-research | generative_forests/src/Wrapper.java |
116 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.script;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
/**
* Ingest and update metadata available to write scripts.
*
* Provides a map-like interface for backwards compatibility with the ctx map.
* - {@link #put(String, Object)}
* - {@link #get(String)}
* - {@link #remove(String)}
* - {@link #containsKey(String)}
* - {@link #containsValue(Object)}
* - {@link #keySet()} for iteration
* - {@link #size()}
* - {@link #isAvailable(String)} for determining if a key is a metadata key
*
* Provides getters and setters for script usage.
*
* Validates all updates whether originating in map-like interface or setters.
*/
public class Metadata {
protected static final String INDEX = "_index";
protected static final String ID = "_id";
protected static final String ROUTING = "_routing";
protected static final String VERSION_TYPE = "_version_type";
protected static final String VERSION = "_version";
protected static final String TYPE = "_type"; // type is deprecated, so it's supported in the map but not available as a getter
protected static final String NOW = "_now";
protected static final String OP = "op";
protected static final String IF_SEQ_NO = "_if_seq_no";
protected static final String IF_PRIMARY_TERM = "_if_primary_term";
protected static final String DYNAMIC_TEMPLATES = "_dynamic_templates";
public static FieldProperty<Object> ObjectField = new FieldProperty<>(Object.class);
public static FieldProperty<String> StringField = new FieldProperty<>(String.class);
public static FieldProperty<Number> LongField = new FieldProperty<>(Number.class).withValidation(FieldProperty.LONGABLE_NUMBER);
protected final Map<String, Object> map;
private final Map<String, FieldProperty<?>> properties;
protected static final FieldProperty<?> BAD_KEY = new FieldProperty<>(null, false, false, null);
/**
* Constructs a new Metadata object represented by the given map and properties.
* <p>
* The passed-in map is used directly -- subsequent modifications to it outside the methods of this class may result in
* undefined behavior. Note also that mutation-like methods (e.g. setters, etc) on this class rely on the map being mutable,
* which is the expected use for this class.
* <p>
* The properties map is used directly as well, but we verify at runtime that it <b>must</b> be an immutable map (i.e. constructed
* via a call to {@link Map#of()} (or similar) in production, or via {@link Map#copyOf(Map)}} in tests). Since it must be an
* immutable map, subsequent modifications are not possible.
*
* @param map the backing map for this metadata instance
* @param properties the immutable map of defined properties for the type of metadata represented by this instance
*/
@SuppressWarnings("this-escape")
protected Metadata(Map<String, Object> map, Map<String, FieldProperty<?>> properties) {
this.map = map;
// we can't tell the compiler that properties must be a java.util.ImmutableCollections.AbstractImmutableMap, but
// we can use this copyOf + assert to verify that at runtime.
this.properties = Map.copyOf(properties);
assert this.properties == properties : "properties map must be constructed via Map.of(...) or Map.copyOf(...)";
validateMetadata();
}
// a 'not found' sentinel value for use in validateMetadata below
private static final Object NOT_FOUND = new Object();
/**
* Check that all metadata map contains only valid metadata and no extraneous keys
*/
protected void validateMetadata() {
int numMetadata = 0;
for (Map.Entry<String, FieldProperty<?>> entry : properties.entrySet()) {
String key = entry.getKey();
Object value = map.getOrDefault(key, NOT_FOUND); // getOrDefault is faster than containsKey + get
if (value == NOT_FOUND) {
// check whether it's permissible to *not* have a value for the property
entry.getValue().check(MapOperation.INIT, key, null);
} else {
numMetadata++;
entry.getValue().check(MapOperation.INIT, key, value);
}
}
if (numMetadata < map.size()) {
Set<String> keys = new HashSet<>(map.keySet());
keys.removeAll(properties.keySet());
throw new IllegalArgumentException(
"Unexpected metadata keys [" + keys.stream().sorted().map(k -> k + ":" + map.get(k)).collect(Collectors.joining(", ")) + "]"
);
}
}
// These are available to scripts
public String getIndex() {
return getString(INDEX);
}
public void setIndex(String index) {
put(INDEX, index);
}
public String getId() {
return getString(ID);
}
public void setId(String id) {
put(ID, id);
}
public String getRouting() {
return getString(ROUTING);
}
public void setRouting(String routing) {
put(ROUTING, routing);
}
public String getVersionType() {
return getString(VERSION_TYPE);
}
public void setVersionType(String versionType) {
put(VERSION_TYPE, versionType);
}
public long getVersion() {
return getNumber(VERSION).longValue();
}
public void setVersion(long version) {
put(VERSION, version);
}
public ZonedDateTime getNow() {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(getNumber(NOW).longValue()), ZoneOffset.UTC);
}
public String getOp() {
return getString(OP);
}
public void setOp(String op) {
put(OP, op);
}
// These are not available to scripts
public Number getIfSeqNo() {
return getNumber(IF_SEQ_NO);
}
public Number getIfPrimaryTerm() {
return getNumber(IF_PRIMARY_TERM);
}
@SuppressWarnings("unchecked")
public Map<String, String> getDynamicTemplates() {
return (Map<String, String>) get(DYNAMIC_TEMPLATES);
}
/**
* Get the String version of the value associated with {@code key}, or null
*/
protected String getString(String key) {
return Objects.toString(get(key), null);
}
/**
* Get the {@link Number} associated with key, or null
* @throws IllegalArgumentException if the value is not a {@link Number}
*/
protected Number getNumber(String key) {
Object value = get(key);
if (value == null) {
return null;
}
if (value instanceof Number number) {
return number;
}
throw new IllegalStateException(
"unexpected type for [" + key + "] with value [" + value + "], expected Number, got [" + value.getClass().getName() + "]"
);
}
/**
* Is this key a Metadata key? A {@link #remove}d key would return false for {@link #containsKey(String)} but true for
* this call.
*/
public boolean isAvailable(String key) {
return properties.containsKey(key);
}
/**
* Create the mapping from key to value.
* @throws IllegalArgumentException if {@link #isAvailable(String)} is false or the key cannot be updated to the value.
*/
public Object put(String key, Object value) {
properties.getOrDefault(key, Metadata.BAD_KEY).check(MapOperation.UPDATE, key, value);
return map.put(key, value);
}
/**
* Does the metadata contain the key?
*/
public boolean containsKey(String key) {
return map.containsKey(key);
}
/**
* Does the metadata contain the value.
*/
public boolean containsValue(Object value) {
return map.containsValue(value);
}
/**
* Get the value associated with {@param key}
*/
public Object get(String key) {
return map.get(key);
}
/**
* Remove the mapping associated with {@param key}
* @throws IllegalArgumentException if {@link #isAvailable(String)} is false or the key cannot be removed.
*/
public Object remove(String key) {
properties.getOrDefault(key, Metadata.BAD_KEY).check(MapOperation.REMOVE, key, null);
return map.remove(key);
}
/**
* Return the list of keys with mappings
*/
public Set<String> keySet() {
return Collections.unmodifiableSet(map.keySet());
}
/**
* The number of metadata keys currently mapped.
*/
public int size() {
return map.size();
}
@Override
public Metadata clone() {
// properties is an unmodifiable map, no need to create a copy here
return new Metadata(new HashMap<>(map), properties);
}
/**
* Get the backing map, if modified then the guarantees of this class may not hold
*/
public Map<String, Object> getMap() {
return map;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if ((o instanceof Metadata) == false) return false;
Metadata metadata = (Metadata) o;
return map.equals(metadata.map);
}
@Override
public int hashCode() {
return Objects.hash(map);
}
/**
* The operation being performed on the value in the map.
* INIT: Initial value - the metadata value as passed into this class
* UPDATE: the metadata is being set to a different value
* REMOVE: the metadata mapping is being removed
*/
public enum MapOperation {
INIT,
UPDATE,
REMOVE
}
/**
* The properties of a metadata field.
* @param type - the class of the field. Updates must be assignable to this type. If null, no type checking is performed.
* @param nullable - can the field value be null and can it be removed
* @param writable - can the field be updated after the initial set
* @param extendedValidation - value validation after type checking, may be used for values that may be one of a set
*/
public record FieldProperty<T>(Class<T> type, boolean nullable, boolean writable, BiConsumer<String, T> extendedValidation) {
public FieldProperty(Class<T> type) {
this(type, false, false, null);
}
public FieldProperty<T> withNullable() {
if (nullable) {
return this;
}
return new FieldProperty<>(type, true, writable, extendedValidation);
}
public FieldProperty<T> withWritable() {
if (writable) {
return this;
}
return new FieldProperty<>(type, nullable, true, extendedValidation);
}
public FieldProperty<T> withValidation(BiConsumer<String, T> extendedValidation) {
if (this.extendedValidation == extendedValidation) {
return this;
}
return new FieldProperty<>(type, nullable, writable, extendedValidation);
}
public static BiConsumer<String, Number> LONGABLE_NUMBER = (k, v) -> {
long version = v.longValue();
// did we round?
if (v.doubleValue() == version) {
return;
}
throw new IllegalArgumentException(
k + " may only be set to an int or a long but was [" + v + "] with type [" + v.getClass().getName() + "]"
);
};
public static FieldProperty<?> ALLOW_ALL = new FieldProperty<>(null, true, true, null);
@SuppressWarnings("fallthrough")
public void check(MapOperation op, String key, Object value) {
switch (op) {
case UPDATE:
if (writable == false) {
throw new IllegalArgumentException(key + " cannot be updated");
}
// fall through
case INIT:
if (value == null) {
if (nullable == false) {
throw new IllegalArgumentException(key + " cannot be null");
}
} else {
checkType(key, value);
}
break;
case REMOVE:
if (writable == false || nullable == false) {
throw new IllegalArgumentException(key + " cannot be removed");
}
break;
default:
throw new IllegalArgumentException("unexpected op [" + op + "] for key [" + key + "] and value [" + value + "]");
}
}
@SuppressWarnings("unchecked")
private void checkType(String key, Object value) {
if (type == null) {
return;
}
if (type.isAssignableFrom(value.getClass()) == false) {
throw new IllegalArgumentException(
key
+ " ["
+ value
+ "] is wrong type, expected assignable to ["
+ type.getName()
+ "], not ["
+ value.getClass().getName()
+ "]"
);
}
if (extendedValidation != null) {
extendedValidation.accept(key, (T) value);
}
}
}
public static BiConsumer<String, String> stringSetValidator(Set<String> valid) {
return (k, v) -> {
if (valid.contains(v) == false) {
throw new IllegalArgumentException(
"[" + k + "] must be one of " + valid.stream().sorted().collect(Collectors.joining(", ")) + ", not [" + v + "]"
);
}
};
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/script/Metadata.java |
117 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project 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:
*
* 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 io.netty.util;
import io.netty.util.NetUtilInitializations.NetworkIfaceAndInetAddress;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.StringUtil;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collection;
import static io.netty.util.AsciiString.indexOf;
/**
* A class that holds a number of network-related constants.
* <p/>
* This class borrowed some of its methods from a modified fork of the
* <a href="https://svn.apache.org/repos/asf/harmony/enhanced/java/branches/java6/classlib/modules/luni/
* src/main/java/org/apache/harmony/luni/util/Inet6Util.java">Inet6Util class</a> which was part of Apache Harmony.
*/
public final class NetUtil {
/**
* The {@link Inet4Address} that represents the IPv4 loopback address '127.0.0.1'
*/
public static final Inet4Address LOCALHOST4;
/**
* The {@link Inet6Address} that represents the IPv6 loopback address '::1'
*/
public static final Inet6Address LOCALHOST6;
/**
* The {@link InetAddress} that represents the loopback address. If IPv6 stack is available, it will refer to
* {@link #LOCALHOST6}. Otherwise, {@link #LOCALHOST4}.
*/
public static final InetAddress LOCALHOST;
/**
* The loopback {@link NetworkInterface} of the current machine
*/
public static final NetworkInterface LOOPBACK_IF;
/**
* An unmodifiable Collection of all the interfaces on this machine.
*/
public static final Collection<NetworkInterface> NETWORK_INTERFACES;
/**
* The SOMAXCONN value of the current machine. If failed to get the value, {@code 200} is used as a
* default value for Windows and {@code 128} for others.
*/
public static final int SOMAXCONN;
/**
* This defines how many words (represented as ints) are needed to represent an IPv6 address
*/
private static final int IPV6_WORD_COUNT = 8;
/**
* The maximum number of characters for an IPV6 string with no scope
*/
private static final int IPV6_MAX_CHAR_COUNT = 39;
/**
* Number of bytes needed to represent an IPV6 value
*/
private static final int IPV6_BYTE_COUNT = 16;
/**
* Maximum amount of value adding characters in between IPV6 separators
*/
private static final int IPV6_MAX_CHAR_BETWEEN_SEPARATOR = 4;
/**
* Minimum number of separators that must be present in an IPv6 string
*/
private static final int IPV6_MIN_SEPARATORS = 2;
/**
* Maximum number of separators that must be present in an IPv6 string
*/
private static final int IPV6_MAX_SEPARATORS = 8;
/**
* Maximum amount of value adding characters in between IPV4 separators
*/
private static final int IPV4_MAX_CHAR_BETWEEN_SEPARATOR = 3;
/**
* Number of separators that must be present in an IPv4 string
*/
private static final int IPV4_SEPARATORS = 3;
/**
* {@code true} if IPv4 should be used even if the system supports both IPv4 and IPv6.
*/
private static final boolean IPV4_PREFERRED = SystemPropertyUtil.getBoolean("java.net.preferIPv4Stack", false);
/**
* {@code true} if an IPv6 address should be preferred when a host has both an IPv4 address and an IPv6 address.
*/
private static final boolean IPV6_ADDRESSES_PREFERRED;
/**
* The logger being used by this class
*/
private static final InternalLogger logger = InternalLoggerFactory.getInstance(NetUtil.class);
static {
String prefer = SystemPropertyUtil.get("java.net.preferIPv6Addresses", "false");
if ("true".equalsIgnoreCase(prefer.trim())) {
IPV6_ADDRESSES_PREFERRED = true;
} else {
// Let's just use false in this case as only true is "forcing" ipv6.
IPV6_ADDRESSES_PREFERRED = false;
}
logger.debug("-Djava.net.preferIPv4Stack: {}", IPV4_PREFERRED);
logger.debug("-Djava.net.preferIPv6Addresses: {}", prefer);
NETWORK_INTERFACES = NetUtilInitializations.networkInterfaces();
// Create IPv4 loopback address.
LOCALHOST4 = NetUtilInitializations.createLocalhost4();
// Create IPv6 loopback address.
LOCALHOST6 = NetUtilInitializations.createLocalhost6();
NetworkIfaceAndInetAddress loopback =
NetUtilInitializations.determineLoopback(NETWORK_INTERFACES, LOCALHOST4, LOCALHOST6);
LOOPBACK_IF = loopback.iface();
LOCALHOST = loopback.address();
// As a SecurityManager may prevent reading the somaxconn file we wrap this in a privileged block.
//
// See https://github.com/netty/netty/issues/3680
SOMAXCONN = AccessController.doPrivileged(new SoMaxConnAction());
}
private static final class SoMaxConnAction implements PrivilegedAction<Integer> {
@Override
public Integer run() {
// Determine the default somaxconn (server socket backlog) value of the platform.
// The known defaults:
// - Windows NT Server 4.0+: 200
// - Linux and Mac OS X: 128
int somaxconn = PlatformDependent.isWindows() ? 200 : 128;
File file = new File("/proc/sys/net/core/somaxconn");
BufferedReader in = null;
try {
// file.exists() may throw a SecurityException if a SecurityManager is used, so execute it in the
// try / catch block.
// See https://github.com/netty/netty/issues/4936
if (file.exists()) {
in = new BufferedReader(new FileReader(file));
somaxconn = Integer.parseInt(in.readLine());
if (logger.isDebugEnabled()) {
logger.debug("{}: {}", file, somaxconn);
}
} else {
// Try to get from sysctl
Integer tmp = null;
if (SystemPropertyUtil.getBoolean("io.netty.net.somaxconn.trySysctl", false)) {
tmp = sysctlGetInt("kern.ipc.somaxconn");
if (tmp == null) {
tmp = sysctlGetInt("kern.ipc.soacceptqueue");
if (tmp != null) {
somaxconn = tmp;
}
} else {
somaxconn = tmp;
}
}
if (tmp == null) {
logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}", file,
somaxconn);
}
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to get SOMAXCONN from sysctl and file {}. Default: {}",
file, somaxconn, e);
}
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Ignored.
}
}
}
return somaxconn;
}
}
/**
* This will execute <a href ="https://www.freebsd.org/cgi/man.cgi?sysctl(8)">sysctl</a> with the {@code sysctlKey}
* which is expected to return the numeric value for for {@code sysctlKey}.
* @param sysctlKey The key which the return value corresponds to.
* @return The <a href ="https://www.freebsd.org/cgi/man.cgi?sysctl(8)">sysctl</a> value for {@code sysctlKey}.
*/
private static Integer sysctlGetInt(String sysctlKey) throws IOException {
Process process = new ProcessBuilder("sysctl", sysctlKey).start();
try {
// Suppress warnings about resource leaks since the buffered reader is closed below
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
try {
String line = br.readLine();
if (line != null && line.startsWith(sysctlKey)) {
for (int i = line.length() - 1; i > sysctlKey.length(); --i) {
if (!Character.isDigit(line.charAt(i))) {
return Integer.valueOf(line.substring(i + 1));
}
}
}
return null;
} finally {
br.close();
}
} finally {
// No need of 'null' check because we're initializing
// the Process instance in first line. Any exception
// raised will directly lead to throwable.
process.destroy();
}
}
/**
* Returns {@code true} if IPv4 should be used even if the system supports both IPv4 and IPv6. Setting this
* property to {@code true} will disable IPv6 support. The default value of this property is {@code false}.
*
* @see <a href="https://docs.oracle.com/javase/8/docs/api/java/net/doc-files/net-properties.html">Java SE
* networking properties</a>
*/
public static boolean isIpV4StackPreferred() {
return IPV4_PREFERRED;
}
/**
* Returns {@code true} if an IPv6 address should be preferred when a host has both an IPv4 address and an IPv6
* address. The default value of this property is {@code false}.
*
* @see <a href="https://docs.oracle.com/javase/8/docs/api/java/net/doc-files/net-properties.html">Java SE
* networking properties</a>
*/
public static boolean isIpV6AddressesPreferred() {
return IPV6_ADDRESSES_PREFERRED;
}
/**
* Creates an byte[] based on an ipAddressString. No error handling is performed here.
*/
public static byte[] createByteArrayFromIpAddressString(String ipAddressString) {
if (isValidIpV4Address(ipAddressString)) {
return validIpV4ToBytes(ipAddressString);
}
if (isValidIpV6Address(ipAddressString)) {
if (ipAddressString.charAt(0) == '[') {
ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1);
}
int percentPos = ipAddressString.indexOf('%');
if (percentPos >= 0) {
ipAddressString = ipAddressString.substring(0, percentPos);
}
return getIPv6ByName(ipAddressString, true);
}
return null;
}
/**
* Creates an {@link InetAddress} based on an ipAddressString or might return null if it can't be parsed.
* No error handling is performed here.
*/
public static InetAddress createInetAddressFromIpAddressString(String ipAddressString) {
if (isValidIpV4Address(ipAddressString)) {
byte[] bytes = validIpV4ToBytes(ipAddressString);
try {
return InetAddress.getByAddress(bytes);
} catch (UnknownHostException e) {
// Should never happen!
throw new IllegalStateException(e);
}
}
if (isValidIpV6Address(ipAddressString)) {
if (ipAddressString.charAt(0) == '[') {
ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1);
}
int percentPos = ipAddressString.indexOf('%');
if (percentPos >= 0) {
try {
int scopeId = Integer.parseInt(ipAddressString.substring(percentPos + 1));
ipAddressString = ipAddressString.substring(0, percentPos);
byte[] bytes = getIPv6ByName(ipAddressString, true);
if (bytes == null) {
return null;
}
try {
return Inet6Address.getByAddress(null, bytes, scopeId);
} catch (UnknownHostException e) {
// Should never happen!
throw new IllegalStateException(e);
}
} catch (NumberFormatException e) {
return null;
}
}
byte[] bytes = getIPv6ByName(ipAddressString, true);
if (bytes == null) {
return null;
}
try {
return InetAddress.getByAddress(bytes);
} catch (UnknownHostException e) {
// Should never happen!
throw new IllegalStateException(e);
}
}
return null;
}
private static int decimalDigit(String str, int pos) {
return str.charAt(pos) - '0';
}
private static byte ipv4WordToByte(String ip, int from, int toExclusive) {
int ret = decimalDigit(ip, from);
from++;
if (from == toExclusive) {
return (byte) ret;
}
ret = ret * 10 + decimalDigit(ip, from);
from++;
if (from == toExclusive) {
return (byte) ret;
}
return (byte) (ret * 10 + decimalDigit(ip, from));
}
// visible for tests
static byte[] validIpV4ToBytes(String ip) {
int i;
return new byte[] {
ipv4WordToByte(ip, 0, i = ip.indexOf('.', 1)),
ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)),
ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)),
ipv4WordToByte(ip, i + 1, ip.length())
};
}
/**
* Convert {@link Inet4Address} into {@code int}
*/
public static int ipv4AddressToInt(Inet4Address ipAddress) {
byte[] octets = ipAddress.getAddress();
return (octets[0] & 0xff) << 24 |
(octets[1] & 0xff) << 16 |
(octets[2] & 0xff) << 8 |
octets[3] & 0xff;
}
/**
* Converts a 32-bit integer into an IPv4 address.
*/
public static String intToIpAddress(int i) {
StringBuilder buf = new StringBuilder(15);
buf.append(i >> 24 & 0xff);
buf.append('.');
buf.append(i >> 16 & 0xff);
buf.append('.');
buf.append(i >> 8 & 0xff);
buf.append('.');
buf.append(i & 0xff);
return buf.toString();
}
/**
* Converts 4-byte or 16-byte data into an IPv4 or IPv6 string respectively.
*
* @throws IllegalArgumentException
* if {@code length} is not {@code 4} nor {@code 16}
*/
public static String bytesToIpAddress(byte[] bytes) {
return bytesToIpAddress(bytes, 0, bytes.length);
}
/**
* Converts 4-byte or 16-byte data into an IPv4 or IPv6 string respectively.
*
* @throws IllegalArgumentException
* if {@code length} is not {@code 4} nor {@code 16}
*/
public static String bytesToIpAddress(byte[] bytes, int offset, int length) {
switch (length) {
case 4: {
return new StringBuilder(15)
.append(bytes[offset] & 0xff)
.append('.')
.append(bytes[offset + 1] & 0xff)
.append('.')
.append(bytes[offset + 2] & 0xff)
.append('.')
.append(bytes[offset + 3] & 0xff).toString();
}
case 16:
return toAddressString(bytes, offset, false);
default:
throw new IllegalArgumentException("length: " + length + " (expected: 4 or 16)");
}
}
public static boolean isValidIpV6Address(String ip) {
return isValidIpV6Address((CharSequence) ip);
}
public static boolean isValidIpV6Address(CharSequence ip) {
int end = ip.length();
if (end < 2) {
return false;
}
// strip "[]"
int start;
char c = ip.charAt(0);
if (c == '[') {
end--;
if (ip.charAt(end) != ']') {
// must have a close ]
return false;
}
start = 1;
c = ip.charAt(1);
} else {
start = 0;
}
int colons;
int compressBegin;
if (c == ':') {
// an IPv6 address can start with "::" or with a number
if (ip.charAt(start + 1) != ':') {
return false;
}
colons = 2;
compressBegin = start;
start += 2;
} else {
colons = 0;
compressBegin = -1;
}
int wordLen = 0;
loop:
for (int i = start; i < end; i++) {
c = ip.charAt(i);
if (isValidHexChar(c)) {
if (wordLen < 4) {
wordLen++;
continue;
}
return false;
}
switch (c) {
case ':':
if (colons > 7) {
return false;
}
if (ip.charAt(i - 1) == ':') {
if (compressBegin >= 0) {
return false;
}
compressBegin = i - 1;
} else {
wordLen = 0;
}
colons++;
break;
case '.':
// case for the last 32-bits represented as IPv4 x:x:x:x:x:x:d.d.d.d
// check a normal case (6 single colons)
if (compressBegin < 0 && colons != 6 ||
// a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an
// IPv4 ending, otherwise 7 :'s is bad
(colons == 7 && compressBegin >= start || colons > 7)) {
return false;
}
// Verify this address is of the correct structure to contain an IPv4 address.
// It must be IPv4-Mapped or IPv4-Compatible
// (see https://tools.ietf.org/html/rfc4291#section-2.5.5).
int ipv4Start = i - wordLen;
int j = ipv4Start - 2; // index of character before the previous ':'.
if (isValidIPv4MappedChar(ip.charAt(j))) {
if (!isValidIPv4MappedChar(ip.charAt(j - 1)) ||
!isValidIPv4MappedChar(ip.charAt(j - 2)) ||
!isValidIPv4MappedChar(ip.charAt(j - 3))) {
return false;
}
j -= 5;
}
for (; j >= start; --j) {
char tmpChar = ip.charAt(j);
if (tmpChar != '0' && tmpChar != ':') {
return false;
}
}
// 7 - is minimum IPv4 address length
int ipv4End = indexOf(ip, '%', ipv4Start + 7);
if (ipv4End < 0) {
ipv4End = end;
}
return isValidIpV4Address(ip, ipv4Start, ipv4End);
case '%':
// strip the interface name/index after the percent sign
end = i;
break loop;
default:
return false;
}
}
// normal case without compression
if (compressBegin < 0) {
return colons == 7 && wordLen > 0;
}
return compressBegin + 2 == end ||
// 8 colons is valid only if compression in start or end
wordLen > 0 && (colons < 8 || compressBegin <= start);
}
private static boolean isValidIpV4Word(CharSequence word, int from, int toExclusive) {
int len = toExclusive - from;
char c0, c1, c2;
if (len < 1 || len > 3 || (c0 = word.charAt(from)) < '0') {
return false;
}
if (len == 3) {
return (c1 = word.charAt(from + 1)) >= '0' &&
(c2 = word.charAt(from + 2)) >= '0' &&
(c0 <= '1' && c1 <= '9' && c2 <= '9' ||
c0 == '2' && c1 <= '5' && (c2 <= '5' || c1 < '5' && c2 <= '9'));
}
return c0 <= '9' && (len == 1 || isValidNumericChar(word.charAt(from + 1)));
}
private static boolean isValidHexChar(char c) {
return c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f';
}
private static boolean isValidNumericChar(char c) {
return c >= '0' && c <= '9';
}
private static boolean isValidIPv4MappedChar(char c) {
return c == 'f' || c == 'F';
}
private static boolean isValidIPv4MappedSeparators(byte b0, byte b1, boolean mustBeZero) {
// We allow IPv4 Mapped (https://tools.ietf.org/html/rfc4291#section-2.5.5.1)
// and IPv4 compatible (https://tools.ietf.org/html/rfc4291#section-2.5.5.1).
// The IPv4 compatible is deprecated, but it allows parsing of plain IPv4 addressed into IPv6-Mapped addresses.
return b0 == b1 && (b0 == 0 || !mustBeZero && b1 == -1);
}
private static boolean isValidIPv4Mapped(byte[] bytes, int currentIndex, int compressBegin, int compressLength) {
final boolean mustBeZero = compressBegin + compressLength >= 14;
return currentIndex <= 12 && currentIndex >= 2 && (!mustBeZero || compressBegin < 12) &&
isValidIPv4MappedSeparators(bytes[currentIndex - 1], bytes[currentIndex - 2], mustBeZero) &&
PlatformDependent.isZero(bytes, 0, currentIndex - 3);
}
/**
* Takes a {@link CharSequence} and parses it to see if it is a valid IPV4 address.
*
* @return true, if the string represents an IPV4 address in dotted
* notation, false otherwise
*/
public static boolean isValidIpV4Address(CharSequence ip) {
return isValidIpV4Address(ip, 0, ip.length());
}
/**
* Takes a {@link String} and parses it to see if it is a valid IPV4 address.
*
* @return true, if the string represents an IPV4 address in dotted
* notation, false otherwise
*/
public static boolean isValidIpV4Address(String ip) {
return isValidIpV4Address(ip, 0, ip.length());
}
private static boolean isValidIpV4Address(CharSequence ip, int from, int toExcluded) {
return ip instanceof String ? isValidIpV4Address((String) ip, from, toExcluded) :
ip instanceof AsciiString ? isValidIpV4Address((AsciiString) ip, from, toExcluded) :
isValidIpV4Address0(ip, from, toExcluded);
}
@SuppressWarnings("DuplicateBooleanBranch")
private static boolean isValidIpV4Address(String ip, int from, int toExcluded) {
int len = toExcluded - from;
int i;
return len <= 15 && len >= 7 &&
(i = ip.indexOf('.', from + 1)) > 0 && isValidIpV4Word(ip, from, i) &&
(i = ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
(i = ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
isValidIpV4Word(ip, i + 1, toExcluded);
}
@SuppressWarnings("DuplicateBooleanBranch")
private static boolean isValidIpV4Address(AsciiString ip, int from, int toExcluded) {
int len = toExcluded - from;
int i;
return len <= 15 && len >= 7 &&
(i = ip.indexOf('.', from + 1)) > 0 && isValidIpV4Word(ip, from, i) &&
(i = ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
(i = ip.indexOf('.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
isValidIpV4Word(ip, i + 1, toExcluded);
}
@SuppressWarnings("DuplicateBooleanBranch")
private static boolean isValidIpV4Address0(CharSequence ip, int from, int toExcluded) {
int len = toExcluded - from;
int i;
return len <= 15 && len >= 7 &&
(i = indexOf(ip, '.', from + 1)) > 0 && isValidIpV4Word(ip, from, i) &&
(i = indexOf(ip, '.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
(i = indexOf(ip, '.', from = i + 2)) > 0 && isValidIpV4Word(ip, from - 1, i) &&
isValidIpV4Word(ip, i + 1, toExcluded);
}
/**
* Returns the {@link Inet6Address} representation of a {@link CharSequence} IP address.
* <p>
* This method will treat all IPv4 type addresses as "IPv4 mapped" (see {@link #getByName(CharSequence, boolean)})
* @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address}
* @return {@link Inet6Address} representation of the {@code ip} or {@code null} if not a valid IP address.
*/
public static Inet6Address getByName(CharSequence ip) {
return getByName(ip, true);
}
/**
* Returns the {@link Inet6Address} representation of a {@link CharSequence} IP address.
* <p>
* The {@code ipv4Mapped} parameter specifies how IPv4 addresses should be treated.
* "IPv4 mapped" format as
* defined in <a href="https://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> is supported.
* @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address}
* @param ipv4Mapped
* <ul>
* <li>{@code true} To allow IPv4 mapped inputs to be translated into {@link Inet6Address}</li>
* <li>{@code false} Consider IPv4 mapped addresses as invalid.</li>
* </ul>
* @return {@link Inet6Address} representation of the {@code ip} or {@code null} if not a valid IP address.
*/
public static Inet6Address getByName(CharSequence ip, boolean ipv4Mapped) {
byte[] bytes = getIPv6ByName(ip, ipv4Mapped);
if (bytes == null) {
return null;
}
try {
return Inet6Address.getByAddress(null, bytes, -1);
} catch (UnknownHostException e) {
throw new RuntimeException(e); // Should never happen
}
}
/**
* Returns the byte array representation of a {@link CharSequence} IP address.
* <p>
* The {@code ipv4Mapped} parameter specifies how IPv4 addresses should be treated.
* "IPv4 mapped" format as
* defined in <a href="https://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> is supported.
* @param ip {@link CharSequence} IP address to be converted to a {@link Inet6Address}
* @param ipv4Mapped
* <ul>
* <li>{@code true} To allow IPv4 mapped inputs to be translated into {@link Inet6Address}</li>
* <li>{@code false} Consider IPv4 mapped addresses as invalid.</li>
* </ul>
* @return byte array representation of the {@code ip} or {@code null} if not a valid IP address.
*/
// visible for test
static byte[] getIPv6ByName(CharSequence ip, boolean ipv4Mapped) {
final byte[] bytes = new byte[IPV6_BYTE_COUNT];
final int ipLength = ip.length();
int compressBegin = 0;
int compressLength = 0;
int currentIndex = 0;
int value = 0;
int begin = -1;
int i = 0;
int ipv6Separators = 0;
int ipv4Separators = 0;
int tmp;
for (; i < ipLength; ++i) {
final char c = ip.charAt(i);
switch (c) {
case ':':
++ipv6Separators;
if (i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR ||
ipv4Separators > 0 || ipv6Separators > IPV6_MAX_SEPARATORS ||
currentIndex + 1 >= bytes.length) {
return null;
}
value <<= (IPV6_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2;
if (compressLength > 0) {
compressLength -= 2;
}
// The value integer holds at most 4 bytes from right (most significant) to left (least significant).
// The following bit shifting is used to extract and re-order the individual bytes to achieve a
// left (most significant) to right (least significant) ordering.
bytes[currentIndex++] = (byte) (((value & 0xf) << 4) | ((value >> 4) & 0xf));
bytes[currentIndex++] = (byte) ((((value >> 8) & 0xf) << 4) | ((value >> 12) & 0xf));
tmp = i + 1;
if (tmp < ipLength && ip.charAt(tmp) == ':') {
++tmp;
if (compressBegin != 0 || (tmp < ipLength && ip.charAt(tmp) == ':')) {
return null;
}
++ipv6Separators;
compressBegin = currentIndex;
compressLength = bytes.length - compressBegin - 2;
++i;
}
value = 0;
begin = -1;
break;
case '.':
++ipv4Separators;
tmp = i - begin; // tmp is the length of the current segment.
if (tmp > IPV4_MAX_CHAR_BETWEEN_SEPARATOR
|| begin < 0
|| ipv4Separators > IPV4_SEPARATORS
|| (ipv6Separators > 0 && (currentIndex + compressLength < 12))
|| i + 1 >= ipLength
|| currentIndex >= bytes.length
|| ipv4Separators == 1 &&
// We also parse pure IPv4 addresses as IPv4-Mapped for ease of use.
((!ipv4Mapped || currentIndex != 0 && !isValidIPv4Mapped(bytes, currentIndex,
compressBegin, compressLength)) ||
(tmp == 3 && (!isValidNumericChar(ip.charAt(i - 1)) ||
!isValidNumericChar(ip.charAt(i - 2)) ||
!isValidNumericChar(ip.charAt(i - 3))) ||
tmp == 2 && (!isValidNumericChar(ip.charAt(i - 1)) ||
!isValidNumericChar(ip.charAt(i - 2))) ||
tmp == 1 && !isValidNumericChar(ip.charAt(i - 1))))) {
return null;
}
value <<= (IPV4_MAX_CHAR_BETWEEN_SEPARATOR - tmp) << 2;
// The value integer holds at most 3 bytes from right (most significant) to left (least significant).
// The following bit shifting is to restructure the bytes to be left (most significant) to
// right (least significant) while also accounting for each IPv4 digit is base 10.
begin = (value & 0xf) * 100 + ((value >> 4) & 0xf) * 10 + ((value >> 8) & 0xf);
if (begin > 255) {
return null;
}
bytes[currentIndex++] = (byte) begin;
value = 0;
begin = -1;
break;
default:
if (!isValidHexChar(c) || (ipv4Separators > 0 && !isValidNumericChar(c))) {
return null;
}
if (begin < 0) {
begin = i;
} else if (i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR) {
return null;
}
// The value is treated as a sort of array of numbers because we are dealing with
// at most 4 consecutive bytes we can use bit shifting to accomplish this.
// The most significant byte will be encountered first, and reside in the right most
// position of the following integer
value += StringUtil.decodeHexNibble(c) << ((i - begin) << 2);
break;
}
}
final boolean isCompressed = compressBegin > 0;
// Finish up last set of data that was accumulated in the loop (or before the loop)
if (ipv4Separators > 0) {
if (begin > 0 && i - begin > IPV4_MAX_CHAR_BETWEEN_SEPARATOR ||
ipv4Separators != IPV4_SEPARATORS ||
currentIndex >= bytes.length) {
return null;
}
if (!(ipv6Separators == 0 || ipv6Separators >= IPV6_MIN_SEPARATORS &&
(!isCompressed && (ipv6Separators == 6 && ip.charAt(0) != ':') ||
isCompressed && (ipv6Separators < IPV6_MAX_SEPARATORS &&
(ip.charAt(0) != ':' || compressBegin <= 2))))) {
return null;
}
value <<= (IPV4_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2;
// The value integer holds at most 3 bytes from right (most significant) to left (least significant).
// The following bit shifting is to restructure the bytes to be left (most significant) to
// right (least significant) while also accounting for each IPv4 digit is base 10.
begin = (value & 0xf) * 100 + ((value >> 4) & 0xf) * 10 + ((value >> 8) & 0xf);
if (begin > 255) {
return null;
}
bytes[currentIndex++] = (byte) begin;
} else {
tmp = ipLength - 1;
if (begin > 0 && i - begin > IPV6_MAX_CHAR_BETWEEN_SEPARATOR ||
ipv6Separators < IPV6_MIN_SEPARATORS ||
!isCompressed && (ipv6Separators + 1 != IPV6_MAX_SEPARATORS ||
ip.charAt(0) == ':' || ip.charAt(tmp) == ':') ||
isCompressed && (ipv6Separators > IPV6_MAX_SEPARATORS ||
(ipv6Separators == IPV6_MAX_SEPARATORS &&
(compressBegin <= 2 && ip.charAt(0) != ':' ||
compressBegin >= 14 && ip.charAt(tmp) != ':'))) ||
currentIndex + 1 >= bytes.length ||
begin < 0 && ip.charAt(tmp - 1) != ':' ||
compressBegin > 2 && ip.charAt(0) == ':') {
return null;
}
if (begin >= 0 && i - begin <= IPV6_MAX_CHAR_BETWEEN_SEPARATOR) {
value <<= (IPV6_MAX_CHAR_BETWEEN_SEPARATOR - (i - begin)) << 2;
}
// The value integer holds at most 4 bytes from right (most significant) to left (least significant).
// The following bit shifting is used to extract and re-order the individual bytes to achieve a
// left (most significant) to right (least significant) ordering.
bytes[currentIndex++] = (byte) (((value & 0xf) << 4) | ((value >> 4) & 0xf));
bytes[currentIndex++] = (byte) ((((value >> 8) & 0xf) << 4) | ((value >> 12) & 0xf));
}
if (currentIndex < bytes.length) {
int toBeCopiedLength = currentIndex - compressBegin;
int targetIndex = bytes.length - toBeCopiedLength;
System.arraycopy(bytes, compressBegin, bytes, targetIndex, toBeCopiedLength);
// targetIndex is also the `toIndex` to fill 0
Arrays.fill(bytes, compressBegin, targetIndex, (byte) 0);
}
if (ipv4Separators > 0) {
// We only support IPv4-Mapped addresses [1] because IPv4-Compatible addresses are deprecated [2].
// [1] https://tools.ietf.org/html/rfc4291#section-2.5.5.2
// [2] https://tools.ietf.org/html/rfc4291#section-2.5.5.1
bytes[10] = bytes[11] = (byte) 0xff;
}
return bytes;
}
/**
* Returns the {@link String} representation of an {@link InetSocketAddress}.
* <p>
* The output does not include Scope ID.
* @param addr {@link InetSocketAddress} to be converted to an address string
* @return {@code String} containing the text-formatted IP address
*/
public static String toSocketAddressString(InetSocketAddress addr) {
String port = String.valueOf(addr.getPort());
final StringBuilder sb;
if (addr.isUnresolved()) {
String hostname = getHostname(addr);
sb = newSocketAddressStringBuilder(hostname, port, !isValidIpV6Address(hostname));
} else {
InetAddress address = addr.getAddress();
String hostString = toAddressString(address);
sb = newSocketAddressStringBuilder(hostString, port, address instanceof Inet4Address);
}
return sb.append(':').append(port).toString();
}
/**
* Returns the {@link String} representation of a host port combo.
*/
public static String toSocketAddressString(String host, int port) {
String portStr = String.valueOf(port);
return newSocketAddressStringBuilder(
host, portStr, !isValidIpV6Address(host)).append(':').append(portStr).toString();
}
private static StringBuilder newSocketAddressStringBuilder(String host, String port, boolean ipv4) {
int hostLen = host.length();
if (ipv4) {
// Need to include enough space for hostString:port.
return new StringBuilder(hostLen + 1 + port.length()).append(host);
}
// Need to include enough space for [hostString]:port.
StringBuilder stringBuilder = new StringBuilder(hostLen + 3 + port.length());
if (hostLen > 1 && host.charAt(0) == '[' && host.charAt(hostLen - 1) == ']') {
return stringBuilder.append(host);
}
return stringBuilder.append('[').append(host).append(']');
}
/**
* Returns the {@link String} representation of an {@link InetAddress}.
* <ul>
* <li>Inet4Address results are identical to {@link InetAddress#getHostAddress()}</li>
* <li>Inet6Address results adhere to
* <a href="https://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li>
* </ul>
* <p>
* The output does not include Scope ID.
* @param ip {@link InetAddress} to be converted to an address string
* @return {@code String} containing the text-formatted IP address
*/
public static String toAddressString(InetAddress ip) {
return toAddressString(ip, false);
}
/**
* Returns the {@link String} representation of an {@link InetAddress}.
* <ul>
* <li>Inet4Address results are identical to {@link InetAddress#getHostAddress()}</li>
* <li>Inet6Address results adhere to
* <a href="https://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a> if
* {@code ipv4Mapped} is false. If {@code ipv4Mapped} is true then "IPv4 mapped" format
* from <a href="https://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> will be supported.
* The compressed result will always obey the compression rules defined in
* <a href="https://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li>
* </ul>
* <p>
* The output does not include Scope ID.
* @param ip {@link InetAddress} to be converted to an address string
* @param ipv4Mapped
* <ul>
* <li>{@code true} to stray from strict rfc 5952 and support the "IPv4 mapped" format
* defined in <a href="https://tools.ietf.org/html/rfc4291#section-2.5.5">rfc 4291 section 2</a> while still
* following the updated guidelines in
* <a href="https://tools.ietf.org/html/rfc5952#section-4">rfc 5952 section 4</a></li>
* <li>{@code false} to strictly follow rfc 5952</li>
* </ul>
* @return {@code String} containing the text-formatted IP address
*/
public static String toAddressString(InetAddress ip, boolean ipv4Mapped) {
if (ip instanceof Inet4Address) {
return ip.getHostAddress();
}
if (!(ip instanceof Inet6Address)) {
throw new IllegalArgumentException("Unhandled type: " + ip);
}
return toAddressString(ip.getAddress(), 0, ipv4Mapped);
}
private static String toAddressString(byte[] bytes, int offset, boolean ipv4Mapped) {
final int[] words = new int[IPV6_WORD_COUNT];
for (int i = 0; i < words.length; ++i) {
int idx = (i << 1) + offset;
words[i] = ((bytes[idx] & 0xff) << 8) | (bytes[idx + 1] & 0xff);
}
// Find longest run of 0s, tie goes to first found instance
int currentStart = -1;
int currentLength;
int shortestStart = -1;
int shortestLength = 0;
for (int i = 0; i < words.length; ++i) {
if (words[i] == 0) {
if (currentStart < 0) {
currentStart = i;
}
} else if (currentStart >= 0) {
currentLength = i - currentStart;
if (currentLength > shortestLength) {
shortestStart = currentStart;
shortestLength = currentLength;
}
currentStart = -1;
}
}
// If the array ends on a streak of zeros, make sure we account for it
if (currentStart >= 0) {
currentLength = words.length - currentStart;
if (currentLength > shortestLength) {
shortestStart = currentStart;
shortestLength = currentLength;
}
}
// Ignore the longest streak if it is only 1 long
if (shortestLength == 1) {
shortestLength = 0;
shortestStart = -1;
}
// Translate to string taking into account longest consecutive 0s
final int shortestEnd = shortestStart + shortestLength;
final StringBuilder b = new StringBuilder(IPV6_MAX_CHAR_COUNT);
if (shortestEnd < 0) { // Optimization when there is no compressing needed
b.append(Integer.toHexString(words[0]));
for (int i = 1; i < words.length; ++i) {
b.append(':');
b.append(Integer.toHexString(words[i]));
}
} else { // General case that can handle compressing (and not compressing)
// Loop unroll the first index (so we don't constantly check i==0 cases in loop)
final boolean isIpv4Mapped;
if (inRangeEndExclusive(0, shortestStart, shortestEnd)) {
b.append("::");
isIpv4Mapped = ipv4Mapped && (shortestEnd == 5 && words[5] == 0xffff);
} else {
b.append(Integer.toHexString(words[0]));
isIpv4Mapped = false;
}
for (int i = 1; i < words.length; ++i) {
if (!inRangeEndExclusive(i, shortestStart, shortestEnd)) {
if (!inRangeEndExclusive(i - 1, shortestStart, shortestEnd)) {
// If the last index was not part of the shortened sequence
if (!isIpv4Mapped || i == 6) {
b.append(':');
} else {
b.append('.');
}
}
if (isIpv4Mapped && i > 5) {
b.append(words[i] >> 8);
b.append('.');
b.append(words[i] & 0xff);
} else {
b.append(Integer.toHexString(words[i]));
}
} else if (!inRangeEndExclusive(i - 1, shortestStart, shortestEnd)) {
// If we are in the shortened sequence and the last index was not
b.append("::");
}
}
}
return b.toString();
}
/**
* Returns {@link InetSocketAddress#getHostString()} if Java >= 7,
* or {@link InetSocketAddress#getHostName()} otherwise.
* @param addr The address
* @return the host string
*/
public static String getHostname(InetSocketAddress addr) {
return PlatformDependent.javaVersion() >= 7 ? addr.getHostString() : addr.getHostName();
}
/**
* Does a range check on {@code value} if is within {@code start} (inclusive) and {@code end} (exclusive).
* @param value The value to checked if is within {@code start} (inclusive) and {@code end} (exclusive)
* @param start The start of the range (inclusive)
* @param end The end of the range (exclusive)
* @return
* <ul>
* <li>{@code true} if {@code value} if is within {@code start} (inclusive) and {@code end} (exclusive)</li>
* <li>{@code false} otherwise</li>
* </ul>
*/
private static boolean inRangeEndExclusive(int value, int start, int end) {
return value >= start && value < end;
}
/**
* A constructor to stop this class being constructed.
*/
private NetUtil() {
// Unused
}
}
| netty/netty | common/src/main/java/io/netty/util/NetUtil.java |
118 | /*
* Copyright 2002-2023 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.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeSet;
import org.springframework.lang.Nullable;
/**
* Represents a MIME Type, as originally defined in RFC 2046 and subsequently
* used in other Internet protocols including HTTP.
*
* <p>This class, however, does not contain support for the q-parameters used
* in HTTP content negotiation. Those can be found in the subclass
* {@code org.springframework.http.MediaType} in the {@code spring-web} module.
*
* <p>Consists of a {@linkplain #getType() type} and a {@linkplain #getSubtype() subtype}.
* Also has functionality to parse MIME Type values from a {@code String} using
* {@link #valueOf(String)}. For more parsing options see {@link MimeTypeUtils}.
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.0
* @see MimeTypeUtils
*/
public class MimeType implements Comparable<MimeType>, Serializable {
private static final long serialVersionUID = 4085923477777865903L;
protected static final String WILDCARD_TYPE = "*";
private static final String PARAM_CHARSET = "charset";
private static final BitSet TOKEN;
static {
// variable names refer to RFC 2616, section 2.2
BitSet ctl = new BitSet(128);
for (int i = 0; i <= 31; i++) {
ctl.set(i);
}
ctl.set(127);
BitSet separators = new BitSet(128);
separators.set('(');
separators.set(')');
separators.set('<');
separators.set('>');
separators.set('@');
separators.set(',');
separators.set(';');
separators.set(':');
separators.set('\\');
separators.set('\"');
separators.set('/');
separators.set('[');
separators.set(']');
separators.set('?');
separators.set('=');
separators.set('{');
separators.set('}');
separators.set(' ');
separators.set('\t');
TOKEN = new BitSet(128);
TOKEN.set(0, 128);
TOKEN.andNot(ctl);
TOKEN.andNot(separators);
}
private final String type;
private final String subtype;
private final Map<String, String> parameters;
@Nullable
private transient Charset resolvedCharset;
@Nullable
private volatile String toStringValue;
/**
* Create a new {@code MimeType} for the given primary type.
* <p>The {@linkplain #getSubtype() subtype} is set to <code>"*"</code>,
* and the parameters are empty.
* @param type the primary type
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type) {
this(type, WILDCARD_TYPE);
}
/**
* Create a new {@code MimeType} for the given primary type and subtype.
* <p>The parameters are empty.
* @param type the primary type
* @param subtype the subtype
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type, String subtype) {
this(type, subtype, Collections.emptyMap());
}
/**
* Create a new {@code MimeType} for the given type, subtype, and character set.
* @param type the primary type
* @param subtype the subtype
* @param charset the character set
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type, String subtype, Charset charset) {
this(type, subtype, Collections.singletonMap(PARAM_CHARSET, charset.name()));
this.resolvedCharset = charset;
}
/**
* Copy-constructor that copies the type, subtype, parameters of the given {@code MimeType},
* and allows to set the specified character set.
* @param other the other MimeType
* @param charset the character set
* @throws IllegalArgumentException if any of the parameters contains illegal characters
* @since 4.3
*/
public MimeType(MimeType other, Charset charset) {
this(other.getType(), other.getSubtype(), addCharsetParameter(charset, other.getParameters()));
this.resolvedCharset = charset;
}
/**
* Copy-constructor that copies the type and subtype of the given {@code MimeType},
* and allows for different parameter.
* @param other the other MimeType
* @param parameters the parameters (may be {@code null})
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(MimeType other, @Nullable Map<String, String> parameters) {
this(other.getType(), other.getSubtype(), parameters);
}
/**
* Create a new {@code MimeType} for the given type, subtype, and parameters.
* @param type the primary type
* @param subtype the subtype
* @param parameters the parameters (may be {@code null})
* @throws IllegalArgumentException if any of the parameters contains illegal characters
*/
public MimeType(String type, String subtype, @Nullable Map<String, String> parameters) {
Assert.hasLength(type, "'type' must not be empty");
Assert.hasLength(subtype, "'subtype' must not be empty");
checkToken(type);
checkToken(subtype);
this.type = type.toLowerCase(Locale.ENGLISH);
this.subtype = subtype.toLowerCase(Locale.ENGLISH);
if (!CollectionUtils.isEmpty(parameters)) {
Map<String, String> map = new LinkedCaseInsensitiveMap<>(parameters.size(), Locale.ENGLISH);
parameters.forEach((parameter, value) -> {
checkParameters(parameter, value);
map.put(parameter, value);
});
this.parameters = Collections.unmodifiableMap(map);
}
else {
this.parameters = Collections.emptyMap();
}
}
/**
* Copy-constructor that copies the type, subtype and parameters of the given {@code MimeType},
* skipping checks performed in other constructors.
* @param other the other MimeType
* @since 5.3
*/
protected MimeType(MimeType other) {
this.type = other.type;
this.subtype = other.subtype;
this.parameters = other.parameters;
this.resolvedCharset = other.resolvedCharset;
this.toStringValue = other.toStringValue;
}
/**
* Checks the given token string for illegal characters, as defined in RFC 2616,
* section 2.2.
* @throws IllegalArgumentException in case of illegal characters
* @see <a href="https://tools.ietf.org/html/rfc2616#section-2.2">HTTP 1.1, section 2.2</a>
*/
private void checkToken(String token) {
for (int i = 0; i < token.length(); i++) {
char ch = token.charAt(i);
if (!TOKEN.get(ch)) {
throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + token + "\"");
}
}
}
protected void checkParameters(String parameter, String value) {
Assert.hasLength(parameter, "'parameter' must not be empty");
Assert.hasLength(value, "'value' must not be empty");
checkToken(parameter);
if (PARAM_CHARSET.equals(parameter)) {
if (this.resolvedCharset == null) {
this.resolvedCharset = Charset.forName(unquote(value));
}
}
else if (!isQuotedString(value)) {
checkToken(value);
}
}
private boolean isQuotedString(String s) {
if (s.length() < 2) {
return false;
}
else {
return ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'")));
}
}
protected String unquote(String s) {
return (isQuotedString(s) ? s.substring(1, s.length() - 1) : s);
}
/**
* Indicates whether the {@linkplain #getType() type} is the wildcard character
* <code>*</code> or not.
*/
public boolean isWildcardType() {
return WILDCARD_TYPE.equals(getType());
}
/**
* Indicates whether the {@linkplain #getSubtype() subtype} is the wildcard
* character <code>*</code> or the wildcard character followed by a suffix
* (e.g. <code>*+xml</code>).
* @return whether the subtype is a wildcard
*/
public boolean isWildcardSubtype() {
String subtype = getSubtype();
return (WILDCARD_TYPE.equals(subtype) || subtype.startsWith("*+"));
}
/**
* Indicates whether this MIME Type is concrete, i.e. whether neither the type
* nor the subtype is a wildcard character <code>*</code>.
* @return whether this MIME Type is concrete
*/
public boolean isConcrete() {
return !isWildcardType() && !isWildcardSubtype();
}
/**
* Return the primary type.
*/
public String getType() {
return this.type;
}
/**
* Return the subtype.
*/
public String getSubtype() {
return this.subtype;
}
/**
* Return the subtype suffix as defined in RFC 6839.
* @since 5.3
*/
@Nullable
public String getSubtypeSuffix() {
int suffixIndex = this.subtype.lastIndexOf('+');
if (suffixIndex != -1 && this.subtype.length() > suffixIndex) {
return this.subtype.substring(suffixIndex + 1);
}
return null;
}
/**
* Return the character set, as indicated by a {@code charset} parameter, if any.
* @return the character set, or {@code null} if not available
* @since 4.3
*/
@Nullable
public Charset getCharset() {
return this.resolvedCharset;
}
/**
* Return a generic parameter value, given a parameter name.
* @param name the parameter name
* @return the parameter value, or {@code null} if not present
*/
@Nullable
public String getParameter(String name) {
return this.parameters.get(name);
}
/**
* Return all generic parameter values.
* @return a read-only map (possibly empty, never {@code null})
*/
public Map<String, String> getParameters() {
return this.parameters;
}
/**
* Indicate whether this MIME Type includes the given MIME Type.
* <p>For instance, {@code text/*} includes {@code text/plain} and {@code text/html},
* and {@code application/*+xml} includes {@code application/soap+xml}, etc.
* This method is <b>not</b> symmetric.
* @param other the reference MIME Type with which to compare
* @return {@code true} if this MIME Type includes the given MIME Type;
* {@code false} otherwise
*/
public boolean includes(@Nullable MimeType other) {
if (other == null) {
return false;
}
if (isWildcardType()) {
// */* includes anything
return true;
}
else if (getType().equals(other.getType())) {
if (getSubtype().equals(other.getSubtype())) {
return true;
}
if (isWildcardSubtype()) {
// Wildcard with suffix, e.g. application/*+xml
int thisPlusIdx = getSubtype().lastIndexOf('+');
if (thisPlusIdx == -1) {
return true;
}
else {
// application/*+xml includes application/soap+xml
int otherPlusIdx = other.getSubtype().lastIndexOf('+');
if (otherPlusIdx != -1) {
String thisSubtypeNoSuffix = getSubtype().substring(0, thisPlusIdx);
String thisSubtypeSuffix = getSubtype().substring(thisPlusIdx + 1);
String otherSubtypeSuffix = other.getSubtype().substring(otherPlusIdx + 1);
if (thisSubtypeSuffix.equals(otherSubtypeSuffix) && WILDCARD_TYPE.equals(thisSubtypeNoSuffix)) {
return true;
}
}
}
}
}
return false;
}
/**
* Indicate whether this MIME Type is compatible with the given MIME Type.
* <p>For instance, {@code text/*} is compatible with {@code text/plain},
* {@code text/html}, and vice versa. In effect, this method is similar to
* {@link #includes}, except that it <b>is</b> symmetric.
* @param other the reference MIME Type with which to compare
* @return {@code true} if this MIME Type is compatible with the given MIME Type;
* {@code false} otherwise
*/
public boolean isCompatibleWith(@Nullable MimeType other) {
if (other == null) {
return false;
}
if (isWildcardType() || other.isWildcardType()) {
return true;
}
else if (getType().equals(other.getType())) {
if (getSubtype().equals(other.getSubtype())) {
return true;
}
if (isWildcardSubtype() || other.isWildcardSubtype()) {
String thisSuffix = getSubtypeSuffix();
String otherSuffix = other.getSubtypeSuffix();
if (getSubtype().equals(WILDCARD_TYPE) || other.getSubtype().equals(WILDCARD_TYPE)) {
return true;
}
else if (isWildcardSubtype() && thisSuffix != null) {
return (thisSuffix.equals(other.getSubtype()) || thisSuffix.equals(otherSuffix));
}
else if (other.isWildcardSubtype() && otherSuffix != null) {
return (getSubtype().equals(otherSuffix) || otherSuffix.equals(thisSuffix));
}
}
}
return false;
}
/**
* Similar to {@link #equals(Object)} but based on the type and subtype
* only, i.e. ignoring parameters.
* @param other the other mime type to compare to
* @return whether the two mime types have the same type and subtype
* @since 5.1.4
*/
public boolean equalsTypeAndSubtype(@Nullable MimeType other) {
if (other == null) {
return false;
}
return this.type.equalsIgnoreCase(other.type) && this.subtype.equalsIgnoreCase(other.subtype);
}
/**
* Unlike {@link Collection#contains(Object)} which relies on
* {@link MimeType#equals(Object)}, this method only checks the type and the
* subtype, but otherwise ignores parameters.
* @param mimeTypes the list of mime types to perform the check against
* @return whether the list contains the given mime type
* @since 5.1.4
*/
public boolean isPresentIn(Collection<? extends MimeType> mimeTypes) {
for (MimeType mimeType : mimeTypes) {
if (mimeType.equalsTypeAndSubtype(this)) {
return true;
}
}
return false;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof MimeType otherType &&
this.type.equalsIgnoreCase(otherType.type) &&
this.subtype.equalsIgnoreCase(otherType.subtype) &&
parametersAreEqual(otherType)));
}
/**
* Determine if the parameters in this {@code MimeType} and the supplied
* {@code MimeType} are equal, performing case-insensitive comparisons
* for {@link Charset Charsets}.
* @since 4.2
*/
private boolean parametersAreEqual(MimeType other) {
if (this.parameters.size() != other.parameters.size()) {
return false;
}
for (Map.Entry<String, String> entry : this.parameters.entrySet()) {
String key = entry.getKey();
if (!other.parameters.containsKey(key)) {
return false;
}
if (PARAM_CHARSET.equals(key)) {
if (!ObjectUtils.nullSafeEquals(getCharset(), other.getCharset())) {
return false;
}
}
else if (!ObjectUtils.nullSafeEquals(entry.getValue(), other.parameters.get(key))) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int result = this.type.hashCode();
result = 31 * result + this.subtype.hashCode();
result = 31 * result + this.parameters.hashCode();
return result;
}
@Override
public String toString() {
String value = this.toStringValue;
if (value == null) {
StringBuilder builder = new StringBuilder();
appendTo(builder);
value = builder.toString();
this.toStringValue = value;
}
return value;
}
protected void appendTo(StringBuilder builder) {
builder.append(this.type);
builder.append('/');
builder.append(this.subtype);
appendTo(this.parameters, builder);
}
private void appendTo(Map<String, String> map, StringBuilder builder) {
map.forEach((key, val) -> {
builder.append(';');
builder.append(key);
builder.append('=');
builder.append(val);
});
}
/**
* Compares this MIME Type to another alphabetically.
* @param other the MIME Type to compare to
*/
@Override
public int compareTo(MimeType other) {
int comp = getType().compareToIgnoreCase(other.getType());
if (comp != 0) {
return comp;
}
comp = getSubtype().compareToIgnoreCase(other.getSubtype());
if (comp != 0) {
return comp;
}
comp = getParameters().size() - other.getParameters().size();
if (comp != 0) {
return comp;
}
TreeSet<String> thisAttributes = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
thisAttributes.addAll(getParameters().keySet());
TreeSet<String> otherAttributes = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
otherAttributes.addAll(other.getParameters().keySet());
Iterator<String> thisAttributesIterator = thisAttributes.iterator();
Iterator<String> otherAttributesIterator = otherAttributes.iterator();
while (thisAttributesIterator.hasNext()) {
String thisAttribute = thisAttributesIterator.next();
String otherAttribute = otherAttributesIterator.next();
comp = thisAttribute.compareToIgnoreCase(otherAttribute);
if (comp != 0) {
return comp;
}
if (PARAM_CHARSET.equals(thisAttribute)) {
Charset thisCharset = getCharset();
Charset otherCharset = other.getCharset();
if (thisCharset != otherCharset) {
if (thisCharset == null) {
return -1;
}
if (otherCharset == null) {
return 1;
}
comp = thisCharset.compareTo(otherCharset);
if (comp != 0) {
return comp;
}
}
}
else {
String thisValue = getParameters().get(thisAttribute);
String otherValue = other.getParameters().get(otherAttribute);
Assert.notNull(thisValue, "Parameter for " + thisAttribute + " must not be null");
if (otherValue == null) {
otherValue = "";
}
comp = thisValue.compareTo(otherValue);
if (comp != 0) {
return comp;
}
}
}
return 0;
}
/**
* Indicates whether this {@code MimeType} is more specific than the given
* type.
* <ol>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code false}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code true}.</li>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code false}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code true}.</li>
* <li>if the two mime types have identical {@linkplain #getType() type} and
* {@linkplain #getSubtype() subtype}, then the mime type with the most
* parameters is more specific than the other.</li>
* <li>Otherwise, this method returns {@code false}.</li>
* </ol>
* @param other the {@code MimeType} to be compared
* @return the result of the comparison
* @since 6.0
* @see #isLessSpecific(MimeType)
* @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">HTTP 1.1: Semantics
* and Content, section 5.3.2</a>
*/
public boolean isMoreSpecific(MimeType other) {
Assert.notNull(other, "Other must not be null");
boolean thisWildcard = isWildcardType();
boolean otherWildcard = other.isWildcardType();
if (thisWildcard && !otherWildcard) { // */* > audio/*
return false;
}
else if (!thisWildcard && otherWildcard) { // audio/* < */*
return true;
}
else {
boolean thisWildcardSubtype = isWildcardSubtype();
boolean otherWildcardSubtype = other.isWildcardSubtype();
if (thisWildcardSubtype && !otherWildcardSubtype) { // audio/* > audio/basic
return false;
}
else if (!thisWildcardSubtype && otherWildcardSubtype) { // audio/basic < audio/*
return true;
}
else if (getType().equals(other.getType()) && getSubtype().equals(other.getSubtype())) {
int paramsSize1 = getParameters().size();
int paramsSize2 = other.getParameters().size();
return paramsSize1 > paramsSize2;
}
else {
return false;
}
}
}
/**
* Indicates whether this {@code MimeType} is less specific than the given type.
* <ol>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code true}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code false}.</li>
* <li>if this mime type has a {@linkplain #isWildcardType() wildcard type},
* and the other does not, then this method returns {@code true}.</li>
* <li>if this mime type does not have a {@linkplain #isWildcardType() wildcard type},
* and the other does, then this method returns {@code false}.</li>
* <li>if the two mime types have identical {@linkplain #getType() type} and
* {@linkplain #getSubtype() subtype}, then the mime type with the least
* parameters is less specific than the other.</li>
* <li>Otherwise, this method returns {@code false}.</li>
* </ol>
* @param other the {@code MimeType} to be compared
* @return the result of the comparison
* @since 6.0
* @see #isMoreSpecific(MimeType)
* @see <a href="https://tools.ietf.org/html/rfc7231#section-5.3.2">HTTP 1.1: Semantics
* and Content, section 5.3.2</a>
*/
public boolean isLessSpecific(MimeType other) {
Assert.notNull(other, "Other must not be null");
return other.isMoreSpecific(this);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Rely on default serialization, just initialize state after deserialization.
ois.defaultReadObject();
// Initialize transient fields.
String charsetName = getParameter(PARAM_CHARSET);
if (charsetName != null) {
this.resolvedCharset = Charset.forName(unquote(charsetName));
}
}
/**
* Parse the given String value into a {@code MimeType} object,
* with this method name following the 'valueOf' naming convention
* (as supported by {@link org.springframework.core.convert.ConversionService}).
* @see MimeTypeUtils#parseMimeType(String)
*/
public static MimeType valueOf(String value) {
return MimeTypeUtils.parseMimeType(value);
}
private static Map<String, String> addCharsetParameter(Charset charset, Map<String, String> parameters) {
Map<String, String> map = new LinkedHashMap<>(parameters);
map.put(PARAM_CHARSET, charset.name());
return map;
}
/**
* Comparator to sort {@link MimeType MimeTypes} in order of specificity.
*
* @param <T> the type of mime types that may be compared by this comparator
* @deprecated As of 6.0, with no direct replacement
*/
@Deprecated(since = "6.0", forRemoval = true)
public static class SpecificityComparator<T extends MimeType> implements Comparator<T> {
@Override
public int compare(T mimeType1, T mimeType2) {
if (mimeType1.isWildcardType() && !mimeType2.isWildcardType()) { // */* < audio/*
return 1;
}
else if (mimeType2.isWildcardType() && !mimeType1.isWildcardType()) { // audio/* > */*
return -1;
}
else if (!mimeType1.getType().equals(mimeType2.getType())) { // audio/basic == text/html
return 0;
}
else { // mediaType1.getType().equals(mediaType2.getType())
if (mimeType1.isWildcardSubtype() && !mimeType2.isWildcardSubtype()) { // audio/* < audio/basic
return 1;
}
else if (mimeType2.isWildcardSubtype() && !mimeType1.isWildcardSubtype()) { // audio/basic > audio/*
return -1;
}
else if (!mimeType1.getSubtype().equals(mimeType2.getSubtype())) { // audio/basic == audio/wave
return 0;
}
else { // mediaType2.getSubtype().equals(mediaType2.getSubtype())
return compareParameters(mimeType1, mimeType2);
}
}
}
protected int compareParameters(T mimeType1, T mimeType2) {
int paramsSize1 = mimeType1.getParameters().size();
int paramsSize2 = mimeType2.getParameters().size();
return Integer.compare(paramsSize2, paramsSize1); // audio/basic;level=1 < audio/basic
}
}
}
| spring-projects/spring-framework | spring-core/src/main/java/org/springframework/util/MimeType.java |
119 | package org.groestlcoin.qt;
import android.os.Bundle;
import android.system.ErrnoException;
import android.system.Os;
import org.qtproject.qt5.android.bindings.QtActivity;
import java.io.File;
public class BitcoinQtActivity extends QtActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
final File bitcoinDir = new File(getFilesDir().getAbsolutePath() + "/.groestlcoin");
if (!bitcoinDir.exists()) {
bitcoinDir.mkdir();
}
super.onCreate(savedInstanceState);
}
}
| Groestlcoin/groestlcoin | src/qt/android/src/org/groestlcoin/qt/BitcoinQtActivity.java |
120 | // Copyright 2004-present Facebook. All Rights Reserved.
package org.pytorch;
import com.facebook.soloader.nativeloader.NativeLoader;
import com.facebook.soloader.nativeloader.SystemDelegate;
import java.util.Map;
/** Java wrapper for torch::jit::Module. */
public class Module {
private INativePeer mNativePeer;
/**
* Loads a serialized TorchScript module from the specified path on the disk to run on specified
* device.
*
* @param modelPath path to file that contains the serialized TorchScript module.
* @param extraFiles map with extra files names as keys, content of them will be loaded to values.
* @param device {@link org.pytorch.Device} to use for running specified module.
* @return new {@link org.pytorch.Module} object which owns torch::jit::Module.
*/
public static Module load(
final String modelPath, final Map<String, String> extraFiles, final Device device) {
if (!NativeLoader.isInitialized()) {
NativeLoader.init(new SystemDelegate());
}
return new Module(new NativePeer(modelPath, extraFiles, device));
}
/**
* Loads a serialized TorchScript module from the specified path on the disk to run on CPU.
*
* @param modelPath path to file that contains the serialized TorchScript module.
* @return new {@link org.pytorch.Module} object which owns torch::jit::Module.
*/
public static Module load(final String modelPath) {
return load(modelPath, null, Device.CPU);
}
Module(INativePeer nativePeer) {
this.mNativePeer = nativePeer;
}
/**
* Runs the 'forward' method of this module with the specified arguments.
*
* @param inputs arguments for the TorchScript module's 'forward' method.
* @return return value from the 'forward' method.
*/
public IValue forward(IValue... inputs) {
return mNativePeer.forward(inputs);
}
/**
* Runs the specified method of this module with the specified arguments.
*
* @param methodName name of the TorchScript method to run.
* @param inputs arguments that will be passed to TorchScript method.
* @return return value from the method.
*/
public IValue runMethod(String methodName, IValue... inputs) {
return mNativePeer.runMethod(methodName, inputs);
}
/**
* Explicitly destroys the native torch::jit::Module. Calling this method is not required, as the
* native object will be destroyed when this object is garbage-collected. However, the timing of
* garbage collection is not guaranteed, so proactively calling {@code destroy} can free memory
* more quickly. See {@link com.facebook.jni.HybridData#resetNative}.
*/
public void destroy() {
mNativePeer.resetNative();
}
}
| pytorch/pytorch | android/pytorch_android/src/main/java/org/pytorch/Module.java |
122 | /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.lite;
import java.lang.reflect.Array;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.util.Arrays;
import org.checkerframework.checker.nullness.qual.NonNull;
/** Implementation of {@link Tensor}. */
// TODO(b/153882978): Add scalar getters similar to TF's Java API.
final class TensorImpl implements Tensor {
/**
* Creates a Tensor wrapper from the provided interpreter instance and tensor index.
*
* <p>The caller is responsible for closing the created wrapper, and ensuring the provided native
* interpreter is valid until the tensor is closed.
*/
static TensorImpl fromIndex(long nativeInterpreterHandle, int tensorIndex) {
return new TensorImpl(create(nativeInterpreterHandle, tensorIndex, /*subgraphIndex=*/ 0));
}
/**
* Creates a Tensor wrapper for a Signature input.
*
* <p>The caller is responsible for closing the created wrapper, and ensuring the provided native
* SignatureRunner is valid until the tensor is closed.
*/
static TensorImpl fromSignatureInput(long signatureRunnerHandle, String inputName) {
long tensorHandle = createSignatureInputTensor(signatureRunnerHandle, inputName);
if (tensorHandle == -1) {
throw new IllegalArgumentException("Input error: input " + inputName + " not found.");
} else {
return new TensorImpl(tensorHandle);
}
}
/**
* Creates a Tensor wrapper for a Signature output.
*
* <p>The caller is responsible for closing the created wrapper, and ensuring the provided native
* SignatureRunner is valid until the tensor is closed.
*/
static TensorImpl fromSignatureOutput(long signatureRunnerHandle, String outputName) {
long tensorHandle = createSignatureOutputTensor(signatureRunnerHandle, outputName);
if (tensorHandle == -1) {
throw new IllegalArgumentException("Input error: output " + outputName + " not found.");
} else {
return new TensorImpl(tensorHandle);
}
}
/** Disposes of any resources used by the Tensor wrapper. */
void close() {
delete(nativeHandle);
nativeHandle = 0;
}
@Override
public DataType dataType() {
return dtype;
}
@Override
public int numDimensions() {
return shapeCopy.length;
}
@Override
public int numBytes() {
return numBytes(nativeHandle);
}
@Override
public int numElements() {
return computeNumElements(shapeCopy);
}
@Override
public int[] shape() {
return shapeCopy;
}
@Override
public int[] shapeSignature() {
return shapeSignatureCopy;
}
@Override
public int index() {
return index(nativeHandle);
}
@Override
public String name() {
return name(nativeHandle);
}
@Override
public QuantizationParams quantizationParams() {
return quantizationParamsCopy;
}
@Override
public ByteBuffer asReadOnlyBuffer() {
// Note that the ByteBuffer order is not preserved when duplicated or marked read only, so
// we have to repeat the call.
return buffer().asReadOnlyBuffer().order(ByteOrder.nativeOrder());
}
/**
* Copies the contents of the provided {@code src} object to the Tensor.
*
* <p>The {@code src} should either be a (multi-dimensional) array with a shape matching that of
* this tensor, a {@link ByteBuffer} of compatible primitive type with a matching flat size, or
* {@code null} iff the tensor has an underlying delegate buffer handle.
*
* @throws IllegalArgumentException if the tensor is a scalar or if {@code src} is not compatible
* with the tensor (for example, mismatched data types or shapes).
*/
void setTo(Object src) {
if (src == null) {
if (hasDelegateBufferHandle(nativeHandle)) {
return;
}
throw new IllegalArgumentException(
"Null inputs are allowed only if the Tensor is bound to a buffer handle.");
}
throwIfTypeIsIncompatible(src);
throwIfSrcShapeIsIncompatible(src);
if (isBuffer(src)) {
setTo((Buffer) src);
} else if (dtype == DataType.STRING && shapeCopy.length == 0) {
// Update scalar string input with 1-d byte array.
writeScalar(nativeHandle, src);
} else if (src.getClass().isArray()) {
writeMultiDimensionalArray(nativeHandle, src);
} else {
writeScalar(nativeHandle, src);
}
}
private void setTo(Buffer src) {
// Note that we attempt to use a direct memcpy optimization for direct, native-ordered buffers.
// There are no base Buffer#order() or Buffer#put() methods, so again we have to ugly cast.
if (src instanceof ByteBuffer) {
ByteBuffer srcBuffer = (ByteBuffer) src;
if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) {
writeDirectBuffer(nativeHandle, src);
} else {
buffer().put(srcBuffer);
}
} else if (src instanceof LongBuffer) {
LongBuffer srcBuffer = (LongBuffer) src;
if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) {
writeDirectBuffer(nativeHandle, src);
} else {
buffer().asLongBuffer().put(srcBuffer);
}
} else if (src instanceof FloatBuffer) {
FloatBuffer srcBuffer = (FloatBuffer) src;
if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) {
writeDirectBuffer(nativeHandle, src);
} else {
buffer().asFloatBuffer().put(srcBuffer);
}
} else if (src instanceof IntBuffer) {
IntBuffer srcBuffer = (IntBuffer) src;
if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) {
writeDirectBuffer(nativeHandle, src);
} else {
buffer().asIntBuffer().put(srcBuffer);
}
} else if (src instanceof ShortBuffer) {
ShortBuffer srcBuffer = (ShortBuffer) src;
if (srcBuffer.isDirect() && srcBuffer.order() == ByteOrder.nativeOrder()) {
writeDirectBuffer(nativeHandle, src);
} else {
buffer().asShortBuffer().put(srcBuffer);
}
} else {
throw new IllegalArgumentException("Unexpected input buffer type: " + src);
}
}
/**
* Copies the contents of the tensor to {@code dst}.
*
* @param dst the destination buffer, either an explicitly-typed array, a compatible {@link
* Buffer} or {@code null} iff the tensor has an underlying delegate buffer handle. If
* providing a (multi-dimensional) array, its shape must match the tensor shape *exactly*. If
* providing a {@link Buffer}, its capacity must be at least as large as the source tensor's
* capacity.
* @throws IllegalArgumentException if {@code dst} is not compatible with the tensor (for example,
* mismatched data types or shapes).
*/
void copyTo(Object dst) {
if (dst == null) {
if (hasDelegateBufferHandle(nativeHandle)) {
return;
}
throw new IllegalArgumentException(
"Null outputs are allowed only if the Tensor is bound to a buffer handle.");
}
throwIfTypeIsIncompatible(dst);
throwIfDstShapeIsIncompatible(dst);
if (isBuffer(dst)) {
copyTo((Buffer) dst);
} else {
readMultiDimensionalArray(nativeHandle, dst);
}
}
private void copyTo(Buffer dst) {
// There is no base Buffer#put() method, so we have to ugly cast.
if (dst instanceof ByteBuffer) {
((ByteBuffer) dst).put(buffer());
} else if (dst instanceof FloatBuffer) {
((FloatBuffer) dst).put(buffer().asFloatBuffer());
} else if (dst instanceof LongBuffer) {
((LongBuffer) dst).put(buffer().asLongBuffer());
} else if (dst instanceof IntBuffer) {
((IntBuffer) dst).put(buffer().asIntBuffer());
} else if (dst instanceof ShortBuffer) {
((ShortBuffer) dst).put(buffer().asShortBuffer());
} else {
throw new IllegalArgumentException("Unexpected output buffer type: " + dst);
}
}
/** Returns the provided buffer's shape if specified and different from this Tensor's shape. */
// TODO(b/80431971): Remove this method after deprecating multi-dimensional array inputs.
int[] getInputShapeIfDifferent(Object input) {
if (input == null) {
return null;
}
// Implicit resizes based on ByteBuffer capacity isn't supported, so short-circuit that path.
// The Buffer's size will be validated against this Tensor's size in {@link #setTo(Object)}.
if (isBuffer(input)) {
return null;
}
throwIfTypeIsIncompatible(input);
int[] inputShape = computeShapeOf(input);
if (Arrays.equals(shapeCopy, inputShape)) {
return null;
}
return inputShape;
}
/**
* Forces a refresh of the tensor's cached shape.
*
* <p>This is useful if the tensor is resized or has a dynamic shape.
*/
void refreshShape() {
this.shapeCopy = shape(nativeHandle);
}
/** Returns the type of the data. */
DataType dataTypeOf(@NonNull Object o) {
Class<?> c = o.getClass();
// For arrays, the data elements must be a *primitive* type, e.g., an
// array of floats is fine, but not an array of Floats.
if (c.isArray()) {
while (c.isArray()) {
c = c.getComponentType();
}
if (float.class.equals(c)) {
return DataType.FLOAT32;
} else if (int.class.equals(c)) {
return DataType.INT32;
} else if (short.class.equals(c)) {
return DataType.INT16;
} else if (byte.class.equals(c)) {
// Byte array can be used for storing string tensors, especially for ParseExample op.
if (dtype == DataType.STRING) {
return DataType.STRING;
}
return DataType.UINT8;
} else if (long.class.equals(c)) {
return DataType.INT64;
} else if (boolean.class.equals(c)) {
return DataType.BOOL;
} else if (String.class.equals(c)) {
return DataType.STRING;
}
} else {
// For scalars, the type will be boxed.
if (Float.class.equals(c) || o instanceof FloatBuffer) {
return DataType.FLOAT32;
} else if (Integer.class.equals(c) || o instanceof IntBuffer) {
return DataType.INT32;
} else if (Short.class.equals(c) || o instanceof ShortBuffer) {
return DataType.INT16;
} else if (Byte.class.equals(c)) {
// Note that we don't check for ByteBuffer here; ByteBuffer payloads
// are allowed to map to any type, and should be handled earlier
// in the input/output processing pipeline.
return DataType.UINT8;
} else if (Long.class.equals(c) || o instanceof LongBuffer) {
return DataType.INT64;
} else if (Boolean.class.equals(c)) {
return DataType.BOOL;
} else if (String.class.equals(c)) {
return DataType.STRING;
}
}
throw new IllegalArgumentException(
"DataType error: cannot resolve DataType of " + o.getClass().getName());
}
/** Returns the shape of an object as an int array. */
private int[] computeShapeOf(Object o) {
int size = computeNumDimensions(o);
if (dtype == DataType.STRING) {
Class<?> c = o.getClass();
if (c.isArray()) {
while (c.isArray()) {
c = c.getComponentType();
}
// If the given string data is stored in byte streams, the last array dimension should be
// treated as a value.
if (byte.class.equals(c)) {
--size;
}
}
}
int[] dimensions = new int[size];
fillShape(o, 0, dimensions);
return dimensions;
}
/** Returns the number of elements in a flattened (1-D) view of the tensor's shape. */
static int computeNumElements(int[] shape) {
int n = 1;
for (int j : shape) {
n *= j;
}
return n;
}
/** Returns the number of dimensions of a multi-dimensional array, otherwise 0. */
static int computeNumDimensions(Object o) {
if (o == null || !o.getClass().isArray()) {
return 0;
}
if (Array.getLength(o) == 0) {
throw new IllegalArgumentException("Array lengths cannot be 0.");
}
return 1 + computeNumDimensions(Array.get(o, 0));
}
/** Recursively populates the shape dimensions for a given (multi-dimensional) array. */
static void fillShape(Object o, int dim, int[] shape) {
if (shape == null || dim == shape.length) {
return;
}
final int len = Array.getLength(o);
if (shape[dim] == 0) {
shape[dim] = len;
} else if (shape[dim] != len) {
throw new IllegalArgumentException(
String.format("Mismatched lengths (%d and %d) in dimension %d", shape[dim], len, dim));
}
final int nextDim = dim + 1;
// Short-circuit the innermost dimension to avoid unnecessary Array.get() reflection overhead.
if (nextDim == shape.length) {
return;
}
for (int i = 0; i < len; ++i) {
fillShape(Array.get(o, i), nextDim, shape);
}
}
private void throwIfTypeIsIncompatible(@NonNull Object o) {
// ByteBuffer payloads can map to any type, so exempt it from the check.
if (isByteBuffer(o)) {
return;
}
DataType oType = dataTypeOf(o);
if (oType != dtype) {
// INT8 and UINT8 have the same string name, "byte"
if (DataTypeUtils.toStringName(oType).equals(DataTypeUtils.toStringName(dtype))) {
return;
}
throw new IllegalArgumentException(
String.format(
"Cannot convert between a TensorFlowLite tensor with type %s and a Java "
+ "object of type %s (which is compatible with the TensorFlowLite type %s).",
dtype, o.getClass().getName(), oType));
}
}
private void throwIfSrcShapeIsIncompatible(Object src) {
if (isBuffer(src)) {
Buffer srcBuffer = (Buffer) src;
int bytes = numBytes();
// Note that we allow the client to provide a ByteBuffer even for non-byte Tensors.
// In such cases, we only care that the raw byte capacity matches the tensor byte capacity.
int srcBytes =
isByteBuffer(src) ? srcBuffer.capacity() : srcBuffer.capacity() * dtype.byteSize();
if (bytes != srcBytes) {
throw new IllegalArgumentException(
String.format(
"Cannot copy to a TensorFlowLite tensor (%s) with %d bytes from a "
+ "Java Buffer with %d bytes.",
name(), bytes, srcBytes));
}
return;
}
int[] srcShape = computeShapeOf(src);
if (!Arrays.equals(srcShape, shapeCopy)) {
throw new IllegalArgumentException(
String.format(
"Cannot copy to a TensorFlowLite tensor (%s) with shape %s from a Java object "
+ "with shape %s.",
name(), Arrays.toString(shapeCopy), Arrays.toString(srcShape)));
}
}
private void throwIfDstShapeIsIncompatible(Object dst) {
if (isBuffer(dst)) {
Buffer dstBuffer = (Buffer) dst;
int bytes = numBytes();
// Note that we allow the client to provide a ByteBuffer even for non-byte Tensors.
// In such cases, we only care that the raw byte capacity fits the tensor byte capacity.
// This is subtly different than Buffer *inputs*, where the size should be exact.
int dstBytes =
isByteBuffer(dst) ? dstBuffer.capacity() : dstBuffer.capacity() * dtype.byteSize();
if (bytes > dstBytes) {
throw new IllegalArgumentException(
String.format(
"Cannot copy from a TensorFlowLite tensor (%s) with %d bytes to a "
+ "Java Buffer with %d bytes.",
name(), bytes, dstBytes));
}
return;
}
int[] dstShape = computeShapeOf(dst);
if (!Arrays.equals(dstShape, shapeCopy)) {
throw new IllegalArgumentException(
String.format(
"Cannot copy from a TensorFlowLite tensor (%s) with shape %s to a Java object "
+ "with shape %s.",
name(), Arrays.toString(shapeCopy), Arrays.toString(dstShape)));
}
}
private static boolean isBuffer(Object o) {
return o instanceof Buffer;
}
private static boolean isByteBuffer(Object o) {
return o instanceof ByteBuffer;
}
private long nativeHandle;
private final DataType dtype;
private int[] shapeCopy;
private final int[] shapeSignatureCopy;
private final QuantizationParams quantizationParamsCopy;
private TensorImpl(long nativeHandle) {
this.nativeHandle = nativeHandle;
this.dtype = DataTypeUtils.fromC(dtype(nativeHandle));
this.shapeCopy = shape(nativeHandle);
this.shapeSignatureCopy = shapeSignature(nativeHandle);
this.quantizationParamsCopy =
new QuantizationParams(
quantizationScale(nativeHandle), quantizationZeroPoint(nativeHandle));
}
private ByteBuffer buffer() {
return buffer(nativeHandle).order(ByteOrder.nativeOrder());
}
private static native long create(long interpreterHandle, int tensorIndex, int subgraphIndex);
private static native long createSignatureInputTensor(
long signatureRunnerHandle, String inputName);
private static native long createSignatureOutputTensor(
long signatureRunnerHandle, String outputName);
private static native void delete(long handle);
private static native ByteBuffer buffer(long handle);
private static native void writeDirectBuffer(long handle, Buffer src);
private static native int dtype(long handle);
private static native int[] shape(long handle);
private static native int[] shapeSignature(long handle);
private static native int numBytes(long handle);
private static native boolean hasDelegateBufferHandle(long handle);
private static native void readMultiDimensionalArray(long handle, Object dst);
private static native void writeMultiDimensionalArray(long handle, Object src);
private static native void writeScalar(long handle, Object src);
private static native int index(long handle);
private static native String name(long handle);
private static native float quantizationScale(long handle);
private static native int quantizationZeroPoint(long handle);
}
| tensorflow/tensorflow | tensorflow/lite/java/src/main/java/org/tensorflow/lite/TensorImpl.java |
123 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 concreteextensions;
import abstractextensions.SoldierExtension;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import units.SoldierUnit;
/**
* Class defining Soldier.
*/
@Slf4j
public record Soldier(SoldierUnit unit) implements SoldierExtension {
@Override
public void soldierReady() {
LOGGER.info("[Soldier] " + unit.getName() + " is ready!");
}
}
| iluwatar/java-design-patterns | extension-objects/src/main/java/concreteextensions/Soldier.java |
124 | // Implement a trie with insert, search, and startsWith methods.
// Note:
// You may assume that all inputs are consist of lowercase letters a-z.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
class TrieNode {
HashMap<Character, TrieNode> map;
char character;
boolean last;
// Initialize your data structure here.
public TrieNode(char character) {
this.map = new HashMap<Character, TrieNode>();
this.character = character;
this.last = false;
}
}
public class ImplementTrie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
current.map.put(c, new TrieNode(c));
}
current = current.map.get(c);
}
current.last = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
if(current.last == true) {
return true;
} else {
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(char c : prefix.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return true;
}
}
| kdn251/interviews | leetcode/trie/ImplementTrie.java |
125 | /*
* Copyright (c) 2016-present, RxJava Contributors.
*
* 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.
*/
module io.reactivex.rxjava3 {
exports io.reactivex.rxjava3.annotations;
exports io.reactivex.rxjava3.core;
exports io.reactivex.rxjava3.disposables;
exports io.reactivex.rxjava3.exceptions;
exports io.reactivex.rxjava3.flowables;
exports io.reactivex.rxjava3.functions;
exports io.reactivex.rxjava3.observables;
exports io.reactivex.rxjava3.observers;
exports io.reactivex.rxjava3.operators;
exports io.reactivex.rxjava3.parallel;
exports io.reactivex.rxjava3.plugins;
exports io.reactivex.rxjava3.processors;
exports io.reactivex.rxjava3.schedulers;
exports io.reactivex.rxjava3.subjects;
exports io.reactivex.rxjava3.subscribers;
requires transitive org.reactivestreams;
} | ReactiveX/RxJava | src/main/module/module-info.java |
126 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.servant;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
/**
* Servant offers some functionality to a group of classes without defining that functionality in
* each of them. A Servant is a class whose instance provides methods that take care of a desired
* service, while objects for which the servant does something, are taken as parameters.
*
* <p>In this example {@link Servant} is serving {@link King} and {@link Queen}.
*/
@Slf4j
public class App {
private static final Servant jenkins = new Servant("Jenkins");
private static final Servant travis = new Servant("Travis");
/**
* Program entry point.
*/
public static void main(String[] args) {
scenario(jenkins, 1);
scenario(travis, 0);
}
/**
* Can add a List with enum Actions for variable scenarios.
*/
public static void scenario(Servant servant, int compliment) {
var k = new King();
var q = new Queen();
var guests = List.of(k, q);
// feed
servant.feed(k);
servant.feed(q);
// serve drinks
servant.giveWine(k);
servant.giveWine(q);
// compliment
servant.giveCompliments(guests.get(compliment));
// outcome of the night
guests.forEach(Royalty::changeMood);
// check your luck
if (servant.checkIfYouWillBeHanged(guests)) {
LOGGER.info("{} will live another day", servant.name);
} else {
LOGGER.info("Poor {}. His days are numbered", servant.name);
}
}
}
| smedals/java-design-patterns | servant/src/main/java/com/iluwatar/servant/App.java |
127 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.flux.app;
import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.dispatcher.Dispatcher;
import com.iluwatar.flux.store.ContentStore;
import com.iluwatar.flux.store.MenuStore;
import com.iluwatar.flux.view.ContentView;
import com.iluwatar.flux.view.MenuView;
/**
* Flux is the application architecture that Facebook uses for building client-side web
* applications. Flux eschews MVC in favor of a unidirectional data flow. When a user interacts with
* a React view, the view propagates an action through a central dispatcher, to the various stores
* that hold the application's data and business logic, which updates all the views that are
* affected.
*
* <p>This example has two views: menu and content. They represent typical main menu and content
* area of a web page. When menu item is clicked it triggers events through the dispatcher. The
* events are received and handled by the stores updating their data as needed. The stores then
* notify the views that they should rerender themselves.
*
* <p>http://facebook.github.io/flux/docs/overview.html
*/
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// initialize and wire the system
var menuStore = new MenuStore();
Dispatcher.getInstance().registerStore(menuStore);
var contentStore = new ContentStore();
Dispatcher.getInstance().registerStore(contentStore);
var menuView = new MenuView();
menuStore.registerView(menuView);
var contentView = new ContentView();
contentStore.registerView(contentView);
// render initial view
menuView.render();
contentView.render();
// user clicks another menu item
// this triggers action dispatching and eventually causes views to render with new content
menuView.itemClicked(MenuItem.COMPANY);
}
}
| iluwatar/java-design-patterns | flux/src/main/java/com/iluwatar/flux/app/App.java |
128 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.commander.queue;
import com.iluwatar.commander.Order;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
/**
* QueueTask object is the object enqueued in queue.
*/
@RequiredArgsConstructor
public class QueueTask {
/**
* TaskType is the type of task to be done.
*/
public enum TaskType {
MESSAGING,
PAYMENT,
EMPLOYEE_DB
}
public final Order order;
public final TaskType taskType;
public final int messageType; //0-fail, 1-error, 2-success
/*we could have varargs Object instead to pass in any parameter instead of just message type
but keeping it simple here*/
@Getter
@Setter
private long firstAttemptTime = -1L; //when first time attempt made to do task
/**
* getType method.
*
* @return String representing type of task
*/
public String getType() {
if (!this.taskType.equals(TaskType.MESSAGING)) {
return this.taskType.toString();
} else {
if (this.messageType == 0) {
return "Payment Failure Message";
} else if (this.messageType == 1) {
return "Payment Error Message";
} else {
return "Payment Success Message";
}
}
}
public boolean isFirstAttempt() {
return this.firstAttemptTime == -1L;
}
} | iluwatar/java-design-patterns | commander/src/main/java/com/iluwatar/commander/queue/QueueTask.java |
129 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.factory.method;
/**
* Weapon interface.
*/
public interface Weapon {
WeaponType weaponType();
}
| iluwatar/java-design-patterns | factory-method/src/main/java/com/iluwatar/factory/method/Weapon.java |
130 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.fanout.fanin;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* FanOutFanIn class processes long-running requests, when any of the processes gets over, result is
* passed over to the consumer or the callback function. Consumer will aggregate the results as they
* keep on completing.
*/
public class FanOutFanIn {
/**
* the main fanOutFanIn function or orchestrator function.
* @param requests List of numbers that need to be squared and summed up
* @param consumer Takes in the squared number from {@link SquareNumberRequest} and sums it up
* @return Aggregated sum of all squared numbers.
*/
public static Long fanOutFanIn(
final List<SquareNumberRequest> requests, final Consumer consumer) {
ExecutorService service = Executors.newFixedThreadPool(requests.size());
// fanning out
List<CompletableFuture<Void>> futures =
requests.stream()
.map(
request ->
CompletableFuture.runAsync(() -> request.delayedSquaring(consumer), service))
.toList();
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
return consumer.getSumOfSquaredNumbers().get();
}
}
| iluwatar/java-design-patterns | fanout-fanin/src/main/java/com/iluwatar/fanout/fanin/FanOutFanIn.java |
131 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.hexagonal.domain;
/**
* Immutable value object representing lottery ticket.
*/
public record LotteryTicket(LotteryTicketId id, PlayerDetails playerDetails, LotteryNumbers lotteryNumbers) {
@Override
public int hashCode() {
final var prime = 31;
var result = 1;
result = prime * result + ((lotteryNumbers == null) ? 0 : lotteryNumbers.hashCode());
result = prime * result + ((playerDetails == null) ? 0 : playerDetails.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
var other = (LotteryTicket) obj;
if (lotteryNumbers == null) {
if (other.lotteryNumbers != null) {
return false;
}
} else if (!lotteryNumbers.equals(other.lotteryNumbers)) {
return false;
}
if (playerDetails == null) {
return other.playerDetails == null;
} else {
return playerDetails.equals(other.playerDetails);
}
}
}
| iluwatar/java-design-patterns | hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicket.java |
132 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 exception;
import java.io.Serial;
import org.springframework.stereotype.Component;
/**
* Custom exception used in cake baking.
*/
@Component
public class CakeBakingException extends Exception {
@Serial
private static final long serialVersionUID = 1L;
public CakeBakingException() {
}
public CakeBakingException(String message) {
super(message);
}
}
| iluwatar/java-design-patterns | layers/src/main/java/exception/CakeBakingException.java |
133 | // Implement a trie with insert, search, and startsWith methods.
// Note:
// You may assume that all inputs are consist of lowercase letters a-z.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
class TrieNode {
HashMap<Character, TrieNode> map;
char character;
boolean last;
// Initialize your data structure here.
public TrieNode(char character) {
this.map = new HashMap<Character, TrieNode>();
this.character = character;
this.last = false;
}
}
public class ImplementTrie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
current.map.put(c, new TrieNode(c));
}
current = current.map.get(c);
}
current.last = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
if(current.last == true) {
return true;
} else {
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(char c : prefix.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return true;
}
}
| kdn251/interviews | company/facebook/ImplementTrie.java |
134 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.event.queue;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* This class implements the Event Queue pattern.
*
* @author mkuprivecz
*/
@Slf4j
public class Audio {
private static final Audio INSTANCE = new Audio();
private static final int MAX_PENDING = 16;
private int headIndex;
private int tailIndex;
private volatile Thread updateThread = null;
@Getter
private final PlayMessage[] pendingAudio = new PlayMessage[MAX_PENDING];
// Visible only for testing purposes
Audio() {
}
public static Audio getInstance() {
return INSTANCE;
}
/**
* This method stops the Update Method's thread and waits till service stops.
*/
public synchronized void stopService() throws InterruptedException {
if (updateThread != null) {
updateThread.interrupt();
}
updateThread.join();
updateThread = null;
}
/**
* This method check the Update Method's thread is started.
*
* @return boolean
*/
public synchronized boolean isServiceRunning() {
return updateThread != null && updateThread.isAlive();
}
/**
* Starts the thread for the Update Method pattern if it was not started previously. Also, when the
* thread is ready initializes the indexes of the queue
*/
public void init() {
if (updateThread == null) {
updateThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
update();
}
});
}
startThread();
}
/**
* This is a synchronized thread starter.
*/
private synchronized void startThread() {
if (!updateThread.isAlive()) {
updateThread.start();
headIndex = 0;
tailIndex = 0;
}
}
/**
* This method adds a new audio into the queue.
*
* @param stream is the AudioInputStream for the method
* @param volume is the level of the audio's volume
*/
public void playSound(AudioInputStream stream, float volume) {
init();
// Walk the pending requests.
for (var i = headIndex; i != tailIndex; i = (i + 1) % MAX_PENDING) {
var playMessage = getPendingAudio()[i];
if (playMessage.getStream() == stream) {
// Use the larger of the two volumes.
playMessage.setVolume(Math.max(volume, playMessage.getVolume()));
// Don't need to enqueue.
return;
}
}
getPendingAudio()[tailIndex] = new PlayMessage(stream, volume);
tailIndex = (tailIndex + 1) % MAX_PENDING;
}
/**
* This method uses the Update Method pattern. It takes the audio from the queue and plays it
*/
private void update() {
// If there are no pending requests, do nothing.
if (headIndex == tailIndex) {
return;
}
try {
var audioStream = getPendingAudio()[headIndex].getStream();
headIndex++;
var clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
} catch (LineUnavailableException e) {
LOGGER.trace("Error occurred while loading the audio: The line is unavailable", e);
} catch (IOException e) {
LOGGER.trace("Input/Output error while loading the audio", e);
} catch (IllegalArgumentException e) {
LOGGER.trace("The system doesn't support the sound: " + e.getMessage(), e);
}
}
/**
* Returns the AudioInputStream of a file.
*
* @param filePath is the path of the audio file
* @return AudioInputStream
* @throws UnsupportedAudioFileException when the audio file is not supported
* @throws IOException when the file is not readable
*/
public AudioInputStream getAudioStream(String filePath)
throws UnsupportedAudioFileException, IOException {
return AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
}
}
| iluwatar/java-design-patterns | event-queue/src/main/java/com/iluwatar/event/queue/Audio.java |
135 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar;
import lombok.Getter;
import lombok.NoArgsConstructor;
/**
* Layer super type for all Data Transfer Objects.
* Also contains code for accessing our notification.
*/
@Getter
@NoArgsConstructor
public class DataTransferObject {
private final Notification notification = new Notification();
}
| rajprins/java-design-patterns | notification/src/main/java/com/iluwatar/DataTransferObject.java |
136 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.flux.store;
import com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.ActionType;
import com.iluwatar.flux.action.MenuAction;
import com.iluwatar.flux.action.MenuItem;
import lombok.Getter;
/**
* MenuStore is a concrete store.
*/
public class MenuStore extends Store {
@Getter
private MenuItem selected = MenuItem.HOME;
@Override
public void onAction(Action action) {
if (action.getType().equals(ActionType.MENU_ITEM_SELECTED)) {
var menuAction = (MenuAction) action;
selected = menuAction.getMenuItem();
notifyChange();
}
}
}
| iluwatar/java-design-patterns | flux/src/main/java/com/iluwatar/flux/store/MenuStore.java |
137 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.promise;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A Promise represents a proxy for a value not necessarily known when the promise is created. It
* allows you to associate dependent promises to an asynchronous action's eventual success value or
* failure reason. This lets asynchronous methods return values like synchronous methods: instead of
* the final value, the asynchronous method returns a promise of having a value at some point in the
* future.
*
* @param <T> type of result.
*/
public class Promise<T> extends PromiseSupport<T> {
private Runnable fulfillmentAction;
private Consumer<? super Throwable> exceptionHandler;
/**
* Creates a promise that will be fulfilled in the future.
*/
public Promise() {
// Empty constructor
}
/**
* Fulfills the promise with the provided value.
*
* @param value the fulfilled value that can be accessed using {@link #get()}.
*/
@Override
public void fulfill(T value) {
super.fulfill(value);
postFulfillment();
}
/**
* Fulfills the promise with exception due to error in execution.
*
* @param exception the exception will be wrapped in {@link ExecutionException} when accessing the
* value using {@link #get()}.
*/
@Override
public void fulfillExceptionally(Exception exception) {
super.fulfillExceptionally(exception);
handleException(exception);
postFulfillment();
}
private void handleException(Exception exception) {
if (exceptionHandler == null) {
return;
}
exceptionHandler.accept(exception);
}
private void postFulfillment() {
if (fulfillmentAction == null) {
return;
}
fulfillmentAction.run();
}
/**
* Executes the task using the executor in other thread and fulfills the promise returned once the
* task completes either successfully or with an exception.
*
* @param task the task that will provide the value to fulfill the promise.
* @param executor the executor in which the task should be run.
* @return a promise that represents the result of running the task provided.
*/
public Promise<T> fulfillInAsync(final Callable<T> task, Executor executor) {
executor.execute(() -> {
try {
fulfill(task.call());
} catch (Exception ex) {
fulfillExceptionally(ex);
}
});
return this;
}
/**
* Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result
* of this promise as argument to the action provided.
*
* @param action action to be executed.
* @return a new promise.
*/
public Promise<Void> thenAccept(Consumer<? super T> action) {
var dest = new Promise<Void>();
fulfillmentAction = new ConsumeAction(this, dest, action);
return dest;
}
/**
* Set the exception handler on this promise.
*
* @param exceptionHandler a consumer that will handle the exception occurred while fulfilling the
* promise.
* @return this
*/
public Promise<T> onError(Consumer<? super Throwable> exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
/**
* Returns a new promise that, when this promise is fulfilled normally, is fulfilled with result
* of this promise as argument to the function provided.
*
* @param func function to be executed.
* @return a new promise.
*/
public <V> Promise<V> thenApply(Function<? super T, V> func) {
Promise<V> dest = new Promise<>();
fulfillmentAction = new TransformAction<>(this, dest, func);
return dest;
}
/**
* Accesses the value from source promise and calls the consumer, then fulfills the destination
* promise.
*/
private class ConsumeAction implements Runnable {
private final Promise<T> src;
private final Promise<Void> dest;
private final Consumer<? super T> action;
private ConsumeAction(Promise<T> src, Promise<Void> dest, Consumer<? super T> action) {
this.src = src;
this.dest = dest;
this.action = action;
}
@Override
public void run() {
try {
action.accept(src.get());
dest.fulfill(null);
} catch (Throwable throwable) {
dest.fulfillExceptionally((Exception) throwable.getCause());
}
}
}
/**
* Accesses the value from source promise, then fulfills the destination promise using the
* transformed value. The source value is transformed using the transformation function.
*/
private class TransformAction<V> implements Runnable {
private final Promise<T> src;
private final Promise<V> dest;
private final Function<? super T, V> func;
private TransformAction(Promise<T> src, Promise<V> dest, Function<? super T, V> func) {
this.src = src;
this.dest = dest;
this.func = func;
}
@Override
public void run() {
try {
dest.fulfill(func.apply(src.get()));
} catch (Throwable throwable) {
dest.fulfillExceptionally((Exception) throwable.getCause());
}
}
}
} | iluwatar/java-design-patterns | promise/src/main/java/com/iluwatar/promise/Promise.java |
138 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.leaderelection.ring;
import com.iluwatar.leaderelection.Instance;
import com.iluwatar.leaderelection.Message;
import com.iluwatar.leaderelection.MessageType;
import java.util.HashMap;
import java.util.Map;
/**
* Example of how to use ring leader election. Initially 5 instances is created in the clould
* system, and the instance with ID 1 is set as leader. After the system is started stop the leader
* instance, and the new leader will be elected.
*/
public class RingApp {
/**
* Program entry point.
*/
public static void main(String[] args) {
Map<Integer, Instance> instanceMap = new HashMap<>();
var messageManager = new RingMessageManager(instanceMap);
var instance1 = new RingInstance(messageManager, 1, 1);
var instance2 = new RingInstance(messageManager, 2, 1);
var instance3 = new RingInstance(messageManager, 3, 1);
var instance4 = new RingInstance(messageManager, 4, 1);
var instance5 = new RingInstance(messageManager, 5, 1);
instanceMap.put(1, instance1);
instanceMap.put(2, instance2);
instanceMap.put(3, instance3);
instanceMap.put(4, instance4);
instanceMap.put(5, instance5);
instance2.onMessage(new Message(MessageType.HEARTBEAT_INVOKE, ""));
final var thread1 = new Thread(instance1);
final var thread2 = new Thread(instance2);
final var thread3 = new Thread(instance3);
final var thread4 = new Thread(instance4);
final var thread5 = new Thread(instance5);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
instance1.setAlive(false);
}
}
| iluwatar/java-design-patterns | leader-election/src/main/java/com/iluwatar/leaderelection/ring/RingApp.java |
139 | //Design a data structure that supports all following operations in average O(1) time.
//insert(val): Inserts an item val to the set if not already present.
//remove(val): Removes an item val from the set if present.
//getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
//Example:
// Init an empty set.
//RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
//randomSet.insert(1);
// Returns false as 2 does not exist in the set.
//randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
//randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
//randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
//randomSet.remove(1);
// 2 was already in the set, so return false.
//randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
//randomSet.getRandom();
class RandomizedSet {
HashMap<Integer, Integer> map;
ArrayList<Integer> values;
/** Initialize your data structure here. */
public RandomizedSet() {
map = new HashMap<Integer, Integer>();
values = new ArrayList<Integer>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public boolean insert(int val) {
if(!map.containsKey(val)) {
map.put(val, val);
values.add(val);
return true;
}
else {
return false;
}
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public boolean remove(int val) {
if(map.containsKey(val)) {
map.remove(val);
values.remove(values.indexOf(val));
return true;
}
return false;
}
/** Get a random element from the set. */
public int getRandom() {
int random = (int)(Math.random() * values.size());
int valueToReturn = values.get(random);
return map.get(valueToReturn);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/
| kdn251/interviews | company/google/InsertDeleteGetRandomO1.java |
140 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 concreteextensions;
import abstractextensions.CommanderExtension;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import units.CommanderUnit;
/**
* Class defining Commander.
*/
@Slf4j
public record Commander(CommanderUnit unit) implements CommanderExtension {
@Override
public void commanderReady() {
LOGGER.info("[Commander] " + unit.getName() + " is ready!");
}
}
| iluwatar/java-design-patterns | extension-objects/src/main/java/concreteextensions/Commander.java |
141 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.observer;
import lombok.Getter; /**
* WeatherType enumeration.
*/
public enum WeatherType {
SUNNY("Sunny"),
RAINY("Rainy"),
WINDY("Windy"),
COLD("Cold");
@Getter
private final String description;
WeatherType(String description) {
this.description = description;
}
@Override
public String toString() {
return this.name().toLowerCase();
}
}
| iluwatar/java-design-patterns | observer/src/main/java/com/iluwatar/observer/WeatherType.java |
142 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.identitymap;
import java.io.Serial;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Person definition.
*/
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Getter
@Setter
@AllArgsConstructor
public final class Person implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@EqualsAndHashCode.Include
private int personNationalId;
private String name;
private long phoneNum;
@Override
public String toString() {
return "Person ID is : " + personNationalId + " ; Person Name is : " + name + " ; Phone Number is :" + phoneNum;
}
}
| iluwatar/java-design-patterns | identity-map/src/main/java/com/iluwatar/identitymap/Person.java |
143 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.slob.lob;
import java.io.Serializable;
import java.util.StringJoiner;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
/**
* Creates an object Plant which contains its name and type.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Plant implements Serializable {
private String name;
private String type;
/**
* Provides XML Representation of the Plant.
*
* @param xmlDoc to which the XML representation is to be written to
* @return XML Element contain the Animal representation
*/
public Element toXmlElement(Document xmlDoc) {
Element root = xmlDoc.createElement(Plant.class.getSimpleName());
root.setAttribute("name", name);
root.setAttribute("type", type);
xmlDoc.appendChild(root);
return xmlDoc.getDocumentElement();
}
/**
* Parses the Plant Object from the input XML Node.
*
* @param node the XML Node from which the Animal Object is to be parsed
*/
public void createObjectFromXml(Node node) {
NamedNodeMap attributes = node.getAttributes();
name = attributes.getNamedItem("name").getNodeValue();
type = attributes.getNamedItem("type").getNodeValue();
}
@Override
public String toString() {
StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add("Name = " + name);
stringJoiner.add("Type = " + type);
return stringJoiner.toString();
}
}
| rajprins/java-design-patterns | slob/src/main/java/com/iluwatar/slob/lob/Plant.java |
144 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
/**
* AppEmployeeDbFailCases class looks at possible cases when Employee handle service is
* available/unavailable.
*/
public class AppEmployeeDbFailCases {
private static final RetryParams retryParams = RetryParams.DEFAULT;
private static final TimeLimits timeLimits = TimeLimits.DEFAULT;
void employeeDatabaseUnavailableCase() {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void employeeDbSuccessCase() {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb = new QueueDatabase();
var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var aefc = new AppEmployeeDbFailCases();
aefc.employeeDbSuccessCase();
}
} | iluwatar/java-design-patterns | commander/src/main/java/com/iluwatar/commander/AppEmployeeDbFailCases.java |
145 | //Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
//push(x) -- Push element x onto stack.
//pop() -- Removes the element on top of the stack.
//top() -- Get the top element.
//getMin() -- Retrieve the minimum element in the stack.
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
| kdn251/interviews | leetcode/stack/MinStack.java |
146 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.iterator.bst;
import lombok.Getter;
import lombok.Setter;
/**
* TreeNode Class, representing one node in a Binary Search Tree. Allows for a generically typed
* value.
*
* @param <T> generically typed to accept various data types for the val property
*/
public class TreeNode<T extends Comparable<T>> {
private final T val;
@Getter
@Setter
private TreeNode<T> left;
@Getter
@Setter
private TreeNode<T> right;
/**
* Creates a TreeNode with a given value, and null children.
*
* @param val The value of the given node
*/
public TreeNode(T val) {
this.val = val;
this.left = null;
this.right = null;
}
public T getVal() {
return val;
}
/**
* Inserts new TreeNode based on a given value into the subtree represented by self.
*
* @param valToInsert The value to insert as a new TreeNode
*/
public void insert(T valToInsert) {
var parent = getParentNodeOfValueToBeInserted(valToInsert);
parent.insertNewChild(valToInsert);
}
/**
* Fetch the Parent TreeNode for a given value to insert into the BST.
*
* @param valToInsert Value of the new TreeNode to be inserted
* @return Parent TreeNode of `valToInsert`
*/
private TreeNode<T> getParentNodeOfValueToBeInserted(T valToInsert) {
TreeNode<T> parent = null;
var curr = this;
while (curr != null) {
parent = curr;
curr = curr.traverseOneLevelDown(valToInsert);
}
return parent;
}
/**
* Returns left or right child of self based on a value that would be inserted; maintaining the
* integrity of the BST.
*
* @param value The value of the TreeNode that would be inserted beneath self
* @return The child TreeNode of self which represents the subtree where `value` would be inserted
*/
private TreeNode<T> traverseOneLevelDown(T value) {
if (this.isGreaterThan(value)) {
return this.left;
}
return this.right;
}
/**
* Add a new Child TreeNode of given value to self. WARNING: This method is destructive (will
* overwrite existing tree structure, if any), and should be called only by this class's insert()
* method.
*
* @param valToInsert Value of the new TreeNode to be inserted
*/
private void insertNewChild(T valToInsert) {
if (this.isLessThanOrEqualTo(valToInsert)) {
this.setRight(new TreeNode<>(valToInsert));
} else {
this.setLeft(new TreeNode<>(valToInsert));
}
}
private boolean isGreaterThan(T val) {
return this.val.compareTo(val) > 0;
}
private boolean isLessThanOrEqualTo(T val) {
return this.val.compareTo(val) < 1;
}
@Override
public String toString() {
return val.toString();
}
}
| iluwatar/java-design-patterns | iterator/src/main/java/com/iluwatar/iterator/bst/TreeNode.java |
147 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.iterator.list;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
* Item.
*/
@AllArgsConstructor
public class Item {
@Getter
@Setter
private ItemType type;
private final String name;
@Override
public String toString() {
return name;
}
}
| iluwatar/java-design-patterns | iterator/src/main/java/com/iluwatar/iterator/list/Item.java |
148 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.embedded.value;
import lombok.extern.slf4j.Slf4j;
/**
* <p> Many small objects make sense in an OO system that don’t make sense as
* tables in a database. Examples include currency-aware money objects (amount, currency) and date
* ranges. Although the default thinking is to save an object as a table, no sane
* person would want a table of money values. </p>
*
* <p> An Embedded Value maps the values of an object to fields in the record of
* the object’s owner. In this implementation we have an Order object with links to an
* ShippingAddress object. In the resulting table the fields in the ShippingAddress
* object map to fields in the Order table rather than make new records
* themselves. </p>
*/
@Slf4j
public class App {
private static final String BANGLORE = "Banglore";
private static final String KARNATAKA = "Karnataka";
/**
* Program entry point.
*
* @param args command line args.
* @throws Exception if any error occurs.
*
*/
public static void main(String[] args) throws Exception {
final var dataSource = new DataSource();
// Orders to insert into database
final var order1 = new Order("JBL headphone", "Ram",
new ShippingAddress(BANGLORE, KARNATAKA, "560040"));
final var order2 = new Order("MacBook Pro", "Manjunath",
new ShippingAddress(BANGLORE, KARNATAKA, "581204"));
final var order3 = new Order("Carrie Soto is Back", "Shiva",
new ShippingAddress(BANGLORE, KARNATAKA, "560004"));
// Create table for orders - Orders(id, name, orderedBy, city, state, pincode).
// We can see that table is different from the Order object we have.
// We're mapping ShippingAddress into city, state, pincode columns of the database and not creating a separate table.
if (dataSource.createSchema()) {
LOGGER.info("TABLE CREATED");
LOGGER.info("Table \"Orders\" schema:\n" + dataSource.getSchema());
} else {
//If not able to create table, there's nothing we can do further.
LOGGER.error("Error creating table");
System.exit(0);
}
// Initially, database is empty
LOGGER.info("Orders Query: {}", dataSource.queryOrders().toList());
//Insert orders where shippingAddress is mapped to different columns of the same table
dataSource.insertOrder(order1);
dataSource.insertOrder(order2);
dataSource.insertOrder(order3);
// Query orders.
// We'll create ShippingAddress object from city, state, pincode values from the table and add it to Order object
LOGGER.info("Orders Query: {}", dataSource.queryOrders().toList() + "\n");
//Query order by given id
LOGGER.info("Query Order with id=2: {}", dataSource.queryOrder(2));
//Remove order by given id.
//Since we'd mapped address in the same table, deleting order will also take out the shipping address details.
LOGGER.info("Remove Order with id=1");
dataSource.removeOrder(1);
LOGGER.info("\nOrders Query: {}", dataSource.queryOrders().toList() + "\n");
//After successful demonstration of the pattern, drop the table
if (dataSource.deleteSchema()) {
LOGGER.info("TABLE DROPPED");
} else {
//If there's a potential error while dropping table
LOGGER.error("Error deleting table");
}
}
} | iluwatar/java-design-patterns | embedded-value/src/main/java/com/iluwatar/embedded/value/App.java |
149 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch;
import org.elasticsearch.core.Assertions;
import org.elasticsearch.core.UpdateForV9;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.IntFunction;
/**
* <p>Transport version is used to coordinate compatible wire protocol communication between nodes, at a fine-grained level. This replaces
* and supersedes the old Version constants.</p>
*
* <p>Before adding a new version constant, please read the block comment at the end of the list of constants.</p>
*/
public class TransportVersions {
/*
* NOTE: IntelliJ lies!
* This map is used during class construction, referenced by the registerTransportVersion method.
* When all the transport version constants have been registered, the map is cleared & never touched again.
*/
static TreeSet<Integer> IDS = new TreeSet<>();
static TransportVersion def(int id) {
if (IDS == null) throw new IllegalStateException("The IDS map needs to be present to call this method");
if (IDS.add(id) == false) {
throw new IllegalArgumentException("Version id " + id + " defined twice");
}
if (id < IDS.last()) {
throw new IllegalArgumentException("Version id " + id + " is not defined in the right location. Keep constants sorted");
}
return new TransportVersion(id);
}
@UpdateForV9 // remove the transport versions with which v9 will not need to interact
public static final TransportVersion ZERO = def(0);
public static final TransportVersion V_7_0_0 = def(7_00_00_99);
public static final TransportVersion V_7_0_1 = def(7_00_01_99);
public static final TransportVersion V_7_1_0 = def(7_01_00_99);
public static final TransportVersion V_7_2_0 = def(7_02_00_99);
public static final TransportVersion V_7_2_1 = def(7_02_01_99);
public static final TransportVersion V_7_3_0 = def(7_03_00_99);
public static final TransportVersion V_7_3_2 = def(7_03_02_99);
public static final TransportVersion V_7_4_0 = def(7_04_00_99);
public static final TransportVersion V_7_5_0 = def(7_05_00_99);
public static final TransportVersion V_7_6_0 = def(7_06_00_99);
public static final TransportVersion V_7_7_0 = def(7_07_00_99);
public static final TransportVersion V_7_8_0 = def(7_08_00_99);
public static final TransportVersion V_7_8_1 = def(7_08_01_99);
public static final TransportVersion V_7_9_0 = def(7_09_00_99);
public static final TransportVersion V_7_10_0 = def(7_10_00_99);
public static final TransportVersion V_7_10_1 = def(7_10_01_99);
public static final TransportVersion V_7_11_0 = def(7_11_00_99);
public static final TransportVersion V_7_12_0 = def(7_12_00_99);
public static final TransportVersion V_7_13_0 = def(7_13_00_99);
public static final TransportVersion V_7_14_0 = def(7_14_00_99);
public static final TransportVersion V_7_15_0 = def(7_15_00_99);
public static final TransportVersion V_7_15_1 = def(7_15_01_99);
public static final TransportVersion V_7_16_0 = def(7_16_00_99);
public static final TransportVersion V_7_17_0 = def(7_17_00_99);
public static final TransportVersion V_7_17_1 = def(7_17_01_99);
public static final TransportVersion V_7_17_8 = def(7_17_08_99);
public static final TransportVersion V_8_0_0 = def(8_00_00_99);
public static final TransportVersion V_8_1_0 = def(8_01_00_99);
public static final TransportVersion V_8_2_0 = def(8_02_00_99);
public static final TransportVersion V_8_3_0 = def(8_03_00_99);
public static final TransportVersion V_8_4_0 = def(8_04_00_99);
public static final TransportVersion V_8_5_0 = def(8_05_00_99);
public static final TransportVersion V_8_6_0 = def(8_06_00_99);
public static final TransportVersion V_8_6_1 = def(8_06_01_99);
public static final TransportVersion V_8_7_0 = def(8_07_00_99);
public static final TransportVersion V_8_7_1 = def(8_07_01_99);
public static final TransportVersion V_8_8_0 = def(8_08_00_99);
public static final TransportVersion V_8_8_1 = def(8_08_01_99);
/*
* READ THE COMMENT BELOW THIS BLOCK OF DECLARATIONS BEFORE ADDING NEW TRANSPORT VERSIONS
* Detached transport versions added below here.
*/
public static final TransportVersion V_8_9_X = def(8_500_020);
public static final TransportVersion V_8_10_X = def(8_500_061);
public static final TransportVersion V_8_11_X = def(8_512_00_1);
public static final TransportVersion V_8_12_0 = def(8_560_00_0);
public static final TransportVersion DATE_HISTOGRAM_SUPPORT_DOWNSAMPLED_TZ_8_12_PATCH = def(8_560_00_1);
public static final TransportVersion NODE_STATS_REQUEST_SIMPLIFIED = def(8_561_00_0);
public static final TransportVersion TEXT_EXPANSION_TOKEN_PRUNING_CONFIG_ADDED = def(8_562_00_0);
public static final TransportVersion ESQL_ASYNC_QUERY = def(8_563_00_0);
public static final TransportVersion ESQL_STATUS_INCLUDE_LUCENE_QUERIES = def(8_564_00_0);
public static final TransportVersion ESQL_CLUSTER_ALIAS = def(8_565_00_0);
public static final TransportVersion SNAPSHOTS_IN_PROGRESS_TRACKING_REMOVING_NODES_ADDED = def(8_566_00_0);
public static final TransportVersion SMALLER_RELOAD_SECURE_SETTINGS_REQUEST = def(8_567_00_0);
public static final TransportVersion UPDATE_API_KEY_EXPIRATION_TIME_ADDED = def(8_568_00_0);
public static final TransportVersion LAZY_ROLLOVER_ADDED = def(8_569_00_0);
public static final TransportVersion ESQL_PLAN_POINT_LITERAL_WKB = def(8_570_00_0);
public static final TransportVersion HOT_THREADS_AS_BYTES = def(8_571_00_0);
public static final TransportVersion ML_INFERENCE_REQUEST_INPUT_TYPE_ADDED = def(8_572_00_0);
public static final TransportVersion ESQL_ENRICH_POLICY_CCQ_MODE = def(8_573_00_0);
public static final TransportVersion DATE_HISTOGRAM_SUPPORT_DOWNSAMPLED_TZ = def(8_574_00_0);
public static final TransportVersion PEERFINDER_REPORTS_PEERS_MASTERS = def(8_575_00_0);
public static final TransportVersion ESQL_MULTI_CLUSTERS_ENRICH = def(8_576_00_0);
public static final TransportVersion NESTED_KNN_MORE_INNER_HITS = def(8_577_00_0);
public static final TransportVersion REQUIRE_DATA_STREAM_ADDED = def(8_578_00_0);
public static final TransportVersion ML_INFERENCE_COHERE_EMBEDDINGS_ADDED = def(8_579_00_0);
public static final TransportVersion DESIRED_NODE_VERSION_OPTIONAL_STRING = def(8_580_00_0);
public static final TransportVersion ML_INFERENCE_REQUEST_INPUT_TYPE_UNSPECIFIED_ADDED = def(8_581_00_0);
public static final TransportVersion ASYNC_SEARCH_STATUS_SUPPORTS_KEEP_ALIVE = def(8_582_00_0);
public static final TransportVersion KNN_QUERY_NUMCANDS_AS_OPTIONAL_PARAM = def(8_583_00_0);
public static final TransportVersion TRANSFORM_GET_BASIC_STATS = def(8_584_00_0);
public static final TransportVersion NLP_DOCUMENT_CHUNKING_ADDED = def(8_585_00_0);
public static final TransportVersion SEARCH_TIMEOUT_EXCEPTION_ADDED = def(8_586_00_0);
public static final TransportVersion ML_TEXT_EMBEDDING_INFERENCE_SERVICE_ADDED = def(8_587_00_0);
public static final TransportVersion HEALTH_INFO_ENRICHED_WITH_REPOS = def(8_588_00_0);
public static final TransportVersion RESOLVE_CLUSTER_ENDPOINT_ADDED = def(8_589_00_0);
public static final TransportVersion FIELD_CAPS_FIELD_HAS_VALUE = def(8_590_00_0);
public static final TransportVersion ML_INFERENCE_REQUEST_INPUT_TYPE_CLASS_CLUSTER_ADDED = def(8_591_00_0);
public static final TransportVersion ML_DIMENSIONS_SET_BY_USER_ADDED = def(8_592_00_0);
public static final TransportVersion INDEX_REQUEST_NORMALIZED_BYTES_PARSED = def(8_593_00_0);
public static final TransportVersion INGEST_GRAPH_STRUCTURE_EXCEPTION = def(8_594_00_0);
public static final TransportVersion V_8_13_0 = def(8_595_00_0);
// 8.14.0+
public static final TransportVersion RANDOM_AGG_SHARD_SEED = def(8_596_00_0);
public static final TransportVersion ESQL_TIMINGS = def(8_597_00_0);
public static final TransportVersion DATA_STREAM_AUTO_SHARDING_EVENT = def(8_598_00_0);
public static final TransportVersion ADD_FAILURE_STORE_INDICES_OPTIONS = def(8_599_00_0);
public static final TransportVersion ESQL_ENRICH_OPERATOR_STATUS = def(8_600_00_0);
public static final TransportVersion ESQL_SERIALIZE_ARRAY_VECTOR = def(8_601_00_0);
public static final TransportVersion ESQL_SERIALIZE_ARRAY_BLOCK = def(8_602_00_0);
public static final TransportVersion ADD_DATA_STREAM_GLOBAL_RETENTION = def(8_603_00_0);
public static final TransportVersion ALLOCATION_STATS = def(8_604_00_0);
public static final TransportVersion ESQL_EXTENDED_ENRICH_TYPES = def(8_605_00_0);
public static final TransportVersion KNN_EXPLICIT_BYTE_QUERY_VECTOR_PARSING = def(8_606_00_0);
public static final TransportVersion ESQL_EXTENDED_ENRICH_INPUT_TYPE = def(8_607_00_0);
public static final TransportVersion ESQL_SERIALIZE_BIG_VECTOR = def(8_608_00_0);
public static final TransportVersion AGGS_EXCLUDED_DELETED_DOCS = def(8_609_00_0);
public static final TransportVersion ESQL_SERIALIZE_BIG_ARRAY = def(8_610_00_0);
public static final TransportVersion AUTO_SHARDING_ROLLOVER_CONDITION = def(8_611_00_0);
public static final TransportVersion KNN_QUERY_VECTOR_BUILDER = def(8_612_00_0);
public static final TransportVersion USE_DATA_STREAM_GLOBAL_RETENTION = def(8_613_00_0);
public static final TransportVersion ML_COMPLETION_INFERENCE_SERVICE_ADDED = def(8_614_00_0);
public static final TransportVersion ML_INFERENCE_EMBEDDING_BYTE_ADDED = def(8_615_00_0);
public static final TransportVersion ML_INFERENCE_L2_NORM_SIMILARITY_ADDED = def(8_616_00_0);
public static final TransportVersion SEARCH_NODE_LOAD_AUTOSCALING = def(8_617_00_0);
public static final TransportVersion ESQL_ES_SOURCE_OPTIONS = def(8_618_00_0);
public static final TransportVersion ADD_PERSISTENT_TASK_EXCEPTIONS = def(8_619_00_0);
public static final TransportVersion ESQL_REDUCER_NODE_FRAGMENT = def(8_620_00_0);
public static final TransportVersion FAILURE_STORE_ROLLOVER = def(8_621_00_0);
public static final TransportVersion CCR_STATS_API_TIMEOUT_PARAM = def(8_622_00_0);
public static final TransportVersion ESQL_ORDINAL_BLOCK = def(8_623_00_0);
public static final TransportVersion ML_INFERENCE_COHERE_RERANK = def(8_624_00_0);
public static final TransportVersion INDEXING_PRESSURE_DOCUMENT_REJECTIONS_COUNT = def(8_625_00_0);
public static final TransportVersion ALIAS_ACTION_RESULTS = def(8_626_00_0);
public static final TransportVersion HISTOGRAM_AGGS_KEY_SORTED = def(8_627_00_0);
public static final TransportVersion INFERENCE_FIELDS_METADATA = def(8_628_00_0);
public static final TransportVersion ML_INFERENCE_TIMEOUT_ADDED = def(8_629_00_0);
public static final TransportVersion MODIFY_DATA_STREAM_FAILURE_STORES = def(8_630_00_0);
public static final TransportVersion ML_INFERENCE_RERANK_NEW_RESPONSE_FORMAT = def(8_631_00_0);
public static final TransportVersion HIGHLIGHTERS_TAGS_ON_FIELD_LEVEL = def(8_632_00_0);
public static final TransportVersion TRACK_FLUSH_TIME_EXCLUDING_WAITING_ON_LOCKS = def(8_633_00_0);
public static final TransportVersion ML_INFERENCE_AZURE_OPENAI_EMBEDDINGS = def(8_634_00_0);
public static final TransportVersion ILM_SHRINK_ENABLE_WRITE = def(8_635_00_0);
public static final TransportVersion GEOIP_CACHE_STATS = def(8_636_00_0);
public static final TransportVersion WATERMARK_THRESHOLDS_STATS = def(8_637_00_0);
public static final TransportVersion ENRICH_CACHE_ADDITIONAL_STATS = def(8_638_00_0);
public static final TransportVersion ML_INFERENCE_RATE_LIMIT_SETTINGS_ADDED = def(8_639_00_0);
public static final TransportVersion ML_TRAINED_MODEL_CACHE_METADATA_ADDED = def(8_640_00_0);
public static final TransportVersion TOP_LEVEL_KNN_SUPPORT_QUERY_NAME = def(8_641_00_0);
public static final TransportVersion INDEX_SEGMENTS_VECTOR_FORMATS = def(8_642_00_0);
public static final TransportVersion ADD_RESOURCE_ALREADY_UPLOADED_EXCEPTION = def(8_643_00_0);
public static final TransportVersion ESQL_MV_ORDERING_SORTED_ASCENDING = def(8_644_00_0);
public static final TransportVersion ESQL_PAGE_MAPPING_TO_ITERATOR = def(8_645_00_0);
public static final TransportVersion BINARY_PIT_ID = def(8_646_00_0);
public static final TransportVersion SECURITY_ROLE_MAPPINGS_IN_CLUSTER_STATE = def(8_647_00_0);
public static final TransportVersion ESQL_REQUEST_TABLES = def(8_648_00_0);
public static final TransportVersion ROLE_REMOTE_CLUSTER_PRIVS = def(8_649_00_0);
/*
* STOP! READ THIS FIRST! No, really,
* ____ _____ ___ ____ _ ____ _____ _ ____ _____ _ _ ___ ____ _____ ___ ____ ____ _____ _
* / ___|_ _/ _ \| _ \| | | _ \| ____| / \ | _ \ |_ _| | | |_ _/ ___| | ___|_ _| _ \/ ___|_ _| |
* \___ \ | || | | | |_) | | | |_) | _| / _ \ | | | | | | | |_| || |\___ \ | |_ | || |_) \___ \ | | | |
* ___) || || |_| | __/|_| | _ <| |___ / ___ \| |_| | | | | _ || | ___) | | _| | || _ < ___) || | |_|
* |____/ |_| \___/|_| (_) |_| \_\_____/_/ \_\____/ |_| |_| |_|___|____/ |_| |___|_| \_\____/ |_| (_)
*
* A new transport version should be added EVERY TIME a change is made to the serialization protocol of one or more classes. Each
* transport version should only be used in a single merged commit (apart from the BwC versions copied from o.e.Version, ≤V_8_8_1).
*
* ADDING A TRANSPORT VERSION
* To add a new transport version, add a new constant at the bottom of the list, above this comment. Don't add other lines,
* comments, etc. The version id has the following layout:
*
* M_NNN_SS_P
*
* M - The major version of Elasticsearch
* NNN - The server version part
* SS - The serverless version part. It should always be 00 here, it is used by serverless only.
* P - The patch version part
*
* To determine the id of the next TransportVersion constant, do the following:
* - Use the same major version, unless bumping majors
* - Bump the server version part by 1, unless creating a patch version
* - Leave the serverless part as 00
* - Bump the patch part if creating a patch version
*
* If a patch version is created, it should be placed sorted among the other existing constants.
*
* REVERTING A TRANSPORT VERSION
*
* If you revert a commit with a transport version change, you MUST ensure there is a NEW transport version representing the reverted
* change. DO NOT let the transport version go backwards, it must ALWAYS be incremented.
*
* DETERMINING TRANSPORT VERSIONS FROM GIT HISTORY
*
* If your git checkout has the expected minor-version-numbered branches and the expected release-version tags then you can find the
* transport versions known by a particular release ...
*
* git show v8.11.0:server/src/main/java/org/elasticsearch/TransportVersions.java | grep '= def'
*
* ... or by a particular branch ...
*
* git show 8.11:server/src/main/java/org/elasticsearch/TransportVersions.java | grep '= def'
*
* ... and you can see which versions were added in between two versions too ...
*
* git diff v8.11.0..main -- server/src/main/java/org/elasticsearch/TransportVersions.java
*
* In branches 8.7-8.10 see server/src/main/java/org/elasticsearch/TransportVersion.java for the equivalent definitions.
*/
/**
* Reference to the earliest compatible transport version to this version of the codebase.
* This should be the transport version used by the highest minor version of the previous major.
*/
public static final TransportVersion MINIMUM_COMPATIBLE = V_7_17_0;
/**
* Reference to the minimum transport version that can be used with CCS.
* This should be the transport version used by the previous minor release.
*/
public static final TransportVersion MINIMUM_CCS_VERSION = V_8_13_0;
static final NavigableMap<Integer, TransportVersion> VERSION_IDS = getAllVersionIds(TransportVersions.class);
// the highest transport version constant defined in this file, used as a fallback for TransportVersion.current()
static final TransportVersion LATEST_DEFINED;
static {
LATEST_DEFINED = VERSION_IDS.lastEntry().getValue();
// see comment on IDS field
// now we're registered all the transport versions, we can clear the map
IDS = null;
}
public static NavigableMap<Integer, TransportVersion> getAllVersionIds(Class<?> cls) {
Map<Integer, String> versionIdFields = new HashMap<>();
NavigableMap<Integer, TransportVersion> builder = new TreeMap<>();
Set<String> ignore = Set.of("ZERO", "CURRENT", "MINIMUM_COMPATIBLE", "MINIMUM_CCS_VERSION");
for (Field declaredField : cls.getFields()) {
if (declaredField.getType().equals(TransportVersion.class)) {
String fieldName = declaredField.getName();
if (ignore.contains(fieldName)) {
continue;
}
TransportVersion version;
try {
version = (TransportVersion) declaredField.get(null);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
builder.put(version.id(), version);
if (Assertions.ENABLED) {
// check the version number is unique
var sameVersionNumber = versionIdFields.put(version.id(), fieldName);
assert sameVersionNumber == null
: "Versions ["
+ sameVersionNumber
+ "] and ["
+ fieldName
+ "] have the same version number ["
+ version.id()
+ "]. Each TransportVersion should have a different version number";
}
}
}
return Collections.unmodifiableNavigableMap(builder);
}
static Collection<TransportVersion> getAllVersions() {
return VERSION_IDS.values();
}
static final IntFunction<String> VERSION_LOOKUP = ReleaseVersions.generateVersionsLookup(TransportVersions.class);
// no instance
private TransportVersions() {}
}
| gitpod-io/elasticsearch | server/src/main/java/org/elasticsearch/TransportVersions.java |
150 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.virtual.proxy;
/**
* The main application class that sets up and runs the Virtual Proxy pattern demo.
*/
public class App {
/**
* The entry point of the application.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
ExpensiveObject videoObject = new VideoObjectProxy();
videoObject.process(); // The first call creates and plays the video
videoObject.process(); // Subsequent call uses the already created object
}
} | iluwatar/java-design-patterns | virtual-proxy/src/main/java/com/iluwatar/virtual/proxy/App.java |
151 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.masterworker;
/**
* The abstract Result class, which contains 1 public field containing result data.
*
* @param <T> T will be type of data.
*/
public abstract class Result<T> {
public final T data;
public Result(T data) {
this.data = data;
}
}
| iluwatar/java-design-patterns | master-worker/src/main/java/com/iluwatar/masterworker/Result.java |
152 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.strategy;
import lombok.extern.slf4j.Slf4j;
/**
* Lambda implementation for enum strategy pattern.
*/
@Slf4j
public class LambdaStrategy {
/**
* Enum to demonstrate strategy pattern.
*/
public enum Strategy implements DragonSlayingStrategy {
MELEE_STRATEGY(() -> LOGGER.info(
"With your Excalibur you severe the dragon's head!")),
PROJECTILE_STRATEGY(() -> LOGGER.info(
"You shoot the dragon with the magical crossbow and it falls dead on the ground!")),
SPELL_STRATEGY(() -> LOGGER.info(
"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
private final DragonSlayingStrategy dragonSlayingStrategy;
Strategy(DragonSlayingStrategy dragonSlayingStrategy) {
this.dragonSlayingStrategy = dragonSlayingStrategy;
}
@Override
public void execute() {
dragonSlayingStrategy.execute();
}
}
} | iluwatar/java-design-patterns | strategy/src/main/java/com/iluwatar/strategy/LambdaStrategy.java |
153 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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.
*/
/*
*The MIT License
*Copyright © 2014-2021 Ilkka Seppälä
*
*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 com.iluwatar.monitor;
import java.util.Arrays;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/** Bank Definition. */
@Slf4j
public class Bank {
@Getter
private final int[] accounts;
/**
* Constructor.
*
* @param accountNum - account number
* @param baseAmount - base amount
*/
public Bank(int accountNum, int baseAmount) {
accounts = new int[accountNum];
Arrays.fill(accounts, baseAmount);
}
/**
* Transfer amounts from one account to another.
*
* @param accountA - source account
* @param accountB - destination account
* @param amount - amount to be transferred
*/
public synchronized void transfer(int accountA, int accountB, int amount) {
if (accounts[accountA] >= amount && accountA != accountB) {
accounts[accountB] += amount;
accounts[accountA] -= amount;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Transferred from account: {} to account: {} , amount: {} , bank balance at: {}, source account balance: {}, destination account balance: {}",
accountA,
accountB,
amount,
getBalance(),
getBalance(accountA),
getBalance(accountB));
}
}
}
/**
* Calculates the total balance.
*
* @return balance
*/
public synchronized int getBalance() {
int balance = 0;
for (int account : accounts) {
balance += account;
}
return balance;
}
/**
* Get the accountNumber balance.
*
* @param accountNumber - accountNumber number
* @return accounts[accountNumber]
*/
public synchronized int getBalance(int accountNumber) {
return accounts[accountNumber];
}
}
| iluwatar/java-design-patterns | monitor/src/main/java/com/iluwatar/monitor/Bank.java |
154 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.slob.lob;
import static com.iluwatar.slob.lob.Animal.iterateXmlForAnimalAndPlants;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Creates an object Forest which contains animals and plants as its constituents. Animals may eat
* plants or other animals in the forest.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Forest implements Serializable {
private String name;
private Set<Animal> animals = new HashSet<>();
private Set<Plant> plants = new HashSet<>();
/**
* Provides the representation of Forest in XML form.
*
* @return XML Element
*/
public Element toXmlElement() throws ParserConfigurationException {
Document xmlDoc = getXmlDoc();
Element forestXml = xmlDoc.createElement("Forest");
forestXml.setAttribute("name", name);
Element animalsXml = xmlDoc.createElement("Animals");
for (Animal animal : animals) {
Element animalXml = animal.toXmlElement(xmlDoc);
animalsXml.appendChild(animalXml);
}
forestXml.appendChild(animalsXml);
Element plantsXml = xmlDoc.createElement("Plants");
for (Plant plant : plants) {
Element plantXml = plant.toXmlElement(xmlDoc);
plantsXml.appendChild(plantXml);
}
forestXml.appendChild(plantsXml);
return forestXml;
}
/**
* Returns XMLDoc to use for XML creation.
*
* @return XML DOC Object
* @throws ParserConfigurationException {@inheritDoc}
*/
private Document getXmlDoc() throws ParserConfigurationException {
return DocumentBuilderFactory.newDefaultInstance().newDocumentBuilder().newDocument();
}
/**
* Parses the Forest Object from the input XML Document.
*
* @param document the XML document from which the Forest is to be parsed
*/
public void createObjectFromXml(Document document) {
name = document.getDocumentElement().getAttribute("name");
NodeList nodeList = document.getElementsByTagName("*");
iterateXmlForAnimalAndPlants(nodeList, animals, plants);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("\n");
sb.append("Forest Name = ").append(name).append("\n");
sb.append("Animals found in the ").append(name).append(" Forest: \n");
for (Animal animal : animals) {
sb.append("\n--------------------------\n");
sb.append(animal.toString());
sb.append("\n--------------------------\n");
}
sb.append("\n");
sb.append("Plants in the ").append(name).append(" Forest: \n");
for (Plant plant : plants) {
sb.append("\n--------------------------\n");
sb.append(plant.toString());
sb.append("\n--------------------------\n");
}
return sb.toString();
}
}
| rajprins/java-design-patterns | slob/src/main/java/com/iluwatar/slob/lob/Forest.java |
156 | /**
* The Really Neato Calculator Company, Inc. has recently hired your team to help design their Super
* Neato Model I calculator. As a computer scientist you suggested to the company that it would be neato
* if this new calculator could convert among number bases. The company thought this was a stupendous
* idea and has asked your team to come up with the prototype program for doing base conversion. The
* project manager of the Super Neato Model I calculator has informed you that the calculator will have
* the following neato features:
* • It will have a 7-digit display.
* • Its buttons will include the capital letters A through F in addition to the digits 0 through 9.
* • It will support bases 2 through 16.
* Input
* The input for your prototype program will consist of one base conversion per line. There will be three
* numbers per line. The first number will be the number in the base you are converting from. It may have
* leading ‘0’s. The second number is the base you are converting from. The third number is the base you
* are converting to. There will be one or more blanks surrounding (on either side of) the numbers. There
* are several lines of input and your program should continue to read until the end of file is reached.
* Output
* The output will only be the converted number as it would appear on the display of the calculator.
* The number should be right justified in the 7-digit display. If the number is to large to appear on the
* display, then print ‘ERROR’ (without the quotes) right justified in the display.
* Sample Input
* 1111000 2 10
* 1111000 2 16
* 2102101 3 10
* 2102101 3 15
* 12312 4 2
* 1A 15 2
* ABCD 16 15
* 03 13 10
* Sample Output
* 120
* 78
* 1765
* 7CA
* ERROR
* 11001
* D071
* 3
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=325
import java.math.BigInteger;
import java.util.Scanner;
public class BasicallySpeaking {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
String numberAsString = input.next();
int fromBase = input.nextInt();
int toBase = input.nextInt();
BigInteger number = new BigInteger(numberAsString, fromBase);
String numberThatIsPrinted = number.toString(toBase);
String answer = numberThatIsPrinted.toUpperCase();
if (numberThatIsPrinted.length() > 7) {
answer = "ERROR";
}
System.out.printf("%7s\n", answer);
}
}
}
| kdn251/interviews | uva/BasicallySpeaking.java |
157 | // Given two 1d vectors, implement an iterator to return their elements alternately.
// For example, given two 1d vectors:
// v1 = [1, 2]
// v2 = [3, 4, 5, 6]
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].
// Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i = new ZigzagIterator(v1, v2);
* while (i.hasNext()) v[f()] = i.next();
*/
public class ZigZagIterator {
private Iterator<Integer> i;
private Iterator<Integer> j;
private Iterator<Integer> temp;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
i = v1.iterator();
j = v2.iterator();
}
public int next() {
if(i.hasNext()) {
temp = i;
i = j;
j = temp;
}
return j.next();
}
public boolean hasNext() {
return i.hasNext() || j.hasNext();
}
}
| kdn251/interviews | leetcode/design/ZigZagIterator.java |
159 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.gateway;
import lombok.extern.slf4j.Slf4j;
/**
* ExternalServiceA is one of external services.
*/
@Slf4j
class ExternalServiceA implements Gateway {
@Override
public void execute() throws Exception {
LOGGER.info("Executing Service A");
// Simulate a time-consuming task
Thread.sleep(1000);
}
}
| iluwatar/java-design-patterns | gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java |
160 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.factory;
import lombok.extern.slf4j.Slf4j;
/**
* Factory is an object for creating other objects. It provides a static method to
* create and return objects of varying classes, in order to hide the implementation logic
* and makes client code focus on usage rather than objects initialization and management.
*
* <p>In this example an alchemist manufactures coins. CoinFactory is the factory class, and it
* provides a static method to create different types of coins.
*/
@Slf4j
public class App {
/**
* Program main entry point.
*/
public static void main(String[] args) {
LOGGER.info("The alchemist begins his work.");
var coin1 = CoinFactory.getCoin(CoinType.COPPER);
var coin2 = CoinFactory.getCoin(CoinType.GOLD);
LOGGER.info(coin1.getDescription());
LOGGER.info(coin2.getDescription());
}
}
| iluwatar/java-design-patterns | factory/src/main/java/com/iluwatar/factory/App.java |
161 | /**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
class Node {
int data;
int min;
Node next;
public Node(int data, int min) {
this.data = data;
this.min = min;
this.next = null;
}
}
Node head;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(head == null) {
head = new Node(x, x);
} else {
Node newNode = new Node(x, Math.min(x, head.min));
newNode.next = head;
head = newNode;
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.data;
}
public int getMin() {
return head.min;
}
}
| kdn251/interviews | company/facebook/MinStack.java |
162 | // Given two 1d vectors, implement an iterator to return their elements alternately.
// For example, given two 1d vectors:
// v1 = [1, 2]
// v2 = [3, 4, 5, 6]
// By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].
// Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i = new ZigzagIterator(v1, v2);
* while (i.hasNext()) v[f()] = i.next();
*/
public class ZigZagIterator {
private Iterator<Integer> i;
private Iterator<Integer> j;
private Iterator<Integer> temp;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
i = v1.iterator();
j = v2.iterator();
}
public int next() {
if(i.hasNext()) {
temp = i;
i = j;
j = temp;
}
return j.next();
}
public boolean hasNext() {
return i.hasNext() || j.hasNext();
}
}
| kdn251/interviews | company/google/ZigZagIterator.java |
163 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.lockableobject;
import com.iluwatar.lockableobject.domain.Creature;
import com.iluwatar.lockableobject.domain.Elf;
import com.iluwatar.lockableobject.domain.Feind;
import com.iluwatar.lockableobject.domain.Human;
import com.iluwatar.lockableobject.domain.Orc;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
/**
* The Lockable Object pattern is a concurrency pattern. Instead of using the "synchronized" word
* upon the methods to be synchronized, the object which implements the Lockable interface handles
* the request.
*
* <p>In this example, we create a new Lockable object with the SwordOfAragorn implementation of it.
* Afterward we create 6 Creatures with the Elf, Orc and Human implementations and assign them each
* to a Fiend object and the Sword is the target object. Because there is only one Sword, and it uses
* the Lockable Object pattern, only one creature can hold the sword at a given time. When the sword
* is locked, any other alive Fiends will try to lock, which will result in a race to lock the
* sword.
*
* @author Noam Greenshtain
*/
@Slf4j
public class App implements Runnable {
private static final int WAIT_TIME = 3;
private static final int WORKERS = 2;
private static final int MULTIPLICATION_FACTOR = 3;
/**
* main method.
*
* @param args as arguments for the main method.
*/
public static void main(String[] args) {
var app = new App();
app.run();
}
@Override
public void run() {
// The target object for this example.
var sword = new SwordOfAragorn();
// Creation of creatures.
List<Creature> creatures = new ArrayList<>();
for (var i = 0; i < WORKERS; i++) {
creatures.add(new Elf(String.format("Elf %s", i)));
creatures.add(new Orc(String.format("Orc %s", i)));
creatures.add(new Human(String.format("Human %s", i)));
}
int totalFiends = WORKERS * MULTIPLICATION_FACTOR;
ExecutorService service = Executors.newFixedThreadPool(totalFiends);
// Attach every creature and the sword is a Fiend to fight for the sword.
for (var i = 0; i < totalFiends; i = i + MULTIPLICATION_FACTOR) {
service.submit(new Feind(creatures.get(i), sword));
service.submit(new Feind(creatures.get(i + 1), sword));
service.submit(new Feind(creatures.get(i + 2), sword));
}
// Wait for program to terminate.
try {
if (!service.awaitTermination(WAIT_TIME, TimeUnit.SECONDS)) {
LOGGER.info("The master of the sword is now {}.", sword.getLocker().getName());
}
} catch (InterruptedException e) {
LOGGER.error(e.getMessage());
Thread.currentThread().interrupt();
} finally {
service.shutdown();
}
}
}
| iluwatar/java-design-patterns | lockable-object/src/main/java/com/iluwatar/lockableobject/App.java |
164 | // Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.
// Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.
// It is possible that several messages arrive roughly at the same time.
// Example:
// Logger logger = new Logger();
// // logging string "foo" at timestamp 1
// logger.shouldPrintMessage(1, "foo"); returns true;
// // logging string "bar" at timestamp 2
// logger.shouldPrintMessage(2,"bar"); returns true;
// // logging string "foo" at timestamp 3
// logger.shouldPrintMessage(3,"foo"); returns false;
// // logging string "bar" at timestamp 8
// logger.shouldPrintMessage(8,"bar"); returns false;
// // logging string "foo" at timestamp 10
// logger.shouldPrintMessage(10,"foo"); returns false;
// // logging string "foo" at timestamp 11
// logger.shouldPrintMessage(11,"foo"); returns true;
public class LoggerRateLimiter {
HashMap<String, Integer> messages;
/** Initialize your data structure here. */
public Logger() {
this.messages = new HashMap<String, Integer>();
}
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity. */
public boolean shouldPrintMessage(int timestamp, String message) {
if(messages.containsKey(message)) {
if(timestamp - messages.get(message) >= 10) {
messages.put(message, timestamp);
return true;
} else {
return false;
}
} else {
messages.put(message, timestamp);
return true;
}
}
}
/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* boolean param_1 = obj.shouldPrintMessage(timestamp,message);
*/
| kdn251/interviews | company/google/LoggerRateLimiter.java |
165 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.lite;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime;
import org.tensorflow.lite.InterpreterImpl.Options;
import org.tensorflow.lite.annotations.UsedByReflection;
import org.tensorflow.lite.nnapi.NnApiDelegate;
/**
* An internal wrapper that wraps native interpreter and controls model execution.
*
* <p><b>WARNING:</b> Resources consumed by the {@code NativeInterpreterWrapper} object must be
* explicitly freed by invoking the {@link #close()} method when the {@code
* NativeInterpreterWrapper} object is no longer needed.
*
* <p>Note: This class is not thread safe.
*/
class NativeInterpreterWrapper implements AutoCloseable {
// This is changed to RuntimeFlavor.SYSTEM for TF Lite in Google Play Services.
private static final RuntimeFlavor RUNTIME_FLAVOR = RuntimeFlavor.APPLICATION;
NativeInterpreterWrapper(String modelPath) {
this(modelPath, /* options= */ null);
}
NativeInterpreterWrapper(ByteBuffer byteBuffer) {
this(byteBuffer, /* options= */ null);
}
NativeInterpreterWrapper(String modelPath, InterpreterImpl.Options options) {
TensorFlowLite.init();
long errorHandle = createErrorReporter(ERROR_BUFFER_SIZE);
long modelHandle = createModel(modelPath, errorHandle);
init(errorHandle, modelHandle, options);
}
NativeInterpreterWrapper(ByteBuffer buffer, InterpreterImpl.Options options) {
TensorFlowLite.init();
if (buffer == null
|| (!(buffer instanceof MappedByteBuffer)
&& (!buffer.isDirect() || buffer.order() != ByteOrder.nativeOrder()))) {
throw new IllegalArgumentException(
"Model ByteBuffer should be either a MappedByteBuffer of the model file, or a direct "
+ "ByteBuffer using ByteOrder.nativeOrder() which contains bytes of model content.");
}
this.modelByteBuffer = buffer;
long errorHandle = createErrorReporter(ERROR_BUFFER_SIZE);
long modelHandle = createModelWithBuffer(modelByteBuffer, errorHandle);
init(errorHandle, modelHandle, options);
}
private void init(long errorHandle, long modelHandle, InterpreterImpl.Options options) {
if (options == null) {
options = new InterpreterImpl.Options();
}
if (options.getAccelerationConfig() != null) {
// Apply the validated acceleration config
options.getAccelerationConfig().apply(options);
}
this.errorHandle = errorHandle;
this.modelHandle = modelHandle;
// First create the interpreter without delegates. We need an interpreter in order to figure
// out whether the model contains any unresolved flex ops, and creating the interpreter with
// delegates might fail if there are any unresolved flex ops.
// (Alternatively, we could determine this without needing to recreate the interpreter
// by passing the tflite::Model in to here, and then traversing that?)
ArrayList<Long> delegateHandles = new ArrayList<>();
this.interpreterHandle =
createInterpreter(
modelHandle,
errorHandle,
options.getNumThreads(),
options.getUseXNNPACK(),
delegateHandles);
this.originalGraphHasUnresolvedFlexOp = hasUnresolvedFlexOp(interpreterHandle);
addDelegates(options);
initDelegatesWithInterpreterFactory();
delegateHandles.ensureCapacity(delegates.size());
for (Delegate delegate : delegates) {
delegateHandles.add(delegate.getNativeHandle());
}
if (!delegateHandles.isEmpty()) {
// If there are any delegates enabled, recreate the interpreter with those delegates.
delete(/* errorHandle= */ 0, /* modelHandle= */ 0, this.interpreterHandle);
this.interpreterHandle =
createInterpreter(
modelHandle,
errorHandle,
options.getNumThreads(),
options.getUseXNNPACK(),
delegateHandles);
}
if (options.allowFp16PrecisionForFp32 != null) {
allowFp16PrecisionForFp32(interpreterHandle, options.allowFp16PrecisionForFp32);
}
if (options.allowBufferHandleOutput != null) {
allowBufferHandleOutput(interpreterHandle, options.allowBufferHandleOutput);
}
if (options.isCancellable()) {
this.cancellationFlagHandle = createCancellationFlag(interpreterHandle);
}
this.inputTensors = new TensorImpl[getInputCount(interpreterHandle)];
this.outputTensors = new TensorImpl[getOutputCount(interpreterHandle)];
if (options.allowFp16PrecisionForFp32 != null) {
allowFp16PrecisionForFp32(interpreterHandle, options.allowFp16PrecisionForFp32);
}
if (options.allowBufferHandleOutput != null) {
allowBufferHandleOutput(interpreterHandle, options.allowBufferHandleOutput);
}
allocateTensors(interpreterHandle, errorHandle);
this.isMemoryAllocated = true;
}
/** Releases resources associated with this {@code NativeInterpreterWrapper}. */
@Override
public void close() {
// Close the tensors first as they may reference the native interpreter.
for (int i = 0; i < inputTensors.length; ++i) {
if (inputTensors[i] != null) {
inputTensors[i].close();
inputTensors[i] = null;
}
}
for (int i = 0; i < outputTensors.length; ++i) {
if (outputTensors[i] != null) {
outputTensors[i].close();
outputTensors[i] = null;
}
}
delete(errorHandle, modelHandle, interpreterHandle);
deleteCancellationFlag(cancellationFlagHandle);
errorHandle = 0;
modelHandle = 0;
interpreterHandle = 0;
cancellationFlagHandle = 0;
modelByteBuffer = null;
inputsIndexes = null;
outputsIndexes = null;
isMemoryAllocated = false;
delegates.clear();
for (Delegate ownedDelegate : ownedDelegates) {
ownedDelegate.close();
}
ownedDelegates.clear();
}
/** Runs model inference based on SignatureDef provided through {@code signatureKey}. */
public void runSignature(
Map<String, Object> inputs, Map<String, Object> outputs, String signatureKey) {
inferenceDurationNanoseconds = -1;
if (inputs == null || inputs.isEmpty()) {
throw new IllegalArgumentException("Input error: Inputs should not be null or empty.");
}
if (outputs == null) {
throw new IllegalArgumentException("Input error: Outputs should not be null.");
}
NativeSignatureRunnerWrapper signatureRunnerWrapper = getSignatureRunnerWrapper(signatureKey);
int subgraphIndex = signatureRunnerWrapper.getSubgraphIndex();
if (subgraphIndex == 0) {
// Map inputs/output to input indexes.
Object[] inputsList = new Object[inputs.size()];
for (Map.Entry<String, Object> input : inputs.entrySet()) {
inputsList[signatureRunnerWrapper.getInputIndex(input.getKey())] = input.getValue();
}
Map<Integer, Object> outputsWithOutputIndex = new TreeMap<>();
for (Map.Entry<String, Object> output : outputs.entrySet()) {
outputsWithOutputIndex.put(
signatureRunnerWrapper.getOutputIndex(output.getKey()), output.getValue());
}
run(inputsList, outputsWithOutputIndex);
return;
}
for (Map.Entry<String, Object> input : inputs.entrySet()) {
TensorImpl tensor = getInputTensor(input.getKey(), signatureKey);
int[] newShape = tensor.getInputShapeIfDifferent(input.getValue());
if (newShape != null) {
try {
signatureRunnerWrapper.resizeInput(input.getKey(), newShape);
} catch (IllegalArgumentException e) {
throw (IllegalArgumentException)
new IllegalArgumentException(
String.format(
"Tensor passed for input '%s' of signature '%s' has different "
+ "shape than expected",
input.getKey(), signatureKey))
.initCause(e);
}
}
}
signatureRunnerWrapper.allocateTensorsIfNeeded();
for (Map.Entry<String, Object> input : inputs.entrySet()) {
signatureRunnerWrapper.getInputTensor(input.getKey()).setTo(input.getValue());
}
long inferenceStartNanos = System.nanoTime();
signatureRunnerWrapper.invoke();
long inferenceDurationNanoseconds = System.nanoTime() - inferenceStartNanos;
for (Map.Entry<String, Object> output : outputs.entrySet()) {
// Null output placeholders are allowed and ignored.
if (output.getValue() != null) {
signatureRunnerWrapper.getOutputTensor(output.getKey()).copyTo(output.getValue());
}
}
// Only set if the entire operation succeeds.
this.inferenceDurationNanoseconds = inferenceDurationNanoseconds;
}
/** Sets inputs, runs model inference and returns outputs. */
void run(Object[] inputs, Map<Integer, Object> outputs) {
inferenceDurationNanoseconds = -1;
if (inputs == null || inputs.length == 0) {
throw new IllegalArgumentException("Input error: Inputs should not be null or empty.");
}
if (outputs == null) {
throw new IllegalArgumentException("Input error: Outputs should not be null.");
}
// TODO(b/80431971): Remove implicit resize after deprecating multi-dimensional array inputs.
// Rather than forcing an immediate resize + allocation if an input's shape differs, we first
// flush all resizes, avoiding redundant allocations.
for (int i = 0; i < inputs.length; ++i) {
TensorImpl tensor = getInputTensor(i);
int[] newShape = tensor.getInputShapeIfDifferent(inputs[i]);
if (newShape != null) {
resizeInput(i, newShape);
}
}
boolean allocatedTensors = allocateTensorsIfNeeded();
for (int i = 0; i < inputs.length; ++i) {
getInputTensor(i).setTo(inputs[i]);
}
long inferenceStartNanos = System.nanoTime();
run(interpreterHandle, errorHandle);
long inferenceDurationNanoseconds = System.nanoTime() - inferenceStartNanos;
// Allocation can trigger dynamic resizing of output tensors, so refresh all output shapes.
if (allocatedTensors) {
for (TensorImpl outputTensor : outputTensors) {
if (outputTensor != null) {
outputTensor.refreshShape();
}
}
}
for (Map.Entry<Integer, Object> output : outputs.entrySet()) {
// Null output placeholders are allowed and ignored.
if (output.getValue() != null) {
getOutputTensor(output.getKey()).copyTo(output.getValue());
}
}
// Only set if the entire operation succeeds.
this.inferenceDurationNanoseconds = inferenceDurationNanoseconds;
}
/** Resizes dimensions of a specific input. */
void resizeInput(int idx, int[] dims) {
resizeInput(idx, dims, false);
}
/** Resizes dimensions of a specific input. */
void resizeInput(int idx, int[] dims, boolean strict) {
if (resizeInput(interpreterHandle, errorHandle, idx, dims, strict)) {
// Tensor allocation is deferred until either an explicit `allocateTensors()` call or
// `invoke()` avoiding redundant allocations if multiple tensors are simultaneosly resized.
isMemoryAllocated = false;
if (inputTensors[idx] != null) {
inputTensors[idx].refreshShape();
}
}
}
/** Triggers explicit allocation of tensors. */
void allocateTensors() {
allocateTensorsIfNeeded();
}
/**
* Allocates tensor memory space in the given subgraph and returns true when allocation happens
*/
private boolean allocateTensorsIfNeeded() {
if (isMemoryAllocated) {
return false;
}
isMemoryAllocated = true;
allocateTensors(interpreterHandle, errorHandle);
for (TensorImpl outputTensor : outputTensors) {
if (outputTensor != null) {
outputTensor.refreshShape();
}
}
return true;
}
/** Gets index of an input given its name. */
int getInputIndex(String name) {
if (inputsIndexes == null) {
String[] names = getInputNames(interpreterHandle);
inputsIndexes = new HashMap<>();
if (names != null) {
for (int i = 0; i < names.length; ++i) {
inputsIndexes.put(names[i], i);
}
}
}
if (inputsIndexes.containsKey(name)) {
return inputsIndexes.get(name);
} else {
throw new IllegalArgumentException(
String.format(
"Input error: '%s' is not a valid name for any input. Names of inputs and their "
+ "indexes are %s",
name, inputsIndexes));
}
}
/** Gets index of an output given its name. */
int getOutputIndex(String name) {
if (outputsIndexes == null) {
String[] names = getOutputNames(interpreterHandle);
outputsIndexes = new HashMap<>();
if (names != null) {
for (int i = 0; i < names.length; ++i) {
outputsIndexes.put(names[i], i);
}
}
}
if (outputsIndexes.containsKey(name)) {
return outputsIndexes.get(name);
} else {
throw new IllegalArgumentException(
String.format(
"Input error: '%s' is not a valid name for any output. Names of outputs and their "
+ "indexes are %s",
name, outputsIndexes));
}
}
/**
* Gets the last inference duration in nanoseconds. It returns null if there is no previous
* inference run or the last inference run failed.
*/
Long getLastNativeInferenceDurationNanoseconds() {
return (inferenceDurationNanoseconds < 0) ? null : inferenceDurationNanoseconds;
}
/** Gets the number of input tensors. */
int getInputTensorCount() {
return inputTensors.length;
}
/**
* Gets the input {@link TensorImpl} for the provided input index.
*
* @throws IllegalArgumentException if the input index is invalid.
*/
TensorImpl getInputTensor(int index) {
if (index < 0 || index >= inputTensors.length) {
throw new IllegalArgumentException("Invalid input Tensor index: " + index);
}
TensorImpl inputTensor = inputTensors[index];
if (inputTensor == null) {
inputTensor =
inputTensors[index] =
TensorImpl.fromIndex(
interpreterHandle, getInputTensorIndex(interpreterHandle, index));
}
return inputTensor;
}
/**
* Gets the input {@link TensorImpl} given the tensor name and method in the signature.
*
* @throws IllegalArgumentException if the input name is invalid.
*/
TensorImpl getInputTensor(String inputName, String signatureKey) {
if (inputName == null) {
throw new IllegalArgumentException("Invalid input tensor name provided (null)");
}
NativeSignatureRunnerWrapper signatureRunnerWrapper = getSignatureRunnerWrapper(signatureKey);
int subgraphIndex = signatureRunnerWrapper.getSubgraphIndex();
if (subgraphIndex == 0) {
int inputIndex = signatureRunnerWrapper.getInputIndex(inputName);
return getInputTensor(inputIndex);
}
return signatureRunnerWrapper.getInputTensor(inputName);
}
/** Gets the keys of SignatureDefs available in the model, if any. */
public String[] getSignatureKeys() {
return getSignatureKeys(interpreterHandle);
}
/** Gets the list of SignatureDefs inputs for method {@code signatureKey} */
String[] getSignatureInputs(String signatureKey) {
return getSignatureRunnerWrapper(signatureKey).inputNames();
}
/** Gets the list of SignatureDefs outputs for method {@code signatureKey} */
String[] getSignatureOutputs(String signatureKey) {
return getSignatureRunnerWrapper(signatureKey).outputNames();
}
/** Gets the number of output tensors. */
int getOutputTensorCount() {
return outputTensors.length;
}
/**
* Gets the output {@link TensorImpl} for the provided output index.
*
* @throws IllegalArgumentException if the output index is invalid.
*/
TensorImpl getOutputTensor(int index) {
if (index < 0 || index >= outputTensors.length) {
throw new IllegalArgumentException("Invalid output Tensor index: " + index);
}
TensorImpl outputTensor = outputTensors[index];
if (outputTensor == null) {
outputTensor =
outputTensors[index] =
TensorImpl.fromIndex(
interpreterHandle, getOutputTensorIndex(interpreterHandle, index));
}
return outputTensor;
}
/**
* Gets the output {@link TensorImpl} given the tensor name and method in the signature.
*
* @throws IllegalArgumentException if the output name is invalid.
*/
TensorImpl getOutputTensor(String outputName, String signatureKey) {
if (outputName == null) {
throw new IllegalArgumentException("Invalid output tensor name provided (null)");
}
NativeSignatureRunnerWrapper signatureRunnerWrapper = getSignatureRunnerWrapper(signatureKey);
int subgraphIndex = signatureRunnerWrapper.getSubgraphIndex();
if (subgraphIndex == 0) {
int outputIndex = signatureRunnerWrapper.getOutputIndex(outputName);
return getOutputTensor(outputIndex);
}
return signatureRunnerWrapper.getOutputTensor(outputName);
}
/** Gets the number of ops in the execution plan. */
int getExecutionPlanLength() {
return getExecutionPlanLength(interpreterHandle);
}
/**
* Sets internal cancellation flag. If it's true, the interpreter will try to interrupt any
* invocation between ops.
*/
void setCancelled(boolean value) {
if (cancellationFlagHandle == 0) {
throw new IllegalStateException(
"Cannot cancel the inference. Have you called InterpreterApi.Options.setCancellable?");
}
setCancelled(interpreterHandle, cancellationFlagHandle, value);
}
// Add all the delegates specified in the options (other than XNNPACK) to this.delegates.
private void addDelegates(InterpreterImpl.Options options) {
// First add the flex delegate if necessary. This ensures the graph is fully resolved before
// applying other delegates.
if (originalGraphHasUnresolvedFlexOp) {
Delegate optionalFlexDelegate = maybeCreateFlexDelegate(options.getDelegates());
if (optionalFlexDelegate != null) {
ownedDelegates.add(optionalFlexDelegate);
delegates.add(optionalFlexDelegate);
}
}
// Now add the user-supplied delegates.
addUserProvidedDelegates(options);
for (DelegateFactory delegateFactory : options.getDelegateFactories()) {
Delegate delegate = delegateFactory.create(RUNTIME_FLAVOR);
ownedDelegates.add(delegate);
delegates.add(delegate);
}
if (options.getUseNNAPI()) {
NnApiDelegate optionalNnApiDelegate = new NnApiDelegate();
ownedDelegates.add(optionalNnApiDelegate);
delegates.add(optionalNnApiDelegate);
}
}
private void addUserProvidedDelegates(Options options) {
for (Delegate delegate : options.getDelegates()) {
// NnApiDelegate is compatible with both the system and built-in runtimes and therefore can be
// added directly even when using TF Lite from the system.
if (options.getRuntime() != TfLiteRuntime.FROM_APPLICATION_ONLY
&& !(delegate instanceof NnApiDelegate)) {
throw new IllegalArgumentException(
"Instantiated delegates (other than NnApiDelegate) are not allowed when using TF Lite"
+ " from Google Play Services. Please use"
+ " InterpreterApi.Options.addDelegateFactory() with an appropriate DelegateFactory"
+ " instead.");
}
delegates.add(delegate);
}
}
// Complete the initialization of any delegates that require an InterpreterFactoryApi instance.
private void initDelegatesWithInterpreterFactory() {
InterpreterFactoryApi interpreterFactoryApi = new InterpreterFactoryImpl();
for (Delegate delegate : delegates) {
if (delegate instanceof NnApiDelegate) {
((NnApiDelegate) delegate).initWithInterpreterFactoryApi(interpreterFactoryApi);
}
}
}
private NativeSignatureRunnerWrapper getSignatureRunnerWrapper(String signatureKey) {
if (signatureRunnerMap == null) {
signatureRunnerMap = new HashMap<>();
}
if (!signatureRunnerMap.containsKey(signatureKey)) {
signatureRunnerMap.put(
signatureKey,
new NativeSignatureRunnerWrapper(interpreterHandle, errorHandle, signatureKey));
}
return signatureRunnerMap.get(signatureKey);
}
private static Delegate maybeCreateFlexDelegate(List<Delegate> delegates) {
try {
Class<?> clazz = Class.forName("org.tensorflow.lite.flex.FlexDelegate");
// No need to create the Flex delegate if one has already been provided.
for (Delegate delegate : delegates) {
if (clazz.isInstance(delegate)) {
return null;
}
}
return (Delegate) clazz.getConstructor().newInstance();
} catch (ClassNotFoundException
| IllegalAccessException
| IllegalArgumentException
| InstantiationException
| InvocationTargetException
| NoSuchMethodException
| SecurityException e) {
// The error will propagate when tensors are allocated.
return null;
}
}
private static final int ERROR_BUFFER_SIZE = 512;
long errorHandle;
long interpreterHandle;
private long modelHandle;
private long cancellationFlagHandle = 0;
@UsedByReflection("nativeinterpreterwrapper_jni.cc")
private long inferenceDurationNanoseconds = -1;
private ByteBuffer modelByteBuffer;
// Lazily constructed maps of input and output names to input and output Tensor indexes.
private Map<String, Integer> inputsIndexes;
private Map<String, Integer> outputsIndexes;
// A map from signature key to its native wrapper object.
private Map<String, NativeSignatureRunnerWrapper> signatureRunnerMap;
// Lazily constructed and populated arrays of input and output Tensor wrappers.
private TensorImpl[] inputTensors;
private TensorImpl[] outputTensors;
// Whether subgraph's tensor memory space is allocated.
private boolean isMemoryAllocated = false;
// Whether the model has any Flex custom ops that can't be resolved by the OpResolver.
private boolean originalGraphHasUnresolvedFlexOp = false;
// As the Java Delegate owns the native delegate instance, we keep a strong ref to any injected
// delegates for safety.
private final List<Delegate> delegates = new ArrayList<>();
// List of owned delegates that must be closed when the interpreter is closed.
private final List<Delegate> ownedDelegates = new ArrayList<>();
private static native void run(long interpreterHandle, long errorHandle);
private static native boolean resizeInput(
long interpreterHandle, long errorHandle, int inputIdx, int[] dims, boolean strict);
private static native long allocateTensors(long interpreterHandle, long errorHandle);
private static native String[] getSignatureKeys(long interpreterHandle);
private static native void setCancelled(
long interpreterHandle, long cancellationFlagHandle, boolean value);
private static native boolean hasUnresolvedFlexOp(long interpreterHandle);
private static native int getInputTensorIndex(long interpreterHandle, int inputIdx);
private static native int getOutputTensorIndex(long interpreterHandle, int outputIdx);
private static native int getInputCount(long interpreterHandle);
private static native int getOutputCount(long interpreterHandle);
private static native int getExecutionPlanLength(long interpreterHandle);
private static native String[] getInputNames(long interpreterHandle);
private static native String[] getOutputNames(long interpreterHandle);
private static native void allowFp16PrecisionForFp32(long interpreterHandle, boolean allow);
private static native void allowBufferHandleOutput(long interpreterHandle, boolean allow);
private static native long createErrorReporter(int size);
private static native long createModel(String modelPathOrBuffer, long errorHandle);
private static native long createModelWithBuffer(ByteBuffer modelBuffer, long errorHandle);
private static native long createInterpreter(
long modelHandle,
long errorHandle,
int numThreads,
boolean useXnnpack,
List<Long> delegateHandles);
private static native long createCancellationFlag(long interpreterHandle);
private static native long deleteCancellationFlag(long cancellationFlagHandle);
private static native void delete(long errorHandle, long modelHandle, long interpreterHandle);
}
| tensorflow/tensorflow | tensorflow/lite/java/src/main/java/org/tensorflow/lite/NativeInterpreterWrapper.java |
166 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.filterer;
import com.iluwatar.filterer.threat.ProbableThreat;
import com.iluwatar.filterer.threat.SimpleProbabilisticThreatAwareSystem;
import com.iluwatar.filterer.threat.SimpleProbableThreat;
import com.iluwatar.filterer.threat.SimpleThreat;
import com.iluwatar.filterer.threat.SimpleThreatAwareSystem;
import com.iluwatar.filterer.threat.Threat;
import com.iluwatar.filterer.threat.ThreatAwareSystem;
import com.iluwatar.filterer.threat.ThreatType;
import java.util.List;
import java.util.function.Predicate;
import lombok.extern.slf4j.Slf4j;
/**
* This demo class represent how {@link com.iluwatar.filterer.domain.Filterer} pattern is used to
* filter container-like objects to return filtered versions of themselves. The container like
* objects are systems that are aware of threats that they can be vulnerable to. We would like
* to have a way to create copy of different system objects but with filtered threats.
* The thing is to keep it simple if we add new subtype of {@link Threat}
* (for example {@link ProbableThreat}) - we still need to be able to filter by its properties.
*/
@Slf4j
public class App {
public static void main(String[] args) {
filteringSimpleThreats();
filteringSimpleProbableThreats();
}
/**
* Demonstrates how to filter {@link com.iluwatar.filterer.threat.ProbabilisticThreatAwareSystem}
* based on probability property. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)}
* method is able to use {@link com.iluwatar.filterer.threat.ProbableThreat}
* as predicate argument.
*/
private static void filteringSimpleProbableThreats() {
LOGGER.info("### Filtering ProbabilisticThreatAwareSystem by probability ###");
var trojanArcBomb = new SimpleProbableThreat("Trojan-ArcBomb", 1, ThreatType.TROJAN, 0.99);
var rootkit = new SimpleProbableThreat("Rootkit-Kernel", 2, ThreatType.ROOTKIT, 0.8);
List<ProbableThreat> probableThreats = List.of(trojanArcBomb, rootkit);
var probabilisticThreatAwareSystem =
new SimpleProbabilisticThreatAwareSystem("Sys-1", probableThreats);
LOGGER.info("Filtering ProbabilisticThreatAwareSystem. Initial : "
+ probabilisticThreatAwareSystem);
//Filtering using filterer
var filteredThreatAwareSystem = probabilisticThreatAwareSystem.filtered()
.by(probableThreat -> Double.compare(probableThreat.probability(), 0.99) == 0);
LOGGER.info("Filtered by probability = 0.99 : " + filteredThreatAwareSystem);
}
/**
* Demonstrates how to filter {@link ThreatAwareSystem} based on startingOffset property
* of {@link SimpleThreat}. The @{@link com.iluwatar.filterer.domain.Filterer#by(Predicate)}
* method is able to use {@link Threat} as predicate argument.
*/
private static void filteringSimpleThreats() {
LOGGER.info("### Filtering ThreatAwareSystem by ThreatType ###");
var rootkit = new SimpleThreat(ThreatType.ROOTKIT, 1, "Simple-Rootkit");
var trojan = new SimpleThreat(ThreatType.TROJAN, 2, "Simple-Trojan");
List<Threat> threats = List.of(rootkit, trojan);
var threatAwareSystem = new SimpleThreatAwareSystem("Sys-1", threats);
LOGGER.info("Filtering ThreatAwareSystem. Initial : " + threatAwareSystem);
//Filtering using Filterer
var rootkitThreatAwareSystem = threatAwareSystem.filtered()
.by(threat -> threat.type() == ThreatType.ROOTKIT);
LOGGER.info("Filtered by threatType = ROOTKIT : " + rootkitThreatAwareSystem);
}
}
| iluwatar/java-design-patterns | filterer/src/main/java/com/iluwatar/filterer/App.java |
167 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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.tensorflow;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Helper class for loading the TensorFlow Java native library.
*
* <p>The Java TensorFlow bindings require a native (JNI) library. This library
* (libtensorflow_jni.so on Linux, libtensorflow_jni.dylib on OS X, tensorflow_jni.dll on Windows)
* can be made available to the JVM using the java.library.path System property (e.g., using
* -Djava.library.path command-line argument). However, doing so requires an additional step of
* configuration.
*
* <p>Alternatively, the native libraries can be packaed in a .jar, making them easily usable from
* build systems like Maven. However, in such cases, the native library has to be extracted from the
* .jar archive.
*
* <p>NativeLibrary.load() takes care of this. First looking for the library in java.library.path
* and failing that, it tries to find the OS and architecture specific version of the library in the
* set of ClassLoader resources (under org/tensorflow/native/OS-ARCH). The resources paths used for
* lookup must be consistent with any packaging (such as on Maven Central) of the TensorFlow Java
* native libraries.
*/
final class NativeLibrary {
private static final boolean DEBUG =
System.getProperty("org.tensorflow.NativeLibrary.DEBUG") != null;
private static final String JNI_LIBNAME = "tensorflow_jni";
public static void load() {
if (isLoaded() || tryLoadLibrary()) {
// Either:
// (1) The native library has already been statically loaded, OR
// (2) The required native code has been statically linked (through a custom launcher), OR
// (3) The native code is part of another library (such as an application-level library)
// that has already been loaded. For example, tensorflow/tools/android/test and
// tensorflow/tools/android/inference_interface include the required native code in
// differently named libraries.
//
// Doesn't matter how, but it seems the native code is loaded, so nothing else to do.
return;
}
// Native code is not present, perhaps it has been packaged into the .jar file containing this.
// Extract the JNI library itself
final String jniLibName = System.mapLibraryName(JNI_LIBNAME);
final String jniResourceName = makeResourceName(jniLibName);
log("jniResourceName: " + jniResourceName);
final InputStream jniResource =
NativeLibrary.class.getClassLoader().getResourceAsStream(jniResourceName);
// Extract the JNI's dependency
final String frameworkLibName =
getVersionedLibraryName(System.mapLibraryName("tensorflow_framework"));
final String frameworkResourceName = makeResourceName(frameworkLibName);
log("frameworkResourceName: " + frameworkResourceName);
final InputStream frameworkResource =
NativeLibrary.class.getClassLoader().getResourceAsStream(frameworkResourceName);
// Do not complain if the framework resource wasn't found. This may just mean that we're
// building with --config=monolithic (in which case it's not needed and not included).
if (jniResource == null) {
throw new UnsatisfiedLinkError(
String.format(
"Cannot find TensorFlow native library for OS: %s, architecture: %s. See "
+ "https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java/README.md"
+ " for possible solutions (such as building the library from source). Additional"
+ " information on attempts to find the native library can be obtained by adding"
+ " org.tensorflow.NativeLibrary.DEBUG=1 to the system properties of the JVM.",
os(), architecture()));
}
try {
// Create a temporary directory for the extracted resource and its dependencies.
final File tempPath = createTemporaryDirectory();
// Deletions are in the reverse order of requests, so we need to request that the directory be
// deleted first, so that it is empty when the request is fulfilled.
tempPath.deleteOnExit();
final String tempDirectory = tempPath.getCanonicalPath();
if (frameworkResource != null) {
extractResource(frameworkResource, frameworkLibName, tempDirectory);
} else {
log(
frameworkResourceName
+ " not found. This is fine assuming "
+ jniResourceName
+ " is not built to depend on it.");
}
System.load(extractResource(jniResource, jniLibName, tempDirectory));
} catch (IOException e) {
throw new UnsatisfiedLinkError(
String.format(
"Unable to extract native library into a temporary file (%s)", e.toString()));
}
}
private static boolean tryLoadLibrary() {
try {
System.loadLibrary(JNI_LIBNAME);
return true;
} catch (UnsatisfiedLinkError e) {
log("tryLoadLibraryFailed: " + e.getMessage());
return false;
}
}
private static boolean isLoaded() {
try {
TensorFlow.version();
log("isLoaded: true");
return true;
} catch (UnsatisfiedLinkError e) {
return false;
}
}
private static boolean resourceExists(String baseName) {
return NativeLibrary.class.getClassLoader().getResource(makeResourceName(baseName)) != null;
}
private static String getVersionedLibraryName(String libFilename) {
final String versionName = getMajorVersionNumber();
// If we're on darwin, the versioned libraries look like blah.1.dylib.
final String darwinSuffix = ".dylib";
if (libFilename.endsWith(darwinSuffix)) {
final String prefix = libFilename.substring(0, libFilename.length() - darwinSuffix.length());
if (versionName != null) {
final String darwinVersionedLibrary = prefix + "." + versionName + darwinSuffix;
if (resourceExists(darwinVersionedLibrary)) {
return darwinVersionedLibrary;
}
} else {
// If we're here, we're on darwin, but we couldn't figure out the major version number. We
// already tried the library name without any changes, but let's do one final try for the
// library with a .so suffix.
final String darwinSoName = prefix + ".so";
if (resourceExists(darwinSoName)) {
return darwinSoName;
}
}
} else if (libFilename.endsWith(".so")) {
// Libraries ending in ".so" are versioned like "libfoo.so.1", so try that.
final String versionedSoName = libFilename + "." + versionName;
if (versionName != null && resourceExists(versionedSoName)) {
return versionedSoName;
}
}
// Otherwise, we've got no idea.
return libFilename;
}
/**
* Returns the major version number of this TensorFlow Java API, or {@code null} if it cannot be
* determined.
*/
private static String getMajorVersionNumber() {
InputStream resourceStream =
NativeLibrary.class.getClassLoader().getResourceAsStream("tensorflow-version-info");
if (resourceStream == null) {
return null;
}
try {
Properties props = new Properties();
props.load(resourceStream);
String version = props.getProperty("version");
// expecting a string like 1.14.0, we want to get the first '1'.
int dotIndex;
if (version == null || (dotIndex = version.indexOf('.')) == -1) {
return null;
}
String majorVersion = version.substring(0, dotIndex);
try {
Integer.parseInt(majorVersion);
return majorVersion;
} catch (NumberFormatException unused) {
return null;
}
} catch (IOException e) {
log("failed to load tensorflow version info.");
return null;
}
}
private static String extractResource(
InputStream resource, String resourceName, String extractToDirectory) throws IOException {
final File dst = new File(extractToDirectory, resourceName);
dst.deleteOnExit();
final String dstPath = dst.toString();
log("extracting native library to: " + dstPath);
final long nbytes = copy(resource, dst);
log(String.format("copied %d bytes to %s", nbytes, dstPath));
return dstPath;
}
private static String os() {
final String p = System.getProperty("os.name").toLowerCase();
if (p.contains("linux")) {
return "linux";
} else if (p.contains("os x") || p.contains("darwin")) {
return "darwin";
} else if (p.contains("windows")) {
return "windows";
} else {
return p.replaceAll("\\s", "");
}
}
private static String architecture() {
final String arch = System.getProperty("os.arch").toLowerCase();
return (arch.equals("amd64")) ? "x86_64" : arch;
}
private static void log(String msg) {
if (DEBUG) {
System.err.println("org.tensorflow.NativeLibrary: " + msg);
}
}
private static String makeResourceName(String baseName) {
return "org/tensorflow/native/" + String.format("%s-%s/", os(), architecture()) + baseName;
}
private static long copy(InputStream src, File dstFile) throws IOException {
FileOutputStream dst = new FileOutputStream(dstFile);
try {
byte[] buffer = new byte[1 << 20]; // 1MB
long ret = 0;
int n = 0;
while ((n = src.read(buffer)) >= 0) {
dst.write(buffer, 0, n);
ret += n;
}
return ret;
} finally {
dst.close();
src.close();
}
}
// Shamelessly adapted from Guava to avoid using java.nio, for Android API
// compatibility.
private static File createTemporaryDirectory() {
File baseDirectory = new File(System.getProperty("java.io.tmpdir"));
String directoryName = "tensorflow_native_libraries-" + System.currentTimeMillis() + "-";
for (int attempt = 0; attempt < 1000; attempt++) {
File temporaryDirectory = new File(baseDirectory, directoryName + attempt);
if (temporaryDirectory.mkdir()) {
return temporaryDirectory;
}
}
throw new IllegalStateException(
"Could not create a temporary directory (tried to make "
+ directoryName
+ "*) to extract TensorFlow native libraries.");
}
private NativeLibrary() {}
}
| tahmaz/arobi | pc/PycharmProjects/speech/tensorflow_src/tensorflow/java/src/main/java/org/tensorflow/NativeLibrary.java |
168 | // Implement a trie with insert, search, and startsWith methods.
// Note:
// You may assume that all inputs are consist of lowercase letters a-z.
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
class TrieNode {
HashMap<Character, TrieNode> map;
char character;
boolean last;
// Initialize your data structure here.
public TrieNode(char character) {
this.map = new HashMap<Character, TrieNode>();
this.character = character;
this.last = false;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode(' ');
}
// Inserts a word into the trie.
public void insert(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
current.map.put(c, new TrieNode(c));
}
current = current.map.get(c);
}
current.last = true;
}
// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(char c : word.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
if(current.last == true) {
return true;
} else {
return false;
}
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(char c : prefix.toCharArray()) {
if(!current.map.containsKey(c)) {
return false;
}
current = current.map.get(c);
}
return true;
}
}
| kdn251/interviews | company/google/ImplementTrie.java |
169 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.memento;
import lombok.Getter;
import lombok.Setter;
/**
* Star uses "mementos" to store and restore state.
*/
public class Star {
private StarType type;
private int ageYears;
private int massTons;
/**
* Constructor.
*/
public Star(StarType startType, int startAge, int startMass) {
this.type = startType;
this.ageYears = startAge;
this.massTons = startMass;
}
/**
* Makes time pass for the star.
*/
public void timePasses() {
ageYears *= 2;
massTons *= 8;
switch (type) {
case RED_GIANT -> type = StarType.WHITE_DWARF;
case SUN -> type = StarType.RED_GIANT;
case SUPERNOVA -> type = StarType.DEAD;
case WHITE_DWARF -> type = StarType.SUPERNOVA;
case DEAD -> {
ageYears *= 2;
massTons = 0;
}
default -> {
}
}
}
StarMemento getMemento() {
var state = new StarMementoInternal();
state.setAgeYears(ageYears);
state.setMassTons(massTons);
state.setType(type);
return state;
}
void setMemento(StarMemento memento) {
var state = (StarMementoInternal) memento;
this.type = state.getType();
this.ageYears = state.getAgeYears();
this.massTons = state.getMassTons();
}
@Override
public String toString() {
return String.format("%s age: %d years mass: %d tons", type.toString(), ageYears, massTons);
}
/**
* StarMemento implementation.
*/
@Getter
@Setter
private static class StarMementoInternal implements StarMemento {
private StarType type;
private int ageYears;
private int massTons;
}
}
| iluwatar/java-design-patterns | memento/src/main/java/com/iluwatar/memento/Star.java |
170 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.factory.method;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* ElfWeapon.
*/
public record ElfWeapon(WeaponType weaponType) implements Weapon {
@Override
public String toString() {
return "an elven " + weaponType;
}
}
| iluwatar/java-design-patterns | factory-method/src/main/java/com/iluwatar/factory/method/ElfWeapon.java |
171 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.commander;
import com.iluwatar.commander.employeehandle.EmployeeDatabase;
import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException;
import com.iluwatar.commander.messagingservice.MessagingDatabase;
import com.iluwatar.commander.messagingservice.MessagingService;
import com.iluwatar.commander.paymentservice.PaymentDatabase;
import com.iluwatar.commander.paymentservice.PaymentService;
import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.shippingservice.ShippingDatabase;
import com.iluwatar.commander.shippingservice.ShippingService;
/**
* AppQueueFailCases class looks at possible cases when Queue Database is available/unavailable.
*/
public class AppQueueFailCases {
private static final RetryParams retryParams = RetryParams.DEFAULT;
private static final TimeLimits timeLimits = TimeLimits.DEFAULT;
void queuePaymentTaskDatabaseUnavailableCase() {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueMessageTaskDatabaseUnavailableCase() {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase());
var ms = new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueEmployeeDbTaskDatabaseUnavailableCase() {
var ps = new PaymentService(new PaymentDatabase());
var ss = new ShippingService(new ShippingDatabase(), new ItemUnavailableException());
var ms = new MessagingService(new MessagingDatabase());
var eh = new EmployeeHandle(new EmployeeDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
void queueSuccessCase() {
var ps = new PaymentService(new PaymentDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var ss = new ShippingService(new ShippingDatabase());
var ms =
new MessagingService(new MessagingDatabase(), new DatabaseUnavailableException(),
new DatabaseUnavailableException());
var eh = new EmployeeHandle(new EmployeeDatabase());
var qdb =
new QueueDatabase(new DatabaseUnavailableException(), new DatabaseUnavailableException());
var c = new Commander(eh, ps, ss, ms, qdb, retryParams, timeLimits);
var user = new User("Jim", "ABCD");
var order = new Order(user, "book", 10f);
c.placeOrder(order);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var aqfc = new AppQueueFailCases();
aqfc.queueSuccessCase();
}
} | iluwatar/java-design-patterns | commander/src/main/java/com/iluwatar/commander/AppQueueFailCases.java |
172 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.monostate;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* The Server class. Each Server sits behind a LoadBalancer which delegates the call to the servers
* in a simplistic Round Robin fashion.
*/
@Slf4j
@Getter
public class Server {
public final String host;
public final int port;
public final int id;
/**
* Constructor.
*/
public Server(String host, int port, int id) {
this.host = host;
this.port = port;
this.id = id;
}
public void serve(Request request) {
LOGGER.info("Server ID {} associated to host : {} and port {}. Processed request with value {}",
id, host, port, request.value());
}
}
| iluwatar/java-design-patterns | monostate/src/main/java/com/iluwatar/monostate/Server.java |
173 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.flux.dispatcher;
import com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.action.ContentAction;
import com.iluwatar.flux.action.MenuAction;
import com.iluwatar.flux.action.MenuItem;
import com.iluwatar.flux.store.Store;
import java.util.LinkedList;
import java.util.List;
import lombok.Getter;
/**
* Dispatcher sends Actions to registered Stores.
*/
public final class Dispatcher {
@Getter
private static Dispatcher instance = new Dispatcher();
private final List<Store> stores = new LinkedList<>();
private Dispatcher() {
}
public void registerStore(Store store) {
stores.add(store);
}
/**
* Menu item selected handler.
*/
public void menuItemSelected(MenuItem menuItem) {
dispatchAction(new MenuAction(menuItem));
if (menuItem == MenuItem.COMPANY) {
dispatchAction(new ContentAction(Content.COMPANY));
} else {
dispatchAction(new ContentAction(Content.PRODUCTS));
}
}
private void dispatchAction(Action action) {
stores.forEach(store -> store.onAction(action));
}
}
| iluwatar/java-design-patterns | flux/src/main/java/com/iluwatar/flux/dispatcher/Dispatcher.java |
174 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.roleobject;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Possible roles.
*/
public enum Role {
BORROWER(BorrowerRole.class), INVESTOR(InvestorRole.class);
private final Class<? extends CustomerRole> typeCst;
Role(Class<? extends CustomerRole> typeCst) {
this.typeCst = typeCst;
}
private static final Logger logger = LoggerFactory.getLogger(Role.class);
/**
* Get instance.
*/
@SuppressWarnings("unchecked")
public <T extends CustomerRole> Optional<T> instance() {
var typeCst = this.typeCst;
try {
return (Optional<T>) Optional.of(typeCst.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
logger.error("error creating an object", e);
}
return Optional.empty();
}
} | iluwatar/java-design-patterns | role-object/src/main/java/com/iluwatar/roleobject/Role.java |
175 | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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.tensorflow;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* An environment for executing TensorFlow operations eagerly.
*
* <p>Eager execution is an imperative programming environment that evaluates operations
* immediately, without building graphs. Operations return concrete values instead of constructing a
* computational graph to run later, as with {@link Graph}s and {@link Session}s.
*
* <p>This makes it easy to develop with TensorFlow and debug models, as it behaves more like a
* standard programming library.
*
* <p>Instances of a {@code EagerSession} are thread-safe.
*/
public final class EagerSession implements ExecutionEnvironment, AutoCloseable {
/**
* Controls how to act when we try to run an operation on a given device but some input tensors
* are not on that device.
*/
public static enum DevicePlacementPolicy {
/** Running operations with input tensors on the wrong device will fail. */
EXPLICIT(0),
/** Copy the tensor to the right device but log a warning. */
WARN(1),
/**
* Silently copy the tensor, which has a performance cost since the operation will be blocked
* till the copy completes. This is the default placement policy.
*/
SILENT(2),
/** Placement policy which silently copies int32 tensors but not other dtypes. */
SILENT_FOR_INT32(3);
private DevicePlacementPolicy(int code) {
this.code = code;
}
private final int code;
}
/**
* Controls how TensorFlow resources are cleaned up when they are no longer needed.
*
* <p>All resources allocated during an {@code EagerSession} are deleted when the session is
* closed. To prevent out-of-memory errors, it is also strongly suggest to cleanup those resources
* during the session. For example, executing n operations in a loop of m iterations will allocate
* a minimum of n*m resources while in most cases, only resources of the last iteration are still
* being used.
*
* <p>{@code EagerSession} instances can be notified in different ways when TensorFlow objects are
* no longer being referred, so they can proceed to the cleanup of any resources they owned.
*/
public static enum ResourceCleanupStrategy {
/**
* Monitor and delete unused resources from a new thread running in background.
*
* <p>This is the most reliable approach to cleanup TensorFlow resources, at the cost of
* starting and running an additional thread dedicated to this task. Each {@code EagerSession}
* instance has its own thread, which is stopped only when the session is closed.
*
* <p>This strategy is used by default.
*/
IN_BACKGROUND,
/**
* Monitor and delete unused resources from existing threads, before or after they complete
* another task.
*
* <p>Unused resources are released when a call to the TensorFlow library reaches a safe point
* for cleanup. This is done synchronously and might block for a short period of time the thread
* who triggered that call.
*
* <p>This strategy should be used only if, for some reasons, no additional thread should be
* allocated for cleanup. Otherwise, {@link #IN_BACKGROUND} should be preferred.
*/
ON_SAFE_POINTS,
/**
* Only delete resources when the session is closed.
*
* <p>All resources allocated during the session will remained in memory until the session is
* explicitly closed (or via the traditional `try-with-resource` technique). No extra task for
* resource cleanup will be attempted.
*
* <p>This strategy can lead up to out-of-memory errors and its usage is not recommended, unless
* the scope of the session is limited to execute only a small amount of operations.
*/
ON_SESSION_CLOSE,
}
public static class Options {
/**
* Controls how operations dispatched are actually executed.
*
* <p>When set to true, each operation are executed asynchronously (in which case some
* operations might return "non-ready" outputs). When set to false, all operations are executed
* synchronously.
*
* <p>Synchronous execution is used by default.
*
* @param value true for asynchronous execution, false for synchronous.
*/
public Options async(boolean value) {
async = value;
return this;
}
/**
* Controls how to act when we try to run an operation on a given device but some input tensors
* are not on that device.
*
* <p>{@link DevicePlacementPolicy#SILENT} is used by default.
*
* @param value policy to apply
* @see DevicePlacementPolicy
*/
public Options devicePlacementPolicy(DevicePlacementPolicy value) {
devicePlacementPolicy = value;
return this;
}
/**
* Controls how TensorFlow resources are cleaned up when no longer needed.
*
* <p>{@link ResourceCleanupStrategy#IN_BACKGROUND} is used by default.
*
* @param value strategy to use
* @see ResourceCleanupStrategy
*/
public Options resourceCleanupStrategy(ResourceCleanupStrategy value) {
resourceCleanupStrategy = value;
return this;
}
/**
* Configures the session based on the data found in the provided buffer, which is serialized
* TensorFlow config proto.
*
* <p>Warning: the support of this feature is subject to changes since TensorFlow protos might
* not be supported on public endpoints in the future.
*
* <p>See also: <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/config.proto">config.proto</a>
*
* @param value a serialized config proto
*/
public Options config(byte[] value) {
config = value;
return this;
}
/** Builds an eager session with the selected options. */
public EagerSession build() {
return new EagerSession(this, new ReferenceQueue<Object>());
}
// For garbage-collection tests only
EagerSession buildForGcTest(ReferenceQueue<Object> gcQueue) {
return new EagerSession(this, gcQueue);
}
private boolean async;
private DevicePlacementPolicy devicePlacementPolicy;
private ResourceCleanupStrategy resourceCleanupStrategy;
private byte[] config;
private Options() {
async = false;
devicePlacementPolicy = DevicePlacementPolicy.SILENT;
resourceCleanupStrategy = ResourceCleanupStrategy.IN_BACKGROUND;
config = null;
}
}
/**
* Initializes the default eager session, which remains active for the lifetime of the
* application.
*
* <p>This method is implicitly invoked on the first call to {@link #getDefault()}, but can also
* be invoked explicitly to override default options.
*
* <p>Note that calling this method more than once will throw an {@code IllegalArgumentException}
* as the default session cannot be modified once it has been created. Therefore, it is important
* to explicitly initialize it before {@link #getDefault()} is invoked for the first time from any
* thread.
*
* <p>Example usage:
*
* <pre>{@code
* // Initializing default session to override default options is valid but
* // is optional
* EagerSession.initDefault(EagerSession.options().async(true));
*
* // Starting to build eager operations using default session, by calling
* // EagerSession.getDefault() implicitly
* Ops tf = Ops.create();
*
* // Initializing default session more than once or after using it is not
* // permitted and throws an exception
* EagerSession.initDefault(EagerSession.options().async(true)); // throws
* }</pre>
*
* @param options options to use to build default session
* @return default eager session
* @throws IllegalStateException if the default session is already initialized
* @see #getDefault()
*/
public static EagerSession initDefault(Options options) {
synchronized (EagerSession.class) {
if (defaultSession != null) {
throw new IllegalStateException("Default eager session is already initialized");
}
defaultSession = options.build();
}
return defaultSession;
}
/**
* Returns the default eager session
*
* <p>Once initialized, the default eager session remains active for the whole life of the
* application, as opposed to sessions obtained from {@link #create()} or {@link Options#build()}
* which should be closed after their usage.
*
* <p>The default set of {@link Options} is used to initialize the session on the first call. To
* override this behavior, it is possible to invoke {@link #initDefault(Options)} with a different
* set of options prior to this first call.
*
* <p>Example usage:
*
* <pre>{@code
* // Starting to build eager operations using default session, by calling
* // EagerSession.getDefault() implicitly
* Ops tf = Ops.create();
*
* // Starting to build eager operations using default session, by calling
* // EagerSession.getDefault() explicitly
* Ops tf = Ops.create(EagerSession.getDefault());
* }</pre>
*
* @return default eager session
* @see #initDefault
*/
public static EagerSession getDefault() {
if (defaultSession == null) {
synchronized (EagerSession.class) {
if (defaultSession == null) {
defaultSession = options().build();
}
}
}
return defaultSession;
}
/**
* Returns an {@code EagerSession} configured with default options.
*
* <p><b>WARNING:</b>Instances of {@code EagerSession} returned by this method must be explicitly
* freed by invoking {@link #close()} when they are no longer needed. This could be achieve using
* the `try-with-resources` technique.
*
* <p>Example usage:
*
* <pre>{@code
* try (EagerSession session = EagerSession.create()) {
* Ops tf = Ops.create(session);
* // build execute operations eagerly...
* }
* }</pre>
*/
public static EagerSession create() {
return options().build();
}
/**
* Returns an object that configures and builds a {@code EagerSession} with custom options.
*
* <p><b>WARNING:</b>Instances of {@code EagerSession} returned by this method must be explicitly
* freed by invoking {@link #close()} when they are no longer needed. This could be achieve using
* the `try-with-resources` technique.
*
* <p>Example usage:
*
* <pre>{@code
* try (EagerSession session = EagerSession.options().async(true).build()) {
* Ops tf = Ops.create(session);
* // build execute operations eagerly and asynchronously...
* }
* }</pre>
*/
public static EagerSession.Options options() {
return new Options();
}
@Override
public synchronized void close() {
if (this == defaultSession) {
throw new IllegalStateException("Default eager session cannot be closed");
}
if (nativeHandle != 0L) {
if (resourceCleanupStrategy == ResourceCleanupStrategy.IN_BACKGROUND) {
nativeResources.stopCleanupThread();
}
nativeResources.deleteAll();
delete(nativeHandle);
nativeHandle = 0L;
}
}
@Override
public OperationBuilder opBuilder(String type, String name) {
if (resourceCleanupStrategy == ResourceCleanupStrategy.ON_SAFE_POINTS) {
nativeResources.tryCleanup();
}
checkSession();
return new EagerOperationBuilder(this, type, name);
}
long nativeHandle() {
checkSession();
return nativeHandle;
}
ResourceCleanupStrategy resourceCleanupStrategy() {
return resourceCleanupStrategy;
}
/**
* A reference to one or more allocated native resources.
*
* <p>Any Java objects owning native resources must declare a reference to those resources in a
* subclass that extends from {@code NativeReference}. When {@link NativeReference#delete()} is
* invoked, the resources must be freed. For example:
*
* <pre>{@code
* private static class NativeReference extends EagerSession.NativeReference {
*
* NativeReference(EagerSession session, MyClass referent, long handle) {
* super(session, referent);
* this.handle = handle;
* }
*
* @Override
* void delete() {
* MyClass.nativeDelete(handle);
* }
*
* private final long handle;
* }
* }</pre>
*
* A Java object "owns" a native resource if this resource should not survive beyond the lifetime
* of this object.
*
* <p><b>IMPORTANT</b>: All nested subclasses of {@code NativeReference} must be declared as
* static, otherwise their instances will hold an implicit reference to their enclosing object,
* preventing the garbage collector to release them when they are no longer needed.
*/
abstract static class NativeReference extends PhantomReference<Object> {
/** Attach a new phantom reference of {@code referent} to {@code session}. */
public NativeReference(EagerSession session, Object referent) {
super(referent, session.nativeResources.garbageQueue);
session.checkSession();
nativeResources = session.nativeResources;
nativeResources.attach(this);
}
/**
* Detach this reference from its current session.
*
* <p>Clearing a NativeReference does not invoke {@link #delete()}, thus won't release the
* native resources it refers to. It can be used when passing the ownership of those resources
* to another object.
*
* <p>If native resources needs to be deleted as well, call {@link #delete()} explicitly.
*/
@Override
public void clear() {
nativeResources.detach(this);
super.clear();
}
/** Releases all native resources owned by the referred object, now deleted. */
abstract void delete();
private final NativeResourceCollector nativeResources;
}
/**
* Collects native references attached to this session and releases their resources if they are no
* longer needed.
*/
private static class NativeResourceCollector {
NativeResourceCollector(ReferenceQueue<Object> garbageQueue) {
this.garbageQueue = garbageQueue;
}
void attach(NativeReference nativeRef) {
synchronized (nativeRefs) {
nativeRefs.put(nativeRef, null);
}
}
void detach(NativeReference nativeRef) {
synchronized (nativeRefs) {
nativeRefs.remove(nativeRef);
}
}
void delete(NativeReference nativeRef) {
synchronized (nativeRefs) {
if (!nativeRefs.keySet().remove(nativeRef)) {
return; // safety check
}
}
nativeRef.delete();
}
void deleteAll() {
synchronized (nativeRefs) {
for (NativeReference nativeRef : nativeRefs.keySet()) {
nativeRef.delete();
}
nativeRefs.clear();
}
}
void tryCleanup() {
Reference<?> nativeRef;
synchronized (nativeRefs) {
while ((nativeRef = garbageQueue.poll()) != null) {
delete((NativeReference) nativeRef);
}
}
}
synchronized void startCleanupThread() {
if (cleanupInBackground) {
return; // ignore if cleanup thread is already running
}
try {
cleanupInBackground = true;
cleanupService.execute(
new Runnable() {
@Override
public void run() {
try {
while (cleanupInBackground) {
NativeReference nativeRef = (NativeReference) garbageQueue.remove();
delete(nativeRef);
}
} catch (InterruptedException e) {
// exit
}
}
});
} catch (Exception e) {
cleanupInBackground = false;
throw e;
}
}
void stopCleanupThread() {
cleanupInBackground = false;
cleanupService.shutdownNow(); // returns without waiting for the thread to stop
}
private final ExecutorService cleanupService = Executors.newSingleThreadExecutor();
private final Map<NativeReference, Void> nativeRefs = new IdentityHashMap<>();
private final ReferenceQueue<Object> garbageQueue;
private volatile boolean cleanupInBackground = false;
}
private static volatile EagerSession defaultSession = null;
private final NativeResourceCollector nativeResources;
private final ResourceCleanupStrategy resourceCleanupStrategy;
private long nativeHandle;
private EagerSession(Options options, ReferenceQueue<Object> garbageQueue) {
this.nativeResources = new NativeResourceCollector(garbageQueue);
this.nativeHandle = allocate(options.async, options.devicePlacementPolicy.code, options.config);
this.resourceCleanupStrategy = options.resourceCleanupStrategy;
if (resourceCleanupStrategy == ResourceCleanupStrategy.IN_BACKGROUND) {
nativeResources.startCleanupThread();
}
}
private void checkSession() {
if (nativeHandle == 0L) {
throw new IllegalStateException("Eager session has been closed");
}
}
private static native long allocate(boolean async, int devicePlacementPolicy, byte[] config);
private static native void delete(long handle);
static {
TensorFlow.init();
}
}
| tensorflow/tensorflow | tensorflow/java/src/main/java/org/tensorflow/EagerSession.java |
176 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.metamapping;
import com.iluwatar.metamapping.model.User;
import com.iluwatar.metamapping.service.UserService;
import com.iluwatar.metamapping.utils.DatabaseUtil;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.ServiceRegistry;
/**
* Metadata Mapping specifies the mapping
* between classes and tables so that
* we could treat a table of any database like a Java class.
*
* <p>With hibernate, we achieve list/create/update/delete/get operations:
* 1)Create the H2 Database in {@link DatabaseUtil}.
* 2)Hibernate resolve hibernate.cfg.xml and generate service like save/list/get/delete.
* For learning metadata mapping pattern, we go deeper into Hibernate here:
* a)read properties from hibernate.cfg.xml and mapping from *.hbm.xml
* b)create session factory to generate session interacting with database
* c)generate session with factory pattern
* d)create query object or use basic api with session,
* hibernate will convert all query to database query according to metadata
* 3)We encapsulate hibernate service in {@link UserService} for our use.
* @see org.hibernate.cfg.Configuration#configure(String)
* @see org.hibernate.cfg.Configuration#buildSessionFactory(ServiceRegistry)
* @see org.hibernate.internal.SessionFactoryImpl#openSession()
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args.
*/
public static void main(String[] args) {
// get service
var userService = new UserService();
// use create service to add users
for (var user : generateSampleUsers()) {
var id = userService.createUser(user);
LOGGER.info("Add user" + user + "at" + id + ".");
}
// use list service to get users
var users = userService.listUser();
LOGGER.info(String.valueOf(users));
// use get service to get a user
var user = userService.getUser(1);
LOGGER.info(String.valueOf(user));
// change password of user 1
user.setPassword("new123");
// use update service to update user 1
userService.updateUser(1, user);
// use delete service to delete user 2
userService.deleteUser(2);
// close service
userService.close();
}
/**
* Generate users.
*
* @return list of users.
*/
public static List<User> generateSampleUsers() {
final var user1 = new User("ZhangSan", "zhs123");
final var user2 = new User("LiSi", "ls123");
final var user3 = new User("WangWu", "ww123");
return List.of(user1, user2, user3);
}
} | iluwatar/java-design-patterns | metadata-mapping/src/main/java/com/iluwatar/metamapping/App.java |
177 | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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.tensorflow.lite;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Package-private class that implements InterpreterApi. This class implements all the
* non-experimental API methods. It is used both by the public InterpreterFactory, and as a base
* class for the public Interpreter class,
*/
class InterpreterImpl implements InterpreterApi {
/**
* An options class for controlling runtime interpreter behavior. Compared to the base class
* InterpreterApi.Options, this adds fields corresponding to experimental features. But it does
* not provide accessors to set those fields -- those are only provided in the derived class
* Interpreter.Options.
*/
static class Options extends InterpreterApi.Options {
public Options() {}
public Options(InterpreterApi.Options options) {
super(options);
}
public Options(Options other) {
super(other);
allowFp16PrecisionForFp32 = other.allowFp16PrecisionForFp32;
allowBufferHandleOutput = other.allowBufferHandleOutput;
}
// See Interpreter.Options#setAllowFp16PrecisionForFp32(boolean).
Boolean allowFp16PrecisionForFp32;
// See Interpreter.Options#setAllowBufferHandleOutput(boolean).
Boolean allowBufferHandleOutput;
}
/**
* Initializes an {@code InterpreterImpl} and specifies options for customizing interpreter
* behavior.
*
* @param modelFile a file of a pre-trained TF Lite model
* @param options a set of options for customizing interpreter behavior
* @throws IllegalArgumentException if {@code modelFile} does not encode a valid TensorFlow Lite
* model.
*/
InterpreterImpl(@NonNull File modelFile, Options options) {
wrapper = new NativeInterpreterWrapper(modelFile.getAbsolutePath(), options);
}
/**
* Initializes an {@code InterpreterImpl} with a {@code ByteBuffer} of a model file and a set of
* custom {@link Interpreter.Options}.
*
* <p>The {@code ByteBuffer} should not be modified after the construction of an {@code
* InterpreterImpl}. The {@code ByteBuffer} can be either a {@code MappedByteBuffer} that
* memory-maps a model file, or a direct {@code ByteBuffer} of nativeOrder() that contains the
* bytes content of a model.
*
* @throws IllegalArgumentException if {@code byteBuffer} is not a {@code MappedByteBuffer} nor a
* direct {@code ByteBuffer} of nativeOrder.
*/
InterpreterImpl(@NonNull ByteBuffer byteBuffer, Options options) {
wrapper = new NativeInterpreterWrapper(byteBuffer, options);
}
InterpreterImpl(NativeInterpreterWrapper wrapper) {
this.wrapper = wrapper;
}
@Override
public void run(Object input, Object output) {
Object[] inputs = {input};
Map<Integer, Object> outputs = new HashMap<>();
outputs.put(0, output);
runForMultipleInputsOutputs(inputs, outputs);
}
@Override
public void runForMultipleInputsOutputs(
Object @NonNull [] inputs, @NonNull Map<Integer, Object> outputs) {
checkNotClosed();
wrapper.run(inputs, outputs);
}
@Override
public void allocateTensors() {
checkNotClosed();
wrapper.allocateTensors();
}
@Override
public void resizeInput(int idx, int @NonNull [] dims) {
checkNotClosed();
wrapper.resizeInput(idx, dims, false);
}
@Override
public void resizeInput(int idx, int @NonNull [] dims, boolean strict) {
checkNotClosed();
wrapper.resizeInput(idx, dims, strict);
}
@Override
public int getInputTensorCount() {
checkNotClosed();
return wrapper.getInputTensorCount();
}
@Override
public int getInputIndex(String opName) {
checkNotClosed();
return wrapper.getInputIndex(opName);
}
@Override
public Tensor getInputTensor(int inputIndex) {
checkNotClosed();
return wrapper.getInputTensor(inputIndex);
}
/** Gets the number of output Tensors. */
@Override
public int getOutputTensorCount() {
checkNotClosed();
return wrapper.getOutputTensorCount();
}
@Override
public int getOutputIndex(String opName) {
checkNotClosed();
return wrapper.getOutputIndex(opName);
}
@Override
public Tensor getOutputTensor(int outputIndex) {
checkNotClosed();
return wrapper.getOutputTensor(outputIndex);
}
@Override
public Long getLastNativeInferenceDurationNanoseconds() {
checkNotClosed();
return wrapper.getLastNativeInferenceDurationNanoseconds();
}
int getExecutionPlanLength() {
checkNotClosed();
return wrapper.getExecutionPlanLength();
}
@Override
public void close() {
if (wrapper != null) {
wrapper.close();
wrapper = null;
}
}
@SuppressWarnings("deprecation")
@Override
protected void finalize() throws Throwable {
try {
close();
} finally {
super.finalize();
}
}
void checkNotClosed() {
if (wrapper == null) {
throw new IllegalStateException("Internal error: The Interpreter has already been closed.");
}
}
NativeInterpreterWrapper wrapper;
}
| tensorflow/tensorflow | tensorflow/lite/java/src/main/java/org/tensorflow/lite/InterpreterImpl.java |
178 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.component;
import com.iluwatar.component.component.graphiccomponent.GraphicComponent;
import com.iluwatar.component.component.graphiccomponent.ObjectGraphicComponent;
import com.iluwatar.component.component.inputcomponent.DemoInputComponent;
import com.iluwatar.component.component.inputcomponent.InputComponent;
import com.iluwatar.component.component.inputcomponent.PlayerInputComponent;
import com.iluwatar.component.component.physiccomponent.ObjectPhysicComponent;
import com.iluwatar.component.component.physiccomponent.PhysicComponent;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* The GameObject class has three component class instances that allow
* the creation of different game objects based on the game design requirements.
*/
@Getter
@RequiredArgsConstructor
public class GameObject {
private final InputComponent inputComponent;
private final PhysicComponent physicComponent;
private final GraphicComponent graphicComponent;
private final String name;
private int velocity = 0;
private int coordinate = 0;
/**
* Creates a player game object.
*
* @return player object
*/
public static GameObject createPlayer() {
return new GameObject(new PlayerInputComponent(),
new ObjectPhysicComponent(),
new ObjectGraphicComponent(),
"player");
}
/**
* Creates a NPC game object.
*
* @return npc object
*/
public static GameObject createNpc() {
return new GameObject(
new DemoInputComponent(),
new ObjectPhysicComponent(),
new ObjectGraphicComponent(),
"npc");
}
/**
* Updates the three components of the NPC object used in the demo in App.java
* note that this is simply a duplicate of update() without the key event for
* demonstration purposes.
*
* <p>This method is usually used in games if the player becomes inactive.
*/
public void demoUpdate() {
inputComponent.update(this, 0);
physicComponent.update(this);
graphicComponent.update(this);
}
/**
* Updates the three components for objects based on key events.
*
* @param e key event from the player.
*/
public void update(int e) {
inputComponent.update(this, e);
physicComponent.update(this);
graphicComponent.update(this);
}
/**
* Update the velocity based on the acceleration of the GameObject.
*
* @param acceleration the acceleration of the GameObject
*/
public void updateVelocity(int acceleration) {
this.velocity += acceleration;
}
/**
* Set the c based on the current velocity.
*/
public void updateCoordinate() {
this.coordinate += this.velocity;
}
}
| rajprins/java-design-patterns | component/src/main/java/com/iluwatar/component/GameObject.java |
179 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.flux.action;
import lombok.Getter;
/**
* MenuAction is a concrete action.
*/
public class MenuAction extends Action {
@Getter
private final MenuItem menuItem;
public MenuAction(MenuItem menuItem) {
super(ActionType.MENU_ITEM_SELECTED);
this.menuItem = menuItem;
}
}
| iluwatar/java-design-patterns | flux/src/main/java/com/iluwatar/flux/action/MenuAction.java |
180 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.dirtyflag;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* A mock database manager -- Fetches data from a raw file.
*
* @author swaisuan
*/
@Slf4j
public class DataFetcher {
private static final String FILENAME = "world.txt";
private long lastFetched;
public DataFetcher() {
this.lastFetched = -1;
}
private boolean isDirty(long fileLastModified) {
if (lastFetched != fileLastModified) {
lastFetched = fileLastModified;
return true;
}
return false;
}
/**
* Fetches data/content from raw file.
*
* @return List of strings
*/
public List<String> fetch() {
var classLoader = getClass().getClassLoader();
var file = new File(classLoader.getResource(FILENAME).getFile());
if (isDirty(file.lastModified())) {
LOGGER.info(FILENAME + " is dirty! Re-fetching file content...");
try (var br = new BufferedReader(new FileReader(file))) {
return br.lines().collect(Collectors.collectingAndThen(Collectors.toList(), List::copyOf));
} catch (IOException e) {
LOGGER.error("An error occurred: ", e);
}
}
return List.of();
}
}
| iluwatar/java-design-patterns | dirty-flag/src/main/java/com/iluwatar/dirtyflag/DataFetcher.java |
181 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.strategy;
import lombok.extern.slf4j.Slf4j;
/**
* Projectile strategy.
*/
@Slf4j
public class ProjectileStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
}
}
| smedals/java-design-patterns | strategy/src/main/java/com/iluwatar/strategy/ProjectileStrategy.java |
182 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.memento;
import java.util.Stack;
import lombok.extern.slf4j.Slf4j;
/**
* The Memento pattern is a software design pattern that provides the ability to restore an object
* to its previous state (undo via rollback).
*
* <p>The Memento pattern is implemented with three objects: the originator, a caretaker and a
* memento. The originator is some object that has an internal state. The caretaker is going to do
* something to the originator, but wants to be able to undo the change. The caretaker first asks
* the originator for a memento object. Then it does whatever operation (or sequence of operations)
* it was going to do. To roll back to the state before the operations, it returns the memento
* object to the originator. The memento object itself is an opaque object (one which the caretaker
* cannot, or should not, change). When using this pattern, care should be taken if the originator
* may change other objects or resources - the memento pattern operates on a single object.
*
* <p>In this example the object ({@link Star}) gives out a "memento" ({@link StarMemento}) that
* contains the state of the object. Later on the memento can be set back to the object restoring
* the state.
*/
@Slf4j
public class App {
/**
* Program entry point.
*/
public static void main(String[] args) {
var states = new Stack<StarMemento>();
var star = new Star(StarType.SUN, 10000000, 500000);
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
states.add(star.getMemento());
star.timePasses();
LOGGER.info(star.toString());
while (!states.isEmpty()) {
star.setMemento(states.pop());
LOGGER.info(star.toString());
}
}
}
| iluwatar/java-design-patterns | memento/src/main/java/com/iluwatar/memento/App.java |
183 | // ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// 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. Neither the name of the copyright holders 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 OWNER 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 org.springframework.asm;
/**
* An entry of the constant pool, of the BootstrapMethods attribute, or of the (ASM specific) type
* table of a class.
*
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4">JVMS
* 4.4</a>
* @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.23">JVMS
* 4.7.23</a>
* @author Eric Bruneton
*/
abstract class Symbol {
// Tag values for the constant pool entries (using the same order as in the JVMS).
/** The tag value of CONSTANT_Class_info JVMS structures. */
static final int CONSTANT_CLASS_TAG = 7;
/** The tag value of CONSTANT_Fieldref_info JVMS structures. */
static final int CONSTANT_FIELDREF_TAG = 9;
/** The tag value of CONSTANT_Methodref_info JVMS structures. */
static final int CONSTANT_METHODREF_TAG = 10;
/** The tag value of CONSTANT_InterfaceMethodref_info JVMS structures. */
static final int CONSTANT_INTERFACE_METHODREF_TAG = 11;
/** The tag value of CONSTANT_String_info JVMS structures. */
static final int CONSTANT_STRING_TAG = 8;
/** The tag value of CONSTANT_Integer_info JVMS structures. */
static final int CONSTANT_INTEGER_TAG = 3;
/** The tag value of CONSTANT_Float_info JVMS structures. */
static final int CONSTANT_FLOAT_TAG = 4;
/** The tag value of CONSTANT_Long_info JVMS structures. */
static final int CONSTANT_LONG_TAG = 5;
/** The tag value of CONSTANT_Double_info JVMS structures. */
static final int CONSTANT_DOUBLE_TAG = 6;
/** The tag value of CONSTANT_NameAndType_info JVMS structures. */
static final int CONSTANT_NAME_AND_TYPE_TAG = 12;
/** The tag value of CONSTANT_Utf8_info JVMS structures. */
static final int CONSTANT_UTF8_TAG = 1;
/** The tag value of CONSTANT_MethodHandle_info JVMS structures. */
static final int CONSTANT_METHOD_HANDLE_TAG = 15;
/** The tag value of CONSTANT_MethodType_info JVMS structures. */
static final int CONSTANT_METHOD_TYPE_TAG = 16;
/** The tag value of CONSTANT_Dynamic_info JVMS structures. */
static final int CONSTANT_DYNAMIC_TAG = 17;
/** The tag value of CONSTANT_InvokeDynamic_info JVMS structures. */
static final int CONSTANT_INVOKE_DYNAMIC_TAG = 18;
/** The tag value of CONSTANT_Module_info JVMS structures. */
static final int CONSTANT_MODULE_TAG = 19;
/** The tag value of CONSTANT_Package_info JVMS structures. */
static final int CONSTANT_PACKAGE_TAG = 20;
// Tag values for the BootstrapMethods attribute entries (ASM specific tag).
/** The tag value of the BootstrapMethods attribute entries. */
static final int BOOTSTRAP_METHOD_TAG = 64;
// Tag values for the type table entries (ASM specific tags).
/** The tag value of a normal type entry in the (ASM specific) type table of a class. */
static final int TYPE_TAG = 128;
/**
* The tag value of an uninitialized type entry in the type table of a class. This type is used
* for the normal case where the NEW instruction is before the <init> constructor call (in
* bytecode offset order), i.e. when the label of the NEW instruction is resolved when the
* constructor call is visited. If the NEW instruction is after the constructor call, use the
* {@link #FORWARD_UNINITIALIZED_TYPE_TAG} tag value instead.
*/
static final int UNINITIALIZED_TYPE_TAG = 129;
/**
* The tag value of an uninitialized type entry in the type table of a class. This type is used
* for the unusual case where the NEW instruction is after the <init> constructor call (in
* bytecode offset order), i.e. when the label of the NEW instruction is not resolved when the
* constructor call is visited. If the NEW instruction is before the constructor call, use the
* {@link #UNINITIALIZED_TYPE_TAG} tag value instead.
*/
static final int FORWARD_UNINITIALIZED_TYPE_TAG = 130;
/** The tag value of a merged type entry in the (ASM specific) type table of a class. */
static final int MERGED_TYPE_TAG = 131;
// Instance fields.
/**
* The index of this symbol in the constant pool, in the BootstrapMethods attribute, or in the
* (ASM specific) type table of a class (depending on the {@link #tag} value).
*/
final int index;
/**
* A tag indicating the type of this symbol. Must be one of the static tag values defined in this
* class.
*/
final int tag;
/**
* The internal name of the owner class of this symbol. Only used for {@link
* #CONSTANT_FIELDREF_TAG}, {@link #CONSTANT_METHODREF_TAG}, {@link
* #CONSTANT_INTERFACE_METHODREF_TAG}, and {@link #CONSTANT_METHOD_HANDLE_TAG} symbols.
*/
final String owner;
/**
* The name of the class field or method corresponding to this symbol. Only used for {@link
* #CONSTANT_FIELDREF_TAG}, {@link #CONSTANT_METHODREF_TAG}, {@link
* #CONSTANT_INTERFACE_METHODREF_TAG}, {@link #CONSTANT_NAME_AND_TYPE_TAG}, {@link
* #CONSTANT_METHOD_HANDLE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link
* #CONSTANT_INVOKE_DYNAMIC_TAG} symbols.
*/
final String name;
/**
* The string value of this symbol. This is:
*
* <ul>
* <li>a field or method descriptor for {@link #CONSTANT_FIELDREF_TAG}, {@link
* #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG}, {@link
* #CONSTANT_NAME_AND_TYPE_TAG}, {@link #CONSTANT_METHOD_HANDLE_TAG}, {@link
* #CONSTANT_METHOD_TYPE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link
* #CONSTANT_INVOKE_DYNAMIC_TAG} symbols,
* <li>an arbitrary string for {@link #CONSTANT_UTF8_TAG} and {@link #CONSTANT_STRING_TAG}
* symbols,
* <li>an internal class name for {@link #CONSTANT_CLASS_TAG}, {@link #TYPE_TAG}, {@link
* #UNINITIALIZED_TYPE_TAG} and {@link #FORWARD_UNINITIALIZED_TYPE_TAG} symbols,
* <li>{@literal null} for the other types of symbol.
* </ul>
*/
final String value;
/**
* The numeric value of this symbol. This is:
*
* <ul>
* <li>the symbol's value for {@link #CONSTANT_INTEGER_TAG},{@link #CONSTANT_FLOAT_TAG}, {@link
* #CONSTANT_LONG_TAG}, {@link #CONSTANT_DOUBLE_TAG},
* <li>the CONSTANT_MethodHandle_info reference_kind field value for {@link
* #CONSTANT_METHOD_HANDLE_TAG} symbols,
* <li>the CONSTANT_InvokeDynamic_info bootstrap_method_attr_index field value for {@link
* #CONSTANT_INVOKE_DYNAMIC_TAG} symbols,
* <li>the offset of a bootstrap method in the BootstrapMethods boostrap_methods array, for
* {@link #CONSTANT_DYNAMIC_TAG} or {@link #BOOTSTRAP_METHOD_TAG} symbols,
* <li>the bytecode offset of the NEW instruction that created an {@link
* Frame#ITEM_UNINITIALIZED} type for {@link #UNINITIALIZED_TYPE_TAG} symbols,
* <li>the index of the {@link Label} (in the {@link SymbolTable#labelTable} table) of the NEW
* instruction that created an {@link Frame#ITEM_UNINITIALIZED} type for {@link
* #FORWARD_UNINITIALIZED_TYPE_TAG} symbols,
* <li>the indices (in the class' type table) of two {@link #TYPE_TAG} source types for {@link
* #MERGED_TYPE_TAG} symbols,
* <li>0 for the other types of symbol.
* </ul>
*/
final long data;
/**
* Additional information about this symbol, generally computed lazily. <i>Warning: the value of
* this field is ignored when comparing Symbol instances</i> (to avoid duplicate entries in a
* SymbolTable). Therefore, this field should only contain data that can be computed from the
* other fields of this class. It contains:
*
* <ul>
* <li>the {@link Type#getArgumentsAndReturnSizes} of the symbol's method descriptor for {@link
* #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG} and {@link
* #CONSTANT_INVOKE_DYNAMIC_TAG} symbols,
* <li>the index in the InnerClasses_attribute 'classes' array (plus one) corresponding to this
* class, for {@link #CONSTANT_CLASS_TAG} symbols,
* <li>the index (in the class' type table) of the merged type of the two source types for
* {@link #MERGED_TYPE_TAG} symbols,
* <li>0 for the other types of symbol, or if this field has not been computed yet.
* </ul>
*/
int info;
/**
* Constructs a new Symbol. This constructor can't be used directly because the Symbol class is
* abstract. Instead, use the factory methods of the {@link SymbolTable} class.
*
* @param index the symbol index in the constant pool, in the BootstrapMethods attribute, or in
* the (ASM specific) type table of a class (depending on 'tag').
* @param tag the symbol type. Must be one of the static tag values defined in this class.
* @param owner The internal name of the symbol's owner class. Maybe {@literal null}.
* @param name The name of the symbol's corresponding class field or method. Maybe {@literal
* null}.
* @param value The string value of this symbol. Maybe {@literal null}.
* @param data The numeric value of this symbol.
*/
Symbol(
final int index,
final int tag,
final String owner,
final String name,
final String value,
final long data) {
this.index = index;
this.tag = tag;
this.owner = owner;
this.name = name;
this.value = value;
this.data = data;
}
/**
* Returns the result {@link Type#getArgumentsAndReturnSizes} on {@link #value}.
*
* @return the result {@link Type#getArgumentsAndReturnSizes} on {@link #value} (memoized in
* {@link #info} for efficiency). This should only be used for {@link
* #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG} and {@link
* #CONSTANT_INVOKE_DYNAMIC_TAG} symbols.
*/
int getArgumentsAndReturnSizes() {
if (info == 0) {
info = Type.getArgumentsAndReturnSizes(value);
}
return info;
}
}
| unmiusers/problem | src/main/java/spring-projects-spring-framework-ce09323/spring-core/src/main/java/org/springframework/asm/Symbol.java |
184 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.mute;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
/**
* A utility class that allows you to utilize mute idiom.
*/
@Slf4j
public final class Mute {
// The constructor is never meant to be called.
private Mute() {
}
/**
* Executes the <code>runnable</code> and throws the exception occurred within a {@link
* AssertionError}. This method should be utilized to mute the operations that are guaranteed not
* to throw an exception. For instance {@link ByteArrayOutputStream#write(byte[])} declares in
* its signature that it can throw an {@link IOException}, but in reality it cannot. This is
* because the bulk write method is not overridden in {@link ByteArrayOutputStream}.
*
* @param runnable a runnable that should never throw an exception on execution.
*/
public static void mute(CheckedRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
throw new AssertionError(e);
}
}
/**
* Executes the <code>runnable</code> and logs the exception occurred on {@link System#err}. This
* method should be utilized to mute the operations about which most you can do is log. For
* instance while closing a connection to database, or cleaning up a resource, all you can do is
* log the exception occurred.
*
* @param runnable a runnable that may throw an exception on execution.
*/
public static void loggedMute(CheckedRunnable runnable) {
try {
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| iluwatar/java-design-patterns | mute-idiom/src/main/java/com/iluwatar/mute/Mute.java |
185 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.strategy;
import lombok.extern.slf4j.Slf4j;
/**
*
* <p>The Strategy pattern (also known as the policy pattern) is a software design pattern that
* enables an algorithm's behavior to be selected at runtime.</p>
*
* <p>Before Java 8 the Strategies needed to be separate classes forcing the developer
* to write lots of boilerplate code. With modern Java, it is easy to pass behavior
* with method references and lambdas making the code shorter and more readable.</p>
*
* <p>In this example ({@link DragonSlayingStrategy}) encapsulates an algorithm. The containing
* object ({@link DragonSlayer}) can alter its behavior by changing its strategy.</p>
*
*/
@Slf4j
public class App {
private static final String RED_DRAGON_EMERGES = "Red dragon emerges.";
private static final String GREEN_DRAGON_SPOTTED = "Green dragon spotted ahead!";
private static final String BLACK_DRAGON_LANDS = "Black dragon lands before you.";
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// GoF Strategy pattern
LOGGER.info(GREEN_DRAGON_SPOTTED);
var dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
LOGGER.info(RED_DRAGON_EMERGES);
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle();
LOGGER.info(BLACK_DRAGON_LANDS);
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
// Java 8 functional implementation Strategy pattern
LOGGER.info(GREEN_DRAGON_SPOTTED);
dragonSlayer = new DragonSlayer(
() -> LOGGER.info("With your Excalibur you severe the dragon's head!"));
dragonSlayer.goToBattle();
LOGGER.info(RED_DRAGON_EMERGES);
dragonSlayer.changeStrategy(() -> LOGGER.info(
"You shoot the dragon with the magical crossbow and it falls dead on the ground!"));
dragonSlayer.goToBattle();
LOGGER.info(BLACK_DRAGON_LANDS);
dragonSlayer.changeStrategy(() -> LOGGER.info(
"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
dragonSlayer.goToBattle();
// Java 8 lambda implementation with enum Strategy pattern
LOGGER.info(GREEN_DRAGON_SPOTTED);
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MELEE_STRATEGY);
dragonSlayer.goToBattle();
LOGGER.info(RED_DRAGON_EMERGES);
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.PROJECTILE_STRATEGY);
dragonSlayer.goToBattle();
LOGGER.info(BLACK_DRAGON_LANDS);
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SPELL_STRATEGY);
dragonSlayer.goToBattle();
}
} | iluwatar/java-design-patterns | strategy/src/main/java/com/iluwatar/strategy/App.java |
186 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.multiton;
import lombok.extern.slf4j.Slf4j;
/**
* Whereas Singleton design pattern introduces single globally accessible object, the Multiton
* pattern defines many globally accessible objects. The client asks for the correct instance from
* the Multiton by passing an enumeration as a parameter.
*
* <p>There is more than one way to implement the multiton design pattern. In the first example
* {@link Nazgul} is the Multiton, and we can ask single {@link Nazgul} from it using {@link
* NazgulName}. The {@link Nazgul}s are statically initialized and stored in a concurrent hash map.
*
* <p>In the enum implementation {@link NazgulEnum} is the multiton. It is static and mutable
* because of the way java supports enums.
*/
@Slf4j
public class App {
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// eagerly initialized multiton
LOGGER.info("Printing out eagerly initialized multiton contents");
LOGGER.info("KHAMUL={}", Nazgul.getInstance(NazgulName.KHAMUL));
LOGGER.info("MURAZOR={}", Nazgul.getInstance(NazgulName.MURAZOR));
LOGGER.info("DWAR={}", Nazgul.getInstance(NazgulName.DWAR));
LOGGER.info("JI_INDUR={}", Nazgul.getInstance(NazgulName.JI_INDUR));
LOGGER.info("AKHORAHIL={}", Nazgul.getInstance(NazgulName.AKHORAHIL));
LOGGER.info("HOARMURATH={}", Nazgul.getInstance(NazgulName.HOARMURATH));
LOGGER.info("ADUNAPHEL={}", Nazgul.getInstance(NazgulName.ADUNAPHEL));
LOGGER.info("REN={}", Nazgul.getInstance(NazgulName.REN));
LOGGER.info("UVATHA={}", Nazgul.getInstance(NazgulName.UVATHA));
// enum multiton
LOGGER.info("Printing out enum-based multiton contents");
LOGGER.info("KHAMUL={}", NazgulEnum.KHAMUL);
LOGGER.info("MURAZOR={}", NazgulEnum.MURAZOR);
LOGGER.info("DWAR={}", NazgulEnum.DWAR);
LOGGER.info("JI_INDUR={}", NazgulEnum.JI_INDUR);
LOGGER.info("AKHORAHIL={}", NazgulEnum.AKHORAHIL);
LOGGER.info("HOARMURATH={}", NazgulEnum.HOARMURATH);
LOGGER.info("ADUNAPHEL={}", NazgulEnum.ADUNAPHEL);
LOGGER.info("REN={}", NazgulEnum.REN);
LOGGER.info("UVATHA={}", NazgulEnum.UVATHA);
}
}
| iluwatar/java-design-patterns | multiton/src/main/java/com/iluwatar/multiton/App.java |
187 | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
/**
* Defines classes to build, save, load and execute TensorFlow models.
*
*<aside class="warning">
* <b>Warning:</b> This API is deprecated and will be removed in a future
* version of TensorFlow after <a href="https://tensorflow.org/java">the replacement</a>
* is stable.
*</aside>
*
* <p>To get started, see the <a href="https://tensorflow.org/install/lang_java_legacy">
* installation instructions.</a></p>
*
* <p>The <a
* href="https://www.tensorflow.org/code/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java">LabelImage</a>
* example demonstrates use of this API to classify images using a pre-trained <a
* href="http://arxiv.org/abs/1512.00567">Inception</a> architecture convolutional neural network.
* It demonstrates:
*
* <ul>
* <li>Graph construction: using the OperationBuilder class to construct a graph to decode, resize
* and normalize a JPEG image.
* <li>Model loading: Using Graph.importGraphDef() to load a pre-trained Inception model.
* <li>Graph execution: Using a Session to execute the graphs and find the best label for an
* image.
* </ul>
*
* <p>Additional examples can be found in the <a
* href="https://github.com/tensorflow/java">tensorflow/java</a> GitHub repository.
*/
package org.tensorflow;
| tahmaz/arobi | pc/PycharmProjects/speech/tensorflow_src/tensorflow/java/src/main/java/org/tensorflow/package-info.java |
188 | package com.thealgorithms.maths;
/*
* Java program for pollard rho algorithm
* The algorithm is used to factorize a number n = pq,
* where p is a non-trivial factor.
* Pollard's rho algorithm is an algorithm for integer factorization
* and it takes as its inputs n, the integer to be factored;
* and g(x), a polynomial in x computed modulo n.
* In the original algorithm, g(x) = ((x ^ 2) − 1) mod n,
* but nowadays it is more common to use g(x) = ((x ^ 2) + 1 ) mod n.
* The output is either a non-trivial factor of n, or failure.
* It performs the following steps:
* x ← 2
* y ← 2
* d ← 1
* while d = 1:
* x ← g(x)
* y ← g(g(y))
* d ← gcd(|x - y|, n)
* if d = n:
* return failure
* else:
* return d
* Here x and y corresponds to xi and xj in the previous section.
* Note that this algorithm may fail to find a nontrivial factor even when n is composite.
* In that case, the method can be tried again, using a starting value other than 2 or a different
g(x)
*
* Wikipedia: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
*
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
*
* */
public final class PollardRho {
private PollardRho() {
}
/**
* This method returns a polynomial in x computed modulo n
*
* @param base Integer base of the polynomial
* @param modulus Integer is value which is to be used to perform modulo operation over the
* polynomial
* @return Integer (((base * base) - 1) % modulus)
*/
static int g(int base, int modulus) {
return ((base * base) - 1) % modulus;
}
/**
* This method returns a non-trivial factor of given integer number
*
* @param number Integer is a integer value whose non-trivial factor is to be found
* @return Integer non-trivial factor of number
* @throws RuntimeException object if GCD of given number cannot be found
*/
static int pollardRho(int number) {
int x = 2, y = 2, d = 1;
while (d == 1) {
// tortoise move
x = g(x, number);
// hare move
y = g(g(y, number), number);
// check GCD of |x-y| and number
d = GCD.gcd(Math.abs(x - y), number);
}
if (d == number) {
throw new RuntimeException("GCD cannot be found.");
}
return d;
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/maths/PollardRho.java |
189 | package com.thealgorithms.ciphers.a5;
// Source
// http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html
// package com.java2s;
// License from project: Open Source License
import java.util.BitSet;
public final class Utils {
private Utils() {
}
public static boolean increment(BitSet bits, int size) {
int i = size - 1;
while (i >= 0 && bits.get(i)) {
bits.set(i--, false); /*from w w w . j a v a 2s .c o m*/
}
if (i < 0) {
return false;
}
bits.set(i, true);
return true;
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/ciphers/a5/Utils.java |
190 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 concreteextensions;
import abstractextensions.SergeantExtension;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import units.SergeantUnit;
/**
* Class defining Sergeant.
*/
@Slf4j
public record Sergeant(SergeantUnit unit) implements SergeantExtension {
@Override
public void sergeantReady() {
LOGGER.info("[Sergeant] " + unit.getName() + " is ready!");
}
}
| iluwatar/java-design-patterns | extension-objects/src/main/java/concreteextensions/Sergeant.java |
191 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.promise;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
/**
* Utility to perform various operations.
*/
@Slf4j
public class Utility {
/**
* Calculates character frequency of the file provided.
*
* @param fileLocation location of the file.
* @return a map of character to its frequency, an empty map if file does not exist.
*/
public static Map<Character, Long> characterFrequency(String fileLocation) {
try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) {
return bufferedReader.lines()
.flatMapToInt(String::chars)
.mapToObj(x -> (char) x)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
} catch (IOException ex) {
LOGGER.error("An error occurred: ", ex);
}
return Collections.emptyMap();
}
/**
* Return the character with the lowest frequency, if exists.
*
* @return the character, {@code Optional.empty()} otherwise.
*/
public static Character lowestFrequencyChar(Map<Character, Long> charFrequency) {
return charFrequency
.entrySet()
.stream()
.min(Comparator.comparingLong(Entry::getValue))
.map(Entry::getKey)
.orElseThrow();
}
/**
* Count the number of lines in a file.
*
* @return number of lines, 0 if file does not exist.
*/
public static Integer countLines(String fileLocation) {
try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) {
return (int) bufferedReader.lines().count();
} catch (IOException ex) {
LOGGER.error("An error occurred: ", ex);
}
return 0;
}
/**
* Downloads the contents from the given urlString, and stores it in a temporary directory.
*
* @return the absolute path of the file downloaded.
*/
public static String downloadFile(String urlString) throws IOException {
LOGGER.info("Downloading contents from url: {}", urlString);
var url = new URL(urlString);
var file = File.createTempFile("promise_pattern", null);
try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
var writer = new FileWriter(file)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.write(line);
writer.write("\n");
}
LOGGER.info("File downloaded at: {}", file.getAbsolutePath());
return file.getAbsolutePath();
}
}
}
| iluwatar/java-design-patterns | promise/src/main/java/com/iluwatar/promise/Utility.java |
192 | package com.thealgorithms.others;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
// node class is the basic structure
// of each node present in the Huffman - tree.
class HuffmanNode {
int data;
char c;
HuffmanNode left;
HuffmanNode right;
}
// comparator class helps to compare the node
// on the basis of one of its attribute.
// Here we will be compared
// on the basis of data values of the nodes.
class MyComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y) {
return x.data - y.data;
}
}
public final class Huffman {
private Huffman() {
}
// recursive function to print the
// huffman-code through the tree traversal.
// Here s is the huffman - code generated.
public static void printCode(HuffmanNode root, String s) {
// base case; if the left and right are null
// then its a leaf node and we print
// the code s generated by traversing the tree.
if (root.left == null && root.right == null && Character.isLetter(root.c)) {
// c is the character in the node
System.out.println(root.c + ":" + s);
return;
}
// if we go to left then add "0" to the code.
// if we go to the right add"1" to the code.
// recursive calls for left and
// right sub-tree of the generated tree.
printCode(root.left, s + "0");
printCode(root.right, s + "1");
}
// main function
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// number of characters.
int n = 6;
char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
int[] charfreq = {5, 9, 12, 13, 16, 45};
// creating a priority queue q.
// makes a min-priority queue(min-heap).
PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator());
for (int i = 0; i < n; i++) {
// creating a Huffman node object
// and add it to the priority queue.
HuffmanNode hn = new HuffmanNode();
hn.c = charArray[i];
hn.data = charfreq[i];
hn.left = null;
hn.right = null;
// add functions adds
// the huffman node to the queue.
q.add(hn);
}
// create a root node
HuffmanNode root = null;
// Here we will extract the two minimum value
// from the heap each time until
// its size reduces to 1, extract until
// all the nodes are extracted.
while (q.size() > 1) {
// first min extract.
HuffmanNode x = q.peek();
q.poll();
// second min extarct.
HuffmanNode y = q.peek();
q.poll();
// new node f which is equal
HuffmanNode f = new HuffmanNode();
// to the sum of the frequency of the two nodes
// assigning values to the f node.
f.data = x.data + y.data;
f.c = '-';
// first extracted node as left child.
f.left = x;
// second extracted node as the right child.
f.right = y;
// marking the f node as the root node.
root = f;
// add this node to the priority-queue.
q.add(f);
}
// print the codes by traversing the tree
printCode(root, "");
s.close();
}
}
| TheAlgorithms/Java | src/main/java/com/thealgorithms/others/Huffman.java |
193 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.object.pool;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
/**
* Oliphaunts are expensive to create.
*/
@Slf4j
public class Oliphaunt {
private static final AtomicInteger counter = new AtomicInteger(0);
private final int id;
/**
* Constructor.
*/
public Oliphaunt() {
id = counter.incrementAndGet();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.error("Error occurred: ", e);
}
}
public int getId() {
return id;
}
@Override
public String toString() {
return String.format("Oliphaunt id=%d", id);
}
}
| iluwatar/java-design-patterns | object-pool/src/main/java/com/iluwatar/object/pool/Oliphaunt.java |
195 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.promise;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;
/**
* The Promise object is used for asynchronous computations. A Promise represents an operation that
* hasn't completed yet, but is expected in the future.
*
* <p>A Promise represents a proxy for a value not necessarily known when the promise is created.
* It allows you to associate dependent promises to an asynchronous action's eventual success value
* or failure reason. This lets asynchronous methods return values like synchronous methods: instead
* of the final value, the asynchronous method returns a promise of having a value at some point in
* the future.
*
* <p>Promises provide a few advantages over callback objects:
* <ul>
* <li> Functional composition and error handling
* <li> Prevents callback hell and provides callback aggregation
* </ul>
*
* <p>In this application the usage of promise is demonstrated with two examples:
* <ul>
* <li>Count Lines: In this example a file is downloaded and its line count is calculated.
* The calculated line count is then consumed and printed on console.
* <li>Lowest Character Frequency: In this example a file is downloaded and its lowest frequency
* character is found and printed on console. This happens via a chain of promises, we start with
* a file download promise, then a promise of character frequency, then a promise of lowest
* frequency character which is finally consumed and result is printed on console.
* </ul>
*
* @see CompletableFuture
*/
@Slf4j
public class App {
private static final String DEFAULT_URL =
"https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md";
private final ExecutorService executor;
private final CountDownLatch stopLatch;
private App() {
executor = Executors.newFixedThreadPool(2);
stopLatch = new CountDownLatch(2);
}
/**
* Program entry point.
*
* @param args arguments
* @throws InterruptedException if main thread is interrupted.
*/
public static void main(String[] args) throws InterruptedException {
var app = new App();
try {
app.promiseUsage();
} finally {
app.stop();
}
}
private void promiseUsage() {
calculateLineCount();
calculateLowestFrequencyChar();
}
/*
* Calculate the lowest frequency character and when that promise is fulfilled,
* consume the result in a Consumer<Character>
*/
private void calculateLowestFrequencyChar() {
lowestFrequencyChar().thenAccept(
charFrequency -> {
LOGGER.info("Char with lowest frequency is: {}", charFrequency);
taskCompleted();
}
);
}
/*
* Calculate the line count and when that promise is fulfilled, consume the result
* in a Consumer<Integer>
*/
private void calculateLineCount() {
countLines().thenAccept(
count -> {
LOGGER.info("Line count is: {}", count);
taskCompleted();
}
);
}
/*
* Calculate the character frequency of a file and when that promise is fulfilled,
* then promise to apply function to calculate the lowest character frequency.
*/
private Promise<Character> lowestFrequencyChar() {
return characterFrequency().thenApply(Utility::lowestFrequencyChar);
}
/*
* Download the file at DEFAULT_URL and when that promise is fulfilled,
* then promise to apply function to calculate character frequency.
*/
private Promise<Map<Character, Long>> characterFrequency() {
return download(DEFAULT_URL).thenApply(Utility::characterFrequency);
}
/*
* Download the file at DEFAULT_URL and when that promise is fulfilled,
* then promise to apply function to count lines in that file.
*/
private Promise<Integer> countLines() {
return download(DEFAULT_URL).thenApply(Utility::countLines);
}
/*
* Return a promise to provide the local absolute path of the file downloaded in background.
* This is an async method and does not wait until the file is downloaded.
*/
private Promise<String> download(String urlString) {
return new Promise<String>()
.fulfillInAsync(
() -> Utility.downloadFile(urlString), executor)
.onError(
throwable -> {
LOGGER.error("An error occurred: ", throwable);
taskCompleted();
}
);
}
private void stop() throws InterruptedException {
stopLatch.await();
executor.shutdownNow();
}
private void taskCompleted() {
stopLatch.countDown();
}
}
| iluwatar/java-design-patterns | promise/src/main/java/com/iluwatar/promise/App.java |
196 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.flux.store;
import com.iluwatar.flux.action.Action;
import com.iluwatar.flux.action.ActionType;
import com.iluwatar.flux.action.Content;
import com.iluwatar.flux.action.ContentAction;
import lombok.Getter;
/**
* ContentStore is a concrete store.
*/
public class ContentStore extends Store {
@Getter
private Content content = Content.PRODUCTS;
@Override
public void onAction(Action action) {
if (action.getType().equals(ActionType.CONTENT_CHANGED)) {
var contentAction = (ContentAction) action;
content = contentAction.getContent();
notifyChange();
}
}
}
| iluwatar/java-design-patterns | flux/src/main/java/com/iluwatar/flux/store/ContentStore.java |
197 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.partialresponse;
/**
* {@link Video} is an entity to serve from server.It contains all video related information.
* Video is a record class.
*/
public record Video(Integer id, String title, Integer length, String description, String director, String language) {
/**
* ToString.
*
* @return json representation of video
*/
@Override
public String toString() {
return "{"
+ "\"id\": " + id + ","
+ "\"title\": \"" + title + "\","
+ "\"length\": " + length + ","
+ "\"description\": \"" + description + "\","
+ "\"director\": \"" + director + "\","
+ "\"language\": \"" + language + "\","
+ "}";
}
}
| iluwatar/java-design-patterns | partial-response/src/main/java/com/iluwatar/partialresponse/Video.java |
198 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.sessionserver;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.time.Instant;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
/**
* The server session pattern is a behavioral design pattern concerned with assigning the responsibility
* of storing session data on the server side. Within the context of stateless protocols like HTTP all
* requests are isolated events independent of previous requests. In order to create sessions during
* user-access for a particular web application various methods can be used, such as cookies. Cookies
* are a small piece of data that can be sent between client and server on every request and response
* so that the server can "remember" the previous requests. In general cookies can either store the session
* data or the cookie can store a session identifier and be used to access appropriate data from a persistent
* storage. In the latter case the session data is stored on the server-side and appropriate data is
* identified by the cookie sent from a client's request.
* This project demonstrates the latter case.
* In the following example the ({@link App}) class starts a server and assigns ({@link LoginHandler})
* class to handle login request. When a user logs in a session identifier is created and stored for future
* requests in a list. When a user logs out the session identifier is deleted from the list along with
* the appropriate user session data, which is handle by the ({@link LogoutHandler}) class.
*/
@Slf4j
public class App {
// Map to store session data (simulated using a HashMap)
private static Map<String, Integer> sessions = new HashMap<>();
private static Map<String, Instant> sessionCreationTimes = new HashMap<>();
private static final long SESSION_EXPIRATION_TIME = 10000;
/**
* Main entry point.
* @param args arguments
* @throws IOException ex
*/
public static void main(String[] args) throws IOException {
// Create HTTP server listening on port 8000
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
// Set up session management endpoints
server.createContext("/login", new LoginHandler(sessions, sessionCreationTimes));
server.createContext("/logout", new LogoutHandler(sessions, sessionCreationTimes));
// Start the server
server.start();
// Start background task to check for expired sessions
sessionExpirationTask();
LOGGER.info("Server started. Listening on port 8080...");
}
private static void sessionExpirationTask() {
new Thread(() -> {
while (true) {
try {
LOGGER.info("Session expiration checker started...");
Thread.sleep(SESSION_EXPIRATION_TIME); // Sleep for expiration time
Instant currentTime = Instant.now();
synchronized (sessions) {
synchronized (sessionCreationTimes) {
Iterator<Map.Entry<String, Instant>> iterator =
sessionCreationTimes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Instant> entry = iterator.next();
if (entry.getValue().plusMillis(SESSION_EXPIRATION_TIME).isBefore(currentTime)) {
sessions.remove(entry.getKey());
iterator.remove();
}
}
}
}
LOGGER.info("Session expiration checker finished!");
} catch (InterruptedException e) {
LOGGER.error("An error occurred: ", e);
Thread.currentThread().interrupt();
}
}
}).start();
}
} | iluwatar/java-design-patterns | server-session/src/main/java/com/iluwatar/sessionserver/App.java |
199 | // Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.
// Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false.
// It is possible that several messages arrive roughly at the same time.
// Example:
// Logger logger = new Logger();
// // logging string "foo" at timestamp 1
// logger.shouldPrintMessage(1, "foo"); returns true;
// // logging string "bar" at timestamp 2
// logger.shouldPrintMessage(2,"bar"); returns true;
// // logging string "foo" at timestamp 3
// logger.shouldPrintMessage(3,"foo"); returns false;
// // logging string "bar" at timestamp 8
// logger.shouldPrintMessage(8,"bar"); returns false;
// // logging string "foo" at timestamp 10
// logger.shouldPrintMessage(10,"foo"); returns false;
// // logging string "foo" at timestamp 11
// logger.shouldPrintMessage(11,"foo"); returns true;
public class LoggerRateLimiter {
HashMap<String, Integer> messages;
/** Initialize your data structure here. */
public Logger() {
this.messages = new HashMap<String, Integer>();
}
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity. */
public boolean shouldPrintMessage(int timestamp, String message) {
if(messages.containsKey(message)) {
if(timestamp - messages.get(message) >= 10) {
messages.put(message, timestamp);
return true;
} else {
return false;
}
} else {
messages.put(message, timestamp);
return true;
}
}
}
/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* boolean param_1 = obj.shouldPrintMessage(timestamp,message);
*/
| kdn251/interviews | leetcode/hash-table/LoggerRateLimiter.java |
200 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 com.iluwatar.slob.lob;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Creates an object Animal with a list of animals and/or plants it consumes.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Animal implements Serializable {
private String name;
private Set<Plant> plantsEaten = new HashSet<>();
private Set<Animal> animalsEaten = new HashSet<>();
/**
* Iterates over the input nodes recursively and adds new plants to {@link Animal#plantsEaten} or
* animals to {@link Animal#animalsEaten} found to input sets respectively.
*
* @param childNodes contains the XML Node containing the Forest
* @param animalsEaten set of Animals eaten
* @param plantsEaten set of Plants eaten
*/
protected static void iterateXmlForAnimalAndPlants(NodeList childNodes, Set<Animal> animalsEaten,
Set<Plant> plantsEaten) {
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
if (child.getNodeName().equals(Animal.class.getSimpleName())) {
Animal animalEaten = new Animal();
animalEaten.createObjectFromXml(child);
animalsEaten.add(animalEaten);
} else if (child.getNodeName().equals(Plant.class.getSimpleName())) {
Plant plant = new Plant();
plant.createObjectFromXml(child);
plantsEaten.add(plant);
}
}
}
}
/**
* Provides XML Representation of the Animal.
*
* @param xmlDoc object to which the XML representation is to be written to
* @return XML Element contain the Animal representation
*/
public Element toXmlElement(Document xmlDoc) {
Element root = xmlDoc.createElement(Animal.class.getSimpleName());
root.setAttribute("name", name);
for (Plant plant : plantsEaten) {
Element xmlElement = plant.toXmlElement(xmlDoc);
if (xmlElement != null) {
root.appendChild(xmlElement);
}
}
for (Animal animal : animalsEaten) {
Element xmlElement = animal.toXmlElement(xmlDoc);
if (xmlElement != null) {
root.appendChild(xmlElement);
}
}
xmlDoc.appendChild(root);
return (Element) xmlDoc.getFirstChild();
}
/**
* Parses the Animal Object from the input XML Node.
*
* @param node the XML Node from which the Animal Object is to be parsed
*/
public void createObjectFromXml(Node node) {
name = node.getAttributes().getNamedItem("name").getNodeValue();
NodeList childNodes = node.getChildNodes();
iterateXmlForAnimalAndPlants(childNodes, animalsEaten, plantsEaten);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\nAnimal Name = ").append(name);
if (!animalsEaten.isEmpty()) {
sb.append("\n\tAnimals Eaten by ").append(name).append(": ");
}
for (Animal animal : animalsEaten) {
sb.append("\n\t\t").append(animal);
}
sb.append("\n");
if (!plantsEaten.isEmpty()) {
sb.append("\n\tPlants Eaten by ").append(name).append(": ");
}
for (Plant plant : plantsEaten) {
sb.append("\n\t\t").append(plant);
}
return sb.toString();
}
}
| rajprins/java-design-patterns | slob/src/main/java/com/iluwatar/slob/lob/Animal.java |
201 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.MetadataCreateDataStreamService;
import org.elasticsearch.cluster.routing.IndexRouting;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.index.mapper.DataStreamTimestampFieldMapper;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.index.mapper.DocumentDimensions;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.MappingLookup;
import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.NestedLookup;
import org.elasticsearch.index.mapper.ProvidedIdFieldMapper;
import org.elasticsearch.index.mapper.RoutingFieldMapper;
import org.elasticsearch.index.mapper.SourceFieldMapper;
import org.elasticsearch.index.mapper.TimeSeriesIdFieldMapper;
import org.elasticsearch.index.mapper.TimeSeriesRoutingHashFieldMapper;
import org.elasticsearch.index.mapper.TsidExtractingIdFieldMapper;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BooleanSupplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toSet;
/**
* "Mode" that controls which behaviors and settings an index supports.
* <p>
* For the most part this class concentrates on validating settings and
* mappings. Most different behavior is controlled by forcing settings
* to be set or not set and by enabling extra fields in the mapping.
*/
public enum IndexMode {
STANDARD("standard") {
@Override
void validateWithOtherSettings(Map<Setting<?>, Object> settings) {
settingRequiresTimeSeries(settings, IndexMetadata.INDEX_ROUTING_PATH);
settingRequiresTimeSeries(settings, IndexSettings.TIME_SERIES_START_TIME);
settingRequiresTimeSeries(settings, IndexSettings.TIME_SERIES_END_TIME);
}
private static void settingRequiresTimeSeries(Map<Setting<?>, Object> settings, Setting<?> setting) {
if (false == Objects.equals(setting.getDefault(Settings.EMPTY), settings.get(setting))) {
throw new IllegalArgumentException("[" + setting.getKey() + "] requires " + tsdbMode());
}
}
@Override
public void validateMapping(MappingLookup lookup) {};
@Override
public void validateAlias(@Nullable String indexRouting, @Nullable String searchRouting) {}
@Override
public void validateTimestampFieldMapping(boolean isDataStream, MappingLookup mappingLookup) throws IOException {
if (isDataStream) {
MetadataCreateDataStreamService.validateTimestampFieldMapping(mappingLookup);
}
}
@Override
public CompressedXContent getDefaultMapping() {
return null;
}
@Override
public TimestampBounds getTimestampBound(IndexMetadata indexMetadata) {
return null;
}
@Override
public MetadataFieldMapper timeSeriesIdFieldMapper() {
// non time-series indices must not have a TimeSeriesIdFieldMapper
return null;
}
@Override
public MetadataFieldMapper timeSeriesRoutingHashFieldMapper() {
// non time-series indices must not have a TimeSeriesRoutingIdFieldMapper
return null;
}
@Override
public IdFieldMapper idFieldMapperWithoutFieldData() {
return ProvidedIdFieldMapper.NO_FIELD_DATA;
}
@Override
public IdFieldMapper buildIdFieldMapper(BooleanSupplier fieldDataEnabled) {
return new ProvidedIdFieldMapper(fieldDataEnabled);
}
@Override
public DocumentDimensions buildDocumentDimensions(IndexSettings settings) {
return new DocumentDimensions.OnlySingleValueAllowed();
}
@Override
public boolean shouldValidateTimestamp() {
return false;
}
@Override
public void validateSourceFieldMapper(SourceFieldMapper sourceFieldMapper) {}
@Override
public boolean isSyntheticSourceEnabled() {
return false;
}
},
TIME_SERIES("time_series") {
@Override
void validateWithOtherSettings(Map<Setting<?>, Object> settings) {
if (settings.get(IndexMetadata.INDEX_ROUTING_PARTITION_SIZE_SETTING) != Integer.valueOf(1)) {
throw new IllegalArgumentException(error(IndexMetadata.INDEX_ROUTING_PARTITION_SIZE_SETTING));
}
for (Setting<?> unsupported : TIME_SERIES_UNSUPPORTED) {
if (false == Objects.equals(unsupported.getDefault(Settings.EMPTY), settings.get(unsupported))) {
throw new IllegalArgumentException(error(unsupported));
}
}
checkSetting(settings, IndexMetadata.INDEX_ROUTING_PATH);
}
private static void checkSetting(Map<Setting<?>, Object> settings, Setting<?> setting) {
if (Objects.equals(setting.getDefault(Settings.EMPTY), settings.get(setting))) {
throw new IllegalArgumentException(tsdbMode() + " requires a non-empty [" + setting.getKey() + "]");
}
}
private static String error(Setting<?> unsupported) {
return tsdbMode() + " is incompatible with [" + unsupported.getKey() + "]";
}
@Override
public void validateMapping(MappingLookup lookup) {
if (lookup.nestedLookup() != NestedLookup.EMPTY) {
throw new IllegalArgumentException("cannot have nested fields when index is in " + tsdbMode());
}
if (((RoutingFieldMapper) lookup.getMapper(RoutingFieldMapper.NAME)).required()) {
throw new IllegalArgumentException(routingRequiredBad());
}
}
@Override
public void validateAlias(@Nullable String indexRouting, @Nullable String searchRouting) {
if (indexRouting != null || searchRouting != null) {
throw new IllegalArgumentException(routingRequiredBad());
}
}
@Override
public void validateTimestampFieldMapping(boolean isDataStream, MappingLookup mappingLookup) throws IOException {
MetadataCreateDataStreamService.validateTimestampFieldMapping(mappingLookup);
}
@Override
public CompressedXContent getDefaultMapping() {
return DEFAULT_TIME_SERIES_TIMESTAMP_MAPPING;
}
@Override
public TimestampBounds getTimestampBound(IndexMetadata indexMetadata) {
return new TimestampBounds(indexMetadata.getTimeSeriesStart(), indexMetadata.getTimeSeriesEnd());
}
private static String routingRequiredBad() {
return "routing is forbidden on CRUD operations that target indices in " + tsdbMode();
}
@Override
public MetadataFieldMapper timeSeriesIdFieldMapper() {
return TimeSeriesIdFieldMapper.INSTANCE;
}
@Override
public MetadataFieldMapper timeSeriesRoutingHashFieldMapper() {
return TimeSeriesRoutingHashFieldMapper.INSTANCE;
}
public IdFieldMapper idFieldMapperWithoutFieldData() {
return TsidExtractingIdFieldMapper.INSTANCE;
}
@Override
public IdFieldMapper buildIdFieldMapper(BooleanSupplier fieldDataEnabled) {
// We don't support field data on TSDB's _id
return TsidExtractingIdFieldMapper.INSTANCE;
}
@Override
public DocumentDimensions buildDocumentDimensions(IndexSettings settings) {
IndexRouting.ExtractFromSource routing = (IndexRouting.ExtractFromSource) settings.getIndexRouting();
return new TimeSeriesIdFieldMapper.TimeSeriesIdBuilder(routing.builder());
}
@Override
public boolean shouldValidateTimestamp() {
return true;
}
@Override
public void validateSourceFieldMapper(SourceFieldMapper sourceFieldMapper) {
if (sourceFieldMapper.isSynthetic() == false) {
throw new IllegalArgumentException("time series indices only support synthetic source");
}
}
@Override
public boolean isSyntheticSourceEnabled() {
return true;
}
};
protected static String tsdbMode() {
return "[" + IndexSettings.MODE.getKey() + "=time_series]";
}
public static final CompressedXContent DEFAULT_TIME_SERIES_TIMESTAMP_MAPPING;
static {
try {
DEFAULT_TIME_SERIES_TIMESTAMP_MAPPING = new CompressedXContent(
((builder, params) -> builder.startObject(MapperService.SINGLE_MAPPING_NAME)
.startObject(DataStreamTimestampFieldMapper.NAME)
.field("enabled", true)
.endObject()
.startObject("properties")
.startObject(DataStreamTimestampFieldMapper.DEFAULT_PATH)
.field("type", DateFieldMapper.CONTENT_TYPE)
.field("ignore_malformed", "false")
.endObject()
.endObject()
.endObject())
);
} catch (IOException e) {
throw new AssertionError(e);
}
}
private static final List<Setting<?>> TIME_SERIES_UNSUPPORTED = List.of(
IndexSortConfig.INDEX_SORT_FIELD_SETTING,
IndexSortConfig.INDEX_SORT_ORDER_SETTING,
IndexSortConfig.INDEX_SORT_MODE_SETTING,
IndexSortConfig.INDEX_SORT_MISSING_SETTING
);
static final List<Setting<?>> VALIDATE_WITH_SETTINGS = List.copyOf(
Stream.concat(
Stream.of(
IndexMetadata.INDEX_ROUTING_PARTITION_SIZE_SETTING,
IndexMetadata.INDEX_ROUTING_PATH,
IndexSettings.TIME_SERIES_START_TIME,
IndexSettings.TIME_SERIES_END_TIME
),
TIME_SERIES_UNSUPPORTED.stream()
).collect(toSet())
);
private final String name;
IndexMode(String name) {
this.name = name;
}
public String getName() {
return name;
}
abstract void validateWithOtherSettings(Map<Setting<?>, Object> settings);
/**
* Validate the mapping for this index.
*/
public abstract void validateMapping(MappingLookup lookup);
/**
* Validate aliases targeting this index.
*/
public abstract void validateAlias(@Nullable String indexRouting, @Nullable String searchRouting);
/**
* validate timestamp mapping for this index.
*/
public abstract void validateTimestampFieldMapping(boolean isDataStream, MappingLookup mappingLookup) throws IOException;
/**
* Get default mapping for this index or {@code null} if there is none.
*/
@Nullable
public abstract CompressedXContent getDefaultMapping();
/**
* Build the {@link FieldMapper} for {@code _id}.
*/
public abstract IdFieldMapper buildIdFieldMapper(BooleanSupplier fieldDataEnabled);
/**
* Get the singleton {@link FieldMapper} for {@code _id}. It can never support
* field data.
*/
public abstract IdFieldMapper idFieldMapperWithoutFieldData();
/**
* @return the time range based on the provided index metadata and index mode implementation.
* Otherwise <code>null</code> is returned.
*/
@Nullable
public abstract TimestampBounds getTimestampBound(IndexMetadata indexMetadata);
/**
* Return an instance of the {@link TimeSeriesIdFieldMapper} that generates
* the _tsid field. The field mapper will be added to the list of the metadata
* field mappers for the index.
*/
public abstract MetadataFieldMapper timeSeriesIdFieldMapper();
/**
* Return an instance of the {@link TimeSeriesRoutingHashFieldMapper} that generates
* the _ts_routing_hash field. The field mapper will be added to the list of the metadata
* field mappers for the index.
*/
public abstract MetadataFieldMapper timeSeriesRoutingHashFieldMapper();
/**
* How {@code time_series_dimension} fields are handled by indices in this mode.
*/
public abstract DocumentDimensions buildDocumentDimensions(IndexSettings settings);
/**
* @return Whether timestamps should be validated for being withing the time range of an index.
*/
public abstract boolean shouldValidateTimestamp();
/**
* Validates the source field mapper
*/
public abstract void validateSourceFieldMapper(SourceFieldMapper sourceFieldMapper);
/**
* @return whether synthetic source is the only allowed source mode.
*/
public abstract boolean isSyntheticSourceEnabled();
/**
* Parse a string into an {@link IndexMode}.
*/
public static IndexMode fromString(String value) {
return switch (value) {
case "standard" -> IndexMode.STANDARD;
case "time_series" -> IndexMode.TIME_SERIES;
default -> throw new IllegalArgumentException(
"["
+ value
+ "] is an invalid index mode, valid modes are: ["
+ Arrays.stream(IndexMode.values()).map(IndexMode::toString).collect(Collectors.joining())
+ "]"
);
};
}
@Override
public String toString() {
return getName();
}
}
| elastic/elasticsearch | server/src/main/java/org/elasticsearch/index/IndexMode.java |
202 | /*
* Copyright (C) 2012 The Guava 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.
*/
package com.google.common.reflect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Wrapper around either a {@link Method} or a {@link Constructor}. Convenience API is provided to
* make common reflective operation easier to deal with, such as {@link #isPublic}, {@link
* #getParameters} etc.
*
* <p>In addition to convenience methods, {@link TypeToken#method} and {@link TypeToken#constructor}
* will resolve the type parameters of the method or constructor in the context of the owner type,
* which may be a subtype of the declaring class. For example:
*
* <pre>{@code
* Method getMethod = List.class.getMethod("get", int.class);
* Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
* assertEquals(TypeToken.of(String.class), invokable.getReturnType()); // Not Object.class!
* assertEquals(new TypeToken<List<String>>() {}, invokable.getOwnerType());
* }</pre>
*
* <p><b>Note:</b> earlier versions of this class inherited from {@link
* java.lang.reflect.AccessibleObject AccessibleObject} and {@link
* java.lang.reflect.GenericDeclaration GenericDeclaration}. Since version 31.0 that is no longer
* the case. However, most methods from those types are present with the same signature in this
* class.
*
* @param <T> the type that owns this method or constructor.
* @param <R> the return type of (or supertype thereof) the method or the declaring type of the
* constructor.
* @author Ben Yu
* @since 14.0 (no longer implements {@link AccessibleObject} or {@code GenericDeclaration} since
* 31.0)
*/
@ElementTypesAreNonnullByDefault
public abstract class Invokable<T, R> implements AnnotatedElement, Member {
private final AccessibleObject accessibleObject;
private final Member member;
<M extends AccessibleObject & Member> Invokable(M member) {
checkNotNull(member);
this.accessibleObject = member;
this.member = member;
}
/** Returns {@link Invokable} of {@code method}. */
public static Invokable<?, Object> from(Method method) {
return new MethodInvokable<>(method);
}
/** Returns {@link Invokable} of {@code constructor}. */
public static <T> Invokable<T, T> from(Constructor<T> constructor) {
return new ConstructorInvokable<T>(constructor);
}
@Override
public final boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
return accessibleObject.isAnnotationPresent(annotationClass);
}
@Override
@CheckForNull
public final <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
return accessibleObject.getAnnotation(annotationClass);
}
@Override
public final Annotation[] getAnnotations() {
return accessibleObject.getAnnotations();
}
@Override
public final Annotation[] getDeclaredAnnotations() {
return accessibleObject.getDeclaredAnnotations();
}
// We ought to be able to implement GenericDeclaration instead its parent AnnotatedElement.
// That would give us this method declaration. But for some reason, implementing
// GenericDeclaration leads to weird errors in Android tests:
// IncompatibleClassChangeError: interface not implemented
/** See {@link java.lang.reflect.GenericDeclaration#getTypeParameters()}. */
public abstract TypeVariable<?>[] getTypeParameters();
/** See {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)}. */
public final void setAccessible(boolean flag) {
accessibleObject.setAccessible(flag);
}
/** See {@link java.lang.reflect.AccessibleObject#trySetAccessible()}. */
@SuppressWarnings("CatchingUnchecked") // sneaky checked exception
public final boolean trySetAccessible() {
// We can't call accessibleObject.trySetAccessible since that was added in Java 9 and this code
// should work on Java 8. So we emulate it this way.
try {
accessibleObject.setAccessible(true);
return true;
} catch (Exception e) { // sneaky checked exception
return false;
}
}
/** See {@link java.lang.reflect.AccessibleObject#isAccessible()}. */
public final boolean isAccessible() {
return accessibleObject.isAccessible();
}
@Override
public final String getName() {
return member.getName();
}
@Override
public final int getModifiers() {
return member.getModifiers();
}
@Override
public final boolean isSynthetic() {
return member.isSynthetic();
}
/** Returns true if the element is public. */
public final boolean isPublic() {
return Modifier.isPublic(getModifiers());
}
/** Returns true if the element is protected. */
public final boolean isProtected() {
return Modifier.isProtected(getModifiers());
}
/** Returns true if the element is package-private. */
public final boolean isPackagePrivate() {
return !isPrivate() && !isPublic() && !isProtected();
}
/** Returns true if the element is private. */
public final boolean isPrivate() {
return Modifier.isPrivate(getModifiers());
}
/** Returns true if the element is static. */
public final boolean isStatic() {
return Modifier.isStatic(getModifiers());
}
/**
* Returns {@code true} if this method is final, per {@code Modifier.isFinal(getModifiers())}.
*
* <p>Note that a method may still be effectively "final", or non-overridable when it has no
* {@code final} keyword. For example, it could be private, or it could be declared by a final
* class. To tell whether a method is overridable, use {@link Invokable#isOverridable}.
*/
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
/** Returns true if the method is abstract. */
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
/** Returns true if the element is native. */
public final boolean isNative() {
return Modifier.isNative(getModifiers());
}
/** Returns true if the method is synchronized. */
public final boolean isSynchronized() {
return Modifier.isSynchronized(getModifiers());
}
/** Returns true if the field is volatile. */
final boolean isVolatile() {
return Modifier.isVolatile(getModifiers());
}
/** Returns true if the field is transient. */
final boolean isTransient() {
return Modifier.isTransient(getModifiers());
}
@Override
public boolean equals(@CheckForNull Object obj) {
if (obj instanceof Invokable) {
Invokable<?, ?> that = (Invokable<?, ?>) obj;
return getOwnerType().equals(that.getOwnerType()) && member.equals(that.member);
}
return false;
}
@Override
public int hashCode() {
return member.hashCode();
}
@Override
public String toString() {
return member.toString();
}
/**
* Returns {@code true} if this is an overridable method. Constructors, private, static or final
* methods, or methods declared by final classes are not overridable.
*/
public abstract boolean isOverridable();
/** Returns {@code true} if this was declared to take a variable number of arguments. */
public abstract boolean isVarArgs();
/**
* Invokes with {@code receiver} as 'this' and {@code args} passed to the underlying method and
* returns the return value; or calls the underlying constructor with {@code args} and returns the
* constructed instance.
*
* @throws IllegalAccessException if this {@code Constructor} object enforces Java language access
* control and the underlying method or constructor is inaccessible.
* @throws IllegalArgumentException if the number of actual and formal parameters differ; if an
* unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a
* parameter value cannot be converted to the corresponding formal parameter type by a method
* invocation conversion.
* @throws InvocationTargetException if the underlying method or constructor throws an exception.
*/
// All subclasses are owned by us and we'll make sure to get the R type right, including nullness.
@SuppressWarnings({"unchecked", "nullness"})
@CanIgnoreReturnValue
@CheckForNull
public final R invoke(@CheckForNull T receiver, @Nullable Object... args)
throws InvocationTargetException, IllegalAccessException {
return (R) invokeInternal(receiver, checkNotNull(args));
}
/** Returns the return type of this {@code Invokable}. */
// All subclasses are owned by us and we'll make sure to get the R type right.
@SuppressWarnings("unchecked")
public final TypeToken<? extends R> getReturnType() {
return (TypeToken<? extends R>) TypeToken.of(getGenericReturnType());
}
/**
* Returns all declared parameters of this {@code Invokable}. Note that if this is a constructor
* of a non-static inner class, unlike {@link Constructor#getParameterTypes}, the hidden {@code
* this} parameter of the enclosing class is excluded from the returned parameters.
*/
@IgnoreJRERequirement
public final ImmutableList<Parameter> getParameters() {
Type[] parameterTypes = getGenericParameterTypes();
Annotation[][] annotations = getParameterAnnotations();
@Nullable Object[] annotatedTypes =
ANNOTATED_TYPE_EXISTS ? getAnnotatedParameterTypes() : new Object[parameterTypes.length];
ImmutableList.Builder<Parameter> builder = ImmutableList.builder();
for (int i = 0; i < parameterTypes.length; i++) {
builder.add(
new Parameter(
this, i, TypeToken.of(parameterTypes[i]), annotations[i], annotatedTypes[i]));
}
return builder.build();
}
/** Returns all declared exception types of this {@code Invokable}. */
public final ImmutableList<TypeToken<? extends Throwable>> getExceptionTypes() {
ImmutableList.Builder<TypeToken<? extends Throwable>> builder = ImmutableList.builder();
for (Type type : getGenericExceptionTypes()) {
// getGenericExceptionTypes() will never return a type that's not exception
@SuppressWarnings("unchecked")
TypeToken<? extends Throwable> exceptionType =
(TypeToken<? extends Throwable>) TypeToken.of(type);
builder.add(exceptionType);
}
return builder.build();
}
/**
* Explicitly specifies the return type of this {@code Invokable}. For example:
*
* <pre>{@code
* Method factoryMethod = Person.class.getMethod("create");
* Invokable<?, Person> factory = Invokable.of(getNameMethod).returning(Person.class);
* }</pre>
*/
public final <R1 extends R> Invokable<T, R1> returning(Class<R1> returnType) {
return returning(TypeToken.of(returnType));
}
/** Explicitly specifies the return type of this {@code Invokable}. */
public final <R1 extends R> Invokable<T, R1> returning(TypeToken<R1> returnType) {
if (!returnType.isSupertypeOf(getReturnType())) {
throw new IllegalArgumentException(
"Invokable is known to return " + getReturnType() + ", not " + returnType);
}
@SuppressWarnings("unchecked") // guarded by previous check
Invokable<T, R1> specialized = (Invokable<T, R1>) this;
return specialized;
}
@SuppressWarnings("unchecked") // The declaring class is T's raw class, or one of its supertypes.
@Override
public final Class<? super T> getDeclaringClass() {
return (Class<? super T>) member.getDeclaringClass();
}
/** Returns the type of {@code T}. */
// Overridden in TypeToken#method() and TypeToken#constructor()
@SuppressWarnings("unchecked") // The declaring class is T.
public TypeToken<T> getOwnerType() {
return (TypeToken<T>) TypeToken.of(getDeclaringClass());
}
@CheckForNull
abstract Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args)
throws InvocationTargetException, IllegalAccessException;
abstract Type[] getGenericParameterTypes();
@SuppressWarnings("Java7ApiChecker")
abstract AnnotatedType[] getAnnotatedParameterTypes();
/** This should never return a type that's not a subtype of Throwable. */
abstract Type[] getGenericExceptionTypes();
abstract Annotation[][] getParameterAnnotations();
abstract Type getGenericReturnType();
/**
* Returns the {@link AnnotatedType} for the return type.
*
* @since 14.0
*/
@SuppressWarnings("Java7ApiChecker")
public abstract AnnotatedType getAnnotatedReturnType();
static class MethodInvokable<T> extends Invokable<T, Object> {
final Method method;
MethodInvokable(Method method) {
super(method);
this.method = method;
}
@Override
@CheckForNull
final Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args)
throws InvocationTargetException, IllegalAccessException {
return method.invoke(receiver, args);
}
@Override
Type getGenericReturnType() {
return method.getGenericReturnType();
}
@Override
Type[] getGenericParameterTypes() {
return method.getGenericParameterTypes();
}
@Override
@SuppressWarnings("Java7ApiChecker")
AnnotatedType[] getAnnotatedParameterTypes() {
return method.getAnnotatedParameterTypes();
}
@Override
@SuppressWarnings("Java7ApiChecker")
public AnnotatedType getAnnotatedReturnType() {
return method.getAnnotatedReturnType();
}
@Override
Type[] getGenericExceptionTypes() {
return method.getGenericExceptionTypes();
}
@Override
final Annotation[][] getParameterAnnotations() {
return method.getParameterAnnotations();
}
@Override
public final TypeVariable<?>[] getTypeParameters() {
return method.getTypeParameters();
}
@Override
public final boolean isOverridable() {
return !(isFinal()
|| isPrivate()
|| isStatic()
|| Modifier.isFinal(getDeclaringClass().getModifiers()));
}
@Override
public final boolean isVarArgs() {
return method.isVarArgs();
}
}
static class ConstructorInvokable<T> extends Invokable<T, T> {
final Constructor<?> constructor;
ConstructorInvokable(Constructor<?> constructor) {
super(constructor);
this.constructor = constructor;
}
@Override
final Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args)
throws InvocationTargetException, IllegalAccessException {
try {
return constructor.newInstance(args);
} catch (InstantiationException e) {
throw new RuntimeException(constructor + " failed.", e);
}
}
/**
* If the class is parameterized, such as {@link java.util.ArrayList ArrayList}, this returns
* {@code ArrayList<E>}.
*/
@Override
Type getGenericReturnType() {
Class<?> declaringClass = getDeclaringClass();
TypeVariable<?>[] typeParams = declaringClass.getTypeParameters();
if (typeParams.length > 0) {
return Types.newParameterizedType(declaringClass, typeParams);
} else {
return declaringClass;
}
}
@Override
Type[] getGenericParameterTypes() {
Type[] types = constructor.getGenericParameterTypes();
if (types.length > 0 && mayNeedHiddenThis()) {
Class<?>[] rawParamTypes = constructor.getParameterTypes();
if (types.length == rawParamTypes.length
&& rawParamTypes[0] == getDeclaringClass().getEnclosingClass()) {
// first parameter is the hidden 'this'
return Arrays.copyOfRange(types, 1, types.length);
}
}
return types;
}
@Override
@SuppressWarnings("Java7ApiChecker")
AnnotatedType[] getAnnotatedParameterTypes() {
return constructor.getAnnotatedParameterTypes();
}
@Override
@SuppressWarnings("Java7ApiChecker")
public AnnotatedType getAnnotatedReturnType() {
return constructor.getAnnotatedReturnType();
}
@Override
Type[] getGenericExceptionTypes() {
return constructor.getGenericExceptionTypes();
}
@Override
final Annotation[][] getParameterAnnotations() {
return constructor.getParameterAnnotations();
}
/**
* {@inheritDoc}
*
* <p>{@code [<E>]} will be returned for ArrayList's constructor. When both the class and the
* constructor have type parameters, the class parameters are prepended before those of the
* constructor's. This is an arbitrary rule since no existing language spec mandates one way or
* the other. From the declaration syntax, the class type parameter appears first, but the call
* syntax may show up in opposite order such as {@code new <A>Foo<B>()}.
*/
@Override
public final TypeVariable<?>[] getTypeParameters() {
TypeVariable<?>[] declaredByClass = getDeclaringClass().getTypeParameters();
TypeVariable<?>[] declaredByConstructor = constructor.getTypeParameters();
TypeVariable<?>[] result =
new TypeVariable<?>[declaredByClass.length + declaredByConstructor.length];
System.arraycopy(declaredByClass, 0, result, 0, declaredByClass.length);
System.arraycopy(
declaredByConstructor, 0, result, declaredByClass.length, declaredByConstructor.length);
return result;
}
@Override
public final boolean isOverridable() {
return false;
}
@Override
public final boolean isVarArgs() {
return constructor.isVarArgs();
}
private boolean mayNeedHiddenThis() {
Class<?> declaringClass = constructor.getDeclaringClass();
if (declaringClass.getEnclosingConstructor() != null) {
// Enclosed in a constructor, needs hidden this
return true;
}
Method enclosingMethod = declaringClass.getEnclosingMethod();
if (enclosingMethod != null) {
// Enclosed in a method, if it's not static, must need hidden this.
return !Modifier.isStatic(enclosingMethod.getModifiers());
} else {
// Strictly, this doesn't necessarily indicate a hidden 'this' in the case of
// static initializer. But there seems no way to tell in that case. :(
// This may cause issues when an anonymous class is created inside a static initializer,
// and the class's constructor's first parameter happens to be the enclosing class.
// In such case, we may mistakenly think that the class is within a non-static context
// and the first parameter is the hidden 'this'.
return declaringClass.getEnclosingClass() != null
&& !Modifier.isStatic(declaringClass.getModifiers());
}
}
}
private static final boolean ANNOTATED_TYPE_EXISTS = initAnnotatedTypeExists();
private static boolean initAnnotatedTypeExists() {
try {
Class.forName("java.lang.reflect.AnnotatedType");
} catch (ClassNotFoundException e) {
return false;
}
return true;
}
}
| google/guava | guava/src/com/google/common/reflect/Invokable.java |
203 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import static com.google.protobuf.Internal.checkNotNull;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.DescriptorProtos.Edition;
import com.google.protobuf.DescriptorProtos.EnumDescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumOptions;
import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumValueOptions;
import com.google.protobuf.DescriptorProtos.FeatureSet;
import com.google.protobuf.DescriptorProtos.FeatureSetDefaults;
import com.google.protobuf.DescriptorProtos.FeatureSetDefaults.FeatureSetEditionDefault;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldOptions;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileOptions;
import com.google.protobuf.DescriptorProtos.MessageOptions;
import com.google.protobuf.DescriptorProtos.MethodDescriptorProto;
import com.google.protobuf.DescriptorProtos.MethodOptions;
import com.google.protobuf.DescriptorProtos.OneofDescriptorProto;
import com.google.protobuf.DescriptorProtos.OneofOptions;
import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto;
import com.google.protobuf.DescriptorProtos.ServiceOptions;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import com.google.protobuf.JavaFeaturesProto.JavaFeatures;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
/**
* Contains a collection of classes which describe protocol message types.
*
* <p>Every message type has a {@link Descriptor}, which lists all its fields and other information
* about a type. You can get a message type's descriptor by calling {@code
* MessageType.getDescriptor()}, or (given a message object of the type) {@code
* message.getDescriptorForType()}. Furthermore, each message is associated with a {@link
* FileDescriptor} for a relevant {@code .proto} file. You can obtain it by calling {@code
* Descriptor.getFile()}. A {@link FileDescriptor} contains descriptors for all the messages defined
* in that file, and file descriptors for all the imported {@code .proto} files.
*
* <p>Descriptors are built from DescriptorProtos, as defined in {@code
* google/protobuf/descriptor.proto}.
*
* @author [email protected] Kenton Varda
*/
@CheckReturnValue
public final class Descriptors {
private static final Logger logger = Logger.getLogger(Descriptors.class.getName());
private static final int[] EMPTY_INT_ARRAY = new int[0];
private static final Descriptor[] EMPTY_DESCRIPTORS = new Descriptor[0];
private static final FieldDescriptor[] EMPTY_FIELD_DESCRIPTORS = new FieldDescriptor[0];
private static final EnumDescriptor[] EMPTY_ENUM_DESCRIPTORS = new EnumDescriptor[0];
private static final ServiceDescriptor[] EMPTY_SERVICE_DESCRIPTORS = new ServiceDescriptor[0];
private static final OneofDescriptor[] EMPTY_ONEOF_DESCRIPTORS = new OneofDescriptor[0];
private static final ConcurrentHashMap<Integer, FeatureSet> FEATURE_CACHE =
new ConcurrentHashMap<>();
@SuppressWarnings("NonFinalStaticField")
private static volatile FeatureSetDefaults javaEditionDefaults = null;
/** Sets the default feature mappings used during the build. Exposed for tests. */
static void setTestJavaEditionDefaults(FeatureSetDefaults defaults) {
javaEditionDefaults = defaults;
}
/** Gets the default feature mappings used during the build. */
static FeatureSetDefaults getJavaEditionDefaults() {
// Force explicit initialization before synchronized block which can trigger initialization in
// `JavaFeaturesProto.registerAllExtensions()` and `FeatureSetdefaults.parseFrom()` calls.
// Otherwise, this can result in deadlock if another threads holds the static init block's
// implicit lock. This operation should be cheap if initialization has already occurred.
Descriptor unused1 = FeatureSetDefaults.getDescriptor();
FileDescriptor unused2 = JavaFeaturesProto.getDescriptor();
if (javaEditionDefaults == null) {
synchronized (Descriptors.class) {
if (javaEditionDefaults == null) {
try {
ExtensionRegistry registry = ExtensionRegistry.newInstance();
registry.add(JavaFeaturesProto.java_);
setTestJavaEditionDefaults(
FeatureSetDefaults.parseFrom(
JavaEditionDefaults.PROTOBUF_INTERNAL_JAVA_EDITION_DEFAULTS.getBytes(
Internal.ISO_8859_1),
registry));
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
}
return javaEditionDefaults;
}
static FeatureSet getEditionDefaults(Edition edition) {
FeatureSetDefaults javaEditionDefaults = getJavaEditionDefaults();
if (edition.getNumber() < javaEditionDefaults.getMinimumEdition().getNumber()) {
throw new IllegalArgumentException(
"Edition "
+ edition
+ " is lower than the minimum supported edition "
+ javaEditionDefaults.getMinimumEdition()
+ "!");
}
if (edition.getNumber() > javaEditionDefaults.getMaximumEdition().getNumber()) {
throw new IllegalArgumentException(
"Edition "
+ edition
+ " is greater than the maximum supported edition "
+ javaEditionDefaults.getMaximumEdition()
+ "!");
}
FeatureSetEditionDefault found = null;
for (FeatureSetEditionDefault editionDefault : javaEditionDefaults.getDefaultsList()) {
if (editionDefault.getEdition().getNumber() > edition.getNumber()) {
break;
}
found = editionDefault;
}
if (found == null) {
throw new IllegalArgumentException(
"Edition " + edition + " does not have a valid default FeatureSet!");
}
return found.getFixedFeatures().toBuilder().mergeFrom(found.getOverridableFeatures()).build();
}
private static FeatureSet internFeatures(FeatureSet features) {
FeatureSet cached = FEATURE_CACHE.putIfAbsent(features.hashCode(), features);
if (cached == null) {
return features;
}
return cached;
}
/**
* Describes a {@code .proto} file, including everything defined within. That includes, in
* particular, descriptors for all the messages and file descriptors for all other imported {@code
* .proto} files (dependencies).
*/
public static final class FileDescriptor extends GenericDescriptor {
/** Convert the descriptor to its protocol message representation. */
@Override
public FileDescriptorProto toProto() {
return proto;
}
/** Get the file name. */
@Override
public String getName() {
return proto.getName();
}
/** Returns this object. */
@Override
public FileDescriptor getFile() {
return this;
}
/** Returns the same as getName(). */
@Override
public String getFullName() {
return proto.getName();
}
/**
* Get the proto package name. This is the package name given by the {@code package} statement
* in the {@code .proto} file, which differs from the Java package.
*/
public String getPackage() {
return proto.getPackage();
}
/** Get the {@code FileOptions}, defined in {@code descriptor.proto}. */
public FileOptions getOptions() {
if (this.options == null) {
FileOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Get a list of top-level message types declared in this file. */
public List<Descriptor> getMessageTypes() {
return Collections.unmodifiableList(Arrays.asList(messageTypes));
}
/** Get a list of top-level enum types declared in this file. */
public List<EnumDescriptor> getEnumTypes() {
return Collections.unmodifiableList(Arrays.asList(enumTypes));
}
/** Get a list of top-level services declared in this file. */
public List<ServiceDescriptor> getServices() {
return Collections.unmodifiableList(Arrays.asList(services));
}
/** Get a list of top-level extensions declared in this file. */
public List<FieldDescriptor> getExtensions() {
return Collections.unmodifiableList(Arrays.asList(extensions));
}
/** Get a list of this file's dependencies (imports). */
public List<FileDescriptor> getDependencies() {
return Collections.unmodifiableList(Arrays.asList(dependencies));
}
/** Get a list of this file's public dependencies (public imports). */
public List<FileDescriptor> getPublicDependencies() {
return Collections.unmodifiableList(Arrays.asList(publicDependencies));
}
/** Get the edition of the .proto file. */
Edition getEdition() {
switch (proto.getSyntax()) {
case "editions":
return proto.getEdition();
case "proto3":
return Edition.EDITION_PROTO3;
default:
return Edition.EDITION_PROTO2;
}
}
public void copyHeadingTo(FileDescriptorProto.Builder protoBuilder) {
protoBuilder.setName(getName()).setSyntax(proto.getSyntax());
if (!getPackage().isEmpty()) {
protoBuilder.setPackage(getPackage());
}
if (proto.getSyntax().equals("editions")) {
protoBuilder.setEdition(proto.getEdition());
}
if (proto.hasOptions() && !proto.getOptions().equals(FileOptions.getDefaultInstance())) {
protoBuilder.setOptions(proto.getOptions());
}
}
/**
* Find a message type in the file by name. Does not find nested types.
*
* @param name The unqualified type name to look for.
* @return The message type's descriptor, or {@code null} if not found.
*/
public Descriptor findMessageTypeByName(String name) {
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof Descriptor && result.getFile() == this) {
return (Descriptor) result;
} else {
return null;
}
}
/**
* Find an enum type in the file by name. Does not find nested types.
*
* @param name The unqualified type name to look for.
* @return The enum type's descriptor, or {@code null} if not found.
*/
public EnumDescriptor findEnumTypeByName(String name) {
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof EnumDescriptor && result.getFile() == this) {
return (EnumDescriptor) result;
} else {
return null;
}
}
/**
* Find a service type in the file by name.
*
* @param name The unqualified type name to look for.
* @return The service type's descriptor, or {@code null} if not found.
*/
public ServiceDescriptor findServiceByName(String name) {
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof ServiceDescriptor && result.getFile() == this) {
return (ServiceDescriptor) result;
} else {
return null;
}
}
/**
* Find an extension in the file by name. Does not find extensions nested inside message types.
*
* @param name The unqualified extension name to look for.
* @return The extension's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findExtensionByName(String name) {
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof FieldDescriptor && result.getFile() == this) {
return (FieldDescriptor) result;
} else {
return null;
}
}
/**
* Construct a {@code FileDescriptor}.
*
* @param proto the protocol message form of the FileDescriptort
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies.
* @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
* for a number of reasons; for instance, because a field has an undefined type or because
* two messages were defined with the same name.
*/
public static FileDescriptor buildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies)
throws DescriptorValidationException {
return buildFrom(proto, dependencies, false);
}
/**
* Construct a {@code FileDescriptor}.
*
* @param proto the protocol message form of the FileDescriptor
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies
* @param allowUnknownDependencies if true, non-existing dependencies will be ignored and
* undefined message types will be replaced with a placeholder type. Undefined enum types
* still cause a DescriptorValidationException.
* @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
* for a number of reasons; for instance, because a field has an undefined type or because
* two messages were defined with the same name.
*/
public static FileDescriptor buildFrom(
FileDescriptorProto proto, FileDescriptor[] dependencies, boolean allowUnknownDependencies)
throws DescriptorValidationException {
return buildFrom(proto, dependencies, allowUnknownDependencies, false);
}
private static FileDescriptor buildFrom(
FileDescriptorProto proto,
FileDescriptor[] dependencies,
boolean allowUnknownDependencies,
boolean allowUnresolvedFeatures)
throws DescriptorValidationException {
// Building descriptors involves two steps: translating and linking.
// In the translation step (implemented by FileDescriptor's
// constructor), we build an object tree mirroring the
// FileDescriptorProto's tree and put all of the descriptors into the
// DescriptorPool's lookup tables. In the linking step, we look up all
// type references in the DescriptorPool, so that, for example, a
// FieldDescriptor for an embedded message contains a pointer directly
// to the Descriptor for that message's type. We also detect undefined
// types in the linking step.
DescriptorPool pool = new DescriptorPool(dependencies, allowUnknownDependencies);
FileDescriptor result =
new FileDescriptor(proto, dependencies, pool, allowUnknownDependencies);
result.crossLink();
// Skip feature resolution until later for calls from gencode.
if (!allowUnresolvedFeatures) {
// We do not need to force feature resolution for proto1 dependencies
// since dependencies from non-gencode should already be fully feature resolved.
result.resolveAllFeaturesInternal();
}
return result;
}
private static byte[] latin1Cat(final String[] strings) {
// Hack: We can't embed a raw byte array inside generated Java code
// (at least, not efficiently), but we can embed Strings. So, the
// protocol compiler embeds the FileDescriptorProto as a giant
// string literal which is passed to this function to construct the
// file's FileDescriptor. The string literal contains only 8-bit
// characters, each one representing a byte of the FileDescriptorProto's
// serialized form. So, if we convert it to bytes in ISO-8859-1, we
// should get the original bytes that we want.
// Literal strings are limited to 64k, so it may be split into multiple strings.
if (strings.length == 1) {
return strings[0].getBytes(Internal.ISO_8859_1);
}
StringBuilder descriptorData = new StringBuilder();
for (String part : strings) {
descriptorData.append(part);
}
return descriptorData.toString().getBytes(Internal.ISO_8859_1);
}
private static FileDescriptor[] findDescriptors(
final Class<?> descriptorOuterClass,
final String[] dependencyClassNames,
final String[] dependencyFileNames) {
List<FileDescriptor> descriptors = new ArrayList<>();
for (int i = 0; i < dependencyClassNames.length; i++) {
try {
Class<?> clazz = descriptorOuterClass.getClassLoader().loadClass(dependencyClassNames[i]);
descriptors.add((FileDescriptor) clazz.getField("descriptor").get(null));
} catch (Exception e) {
// We allow unknown dependencies by default. If a dependency cannot
// be found we only generate a warning.
logger.warning("Descriptors for \"" + dependencyFileNames[i] + "\" can not be found.");
}
}
return descriptors.toArray(new FileDescriptor[0]);
}
/**
* This method is to be called by generated code only. It is equivalent to {@code buildFrom}
* except that the {@code FileDescriptorProto} is encoded in protocol buffer wire format.
*/
public static FileDescriptor internalBuildGeneratedFileFrom(
final String[] descriptorDataParts, final FileDescriptor[] dependencies) {
final byte[] descriptorBytes = latin1Cat(descriptorDataParts);
FileDescriptorProto proto;
try {
proto = FileDescriptorProto.parseFrom(descriptorBytes);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
"Failed to parse protocol buffer descriptor for generated code.", e);
}
try {
// When building descriptors for generated code, we allow unknown
// dependencies by default and delay feature resolution until later.
return buildFrom(proto, dependencies, true, true);
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException(
"Invalid embedded descriptor for \"" + proto.getName() + "\".", e);
}
}
/**
* This method is to be called by generated code only. It uses Java reflection to load the
* dependencies' descriptors.
*/
public static FileDescriptor internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
final Class<?> descriptorOuterClass,
final String[] dependencyClassNames,
final String[] dependencyFileNames) {
FileDescriptor[] dependencies =
findDescriptors(descriptorOuterClass, dependencyClassNames, dependencyFileNames);
return internalBuildGeneratedFileFrom(descriptorDataParts, dependencies);
}
/**
* This method is to be called by generated code only. It updates the FileDescriptorProto
* associated with the descriptor by parsing it again with the given ExtensionRegistry. This is
* needed to recognize custom options.
*/
public static void internalUpdateFileDescriptor(
FileDescriptor descriptor, ExtensionRegistry registry) {
ByteString bytes = descriptor.proto.toByteString();
try {
FileDescriptorProto proto = FileDescriptorProto.parseFrom(bytes, registry);
descriptor.setProto(proto);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
"Failed to parse protocol buffer descriptor for generated code.", e);
}
}
/**
* This class should be used by generated code only. When calling {@link
* FileDescriptor#internalBuildGeneratedFileFrom}, the caller provides a callback implementing
* this interface. The callback is called after the FileDescriptor has been constructed, in
* order to assign all the global variables defined in the generated code which point at parts
* of the FileDescriptor. The callback returns an ExtensionRegistry which contains any
* extensions which might be used in the descriptor -- that is, extensions of the various
* "Options" messages defined in descriptor.proto. The callback may also return null to indicate
* that no extensions are used in the descriptor.
*
* <p>This interface is deprecated. Use the return value of internalBuildGeneratedFrom()
* instead.
*/
@Deprecated
public interface InternalDescriptorAssigner {
ExtensionRegistry assignDescriptors(FileDescriptor root);
}
private FileDescriptorProto proto;
private volatile FileOptions options;
private final Descriptor[] messageTypes;
private final EnumDescriptor[] enumTypes;
private final ServiceDescriptor[] services;
private final FieldDescriptor[] extensions;
private final FileDescriptor[] dependencies;
private final FileDescriptor[] publicDependencies;
private final DescriptorPool pool;
private FileDescriptor(
final FileDescriptorProto proto,
final FileDescriptor[] dependencies,
final DescriptorPool pool,
boolean allowUnknownDependencies)
throws DescriptorValidationException {
this.pool = pool;
this.proto = proto;
this.dependencies = dependencies.clone();
HashMap<String, FileDescriptor> nameToFileMap = new HashMap<>();
for (FileDescriptor file : dependencies) {
nameToFileMap.put(file.getName(), file);
}
List<FileDescriptor> publicDependencies = new ArrayList<>();
for (int i = 0; i < proto.getPublicDependencyCount(); i++) {
int index = proto.getPublicDependency(i);
if (index < 0 || index >= proto.getDependencyCount()) {
throw new DescriptorValidationException(this, "Invalid public dependency index.");
}
String name = proto.getDependency(index);
FileDescriptor file = nameToFileMap.get(name);
if (file == null) {
if (!allowUnknownDependencies) {
throw new DescriptorValidationException(this, "Invalid public dependency: " + name);
}
// Ignore unknown dependencies.
} else {
publicDependencies.add(file);
}
}
this.publicDependencies = new FileDescriptor[publicDependencies.size()];
publicDependencies.toArray(this.publicDependencies);
pool.addPackage(getPackage(), this);
messageTypes =
(proto.getMessageTypeCount() > 0)
? new Descriptor[proto.getMessageTypeCount()]
: EMPTY_DESCRIPTORS;
for (int i = 0; i < proto.getMessageTypeCount(); i++) {
messageTypes[i] = new Descriptor(proto.getMessageType(i), this, null, i);
}
enumTypes =
(proto.getEnumTypeCount() > 0)
? new EnumDescriptor[proto.getEnumTypeCount()]
: EMPTY_ENUM_DESCRIPTORS;
for (int i = 0; i < proto.getEnumTypeCount(); i++) {
enumTypes[i] = new EnumDescriptor(proto.getEnumType(i), this, null, i);
}
services =
(proto.getServiceCount() > 0)
? new ServiceDescriptor[proto.getServiceCount()]
: EMPTY_SERVICE_DESCRIPTORS;
for (int i = 0; i < proto.getServiceCount(); i++) {
services[i] = new ServiceDescriptor(proto.getService(i), this, i);
}
extensions =
(proto.getExtensionCount() > 0)
? new FieldDescriptor[proto.getExtensionCount()]
: EMPTY_FIELD_DESCRIPTORS;
for (int i = 0; i < proto.getExtensionCount(); i++) {
extensions[i] = new FieldDescriptor(proto.getExtension(i), this, null, i, true);
}
}
/** Create a placeholder FileDescriptor for a message Descriptor. */
FileDescriptor(String packageName, Descriptor message) throws DescriptorValidationException {
this.parent = null;
this.pool = new DescriptorPool(new FileDescriptor[0], true);
this.proto =
FileDescriptorProto.newBuilder()
.setName(message.getFullName() + ".placeholder.proto")
.setPackage(packageName)
.addMessageType(message.toProto())
.build();
this.dependencies = new FileDescriptor[0];
this.publicDependencies = new FileDescriptor[0];
messageTypes = new Descriptor[] {message};
enumTypes = EMPTY_ENUM_DESCRIPTORS;
services = EMPTY_SERVICE_DESCRIPTORS;
extensions = EMPTY_FIELD_DESCRIPTORS;
pool.addPackage(packageName, this);
pool.addSymbol(message);
}
public void resolveAllFeaturesImmutable() {
try {
resolveAllFeaturesInternal();
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException("Invalid features for \"" + proto.getName() + "\".", e);
}
}
/**
* This method is to be called by generated code only. It resolves features for the descriptor
* and all of its children.
*/
private void resolveAllFeaturesInternal() throws DescriptorValidationException {
if (this.features != null) {
return;
}
synchronized (this) {
if (this.features != null) {
return;
}
resolveFeatures(proto.getOptions().getFeatures());
for (Descriptor messageType : messageTypes) {
messageType.resolveAllFeatures();
}
for (EnumDescriptor enumType : enumTypes) {
enumType.resolveAllFeatures();
}
for (ServiceDescriptor service : services) {
service.resolveAllFeatures();
}
for (FieldDescriptor extension : extensions) {
extension.resolveAllFeatures();
}
}
}
@Override
FeatureSet inferLegacyProtoFeatures() {
FeatureSet.Builder features = FeatureSet.newBuilder();
if (getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) {
return features.build();
}
if (getEdition() == Edition.EDITION_PROTO2) {
if (proto.getOptions().getJavaStringCheckUtf8()) {
features.setExtension(
JavaFeaturesProto.java_,
JavaFeatures.newBuilder()
.setUtf8Validation(JavaFeatures.Utf8Validation.VERIFY)
.build());
}
}
return features.build();
}
@Override
boolean hasInferredLegacyProtoFeatures() {
if (getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) {
return false;
}
if (getEdition() == Edition.EDITION_PROTO2) {
if (proto.getOptions().getJavaStringCheckUtf8()) {
return true;
}
}
return false;
}
/** Look up and cross-link all field types, etc. */
private void crossLink() throws DescriptorValidationException {
for (final Descriptor messageType : messageTypes) {
messageType.crossLink();
}
for (final ServiceDescriptor service : services) {
service.crossLink();
}
for (final FieldDescriptor extension : extensions) {
extension.crossLink();
}
}
/**
* Replace our {@link FileDescriptorProto} with the given one, which is identical except that it
* might contain extensions that weren't present in the original. This method is needed for
* bootstrapping when a file defines custom options. The options may be defined in the file
* itself, so we can't actually parse them until we've constructed the descriptors, but to
* construct the descriptors we have to have parsed the descriptor protos. So, we have to parse
* the descriptor protos a second time after constructing the descriptors.
*/
private synchronized void setProto(final FileDescriptorProto proto) {
this.proto = proto;
this.options = null;
try {
resolveFeatures(proto.getOptions().getFeatures());
for (int i = 0; i < messageTypes.length; i++) {
messageTypes[i].setProto(proto.getMessageType(i));
}
for (int i = 0; i < enumTypes.length; i++) {
enumTypes[i].setProto(proto.getEnumType(i));
}
for (int i = 0; i < services.length; i++) {
services[i].setProto(proto.getService(i));
}
for (int i = 0; i < extensions.length; i++) {
extensions[i].setProto(proto.getExtension(i));
}
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException("Invalid features for \"" + proto.getName() + "\".", e);
}
}
}
// =================================================================
/** Describes a message type. */
public static final class Descriptor extends GenericDescriptor {
/**
* Get the index of this descriptor within its parent. In other words, given a {@link
* FileDescriptor} {@code file}, the following is true:
*
* <pre>
* for all i in [0, file.getMessageTypeCount()):
* file.getMessageType(i).getIndex() == i
* </pre>
*
* Similarly, for a {@link Descriptor} {@code messageType}:
*
* <pre>
* for all i in [0, messageType.getNestedTypeCount()):
* messageType.getNestedType(i).getIndex() == i
* </pre>
*/
public int getIndex() {
return index;
}
/** Convert the descriptor to its protocol message representation. */
@Override
public DescriptorProto toProto() {
return proto;
}
/** Get the type's unqualified name. */
@Override
public String getName() {
return proto.getName();
}
/**
* Get the type's fully-qualified name, within the proto language's namespace. This differs from
* the Java name. For example, given this {@code .proto}:
*
* <pre>
* package foo.bar;
* option java_package = "com.example.protos"
* message Baz {}
* </pre>
*
* {@code Baz}'s full name is "foo.bar.Baz".
*/
@Override
public String getFullName() {
return fullName;
}
/** Get the {@link FileDescriptor} containing this descriptor. */
@Override
public FileDescriptor getFile() {
return file;
}
/** If this is a nested type, get the outer descriptor, otherwise null. */
public Descriptor getContainingType() {
return containingType;
}
/** Get the {@code MessageOptions}, defined in {@code descriptor.proto}. */
public MessageOptions getOptions() {
if (this.options == null) {
MessageOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Get a list of this message type's fields. */
public List<FieldDescriptor> getFields() {
return Collections.unmodifiableList(Arrays.asList(fields));
}
/** Get a list of this message type's oneofs. */
public List<OneofDescriptor> getOneofs() {
return Collections.unmodifiableList(Arrays.asList(oneofs));
}
/** Get a list of this message type's real oneofs. */
public List<OneofDescriptor> getRealOneofs() {
return Collections.unmodifiableList(Arrays.asList(oneofs).subList(0, realOneofCount));
}
/** Get a list of this message type's extensions. */
public List<FieldDescriptor> getExtensions() {
return Collections.unmodifiableList(Arrays.asList(extensions));
}
/** Get a list of message types nested within this one. */
public List<Descriptor> getNestedTypes() {
return Collections.unmodifiableList(Arrays.asList(nestedTypes));
}
/** Get a list of enum types nested within this one. */
public List<EnumDescriptor> getEnumTypes() {
return Collections.unmodifiableList(Arrays.asList(enumTypes));
}
/** Determines if the given field number is an extension. */
public boolean isExtensionNumber(final int number) {
int index = Arrays.binarySearch(extensionRangeLowerBounds, number);
if (index < 0) {
index = ~index - 1;
}
// extensionRangeLowerBounds[index] is the biggest value <= number
return index >= 0 && number < extensionRangeUpperBounds[index];
}
/** Determines if the given field number is reserved. */
public boolean isReservedNumber(final int number) {
for (final DescriptorProto.ReservedRange range : proto.getReservedRangeList()) {
if (range.getStart() <= number && number < range.getEnd()) {
return true;
}
}
return false;
}
/** Determines if the given field name is reserved. */
public boolean isReservedName(final String name) {
checkNotNull(name);
for (final String reservedName : proto.getReservedNameList()) {
if (reservedName.equals(name)) {
return true;
}
}
return false;
}
/**
* Indicates whether the message can be extended. That is, whether it has any "extensions x to
* y" ranges declared on it.
*/
public boolean isExtendable() {
return !proto.getExtensionRangeList().isEmpty();
}
/**
* Finds a field by name.
*
* @param name The unqualified name of the field (e.g. "foo"). For protocol buffer messages that
* follow <a
* href=https://developers.google.com/protocol-buffers/docs/style#message_and_field_names>Google's
* guidance on naming</a> this will be a snake case string, such as
* <pre>song_name</pre>
* .
* @return The field's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findFieldByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof FieldDescriptor) {
return (FieldDescriptor) result;
} else {
return null;
}
}
/**
* Finds a field by field number.
*
* @param number The field number within this message type.
* @return The field's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findFieldByNumber(final int number) {
return binarySearch(
fieldsSortedByNumber, fieldsSortedByNumber.length, FieldDescriptor.NUMBER_GETTER, number);
}
/**
* Finds a nested message type by name.
*
* @param name The unqualified name of the nested type such as "Foo"
* @return The types's descriptor, or {@code null} if not found.
*/
public Descriptor findNestedTypeByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof Descriptor) {
return (Descriptor) result;
} else {
return null;
}
}
/**
* Finds a nested enum type by name.
*
* @param name The unqualified name of the nested type such as "Foo"
* @return The types's descriptor, or {@code null} if not found.
*/
public EnumDescriptor findEnumTypeByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof EnumDescriptor) {
return (EnumDescriptor) result;
} else {
return null;
}
}
private final int index;
private DescriptorProto proto;
private volatile MessageOptions options;
private final String fullName;
private final FileDescriptor file;
private final Descriptor containingType;
private final Descriptor[] nestedTypes;
private final EnumDescriptor[] enumTypes;
private final FieldDescriptor[] fields;
private final FieldDescriptor[] fieldsSortedByNumber;
private final FieldDescriptor[] extensions;
private final OneofDescriptor[] oneofs;
private final int realOneofCount;
private final int[] extensionRangeLowerBounds;
private final int[] extensionRangeUpperBounds;
// Used to create a placeholder when the type cannot be found.
Descriptor(final String fullname) throws DescriptorValidationException {
String name = fullname;
String packageName = "";
int pos = fullname.lastIndexOf('.');
if (pos != -1) {
name = fullname.substring(pos + 1);
packageName = fullname.substring(0, pos);
}
this.index = 0;
this.proto =
DescriptorProto.newBuilder()
.setName(name)
.addExtensionRange(
DescriptorProto.ExtensionRange.newBuilder().setStart(1).setEnd(536870912).build())
.build();
this.fullName = fullname;
this.containingType = null;
this.nestedTypes = EMPTY_DESCRIPTORS;
this.enumTypes = EMPTY_ENUM_DESCRIPTORS;
this.fields = EMPTY_FIELD_DESCRIPTORS;
this.fieldsSortedByNumber = EMPTY_FIELD_DESCRIPTORS;
this.extensions = EMPTY_FIELD_DESCRIPTORS;
this.oneofs = EMPTY_ONEOF_DESCRIPTORS;
this.realOneofCount = 0;
// Create a placeholder FileDescriptor to hold this message.
this.file = new FileDescriptor(packageName, this);
this.parent = this.file;
extensionRangeLowerBounds = new int[] {1};
extensionRangeUpperBounds = new int[] {536870912};
}
private Descriptor(
final DescriptorProto proto,
final FileDescriptor file,
final Descriptor parent,
final int index)
throws DescriptorValidationException {
if (parent == null) {
this.parent = file;
} else {
this.parent = parent;
}
this.index = index;
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
this.file = file;
containingType = parent;
oneofs =
(proto.getOneofDeclCount() > 0)
? new OneofDescriptor[proto.getOneofDeclCount()]
: EMPTY_ONEOF_DESCRIPTORS;
for (int i = 0; i < proto.getOneofDeclCount(); i++) {
oneofs[i] = new OneofDescriptor(proto.getOneofDecl(i), file, this, i);
}
nestedTypes =
(proto.getNestedTypeCount() > 0)
? new Descriptor[proto.getNestedTypeCount()]
: EMPTY_DESCRIPTORS;
for (int i = 0; i < proto.getNestedTypeCount(); i++) {
nestedTypes[i] = new Descriptor(proto.getNestedType(i), file, this, i);
}
enumTypes =
(proto.getEnumTypeCount() > 0)
? new EnumDescriptor[proto.getEnumTypeCount()]
: EMPTY_ENUM_DESCRIPTORS;
for (int i = 0; i < proto.getEnumTypeCount(); i++) {
enumTypes[i] = new EnumDescriptor(proto.getEnumType(i), file, this, i);
}
fields =
(proto.getFieldCount() > 0)
? new FieldDescriptor[proto.getFieldCount()]
: EMPTY_FIELD_DESCRIPTORS;
for (int i = 0; i < proto.getFieldCount(); i++) {
fields[i] = new FieldDescriptor(proto.getField(i), file, this, i, false);
}
this.fieldsSortedByNumber =
(proto.getFieldCount() > 0) ? fields.clone() : EMPTY_FIELD_DESCRIPTORS;
extensions =
(proto.getExtensionCount() > 0)
? new FieldDescriptor[proto.getExtensionCount()]
: EMPTY_FIELD_DESCRIPTORS;
for (int i = 0; i < proto.getExtensionCount(); i++) {
extensions[i] = new FieldDescriptor(proto.getExtension(i), file, this, i, true);
}
for (int i = 0; i < proto.getOneofDeclCount(); i++) {
oneofs[i].fields = new FieldDescriptor[oneofs[i].getFieldCount()];
oneofs[i].fieldCount = 0;
}
for (int i = 0; i < proto.getFieldCount(); i++) {
OneofDescriptor oneofDescriptor = fields[i].getContainingOneof();
if (oneofDescriptor != null) {
oneofDescriptor.fields[oneofDescriptor.fieldCount++] = fields[i];
}
}
int syntheticOneofCount = 0;
for (OneofDescriptor oneof : this.oneofs) {
if (oneof.isSynthetic()) {
syntheticOneofCount++;
} else {
if (syntheticOneofCount > 0) {
throw new DescriptorValidationException(this, "Synthetic oneofs must come last.");
}
}
}
this.realOneofCount = this.oneofs.length - syntheticOneofCount;
file.pool.addSymbol(this);
// NOTE: The defined extension ranges are guaranteed to be disjoint.
if (proto.getExtensionRangeCount() > 0) {
extensionRangeLowerBounds = new int[proto.getExtensionRangeCount()];
extensionRangeUpperBounds = new int[proto.getExtensionRangeCount()];
int i = 0;
for (final DescriptorProto.ExtensionRange range : proto.getExtensionRangeList()) {
extensionRangeLowerBounds[i] = range.getStart();
extensionRangeUpperBounds[i] = range.getEnd();
i++;
}
// Since the ranges are disjoint, sorting these independently must still produce the correct
// order.
Arrays.sort(extensionRangeLowerBounds);
Arrays.sort(extensionRangeUpperBounds);
} else {
extensionRangeLowerBounds = EMPTY_INT_ARRAY;
extensionRangeUpperBounds = EMPTY_INT_ARRAY;
}
}
/** See {@link FileDescriptor#resolveAllFeatures}. */
private void resolveAllFeatures() throws DescriptorValidationException {
resolveFeatures(proto.getOptions().getFeatures());
for (Descriptor nestedType : nestedTypes) {
nestedType.resolveAllFeatures();
}
for (EnumDescriptor enumType : enumTypes) {
enumType.resolveAllFeatures();
}
// Oneofs must be resolved before any children oneof fields.
for (OneofDescriptor oneof : oneofs) {
oneof.resolveAllFeatures();
}
for (FieldDescriptor field : fields) {
field.resolveAllFeatures();
}
for (FieldDescriptor extension : extensions) {
extension.resolveAllFeatures();
}
}
/** Look up and cross-link all field types, etc. */
private void crossLink() throws DescriptorValidationException {
for (final Descriptor nestedType : nestedTypes) {
nestedType.crossLink();
}
for (final FieldDescriptor field : fields) {
field.crossLink();
}
Arrays.sort(fieldsSortedByNumber);
validateNoDuplicateFieldNumbers();
for (final FieldDescriptor extension : extensions) {
extension.crossLink();
}
}
private void validateNoDuplicateFieldNumbers() throws DescriptorValidationException {
for (int i = 0; i + 1 < fieldsSortedByNumber.length; i++) {
FieldDescriptor old = fieldsSortedByNumber[i];
FieldDescriptor field = fieldsSortedByNumber[i + 1];
if (old.getNumber() == field.getNumber()) {
throw new DescriptorValidationException(
field,
"Field number "
+ field.getNumber()
+ " has already been used in \""
+ field.getContainingType().getFullName()
+ "\" by field \""
+ old.getName()
+ "\".");
}
}
}
/** See {@link FileDescriptor#setProto}. */
private void setProto(final DescriptorProto proto) throws DescriptorValidationException {
this.proto = proto;
this.options = null;
resolveFeatures(proto.getOptions().getFeatures());
for (int i = 0; i < nestedTypes.length; i++) {
nestedTypes[i].setProto(proto.getNestedType(i));
}
for (int i = 0; i < oneofs.length; i++) {
oneofs[i].setProto(proto.getOneofDecl(i));
}
for (int i = 0; i < enumTypes.length; i++) {
enumTypes[i].setProto(proto.getEnumType(i));
}
for (int i = 0; i < fields.length; i++) {
fields[i].setProto(proto.getField(i));
}
for (int i = 0; i < extensions.length; i++) {
extensions[i].setProto(proto.getExtension(i));
}
}
}
// =================================================================
/** Describes a field of a message type. */
public static final class FieldDescriptor extends GenericDescriptor
implements Comparable<FieldDescriptor>, FieldSet.FieldDescriptorLite<FieldDescriptor> {
private static final NumberGetter<FieldDescriptor> NUMBER_GETTER =
new NumberGetter<FieldDescriptor>() {
@Override
public int getNumber(FieldDescriptor fieldDescriptor) {
return fieldDescriptor.getNumber();
}
};
/**
* Get the index of this descriptor within its parent.
*
* @see Descriptors.Descriptor#getIndex()
*/
public int getIndex() {
return index;
}
/** Convert the descriptor to its protocol message representation. */
@Override
public FieldDescriptorProto toProto() {
return proto;
}
/** Get the field's unqualified name. */
@Override
public String getName() {
return proto.getName();
}
/** Get the field's number. */
@Override
public int getNumber() {
return proto.getNumber();
}
/**
* Get the field's fully-qualified name.
*
* @see Descriptors.Descriptor#getFullName()
*/
@Override
public String getFullName() {
return fullName;
}
/** Get the JSON name of this field. */
public String getJsonName() {
String result = jsonName;
if (result != null) {
return result;
} else if (proto.hasJsonName()) {
return jsonName = proto.getJsonName();
} else {
return jsonName = fieldNameToJsonName(proto.getName());
}
}
/**
* Get the field's java type. This is just for convenience. Every {@code
* FieldDescriptorProto.Type} maps to exactly one Java type.
*/
public JavaType getJavaType() {
return getType().getJavaType();
}
/** For internal use only. */
@Override
public WireFormat.JavaType getLiteJavaType() {
return getLiteType().getJavaType();
}
/** Get the {@code FileDescriptor} containing this descriptor. */
@Override
public FileDescriptor getFile() {
return file;
}
/** Get the field's declared type. */
public Type getType() {
// Override delimited messages as legacy group type. Leaves unresolved messages as-is
// since these are used before feature resolution when parsing java feature set defaults
// (custom options) into unknown fields.
if (type == Type.MESSAGE
&& this.features != null
&& this.features.getMessageEncoding() == FeatureSet.MessageEncoding.DELIMITED) {
return Type.GROUP;
}
return type;
}
/** For internal use only. */
@Override
public WireFormat.FieldType getLiteType() {
return table[getType().ordinal()];
}
/** For internal use only. */
public boolean needsUtf8Check() {
if (getType() != Type.STRING) {
return false;
}
if (getContainingType().toProto().getOptions().getMapEntry()) {
// Always enforce strict UTF-8 checking for map fields.
return true;
}
if (this.features
.getExtension(JavaFeaturesProto.java_)
.getUtf8Validation()
.equals(JavaFeatures.Utf8Validation.VERIFY)) {
return true;
}
return this.features.getUtf8Validation().equals(FeatureSet.Utf8Validation.VERIFY);
}
public boolean isMapField() {
return getType() == Type.MESSAGE
&& isRepeated()
&& getMessageType().toProto().getOptions().getMapEntry();
}
// I'm pretty sure values() constructs a new array every time, since there
// is nothing stopping the caller from mutating the array. Therefore we
// make a static copy here.
private static final WireFormat.FieldType[] table = WireFormat.FieldType.values();
/** Is this field declared required? */
public boolean isRequired() {
return this.features.getFieldPresence()
== DescriptorProtos.FeatureSet.FieldPresence.LEGACY_REQUIRED;
}
/** Is this field declared optional? */
public boolean isOptional() {
return proto.getLabel() == FieldDescriptorProto.Label.LABEL_OPTIONAL
&& this.features.getFieldPresence()
!= DescriptorProtos.FeatureSet.FieldPresence.LEGACY_REQUIRED;
}
/** Is this field declared repeated? */
@Override
public boolean isRepeated() {
return proto.getLabel() == FieldDescriptorProto.Label.LABEL_REPEATED;
}
/**
* Does this field have the {@code [packed = true]} option or is this field packable in proto3
* and not explicitly set to unpacked?
*/
@Override
public boolean isPacked() {
if (!isPackable()) {
return false;
}
return this.features
.getRepeatedFieldEncoding()
.equals(FeatureSet.RepeatedFieldEncoding.PACKED);
}
/** Can this field be packed? That is, is it a repeated primitive field? */
public boolean isPackable() {
return isRepeated() && getLiteType().isPackable();
}
/** Returns true if the field had an explicitly-defined default value. */
public boolean hasDefaultValue() {
return proto.hasDefaultValue();
}
/**
* Returns the field's default value. Valid for all types except for messages and groups. For
* all other types, the object returned is of the same class that would returned by
* Message.getField(this).
*/
public Object getDefaultValue() {
if (getJavaType() == JavaType.MESSAGE) {
throw new UnsupportedOperationException(
"FieldDescriptor.getDefaultValue() called on an embedded message field.");
}
return defaultValue;
}
/** Get the {@code FieldOptions}, defined in {@code descriptor.proto}. */
public FieldOptions getOptions() {
if (this.options == null) {
FieldOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Is this field an extension? */
public boolean isExtension() {
return proto.hasExtendee();
}
/**
* Get the field's containing type. For extensions, this is the type being extended, not the
* location where the extension was defined. See {@link #getExtensionScope()}.
*/
public Descriptor getContainingType() {
return containingType;
}
/** Get the field's containing oneof. */
public OneofDescriptor getContainingOneof() {
return containingOneof;
}
/** Get the field's containing oneof, only if non-synthetic. */
public OneofDescriptor getRealContainingOneof() {
return containingOneof != null && !containingOneof.isSynthetic() ? containingOneof : null;
}
/**
* Returns true if this field was syntactically written with "optional" in the .proto file.
* Excludes singular proto3 fields that do not have a label.
*/
boolean hasOptionalKeyword() {
return isProto3Optional
|| (file.getEdition() == Edition.EDITION_PROTO2
&& isOptional()
&& getContainingOneof() == null);
}
/**
* Returns true if this field tracks presence, ie. does the field distinguish between "unset"
* and "present with default value."
*
* <p>This includes required, optional, and oneof fields. It excludes maps, repeated fields, and
* singular proto3 fields without "optional".
*
* <p>For fields where hasPresence() == true, the return value of msg.hasField() is semantically
* meaningful.
*/
public boolean hasPresence() {
if (isRepeated()) {
return false;
}
return isProto3Optional
|| getType() == Type.MESSAGE
|| getType() == Type.GROUP
|| isExtension()
|| getContainingOneof() != null
|| this.features.getFieldPresence() != DescriptorProtos.FeatureSet.FieldPresence.IMPLICIT;
}
/**
* Returns true if this field is structured like the synthetic field of a proto2 group. This
* allows us to expand our treatment of delimited fields without breaking proto2 files that have
* been upgraded to editions.
*/
boolean isGroupLike() {
if (features.getMessageEncoding() != DescriptorProtos.FeatureSet.MessageEncoding.DELIMITED) {
// Groups are always tag-delimited.
return false;
}
if (!getMessageType().getName().toLowerCase().equals(getName())) {
// Group fields always are always the lowercase type name.
return false;
}
if (getMessageType().getFile() != getFile()) {
// Groups could only be defined in the same file they're used.
return false;
}
// Group messages are always defined in the same scope as the field. File level extensions
// will compare NULL == NULL here, which is why the file comparison above is necessary to
// ensure both come from the same file.
return isExtension()
? getMessageType().getContainingType() == getExtensionScope()
: getMessageType().getContainingType() == getContainingType();
}
/**
* For extensions defined nested within message types, gets the outer type. Not valid for
* non-extension fields. For example, consider this {@code .proto} file:
*
* <pre>
* message Foo {
* extensions 1000 to max;
* }
* extend Foo {
* optional int32 baz = 1234;
* }
* message Bar {
* extend Foo {
* optional int32 moo = 4321;
* }
* }
* </pre>
*
* Both {@code baz}'s and {@code moo}'s containing type is {@code Foo}. However, {@code baz}'s
* extension scope is {@code null} while {@code moo}'s extension scope is {@code Bar}.
*/
public Descriptor getExtensionScope() {
if (!isExtension()) {
throw new UnsupportedOperationException(
String.format("This field is not an extension. (%s)", fullName));
}
return extensionScope;
}
/** For embedded message and group fields, gets the field's type. */
public Descriptor getMessageType() {
if (getJavaType() != JavaType.MESSAGE) {
throw new UnsupportedOperationException(
String.format("This field is not of message type. (%s)", fullName));
}
return messageType;
}
/** For enum fields, gets the field's type. */
@Override
public EnumDescriptor getEnumType() {
if (getJavaType() != JavaType.ENUM) {
throw new UnsupportedOperationException(
String.format("This field is not of enum type. (%s)", fullName));
}
return enumType;
}
/**
* Determines if the given enum field is treated as closed based on legacy non-conformant
* behavior.
*
* <p>Conformant behavior determines closedness based on the enum and can be queried using
* {@code EnumDescriptor.isClosed()}.
*
* <p>Some runtimes currently have a quirk where non-closed enums are treated as closed when
* used as the type of fields defined in a `syntax = proto2;` file. This quirk is not present in
* all runtimes; as of writing, we know that:
*
* <ul>
* <li>C++, Java, and C++-based Python share this quirk.
* <li>UPB and UPB-based Python do not.
* <li>PHP and Ruby treat all enums as open regardless of declaration.
* </ul>
*
* <p>Care should be taken when using this function to respect the target runtime's enum
* handling quirks.
*/
public boolean legacyEnumFieldTreatedAsClosed() {
// Don't check JavaFeaturesProto extension for files without dependencies.
// This is especially important for descriptor.proto since getting the JavaFeaturesProto
// extension itself involves calling legacyEnumFieldTreatedAsClosed() which would otherwise
// infinite loop.
if (getFile().getDependencies().isEmpty()) {
return getType() == Type.ENUM && enumType.isClosed();
}
return getType() == Type.ENUM
&& (this.features.getExtension(JavaFeaturesProto.java_).getLegacyClosedEnum()
|| enumType.isClosed());
}
/**
* Compare with another {@code FieldDescriptor}. This orders fields in "canonical" order, which
* simply means ascending order by field number. {@code other} must be a field of the same type.
* That is, {@code getContainingType()} must return the same {@code Descriptor} for both fields.
*
* @return negative, zero, or positive if {@code this} is less than, equal to, or greater than
* {@code other}, respectively
*/
@Override
public int compareTo(final FieldDescriptor other) {
if (other.containingType != containingType) {
throw new IllegalArgumentException(
"FieldDescriptors can only be compared to other FieldDescriptors "
+ "for fields of the same message type.");
}
return getNumber() - other.getNumber();
}
@Override
public String toString() {
return getFullName();
}
private final int index;
private FieldDescriptorProto proto;
private volatile FieldOptions options;
private final String fullName;
private String jsonName;
private final FileDescriptor file;
private final Descriptor extensionScope;
private final boolean isProto3Optional;
// Possibly initialized during cross-linking.
private Type type;
private Descriptor containingType;
private Descriptor messageType;
private OneofDescriptor containingOneof;
private EnumDescriptor enumType;
private Object defaultValue;
public enum Type {
DOUBLE(JavaType.DOUBLE),
FLOAT(JavaType.FLOAT),
INT64(JavaType.LONG),
UINT64(JavaType.LONG),
INT32(JavaType.INT),
FIXED64(JavaType.LONG),
FIXED32(JavaType.INT),
BOOL(JavaType.BOOLEAN),
STRING(JavaType.STRING),
GROUP(JavaType.MESSAGE),
MESSAGE(JavaType.MESSAGE),
BYTES(JavaType.BYTE_STRING),
UINT32(JavaType.INT),
ENUM(JavaType.ENUM),
SFIXED32(JavaType.INT),
SFIXED64(JavaType.LONG),
SINT32(JavaType.INT),
SINT64(JavaType.LONG);
// Private copy to avoid repeated allocations from calls to values() in valueOf().
private static final Type[] types = values();
Type(JavaType javaType) {
this.javaType = javaType;
}
private final JavaType javaType;
public FieldDescriptorProto.Type toProto() {
return FieldDescriptorProto.Type.forNumber(ordinal() + 1);
}
public JavaType getJavaType() {
return javaType;
}
public static Type valueOf(final FieldDescriptorProto.Type type) {
return types[type.getNumber() - 1];
}
}
static {
// Refuse to init if someone added a new declared type.
if (Type.types.length != FieldDescriptorProto.Type.values().length) {
throw new RuntimeException(
"descriptor.proto has a new declared type but Descriptors.java wasn't updated.");
}
}
public enum JavaType {
INT(0),
LONG(0L),
FLOAT(0F),
DOUBLE(0D),
BOOLEAN(false),
STRING(""),
BYTE_STRING(ByteString.EMPTY),
ENUM(null),
MESSAGE(null);
JavaType(final Object defaultDefault) {
this.defaultDefault = defaultDefault;
}
/**
* The default default value for fields of this type, if it's a primitive type. This is meant
* for use inside this file only, hence is private.
*/
private final Object defaultDefault;
}
// This method should match exactly with the ToJsonName() function in C++
// descriptor.cc.
private static String fieldNameToJsonName(String name) {
final int length = name.length();
StringBuilder result = new StringBuilder(length);
boolean isNextUpperCase = false;
for (int i = 0; i < length; i++) {
char ch = name.charAt(i);
if (ch == '_') {
isNextUpperCase = true;
} else if (isNextUpperCase) {
// This closely matches the logic for ASCII characters in:
// http://google3/google/protobuf/descriptor.cc?l=249-251&rcl=228891689
if ('a' <= ch && ch <= 'z') {
ch = (char) (ch - 'a' + 'A');
}
result.append(ch);
isNextUpperCase = false;
} else {
result.append(ch);
}
}
return result.toString();
}
private FieldDescriptor(
final FieldDescriptorProto proto,
final FileDescriptor file,
final Descriptor parent,
final int index,
final boolean isExtension)
throws DescriptorValidationException {
this.parent = parent;
this.index = index;
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
this.file = file;
if (proto.hasType()) {
type = Type.valueOf(proto.getType());
}
isProto3Optional = proto.getProto3Optional();
if (getNumber() <= 0) {
throw new DescriptorValidationException(this, "Field numbers must be positive integers.");
}
if (isExtension) {
if (!proto.hasExtendee()) {
throw new DescriptorValidationException(
this, "FieldDescriptorProto.extendee not set for extension field.");
}
containingType = null; // Will be filled in when cross-linking
if (parent != null) {
extensionScope = parent;
} else {
extensionScope = null;
this.parent = file;
}
if (proto.hasOneofIndex()) {
throw new DescriptorValidationException(
this, "FieldDescriptorProto.oneof_index set for extension field.");
}
containingOneof = null;
} else {
if (proto.hasExtendee()) {
throw new DescriptorValidationException(
this, "FieldDescriptorProto.extendee set for non-extension field.");
}
containingType = parent;
if (proto.hasOneofIndex()) {
if (proto.getOneofIndex() < 0
|| proto.getOneofIndex() >= parent.toProto().getOneofDeclCount()) {
throw new DescriptorValidationException(
this,
"FieldDescriptorProto.oneof_index is out of range for type " + parent.getName());
}
containingOneof = parent.getOneofs().get(proto.getOneofIndex());
containingOneof.fieldCount++;
this.parent = containingOneof;
} else {
containingOneof = null;
}
extensionScope = null;
}
file.pool.addSymbol(this);
}
/** See {@link FileDescriptor#resolveAllFeatures}. */
private void resolveAllFeatures() throws DescriptorValidationException {
resolveFeatures(proto.getOptions().getFeatures());
}
@Override
FeatureSet inferLegacyProtoFeatures() {
FeatureSet.Builder features = FeatureSet.newBuilder();
if (getFile().getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) {
return features.build();
}
if (proto.getLabel() == FieldDescriptorProto.Label.LABEL_REQUIRED) {
features.setFieldPresence(FeatureSet.FieldPresence.LEGACY_REQUIRED);
}
if (proto.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
features.setMessageEncoding(FeatureSet.MessageEncoding.DELIMITED);
}
if (getFile().getEdition() == Edition.EDITION_PROTO2 && proto.getOptions().getPacked()) {
features.setRepeatedFieldEncoding(FeatureSet.RepeatedFieldEncoding.PACKED);
}
if (getFile().getEdition() == Edition.EDITION_PROTO3) {
if (proto.getOptions().hasPacked() && !proto.getOptions().getPacked()) {
features.setRepeatedFieldEncoding(FeatureSet.RepeatedFieldEncoding.EXPANDED);
}
}
return features.build();
}
@Override
boolean hasInferredLegacyProtoFeatures() {
if (getFile().getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) {
return false;
}
if (proto.getLabel() == FieldDescriptorProto.Label.LABEL_REQUIRED) {
return true;
}
if (proto.getType() == FieldDescriptorProto.Type.TYPE_GROUP) {
return true;
}
if (proto.getOptions().getPacked()) {
return true;
}
if (getFile().getEdition() == Edition.EDITION_PROTO3) {
if (proto.getOptions().hasPacked() && !proto.getOptions().getPacked()) {
return true;
}
}
return false;
}
@Override
void validateFeatures() throws DescriptorValidationException {
if (containingType != null
&& containingType.toProto().getOptions().getMessageSetWireFormat()) {
if (isExtension()) {
if (!isOptional() || getType() != Type.MESSAGE) {
throw new DescriptorValidationException(
this, "Extensions of MessageSets must be optional messages.");
}
}
}
}
/** Look up and cross-link all field types, etc. */
private void crossLink() throws DescriptorValidationException {
if (proto.hasExtendee()) {
final GenericDescriptor extendee =
file.pool.lookupSymbol(
proto.getExtendee(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!(extendee instanceof Descriptor)) {
throw new DescriptorValidationException(
this, '\"' + proto.getExtendee() + "\" is not a message type.");
}
containingType = (Descriptor) extendee;
if (!getContainingType().isExtensionNumber(getNumber())) {
throw new DescriptorValidationException(
this,
'\"'
+ getContainingType().getFullName()
+ "\" does not declare "
+ getNumber()
+ " as an extension number.");
}
}
if (proto.hasTypeName()) {
final GenericDescriptor typeDescriptor =
file.pool.lookupSymbol(
proto.getTypeName(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!proto.hasType()) {
// Choose field type based on symbol.
if (typeDescriptor instanceof Descriptor) {
type = Type.MESSAGE;
} else if (typeDescriptor instanceof EnumDescriptor) {
type = Type.ENUM;
} else {
throw new DescriptorValidationException(
this, '\"' + proto.getTypeName() + "\" is not a type.");
}
}
if (getJavaType() == JavaType.MESSAGE) {
if (!(typeDescriptor instanceof Descriptor)) {
throw new DescriptorValidationException(
this, '\"' + proto.getTypeName() + "\" is not a message type.");
}
messageType = (Descriptor) typeDescriptor;
if (proto.hasDefaultValue()) {
throw new DescriptorValidationException(this, "Messages can't have default values.");
}
} else if (getJavaType() == JavaType.ENUM) {
if (!(typeDescriptor instanceof EnumDescriptor)) {
throw new DescriptorValidationException(
this, '\"' + proto.getTypeName() + "\" is not an enum type.");
}
enumType = (EnumDescriptor) typeDescriptor;
} else {
throw new DescriptorValidationException(this, "Field with primitive type has type_name.");
}
} else {
if (getJavaType() == JavaType.MESSAGE || getJavaType() == JavaType.ENUM) {
throw new DescriptorValidationException(
this, "Field with message or enum type missing type_name.");
}
}
// Only repeated primitive fields may be packed.
if (proto.getOptions().getPacked() && !isPackable()) {
throw new DescriptorValidationException(
this, "[packed = true] can only be specified for repeated primitive fields.");
}
// We don't attempt to parse the default value until here because for
// enums we need the enum type's descriptor.
if (proto.hasDefaultValue()) {
if (isRepeated()) {
throw new DescriptorValidationException(
this, "Repeated fields cannot have default values.");
}
try {
switch (getType()) {
case INT32:
case SINT32:
case SFIXED32:
defaultValue = TextFormat.parseInt32(proto.getDefaultValue());
break;
case UINT32:
case FIXED32:
defaultValue = TextFormat.parseUInt32(proto.getDefaultValue());
break;
case INT64:
case SINT64:
case SFIXED64:
defaultValue = TextFormat.parseInt64(proto.getDefaultValue());
break;
case UINT64:
case FIXED64:
defaultValue = TextFormat.parseUInt64(proto.getDefaultValue());
break;
case FLOAT:
if (proto.getDefaultValue().equals("inf")) {
defaultValue = Float.POSITIVE_INFINITY;
} else if (proto.getDefaultValue().equals("-inf")) {
defaultValue = Float.NEGATIVE_INFINITY;
} else if (proto.getDefaultValue().equals("nan")) {
defaultValue = Float.NaN;
} else {
defaultValue = Float.valueOf(proto.getDefaultValue());
}
break;
case DOUBLE:
if (proto.getDefaultValue().equals("inf")) {
defaultValue = Double.POSITIVE_INFINITY;
} else if (proto.getDefaultValue().equals("-inf")) {
defaultValue = Double.NEGATIVE_INFINITY;
} else if (proto.getDefaultValue().equals("nan")) {
defaultValue = Double.NaN;
} else {
defaultValue = Double.valueOf(proto.getDefaultValue());
}
break;
case BOOL:
defaultValue = Boolean.valueOf(proto.getDefaultValue());
break;
case STRING:
defaultValue = proto.getDefaultValue();
break;
case BYTES:
try {
defaultValue = TextFormat.unescapeBytes(proto.getDefaultValue());
} catch (TextFormat.InvalidEscapeSequenceException e) {
throw new DescriptorValidationException(
this, "Couldn't parse default value: " + e.getMessage(), e);
}
break;
case ENUM:
defaultValue = enumType.findValueByName(proto.getDefaultValue());
if (defaultValue == null) {
throw new DescriptorValidationException(
this, "Unknown enum default value: \"" + proto.getDefaultValue() + '\"');
}
break;
case MESSAGE:
case GROUP:
throw new DescriptorValidationException(this, "Message type had default value.");
}
} catch (NumberFormatException e) {
throw new DescriptorValidationException(
this, "Could not parse default value: \"" + proto.getDefaultValue() + '\"', e);
}
} else {
// Determine the default default for this field.
if (isRepeated()) {
defaultValue = Collections.emptyList();
} else {
switch (getJavaType()) {
case ENUM:
// We guarantee elsewhere that an enum type always has at least
// one possible value.
defaultValue = enumType.getValues().get(0);
break;
case MESSAGE:
defaultValue = null;
break;
default:
defaultValue = getJavaType().defaultDefault;
break;
}
}
}
}
/** See {@link FileDescriptor#setProto}. */
private void setProto(final FieldDescriptorProto proto) throws DescriptorValidationException {
this.proto = proto;
this.options = null;
resolveFeatures(proto.getOptions().getFeatures());
}
/** For internal use only. This is to satisfy the FieldDescriptorLite interface. */
@Override
public MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from) {
// FieldDescriptors are only used with non-lite messages so we can just
// down-cast and call mergeFrom directly.
return ((Message.Builder) to).mergeFrom((Message) from);
}
}
// =================================================================
/** Describes an enum type. */
public static final class EnumDescriptor extends GenericDescriptor
implements Internal.EnumLiteMap<EnumValueDescriptor> {
/**
* Get the index of this descriptor within its parent.
*
* @see Descriptors.Descriptor#getIndex()
*/
public int getIndex() {
return index;
}
/** Convert the descriptor to its protocol message representation. */
@Override
public EnumDescriptorProto toProto() {
return proto;
}
/** Get the type's unqualified name. */
@Override
public String getName() {
return proto.getName();
}
/**
* Get the type's fully-qualified name.
*
* @see Descriptors.Descriptor#getFullName()
*/
@Override
public String getFullName() {
return fullName;
}
/** Get the {@link FileDescriptor} containing this descriptor. */
@Override
public FileDescriptor getFile() {
return file;
}
/**
* Determines if the given enum is closed.
*
* <p>Closed enum means that it:
*
* <ul>
* <li>Has a fixed set of values, rather than being equivalent to an int32.
* <li>Encountering values not in this set causes them to be treated as unknown fields.
* <li>The first value (i.e., the default) may be nonzero.
* </ul>
*
* <p>WARNING: Some runtimes currently have a quirk where non-closed enums are treated as closed
* when used as the type of fields defined in a `syntax = proto2;` file. This quirk is not
* present in all runtimes; as of writing, we know that:
*
* <ul>
* <li> C++, Java, and C++-based Python share this quirk.
* <li> UPB and UPB-based Python do not.
* <li> PHP and Ruby treat all enums as open regardless of declaration.
* </ul>
*
* <p>Care should be taken when using this function to respect the target runtime's enum
* handling quirks.
*/
public boolean isClosed() {
return this.features.getEnumType() == DescriptorProtos.FeatureSet.EnumType.CLOSED;
}
/** If this is a nested type, get the outer descriptor, otherwise null. */
public Descriptor getContainingType() {
return containingType;
}
/** Get the {@code EnumOptions}, defined in {@code descriptor.proto}. */
public EnumOptions getOptions() {
if (this.options == null) {
EnumOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Get a list of defined values for this enum. */
public List<EnumValueDescriptor> getValues() {
return Collections.unmodifiableList(Arrays.asList(values));
}
/** Determines if the given field number is reserved. */
public boolean isReservedNumber(final int number) {
for (final EnumDescriptorProto.EnumReservedRange range : proto.getReservedRangeList()) {
if (range.getStart() <= number && number <= range.getEnd()) {
return true;
}
}
return false;
}
/** Determines if the given field name is reserved. */
public boolean isReservedName(final String name) {
checkNotNull(name);
for (final String reservedName : proto.getReservedNameList()) {
if (reservedName.equals(name)) {
return true;
}
}
return false;
}
/**
* Find an enum value by name.
*
* @param name the unqualified name of the value such as "FOO"
* @return the value's descriptor, or {@code null} if not found
*/
public EnumValueDescriptor findValueByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof EnumValueDescriptor) {
return (EnumValueDescriptor) result;
} else {
return null;
}
}
/**
* Find an enum value by number. If multiple enum values have the same number, this returns the
* first defined value with that number.
*
* @param number The value's number.
* @return the value's descriptor, or {@code null} if not found.
*/
@Override
public EnumValueDescriptor findValueByNumber(final int number) {
return binarySearch(
valuesSortedByNumber, distinctNumbers, EnumValueDescriptor.NUMBER_GETTER, number);
}
private static class UnknownEnumValueReference extends WeakReference<EnumValueDescriptor> {
private final int number;
private UnknownEnumValueReference(int number, EnumValueDescriptor descriptor) {
super(descriptor);
this.number = number;
}
}
/**
* Get the enum value for a number. If no enum value has this number, construct an
* EnumValueDescriptor for it.
*/
public EnumValueDescriptor findValueByNumberCreatingIfUnknown(final int number) {
EnumValueDescriptor result = findValueByNumber(number);
if (result != null) {
return result;
}
// The number represents an unknown enum value.
synchronized (this) {
if (cleanupQueue == null) {
cleanupQueue = new ReferenceQueue<>();
unknownValues = new HashMap<>();
} else {
while (true) {
UnknownEnumValueReference toClean = (UnknownEnumValueReference) cleanupQueue.poll();
if (toClean == null) {
break;
}
unknownValues.remove(toClean.number);
}
}
// There are two ways we can be missing a value: it wasn't in the map, or the reference
// has been GC'd. (It may even have been GC'd since we cleaned up the references a few
// lines of code ago.) So get out the reference, if it's still present...
WeakReference<EnumValueDescriptor> reference = unknownValues.get(number);
result = (reference == null) ? null : reference.get();
if (result == null) {
result = new EnumValueDescriptor(this, number);
unknownValues.put(number, new UnknownEnumValueReference(number, result));
}
}
return result;
}
// Used in tests only.
int getUnknownEnumValueDescriptorCount() {
return unknownValues.size();
}
private final int index;
private EnumDescriptorProto proto;
private volatile EnumOptions options;
private final String fullName;
private final FileDescriptor file;
private final Descriptor containingType;
private final EnumValueDescriptor[] values;
private final EnumValueDescriptor[] valuesSortedByNumber;
private final int distinctNumbers;
private Map<Integer, WeakReference<EnumValueDescriptor>> unknownValues = null;
private ReferenceQueue<EnumValueDescriptor> cleanupQueue = null;
private EnumDescriptor(
final EnumDescriptorProto proto,
final FileDescriptor file,
final Descriptor parent,
final int index)
throws DescriptorValidationException {
if (parent == null) {
this.parent = file;
} else {
this.parent = parent;
}
this.index = index;
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
this.file = file;
containingType = parent;
if (proto.getValueCount() == 0) {
// We cannot allow enums with no values because this would mean there
// would be no valid default value for fields of this type.
throw new DescriptorValidationException(this, "Enums must contain at least one value.");
}
values = new EnumValueDescriptor[proto.getValueCount()];
for (int i = 0; i < proto.getValueCount(); i++) {
values[i] = new EnumValueDescriptor(proto.getValue(i), file, this, i);
}
valuesSortedByNumber = values.clone();
Arrays.sort(valuesSortedByNumber, EnumValueDescriptor.BY_NUMBER);
// deduplicate
int j = 0;
for (int i = 1; i < proto.getValueCount(); i++) {
EnumValueDescriptor oldValue = valuesSortedByNumber[j];
EnumValueDescriptor newValue = valuesSortedByNumber[i];
if (oldValue.getNumber() != newValue.getNumber()) {
valuesSortedByNumber[++j] = newValue;
}
}
this.distinctNumbers = j + 1;
Arrays.fill(valuesSortedByNumber, distinctNumbers, proto.getValueCount(), null);
file.pool.addSymbol(this);
}
/** See {@link FileDescriptor#resolveAllFeatures}. */
private void resolveAllFeatures() throws DescriptorValidationException {
resolveFeatures(proto.getOptions().getFeatures());
for (EnumValueDescriptor value : values) {
value.resolveAllFeatures();
}
}
/** See {@link FileDescriptor#setProto}. */
private void setProto(final EnumDescriptorProto proto) throws DescriptorValidationException {
this.proto = proto;
this.options = null;
resolveFeatures(proto.getOptions().getFeatures());
for (int i = 0; i < values.length; i++) {
values[i].setProto(proto.getValue(i));
}
}
}
// =================================================================
/**
* Describes one value within an enum type. Note that multiple defined values may have the same
* number. In generated Java code, all values with the same number after the first become aliases
* of the first. However, they still have independent EnumValueDescriptors.
*/
@SuppressWarnings("ShouldNotSubclass")
public static final class EnumValueDescriptor extends GenericDescriptor
implements Internal.EnumLite {
static final Comparator<EnumValueDescriptor> BY_NUMBER =
new Comparator<EnumValueDescriptor>() {
@Override
public int compare(EnumValueDescriptor o1, EnumValueDescriptor o2) {
return Integer.valueOf(o1.getNumber()).compareTo(o2.getNumber());
}
};
static final NumberGetter<EnumValueDescriptor> NUMBER_GETTER =
new NumberGetter<EnumValueDescriptor>() {
@Override
public int getNumber(EnumValueDescriptor enumValueDescriptor) {
return enumValueDescriptor.getNumber();
}
};
/**
* Get the index of this descriptor within its parent.
*
* @see Descriptors.Descriptor#getIndex()
*/
public int getIndex() {
return index;
}
/** Convert the descriptor to its protocol message representation. */
@Override
public EnumValueDescriptorProto toProto() {
return proto;
}
/** Get the value's unqualified name. */
@Override
public String getName() {
return proto.getName();
}
/** Get the value's number. */
@Override
public int getNumber() {
return proto.getNumber();
}
@Override
public String toString() {
return proto.getName();
}
/**
* Get the value's fully-qualified name.
*
* @see Descriptors.Descriptor#getFullName()
*/
@Override
public String getFullName() {
return fullName;
}
/** Get the {@link FileDescriptor} containing this descriptor. */
@Override
public FileDescriptor getFile() {
return type.file;
}
/** Get the value's enum type. */
public EnumDescriptor getType() {
return type;
}
/** Get the {@code EnumValueOptions}, defined in {@code descriptor.proto}. */
public EnumValueOptions getOptions() {
if (this.options == null) {
EnumValueOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
private final int index;
private EnumValueDescriptorProto proto;
private volatile EnumValueOptions options;
private final String fullName;
private final EnumDescriptor type;
private EnumValueDescriptor(
final EnumValueDescriptorProto proto,
final FileDescriptor file,
final EnumDescriptor parent,
final int index)
throws DescriptorValidationException {
this.parent = parent;
this.index = index;
this.proto = proto;
this.type = parent;
this.fullName = parent.getFullName() + '.' + proto.getName();
file.pool.addSymbol(this);
}
// Create an unknown enum value.
private EnumValueDescriptor(final EnumDescriptor parent, final Integer number) {
String name = "UNKNOWN_ENUM_VALUE_" + parent.getName() + "_" + number;
EnumValueDescriptorProto proto =
EnumValueDescriptorProto.newBuilder().setName(name).setNumber(number).build();
this.parent = parent;
this.index = -1;
this.proto = proto;
this.type = parent;
this.fullName = parent.getFullName() + '.' + proto.getName();
// Don't add this descriptor into pool.
}
/** See {@link FileDescriptor#resolveAllFeatures}. */
private void resolveAllFeatures() throws DescriptorValidationException {
resolveFeatures(proto.getOptions().getFeatures());
}
/** See {@link FileDescriptor#setProto}. */
private void setProto(final EnumValueDescriptorProto proto)
throws DescriptorValidationException {
this.proto = proto;
this.options = null;
resolveFeatures(proto.getOptions().getFeatures());
}
}
// =================================================================
/** Describes a service type. */
public static final class ServiceDescriptor extends GenericDescriptor {
/**
* Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex()
*/
public int getIndex() {
return index;
}
/** Convert the descriptor to its protocol message representation. */
@Override
public ServiceDescriptorProto toProto() {
return proto;
}
/** Get the type's unqualified name. */
@Override
public String getName() {
return proto.getName();
}
/**
* Get the type's fully-qualified name.
*
* @see Descriptors.Descriptor#getFullName()
*/
@Override
public String getFullName() {
return fullName;
}
/** Get the {@link FileDescriptor} containing this descriptor. */
@Override
public FileDescriptor getFile() {
return file;
}
/** Get the {@code ServiceOptions}, defined in {@code descriptor.proto}. */
public ServiceOptions getOptions() {
if (this.options == null) {
ServiceOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Get a list of methods for this service. */
public List<MethodDescriptor> getMethods() {
return Collections.unmodifiableList(Arrays.asList(methods));
}
/**
* Find a method by name.
*
* @param name the unqualified name of the method such as "Foo"
* @return the method's descriptor, or {@code null} if not found
*/
public MethodDescriptor findMethodByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof MethodDescriptor) {
return (MethodDescriptor) result;
} else {
return null;
}
}
private final int index;
private ServiceDescriptorProto proto;
private volatile ServiceOptions options;
private final String fullName;
private final FileDescriptor file;
private MethodDescriptor[] methods;
private ServiceDescriptor(
final ServiceDescriptorProto proto, final FileDescriptor file, final int index)
throws DescriptorValidationException {
this.parent = file;
this.index = index;
this.proto = proto;
fullName = computeFullName(file, null, proto.getName());
this.file = file;
methods = new MethodDescriptor[proto.getMethodCount()];
for (int i = 0; i < proto.getMethodCount(); i++) {
methods[i] = new MethodDescriptor(proto.getMethod(i), file, this, i);
}
file.pool.addSymbol(this);
}
/** See {@link FileDescriptor#resolveAllFeatures}. */
private void resolveAllFeatures() throws DescriptorValidationException {
resolveFeatures(proto.getOptions().getFeatures());
for (MethodDescriptor method : methods) {
method.resolveAllFeatures();
}
}
private void crossLink() throws DescriptorValidationException {
for (final MethodDescriptor method : methods) {
method.crossLink();
}
}
/** See {@link FileDescriptor#setProto}. */
private void setProto(final ServiceDescriptorProto proto) throws DescriptorValidationException {
this.proto = proto;
this.options = null;
resolveFeatures(proto.getOptions().getFeatures());
for (int i = 0; i < methods.length; i++) {
methods[i].setProto(proto.getMethod(i));
}
}
}
// =================================================================
/** Describes one method within a service type. */
public static final class MethodDescriptor extends GenericDescriptor {
/**
* Get the index of this descriptor within its parent. * @see Descriptors.Descriptor#getIndex()
*/
public int getIndex() {
return index;
}
/** Convert the descriptor to its protocol message representation. */
@Override
public MethodDescriptorProto toProto() {
return proto;
}
/** Get the method's unqualified name. */
@Override
public String getName() {
return proto.getName();
}
/**
* Get the method's fully-qualified name.
*
* @see Descriptors.Descriptor#getFullName()
*/
@Override
public String getFullName() {
return fullName;
}
/** Get the {@link FileDescriptor} containing this descriptor. */
@Override
public FileDescriptor getFile() {
return file;
}
/** Get the method's service type. */
public ServiceDescriptor getService() {
return service;
}
/** Get the method's input type. */
public Descriptor getInputType() {
return inputType;
}
/** Get the method's output type. */
public Descriptor getOutputType() {
return outputType;
}
/** Get whether or not the inputs are streaming. */
public boolean isClientStreaming() {
return proto.getClientStreaming();
}
/** Get whether or not the outputs are streaming. */
public boolean isServerStreaming() {
return proto.getServerStreaming();
}
/** Get the {@code MethodOptions}, defined in {@code descriptor.proto}. */
public MethodOptions getOptions() {
if (this.options == null) {
MethodOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
private final int index;
private MethodDescriptorProto proto;
private volatile MethodOptions options;
private final String fullName;
private final FileDescriptor file;
private final ServiceDescriptor service;
// Initialized during cross-linking.
private Descriptor inputType;
private Descriptor outputType;
private MethodDescriptor(
final MethodDescriptorProto proto,
final FileDescriptor file,
final ServiceDescriptor parent,
final int index)
throws DescriptorValidationException {
this.parent = parent;
this.index = index;
this.proto = proto;
this.file = file;
service = parent;
fullName = parent.getFullName() + '.' + proto.getName();
file.pool.addSymbol(this);
}
/** See {@link FileDescriptor#resolveAllFeatures}. */
private void resolveAllFeatures() throws DescriptorValidationException {
resolveFeatures(proto.getOptions().getFeatures());
}
private void crossLink() throws DescriptorValidationException {
final GenericDescriptor input =
getFile()
.pool
.lookupSymbol(proto.getInputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!(input instanceof Descriptor)) {
throw new DescriptorValidationException(
this, '\"' + proto.getInputType() + "\" is not a message type.");
}
inputType = (Descriptor) input;
final GenericDescriptor output =
getFile()
.pool
.lookupSymbol(proto.getOutputType(), this, DescriptorPool.SearchFilter.TYPES_ONLY);
if (!(output instanceof Descriptor)) {
throw new DescriptorValidationException(
this, '\"' + proto.getOutputType() + "\" is not a message type.");
}
outputType = (Descriptor) output;
}
/** See {@link FileDescriptor#setProto}. */
private void setProto(final MethodDescriptorProto proto) throws DescriptorValidationException {
this.proto = proto;
this.options = null;
resolveFeatures(proto.getOptions().getFeatures());
}
}
// =================================================================
private static String computeFullName(
final FileDescriptor file, final Descriptor parent, final String name) {
if (parent != null) {
return parent.getFullName() + '.' + name;
}
final String packageName = file.getPackage();
if (!packageName.isEmpty()) {
return packageName + '.' + name;
}
return name;
}
// =================================================================
/**
* All descriptors implement this to make it easier to implement tools like {@code
* DescriptorPool}.
*/
public abstract static class GenericDescriptor {
// Private constructor to prevent subclasses outside of com.google.protobuf.Descriptors
private GenericDescriptor() {}
public abstract Message toProto();
public abstract String getName();
public abstract String getFullName();
public abstract FileDescriptor getFile();
void resolveFeatures(FeatureSet unresolvedFeatures) throws DescriptorValidationException {
if (this.parent != null
&& unresolvedFeatures.equals(FeatureSet.getDefaultInstance())
&& !hasInferredLegacyProtoFeatures()) {
this.features = this.parent.features;
validateFeatures();
return;
}
FeatureSet.Builder features;
if (this.parent == null) {
Edition edition = getFile().getEdition();
features = getEditionDefaults(edition).toBuilder();
} else {
features = this.parent.features.toBuilder();
}
features.mergeFrom(inferLegacyProtoFeatures());
features.mergeFrom(unresolvedFeatures);
this.features = internFeatures(features.build());
validateFeatures();
}
FeatureSet inferLegacyProtoFeatures() {
return FeatureSet.getDefaultInstance();
}
boolean hasInferredLegacyProtoFeatures() {
return false;
}
void validateFeatures() throws DescriptorValidationException {}
GenericDescriptor parent;
volatile FeatureSet features;
}
/** Thrown when building descriptors fails because the source DescriptorProtos are not valid. */
public static class DescriptorValidationException extends Exception {
private static final long serialVersionUID = 5750205775490483148L;
/** Gets the full name of the descriptor where the error occurred. */
public String getProblemSymbolName() {
return name;
}
/** Gets the protocol message representation of the invalid descriptor. */
public Message getProblemProto() {
return proto;
}
/** Gets a human-readable description of the error. */
public String getDescription() {
return description;
}
private final String name;
private final Message proto;
private final String description;
private DescriptorValidationException(
final GenericDescriptor problemDescriptor, final String description) {
super(problemDescriptor.getFullName() + ": " + description);
// Note that problemDescriptor may be partially uninitialized, so we
// don't want to expose it directly to the user. So, we only provide
// the name and the original proto.
name = problemDescriptor.getFullName();
proto = problemDescriptor.toProto();
this.description = description;
}
private DescriptorValidationException(
final GenericDescriptor problemDescriptor,
final String description,
final Throwable cause) {
this(problemDescriptor, description);
initCause(cause);
}
private DescriptorValidationException(
final FileDescriptor problemDescriptor, final String description) {
super(problemDescriptor.getName() + ": " + description);
// Note that problemDescriptor may be partially uninitialized, so we
// don't want to expose it directly to the user. So, we only provide
// the name and the original proto.
name = problemDescriptor.getName();
proto = problemDescriptor.toProto();
this.description = description;
}
}
// =================================================================
/**
* A private helper class which contains lookup tables containing all the descriptors defined in a
* particular file.
*/
private static final class DescriptorPool {
/** Defines what subclass of descriptors to search in the descriptor pool. */
enum SearchFilter {
TYPES_ONLY,
AGGREGATES_ONLY,
ALL_SYMBOLS
}
DescriptorPool(final FileDescriptor[] dependencies, boolean allowUnknownDependencies) {
this.dependencies =
Collections.newSetFromMap(
new IdentityHashMap<FileDescriptor, Boolean>(dependencies.length));
this.allowUnknownDependencies = allowUnknownDependencies;
for (Descriptors.FileDescriptor dependency : dependencies) {
this.dependencies.add(dependency);
importPublicDependencies(dependency);
}
for (final FileDescriptor dependency : this.dependencies) {
try {
addPackage(dependency.getPackage(), dependency);
} catch (DescriptorValidationException e) {
// Can't happen, because addPackage() only fails when the name
// conflicts with a non-package, but we have not yet added any
// non-packages at this point.
throw new AssertionError(e);
}
}
}
/** Find and put public dependencies of the file into dependencies set. */
private void importPublicDependencies(final FileDescriptor file) {
for (FileDescriptor dependency : file.getPublicDependencies()) {
if (dependencies.add(dependency)) {
importPublicDependencies(dependency);
}
}
}
private final Set<FileDescriptor> dependencies;
private final boolean allowUnknownDependencies;
private final Map<String, GenericDescriptor> descriptorsByName = new HashMap<>();
/** Find a generic descriptor by fully-qualified name. */
GenericDescriptor findSymbol(final String fullName) {
return findSymbol(fullName, SearchFilter.ALL_SYMBOLS);
}
/**
* Find a descriptor by fully-qualified name and given option to only search valid field type
* descriptors.
*/
GenericDescriptor findSymbol(final String fullName, final SearchFilter filter) {
GenericDescriptor result = descriptorsByName.get(fullName);
if (result != null) {
if ((filter == SearchFilter.ALL_SYMBOLS)
|| ((filter == SearchFilter.TYPES_ONLY) && isType(result))
|| ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) {
return result;
}
}
for (final FileDescriptor dependency : dependencies) {
result = dependency.pool.descriptorsByName.get(fullName);
if (result != null) {
if ((filter == SearchFilter.ALL_SYMBOLS)
|| ((filter == SearchFilter.TYPES_ONLY) && isType(result))
|| ((filter == SearchFilter.AGGREGATES_ONLY) && isAggregate(result))) {
return result;
}
}
}
return null;
}
/** Checks if the descriptor is a valid type for a message field. */
boolean isType(GenericDescriptor descriptor) {
return (descriptor instanceof Descriptor) || (descriptor instanceof EnumDescriptor);
}
/** Checks if the descriptor is a valid namespace type. */
boolean isAggregate(GenericDescriptor descriptor) {
return (descriptor instanceof Descriptor)
|| (descriptor instanceof EnumDescriptor)
|| (descriptor instanceof PackageDescriptor)
|| (descriptor instanceof ServiceDescriptor);
}
/**
* Look up a type descriptor by name, relative to some other descriptor. The name may be
* fully-qualified (with a leading '.'), partially-qualified, or unqualified. C++-like name
* lookup semantics are used to search for the matching descriptor.
*/
GenericDescriptor lookupSymbol(
final String name,
final GenericDescriptor relativeTo,
final DescriptorPool.SearchFilter filter)
throws DescriptorValidationException {
GenericDescriptor result;
String fullname;
if (name.startsWith(".")) {
// Fully-qualified name.
fullname = name.substring(1);
result = findSymbol(fullname, filter);
} else {
// If "name" is a compound identifier, we want to search for the
// first component of it, then search within it for the rest.
// If name is something like "Foo.Bar.baz", and symbols named "Foo" are
// defined in multiple parent scopes, we only want to find "Bar.baz" in
// the innermost one. E.g., the following should produce an error:
// message Bar { message Baz {} }
// message Foo {
// message Bar {
// }
// optional Bar.Baz baz = 1;
// }
// So, we look for just "Foo" first, then look for "Bar.baz" within it
// if found.
final int firstPartLength = name.indexOf('.');
final String firstPart;
if (firstPartLength == -1) {
firstPart = name;
} else {
firstPart = name.substring(0, firstPartLength);
}
// We will search each parent scope of "relativeTo" looking for the
// symbol.
final StringBuilder scopeToTry = new StringBuilder(relativeTo.getFullName());
while (true) {
// Chop off the last component of the scope.
final int dotpos = scopeToTry.lastIndexOf(".");
if (dotpos == -1) {
fullname = name;
result = findSymbol(name, filter);
break;
} else {
scopeToTry.setLength(dotpos + 1);
// Append firstPart and try to find
scopeToTry.append(firstPart);
result = findSymbol(scopeToTry.toString(), DescriptorPool.SearchFilter.AGGREGATES_ONLY);
if (result != null) {
if (firstPartLength != -1) {
// We only found the first part of the symbol. Now look for
// the whole thing. If this fails, we *don't* want to keep
// searching parent scopes.
scopeToTry.setLength(dotpos + 1);
scopeToTry.append(name);
result = findSymbol(scopeToTry.toString(), filter);
}
fullname = scopeToTry.toString();
break;
}
// Not found. Remove the name so we can try again.
scopeToTry.setLength(dotpos);
}
}
}
if (result == null) {
if (allowUnknownDependencies && filter == SearchFilter.TYPES_ONLY) {
logger.warning(
"The descriptor for message type \""
+ name
+ "\" cannot be found and a placeholder is created for it");
// We create a dummy message descriptor here regardless of the
// expected type. If the type should be message, this dummy
// descriptor will work well and if the type should be enum, a
// DescriptorValidationException will be thrown later. In either
// case, the code works as expected: we allow unknown message types
// but not unknown enum types.
result = new Descriptor(fullname);
// Add the placeholder file as a dependency so we can find the
// placeholder symbol when resolving other references.
this.dependencies.add(result.getFile());
return result;
} else {
throw new DescriptorValidationException(relativeTo, '\"' + name + "\" is not defined.");
}
} else {
return result;
}
}
/**
* Adds a symbol to the symbol table. If a symbol with the same name already exists, throws an
* error.
*/
void addSymbol(final GenericDescriptor descriptor) throws DescriptorValidationException {
validateSymbolName(descriptor);
final String fullName = descriptor.getFullName();
final GenericDescriptor old = descriptorsByName.put(fullName, descriptor);
if (old != null) {
descriptorsByName.put(fullName, old);
if (descriptor.getFile() == old.getFile()) {
final int dotpos = fullName.lastIndexOf('.');
if (dotpos == -1) {
throw new DescriptorValidationException(
descriptor, '\"' + fullName + "\" is already defined.");
} else {
throw new DescriptorValidationException(
descriptor,
'\"'
+ fullName.substring(dotpos + 1)
+ "\" is already defined in \""
+ fullName.substring(0, dotpos)
+ "\".");
}
} else {
throw new DescriptorValidationException(
descriptor,
'\"'
+ fullName
+ "\" is already defined in file \""
+ old.getFile().getName()
+ "\".");
}
}
}
/**
* Represents a package in the symbol table. We use PackageDescriptors just as placeholders so
* that someone cannot define, say, a message type that has the same name as an existing
* package.
*/
private static final class PackageDescriptor extends GenericDescriptor {
@Override
public Message toProto() {
return file.toProto();
}
@Override
public String getName() {
return name;
}
@Override
public String getFullName() {
return fullName;
}
@Override
public FileDescriptor getFile() {
return file;
}
PackageDescriptor(final String name, final String fullName, final FileDescriptor file) {
this.file = file;
this.fullName = fullName;
this.name = name;
}
private final String name;
private final String fullName;
private final FileDescriptor file;
}
/**
* Adds a package to the symbol tables. If a package by the same name already exists, that is
* fine, but if some other kind of symbol exists under the same name, an exception is thrown. If
* the package has multiple components, this also adds the parent package(s).
*/
void addPackage(final String fullName, final FileDescriptor file)
throws DescriptorValidationException {
final int dotpos = fullName.lastIndexOf('.');
final String name;
if (dotpos == -1) {
name = fullName;
} else {
addPackage(fullName.substring(0, dotpos), file);
name = fullName.substring(dotpos + 1);
}
final GenericDescriptor old =
descriptorsByName.put(fullName, new PackageDescriptor(name, fullName, file));
if (old != null) {
descriptorsByName.put(fullName, old);
if (!(old instanceof PackageDescriptor)) {
throw new DescriptorValidationException(
file,
'\"'
+ name
+ "\" is already defined (as something other than a "
+ "package) in file \""
+ old.getFile().getName()
+ "\".");
}
}
}
/**
* Verifies that the descriptor's name is valid. That is, it contains only letters, digits, and
* underscores, and does not start with a digit.
*/
static void validateSymbolName(final GenericDescriptor descriptor)
throws DescriptorValidationException {
final String name = descriptor.getName();
if (name.length() == 0) {
throw new DescriptorValidationException(descriptor, "Missing name.");
}
// Non-ASCII characters are not valid in protobuf identifiers, even
// if they are letters or digits.
// The first character must be a letter or '_'.
// Subsequent characters may be letters, numbers, or digits.
for (int i = 0; i < name.length(); i++) {
final char c = name.charAt(i);
if (('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| (c == '_')
|| ('0' <= c && c <= '9' && i > 0)) {
// Valid
continue;
}
throw new DescriptorValidationException(
descriptor, '\"' + name + "\" is not a valid identifier.");
}
}
}
/** Describes a oneof of a message type. */
public static final class OneofDescriptor extends GenericDescriptor {
/** Get the index of this descriptor within its parent. */
public int getIndex() {
return index;
}
@Override
public String getName() {
return proto.getName();
}
@Override
public FileDescriptor getFile() {
return file;
}
@Override
public String getFullName() {
return fullName;
}
public Descriptor getContainingType() {
return containingType;
}
public int getFieldCount() {
return fieldCount;
}
public OneofOptions getOptions() {
if (this.options == null) {
OneofOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Get a list of this message type's fields. */
public List<FieldDescriptor> getFields() {
return Collections.unmodifiableList(Arrays.asList(fields));
}
public FieldDescriptor getField(int index) {
return fields[index];
}
@Override
public OneofDescriptorProto toProto() {
return proto;
}
boolean isSynthetic() {
return fields.length == 1 && fields[0].isProto3Optional;
}
/** See {@link FileDescriptor#resolveAllFeatures}. */
private void resolveAllFeatures() throws DescriptorValidationException {
resolveFeatures(proto.getOptions().getFeatures());
}
private void setProto(final OneofDescriptorProto proto) throws DescriptorValidationException {
this.proto = proto;
this.options = null;
resolveFeatures(proto.getOptions().getFeatures());
}
private OneofDescriptor(
final OneofDescriptorProto proto,
final FileDescriptor file,
final Descriptor parent,
final int index) {
this.parent = parent;
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
this.file = file;
this.index = index;
containingType = parent;
fieldCount = 0;
}
private final int index;
private OneofDescriptorProto proto;
private volatile OneofOptions options;
private final String fullName;
private final FileDescriptor file;
private Descriptor containingType;
private int fieldCount;
private FieldDescriptor[] fields;
}
private static <T> T binarySearch(T[] array, int size, NumberGetter<T> getter, int number) {
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = (left + right) / 2;
T midValue = array[mid];
int midValueNumber = getter.getNumber(midValue);
if (number < midValueNumber) {
right = mid - 1;
} else if (number > midValueNumber) {
left = mid + 1;
} else {
return midValue;
}
}
return null;
}
private interface NumberGetter<T> {
int getNumber(T t);
}
}
| protocolbuffers/protobuf | java/core/src/main/java/com/google/protobuf/Descriptors.java |
204 |
/**
* A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between
* successive elements take on all the values 1 through n − 1. For instance,
* 1 4 2 3
* is a jolly jumper, because the absolutes differences are 3, 2, and 1 respectively. The definition implies
* that any sequence of a single integer is a jolly jumper. You are to write a program to determine whether
* or not each of a number of sequences is a jolly jumper.
* Input
* Each line of input contains an integer n ≤ 3000 followed by n integers representing the sequence.
* Output
* For each line of input, generate a line of output saying ‘Jolly’ or ‘Not jolly’.
* Sample Input
* 4 1 4 2 3
* 5 1 4 2 -1 6
* Sample Output
* Jolly
* Not jolly
*/
//https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=979
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class JollyJumpers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
Set<Integer> numbersAlreadyAdded = new HashSet<Integer>();
int numberOfElements = input.nextInt();
int[] numbers = new int[numberOfElements];
for (int i = 0; i < numberOfElements; i++) {
numbers[i] = input.nextInt();
}
for (int i = 0; i < numberOfElements - 1; i++) {
int difference = Math.abs(numbers[i] - numbers[i + 1]);
if (difference > 0 && difference < numberOfElements) {
numbersAlreadyAdded.add(difference);
}
}
if (numbersAlreadyAdded.size() == (numberOfElements - 1)) {
System.out.println("Jolly");
} else {
System.out.println("Not jolly");
}
}
}
} | kdn251/interviews | uva/JollyJumpers.java |
205 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* 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 entity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import java.util.HashSet;
import java.util.Set;
import lombok.Getter;
import lombok.Setter;
/**
* Cake entity.
*/
@Entity
@Getter
@Setter
public class Cake {
@Id
@GeneratedValue
private Long id;
@OneToOne(cascade = CascadeType.REMOVE)
private CakeTopping topping;
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER)
private Set<CakeLayer> layers;
public Cake() {
setLayers(new HashSet<>());
}
public void addLayer(CakeLayer layer) {
this.layers.add(layer);
}
@Override
public String toString() {
return String.format("id=%s topping=%s layers=%s", id, topping, layers.toString());
}
}
| iluwatar/java-design-patterns | layers/src/main/java/entity/Cake.java |