code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins.newui; import com.intellij.ide.IdeBundle; import com.intellij.ui.JBColor; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import java.awt.*; /** * @author Alexander Lobas */ public class TagComponent extends LinkComponent { private static final Color BACKGROUND = JBColor.namedColor("Plugins.tagBackground", new JBColor(0xEAEAEC, 0x4D4D4D)); private static final Color EAP_BACKGROUND = JBColor.namedColor("Plugins.eapTagBackground", new JBColor(0xF2D2CF, 0xF2D2CF)); private static final Color PAID_BACKGROUND = JBColor.namedColor("Plugins.paidTagBackground", new JBColor(0xD8EDF8, 0x3E505C)); private static final Color TRIAL_BACKGROUND = JBColor.namedColor("Plugins.trialTagBackground", new JBColor(0xDBE8DD, 0x345574E)); private static final Color FOREGROUND = JBColor.namedColor("Plugins.tagForeground", new JBColor(0x787878, 0x999999)); private Color myColor; public TagComponent() { setForeground(FOREGROUND); setPaintUnderline(false); setOpaque(false); setBorder(JBUI.Borders.empty(1, 8)); } public TagComponent(@NotNull @Nls String name) { this(); setText(name); } @Override public void setText(@NotNull @Nls String name) { String tooltip = null; myColor = BACKGROUND; if (Tags.EAP.name().equals(name)) { myColor = EAP_BACKGROUND; tooltip = IdeBundle.message("tooltip.eap.plugin.version"); } else if (Tags.Trial.name().equals(name) || Tags.Purchased.name().equals(name)) { myColor = TRIAL_BACKGROUND; } else if (Tags.Paid.name().equals(name) || Tags.Freemium.name().equals(name)) { myColor = PAID_BACKGROUND; tooltip = IdeBundle.message("tooltip.paid.plugin"); } super.setText(name); setToolTipText(tooltip); } @Override protected void paintComponent(Graphics g) { //noinspection UseJBColor g.setColor(myUnderline ? new Color(myColor.getRed(), myColor.getGreen(), myColor.getBlue(), 178) : myColor); g.fillRect(0, 0, getWidth(), getHeight()); super.paintComponent(g); } @Override protected boolean isInClickableArea(Point pt) { return true; } }
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/newui/TagComponent.java
Java
apache-2.0
2,357
/* * Copyright 2013-2019 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.cloud.consul.discovery; import org.junit.jupiter.api.Test; import org.springframework.cloud.commons.util.InetUtils; import org.springframework.cloud.commons.util.InetUtilsProperties; import static org.assertj.core.api.Assertions.assertThat; /** * @author Spencer Gibb */ public class ConsulCatalogWatchTests { @Test public void isRunningReportsCorrectly() { ConsulDiscoveryProperties properties = new ConsulDiscoveryProperties(new InetUtils(new InetUtilsProperties())); ConsulCatalogWatch watch = new ConsulCatalogWatch(properties, null) { @Override public void catalogServicesWatch() { // do nothing } }; assertThat(watch.isRunning()).isFalse(); watch.start(); assertThat(watch.isRunning()).isTrue(); watch.stop(); assertThat(watch.isRunning()).isFalse(); } }
spring-cloud/spring-cloud-consul
spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatchTests.java
Java
apache-2.0
1,452
// Copyright 2012 Google Inc. 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 com.google.collide.client.editor; import com.google.collide.client.util.logging.Log; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.util.ListenerRegistrar.Remover; import com.google.collide.shared.util.SortedList; import com.google.collide.shared.util.SortedList.OneWayIntComparator; /** * This class takes care of mapping between the different coordinates used by * the editor. The two supported systems are: * <ul> * <li>Offset (x,y) - in pixels, relative to the top left of line 0 in the * current document. * <li>Line (line, column) - the real line number and column, taking into * account spacer objects in between lines. Lines and columns are 0-indexed. * </ul> */ class CoordinateMap implements Document.LineListener { interface DocumentSizeProvider { float getEditorCharacterWidth(); int getEditorLineHeight(); void handleSpacerHeightChanged(Spacer spacer, int oldHeight); } private static class OffsetCache { private static final SortedList.Comparator<OffsetCache> COMPARATOR = new SortedList.Comparator<OffsetCache>() { @Override public int compare(OffsetCache a, OffsetCache b) { return a.offset - b.offset; } }; private static final SortedList.OneWayIntComparator<OffsetCache> Y_OFFSET_ONE_WAY_COMPARATOR = new SortedList.OneWayIntComparator<OffsetCache>() { @Override public int compareTo(OffsetCache s) { return value - s.offset; } }; private static final SortedList.OneWayIntComparator<OffsetCache> LINE_NUMBER_ONE_WAY_COMPARATOR = new SortedList.OneWayIntComparator<OffsetCache>() { @Override public int compareTo(OffsetCache s) { return value - s.lineNumber; } }; private final int offset; private final int height; private final int lineNumber; private OffsetCache(int offset, int lineNumber, int height) { this.offset = offset; this.height = height; this.lineNumber = lineNumber; } } private static final OffsetCache BEGINNING_EMPTY_OFFSET_CACHE = new OffsetCache(0, 0, 0); private static final AnchorType SPACER_ANCHOR_TYPE = AnchorType.create(CoordinateMap.class, "spacerAnchorType"); private static final Spacer.Comparator SPACER_COMPARATOR = new Spacer.Comparator(); private static final Spacer.OneWaySpacerComparator SPACER_ONE_WAY_COMPARATOR = new Spacer.OneWaySpacerComparator(); /** Used by {@link #getPrecedingOffsetCache(int, int)} */ private static final int IGNORE = Integer.MIN_VALUE; private Document document; private DocumentSizeProvider documentSizeProvider; /** List of offset cache items, sorted by the offset */ private SortedList<OffsetCache> offsetCache; /** * True if there is at least one spacer in the editor, false otherwise (false * means a simple height / line height calculation can be used) */ private boolean requiresMapping; /** Sorted by line number */ private SortedList<Spacer> spacers; /** Summation of all spacers' heights */ private int totalSpacerHeight; /** Remover for listener */ private Remover documentLineListenerRemover; CoordinateMap(DocumentSizeProvider documentSizeProvider) { this.documentSizeProvider = documentSizeProvider; requiresMapping = false; } int convertYToLineNumber(int y) { if (y < 0) { return 0; } int lineHeight = documentSizeProvider.getEditorLineHeight(); if (!requiresMapping) { return y / lineHeight; } OffsetCache precedingOffsetCache = getPrecedingOffsetCache(y, IGNORE); int precedingOffsetCacheBottom = precedingOffsetCache.offset + precedingOffsetCache.height; int lineNumberRelativeToOffsetCacheLine = (y - precedingOffsetCacheBottom) / lineHeight; if (y < precedingOffsetCacheBottom) { // y is inside the spacer return precedingOffsetCache.lineNumber; } else { return precedingOffsetCache.lineNumber + lineNumberRelativeToOffsetCacheLine; } } /** * Returns the top of the given line. */ int convertLineNumberToY(int lineNumber) { int lineHeight = documentSizeProvider.getEditorLineHeight(); if (!requiresMapping) { return lineNumber * lineHeight; } OffsetCache precedingOffsetCache = getPrecedingOffsetCache(IGNORE, lineNumber); int precedingOffsetCacheBottom = precedingOffsetCache.offset + precedingOffsetCache.height; int offsetRelativeToOffsetCacheBottom = (lineNumber - precedingOffsetCache.lineNumber) * lineHeight; return precedingOffsetCacheBottom + offsetRelativeToOffsetCacheBottom; } /** * Returns the first {@link OffsetCache} that is positioned less than or equal * to {@code y} or {@code lineNumber}. This methods fills the * {@link #offsetCache} if necessary ensuring the returned {@link OffsetCache} * is up-to-date. * * @param y the y, or {@link #IGNORE} if looking up by {@code lineNumber} * @param lineNumber the line number, or {@link #IGNORE} if looking up by * {@code y} */ private OffsetCache getPrecedingOffsetCache(int y, int lineNumber) { assert (y != IGNORE && lineNumber == IGNORE) || (lineNumber != IGNORE && y == IGNORE); final int lineHeight = documentSizeProvider.getEditorLineHeight(); OffsetCache previousOffsetCache; if (y != IGNORE) { previousOffsetCache = getCachedPrecedingOffsetCacheImpl(OffsetCache.Y_OFFSET_ONE_WAY_COMPARATOR, y); } else { previousOffsetCache = getCachedPrecedingOffsetCacheImpl(OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR, lineNumber); } if (previousOffsetCache == null) { if (spacers.size() > 0 && spacers.get(0).getLineNumber() == 0) { previousOffsetCache = createOffsetCache(0, 0, spacers.get(0).getHeight()); } else { previousOffsetCache = BEGINNING_EMPTY_OFFSET_CACHE; } } /* * Optimization so the common case that the target has previously been * computed requires no more computation */ int offsetCacheSize = offsetCache.size(); if (offsetCacheSize > 0 && isTargetEarlierThanOffsetCache(y, lineNumber, offsetCache.get(offsetCacheSize - 1))) { return previousOffsetCache; } // This will return this offset cache's matching spacer int spacerPos = getPrecedingSpacerIndex(previousOffsetCache.lineNumber); /* * We want the spacer following this offset cache's spacer, or the first * spacer if none were found */ spacerPos++; for (int n = spacers.size(); spacerPos < n; spacerPos++) { Spacer curSpacer = spacers.get(spacerPos); int previousOffsetCacheBottom = previousOffsetCache.offset + previousOffsetCache.height; int simpleLinesHeight = (curSpacer.getLineNumber() - previousOffsetCache.lineNumber) * lineHeight; if (simpleLinesHeight == 0) { Log.warn(Spacer.class, "More than one spacer on line " + previousOffsetCache.lineNumber); } // Create an offset cache for this spacer OffsetCache curOffsetCache = createOffsetCache(previousOffsetCacheBottom + simpleLinesHeight, curSpacer.getLineNumber(), curSpacer.getHeight()); if (isTargetEarlierThanOffsetCache(y, lineNumber, curOffsetCache)) { return previousOffsetCache; } previousOffsetCache = curOffsetCache; } return previousOffsetCache; } /** * Returns the {@link OffsetCache} instance in list that has the greatest * value less than or equal to the given {@code value}. Returns null if there * isn't one. * * This should only be used by {@link #getPrecedingOffsetCache(int, int)}. */ private OffsetCache getCachedPrecedingOffsetCacheImpl( OneWayIntComparator<OffsetCache> comparator, int value) { comparator.setValue(value); int index = offsetCache.findInsertionIndex(comparator, false); return index >= 0 ? offsetCache.get(index) : null; } private boolean isTargetEarlierThanOffsetCache(int y, int lineNumber, OffsetCache offsetCache) { return ((y != IGNORE && y < offsetCache.offset) || (lineNumber != IGNORE && lineNumber < offsetCache.lineNumber)); } private OffsetCache createOffsetCache(int offset, int lineNumber, int height) { OffsetCache createdOffsetCache = new OffsetCache(offset, lineNumber, height); offsetCache.add(createdOffsetCache); return createdOffsetCache; } private int getPrecedingSpacerIndex(int lineNumber) { SPACER_ONE_WAY_COMPARATOR.setValue(lineNumber); return spacers.findInsertionIndex(SPACER_ONE_WAY_COMPARATOR, false); } /** * Adds a spacer above the given lineInfo line with height heightPx and * returns the created Spacer object. * * @param lineInfo the line before which the spacer will be inserted * @param height the height in pixels of the spacer */ Spacer createSpacer(LineInfo lineInfo, int height, Buffer buffer, String cssClass) { int lineNumber = lineInfo.number(); // create an anchor on the current line Anchor anchor = document.getAnchorManager().createAnchor(SPACER_ANCHOR_TYPE, lineInfo.line(), lineNumber, AnchorManager.IGNORE_COLUMN); anchor.setRemovalStrategy(RemovalStrategy.SHIFT); // account for the height of the line the spacer is on Spacer spacer = new Spacer(anchor, height, this, buffer, cssClass); spacers.add(spacer); totalSpacerHeight += height; invalidateLineNumberAndFollowing(lineNumber); requiresMapping = true; return spacer; } boolean removeSpacer(Spacer spacer) { int lineNumber = spacer.getLineNumber(); if (spacers.remove(spacer)) { document.getAnchorManager().removeAnchor(spacer.getAnchor()); totalSpacerHeight -= spacer.getHeight(); invalidateLineNumberAndFollowing(lineNumber - 1); updateRequiresMapping(); return true; } return false; } void handleDocumentChange(Document document) { if (documentLineListenerRemover != null) { documentLineListenerRemover.remove(); } this.document = document; spacers = new SortedList<Spacer>(SPACER_COMPARATOR); offsetCache = new SortedList<OffsetCache>(OffsetCache.COMPARATOR); documentLineListenerRemover = document.getLineListenerRegistrar().add(this); requiresMapping = false; // starts with no items in list totalSpacerHeight = 0; } @Override public void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines) { invalidateLineNumberAndFollowing(lineNumber); } @Override public void onLineRemoved(Document document, int lineNumber, JsonArray<Line> removedLines) { invalidateLineNumberAndFollowing(lineNumber); } /** * Call this after any line changes (adding/deleting lines, changing line * heights). Only invalidate (delete) cache items >= lineNumber, don't * recalculate. */ void invalidateLineNumberAndFollowing(int lineNumber) { OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR.setValue(lineNumber); int insertionIndex = offsetCache.findInsertionIndex(OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR); offsetCache.removeThisAndFollowing(insertionIndex); } private void updateRequiresMapping() { // check to change active status requiresMapping = spacers.size() > 0; } int getTotalSpacerHeight() { return totalSpacerHeight; } void handleSpacerHeightChanged(Spacer spacer, int oldHeight) { totalSpacerHeight -= oldHeight; totalSpacerHeight += spacer.getHeight(); invalidateLineNumberAndFollowing(spacer.getLineNumber()); documentSizeProvider.handleSpacerHeightChanged(spacer, oldHeight); } }
WeTheInternet/collide
client/src/main/java/com/google/collide/client/editor/CoordinateMap.java
Java
apache-2.0
12,795
package com.unitvectory.shak.jarvis.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.unitvectory.shak.jarvis.util.ResourceHelper; /** * Tests the SmartThingsPublish class * * @author Jared Hatfield * */ public class SmartThingsPublishTest { /** * Test the parser being given a null value */ @Test public void testNullStringParse() { JsonPublishRequest myRequest = null; SmartThingsPublish smart = new SmartThingsPublish(myRequest); assertNotNull(smart); assertNull(smart.getPublish()); assertNull(smart.getAuth()); assertNull(smart.getDate()); assertNull(smart.getDescription()); assertNull(smart.getDescriptionText()); assertNull(smart.getDeviceId()); assertNull(smart.getHubId()); assertNull(smart.getId()); assertNull(smart.getLocationId()); assertNull(smart.getName()); assertNull(smart.getSource()); assertNull(smart.getUnit()); assertNull(smart.getValue()); } /** * Test the parser when things go perfectly. */ @Test public void testValidParse() { // Load the test JSON String json = ResourceHelper.load("/messagebody.json"); assertNotNull(json); assertTrue(json.length() > 0); // Create the object JsonPublishRequest request = new JsonPublishRequest(json); assertNotNull(request); assertTrue(request.isValid()); assertNotNull(request.getData()); // Create the SmartThingsPublish SmartThingsPublish smart = new SmartThingsPublish(request); assertNotNull(smart); assertEquals("foobar", smart.getAuth()); assertEquals("2013-12-30T16:03:08.224Z", smart.getDate()); assertEquals( "raw:08EF170A59FF, dni:08EF, battery:17, batteryDivisor:0A, rssi:59, lqi:FF", smart.getDescription()); assertEquals("Sensor was -39 dBm", smart.getDescriptionText()); assertEquals("2fffffff-fffff-ffff-ffff-fffffffffff", smart.getDeviceId()); assertEquals("3fffffff-fffff-ffff-ffff-fffffffffff", smart.getHubId()); assertEquals("1fffffff-fffff-ffff-ffff-fffffffffff", smart.getId()); assertEquals("4fffffff-fffff-ffff-ffff-fffffffffff", smart.getLocationId()); assertEquals("rssi", smart.getName()); assertEquals("DEVICE", smart.getSource()); assertEquals("dBm", smart.getUnit()); assertEquals("-39", smart.getValue()); } }
JaredHatfield/shak-jarvis
src/test/java/com/unitvectory/shak/jarvis/model/SmartThingsPublishTest.java
Java
apache-2.0
2,402
/* * #%L * wcm.io * %% * Copyright (C) 2015 wcm.io * %% * 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. * #L% */ package io.wcm.devops.conga.plugins.sling.validator; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.wcm.devops.conga.generator.spi.ValidationException; import io.wcm.devops.conga.generator.spi.ValidatorPlugin; import io.wcm.devops.conga.generator.spi.context.FileContext; import io.wcm.devops.conga.generator.util.PluginManagerImpl; public class ProvisioningValidatorTest { private ValidatorPlugin underTest; @BeforeEach public void setUp() { underTest = new PluginManagerImpl().get(ProvisioningValidator.NAME, ValidatorPlugin.class); } @Test public void testValid() throws Exception { File file = new File(getClass().getResource("/validProvisioning.txt").toURI()); FileContext fileContext = new FileContext().file(file).charset(StandardCharsets.UTF_8); assertTrue(underTest.accepts(fileContext, null)); underTest.apply(fileContext, null); } @Test public void testInvalid() throws Exception { File file = new File(getClass().getResource("/invalidProvisioning.txt").toURI()); FileContext fileContext = new FileContext().file(file).charset(StandardCharsets.UTF_8); assertTrue(underTest.accepts(fileContext, null)); assertThrows(ValidationException.class, () -> { underTest.apply(fileContext, null); }); } @Test public void testInvalidFileExtension() throws Exception { File file = new File(getClass().getResource("/noProvisioning.txt").toURI()); FileContext fileContext = new FileContext().file(file).charset(StandardCharsets.UTF_8); assertFalse(underTest.accepts(fileContext, null)); } }
wcm-io-devops/wcm-io-devops-conga-sling-plugin
conga-sling-plugin/src/test/java/io/wcm/devops/conga/plugins/sling/validator/ProvisioningValidatorTest.java
Java
apache-2.0
2,492
package org.targettest.org.apache.lucene.store; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.Closeable; import java.util.Map; import java.util.HashMap; /** Abstract base class for input from a file in a {@link Directory}. A * random-access input stream. Used for all Lucene index input operations. * @see Directory */ public abstract class IndexInput implements Cloneable,Closeable { private boolean preUTF8Strings; // true if we are reading old (modified UTF8) string format /** Reads and returns a single byte. * @see IndexOutput#writeByte(byte) */ public abstract byte readByte() throws IOException; /** Reads a specified number of bytes into an array at the specified offset. * @param b the array to read bytes into * @param offset the offset in the array to start storing bytes * @param len the number of bytes to read * @see IndexOutput#writeBytes(byte[],int) */ public abstract void readBytes(byte[] b, int offset, int len) throws IOException; /** Reads a specified number of bytes into an array at the * specified offset with control over whether the read * should be buffered (callers who have their own buffer * should pass in "false" for useBuffer). Currently only * {@link BufferedIndexInput} respects this parameter. * @param b the array to read bytes into * @param offset the offset in the array to start storing bytes * @param len the number of bytes to read * @param useBuffer set to false if the caller will handle * buffering. * @see IndexOutput#writeBytes(byte[],int) */ public void readBytes(byte[] b, int offset, int len, boolean useBuffer) throws IOException { // Default to ignoring useBuffer entirely readBytes(b, offset, len); } /** Reads four bytes and returns an int. * @see IndexOutput#writeInt(int) */ public int readInt() throws IOException { return ((readByte() & 0xFF) << 24) | ((readByte() & 0xFF) << 16) | ((readByte() & 0xFF) << 8) | (readByte() & 0xFF); } /** Reads an int stored in variable-length format. Reads between one and * five bytes. Smaller values take fewer bytes. Negative numbers are not * supported. * @see IndexOutput#writeVInt(int) */ public int readVInt() throws IOException { byte b = readByte(); int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = readByte(); i |= (b & 0x7F) << shift; } return i; } /** Reads eight bytes and returns a long. * @see IndexOutput#writeLong(long) */ public long readLong() throws IOException { return (((long)readInt()) << 32) | (readInt() & 0xFFFFFFFFL); } /** Reads a long stored in variable-length format. Reads between one and * nine bytes. Smaller values take fewer bytes. Negative numbers are not * supported. */ public long readVLong() throws IOException { byte b = readByte(); long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = readByte(); i |= (b & 0x7FL) << shift; } return i; } /** Call this if readString should read characters stored * in the old modified UTF8 format (length in java chars * and java's modified UTF8 encoding). This is used for * indices written pre-2.4 See LUCENE-510 for details. */ public void setModifiedUTF8StringsMode() { preUTF8Strings = true; } /** Reads a string. * @see IndexOutput#writeString(String) */ public String readString() throws IOException { if (preUTF8Strings) return readModifiedUTF8String(); int length = readVInt(); final byte[] bytes = new byte[length]; readBytes(bytes, 0, length); return new String(bytes, 0, length, "UTF-8"); } private String readModifiedUTF8String() throws IOException { int length = readVInt(); final char[] chars = new char[length]; readChars(chars, 0, length); return new String(chars, 0, length); } /** Reads Lucene's old "modified UTF-8" encoded * characters into an array. * @param buffer the array to read characters into * @param start the offset in the array to start storing characters * @param length the number of characters to read * @see IndexOutput#writeChars(String,int,int) * @deprecated -- please use readString or readBytes * instead, and construct the string * from those utf8 bytes */ public void readChars(char[] buffer, int start, int length) throws IOException { final int end = start + length; for (int i = start; i < end; i++) { byte b = readByte(); if ((b & 0x80) == 0) buffer[i] = (char)(b & 0x7F); else if ((b & 0xE0) != 0xE0) { buffer[i] = (char)(((b & 0x1F) << 6) | (readByte() & 0x3F)); } else buffer[i] = (char)(((b & 0x0F) << 12) | ((readByte() & 0x3F) << 6) | (readByte() & 0x3F)); } } /** * Expert * * Similar to {@link #readChars(char[], int, int)} but does not do any conversion operations on the bytes it is reading in. It still * has to invoke {@link #readByte()} just as {@link #readChars(char[], int, int)} does, but it does not need a buffer to store anything * and it does not have to do any of the bitwise operations, since we don't actually care what is in the byte except to determine * how many more bytes to read * @param length The number of chars to read * @deprecated this method operates on old "modified utf8" encoded * strings */ public void skipChars(int length) throws IOException{ for (int i = 0; i < length; i++) { byte b = readByte(); if ((b & 0x80) == 0){ //do nothing, we only need one byte } else if ((b & 0xE0) != 0xE0) { readByte();//read an additional byte } else{ //read two additional bytes. readByte(); readByte(); } } } /** Closes the stream to further operations. */ public abstract void close() throws IOException; /** Returns the current position in this file, where the next read will * occur. * @see #seek(long) */ public abstract long getFilePointer(); /** Sets current position in this file, where the next read will occur. * @see #getFilePointer() */ public abstract void seek(long pos) throws IOException; /** The number of bytes in the file. */ public abstract long length(); /** Returns a clone of this stream. * * <p>Clones of a stream access the same data, and are positioned at the same * point as the stream they were cloned from. * * <p>Expert: Subclasses must ensure that clones may be positioned at * different points in the input from each other and from the stream they * were cloned from. */ @Override public Object clone() { IndexInput clone = null; try { clone = (IndexInput)super.clone(); } catch (CloneNotSupportedException e) {} return clone; } public Map<String,String> readStringStringMap() throws IOException { final Map<String,String> map = new HashMap<String,String>(); final int count = readInt(); for(int i=0;i<count;i++) { final String key = readString(); final String val = readString(); map.put(key, val); } return map; } }
chrishumphreys/provocateur
provocateur-thirdparty/src/main/java/org/targettest/org/apache/lucene/store/IndexInput.java
Java
apache-2.0
8,089
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.08.19 at 01:05:06 PM PDT // package com.google.api.ads.adwords.lib.jaxb.v201509; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SortOrder. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SortOrder"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="ASCENDING"/&gt; * &lt;enumeration value="DESCENDING"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "SortOrder") @XmlEnum public enum SortOrder { ASCENDING, DESCENDING; public String value() { return name(); } public static SortOrder fromValue(String v) { return valueOf(v); } }
gawkermedia/googleads-java-lib
modules/ads_lib/src/main/java/com/google/api/ads/adwords/lib/jaxb/v201509/SortOrder.java
Java
apache-2.0
1,139
package ru.job4j; import org.junit.Test; import java.util.*; /** * Класс для тестирования. * @author agavrikov * @since 13.07.2017 * @version 1 */ public class TestTimeCollectionTest { /** * Тестирование метода добавления. */ @Test public void add() { TestTimeCollection methods = new TestTimeCollection(); List<String> linkedList = new LinkedList<String>(); long timeStart = new Date().getTime(); long timeEnd = methods.add(linkedList, 1000000); System.out.println(timeEnd - timeStart); List<String> arrayList = new ArrayList<String>(); timeStart = new Date().getTime(); timeEnd = methods.add(arrayList, 1000000); System.out.println(timeEnd - timeStart); Set<String> treeSet = new TreeSet<String>(); timeStart = new Date().getTime(); timeEnd = methods.add(treeSet, 1000000); System.out.println(timeEnd - timeStart); } /** * Тестирование метода удаления. */ @Test public void delete() { TestTimeCollection methods = new TestTimeCollection(); List<String> linkedList = new LinkedList<String>(); methods.add(linkedList, 100000); long timeStart = new Date().getTime(); long timeEnd = methods.delete(linkedList, 10000); System.out.println(timeEnd - timeStart); List<String> arrayList = new ArrayList<String>(); methods.add(arrayList, 100000); timeStart = new Date().getTime(); timeEnd = methods.delete(arrayList, 10000); System.out.println(timeEnd - timeStart); Set<String> treeSet = new TreeSet<String>(); methods.add(treeSet, 100000); timeStart = new Date().getTime(); timeEnd = methods.delete(treeSet, 10000); System.out.println(timeEnd - timeStart); } }
AntonGavr92/agavrikov
chapter_003/src/test/java/ru/job4j/TestTimeCollectionTest.java
Java
apache-2.0
1,926
package tinymonkeys.vue; import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; /** * Classe du panneau de la carte. * * @version 1.0 * @author Camille Constant * */ public class VueCarte extends JPanel { /** * UID auto-généré. */ private static final long serialVersionUID = 4884966649331011259L; /** * Rapport entre la taille de la carte et la taille de l'écran. */ private static final double RAPPORT_ECRAN = 0.75; /** * Constante permettant de placer un objet à la moitié de l'écran. */ private static final int DIVISEUR_MILIEU = 2; /** * Constante permettant de placer un objet au quart de l'écran. */ private static final int DIVISEUR_QUART = 4; /** * Constante indiquant la couleur des cases représentant la mer. */ private static final Color OCEAN = new Color(0, 120, 220); /** * Taille de la case en nombre de pixels. */ private int tailleCase; /** * La coordonnee en abscisse du coin supérieur gauche de la grille. */ private int xGrille; /** * La coordonnee en ordonnée du coin supérieur gauche de la grille. */ private int yGrille; /** * Largeur de l'ecran en nombre de pixels. */ private final int largeurEcran; /** * Hauteur de l'ecran en nombre de pixels. */ private final int hauteurEcran; /** * Largeur de la grille en nombre de cases. */ private int largeurGrille; /** * Hauteur de la grille en nombre de cases. */ private int hauteurGrille; /** * La carte. */ private int[][] carte; /** * Constructeur de la vue de la carte. * * @param largeurEcran largeur de l'ecran en nombre de pixels. * @param hauteurEcran hauteur de l'ecran en nombre de pixels. * @param carte la carte a dessiner */ public VueCarte(int largeurEcran, int hauteurEcran, int[][] carte) { super(); this.largeurEcran = largeurEcran; this.hauteurEcran = hauteurEcran; this.largeurGrille = carte.length; this.hauteurGrille = carte[0].length; this.copieCarte(carte); this.placementGrille(); this.setBounds(this.xGrille, this.yGrille, this.largeurGrille * this.tailleCase + 1, this.hauteurGrille * this.tailleCase + 1); this.setOpaque(false); } /** * Dessine la carte de l'ile avec la grille. * * @param g le graphique dans lequel dessiner. */ public final void paintComponent(Graphics g) { super.paintComponent(g); this.dessineIle(g); this.dessineGrille(g); } /** * Place la carte au centre de l'écran. */ private void placementGrille() { final int diviseurLargeur; final int diviseurHauteur; final int largeurCase = (int) ((this.largeurEcran * RAPPORT_ECRAN) / this.largeurGrille); final int hauteurCase = (int) ((this.hauteurEcran * RAPPORT_ECRAN) / this.hauteurGrille); if (largeurCase < hauteurCase) { this.tailleCase = largeurCase; diviseurLargeur = DIVISEUR_QUART; diviseurHauteur = DIVISEUR_MILIEU; } else { this.tailleCase = hauteurCase; diviseurLargeur = DIVISEUR_MILIEU; diviseurHauteur = DIVISEUR_QUART; } this.xGrille = (int) ((this.largeurEcran - (this.tailleCase * this.largeurGrille)) / diviseurLargeur); this.yGrille = (int) ((this.hauteurEcran - (this.tailleCase * this.hauteurGrille)) / diviseurHauteur); } /** * Dessine la grille. * * @param g le graphique dans lequel dessiner. */ public void dessineGrille(Graphics g) { // La grille apparait en noir. g.setColor(Color.BLACK); // colonnes for (int i = 0; i <= (this.tailleCase * this.largeurGrille); i += this.tailleCase) { g.drawLine(i, 0, i, this.tailleCase * this.hauteurGrille); } // lignes for (int j = 0; j <= this.tailleCase * this.hauteurGrille; j += this.tailleCase) { g.drawLine(0, j, this.tailleCase * this.largeurGrille, j); } } /** * Dessine l'ile. * * @param g le graphique dans lequel dessiner. */ public final void dessineIle(Graphics g) { int i = -1; while (++i < this.largeurGrille) { int j = -1; while (++j < this.hauteurGrille) { // Si la case est de type mer. if (this.carte[i][j] == 0) { g.setColor(OCEAN); g.fillRect(i * this.tailleCase, j * this.tailleCase, this.tailleCase, this.tailleCase); } // Coloration inutile pour les cases terre. } } } /** * Modifie la carte de l'ile. * * @param carte la nouvelle carte. */ public final void setVueCarte(int[][] carte) { this.largeurGrille = carte.length; this.hauteurGrille = carte[0].length; this.copieCarte(carte); this.placementGrille(); this.setBounds(this.xGrille, this.yGrille, this.largeurGrille * this.tailleCase + 1, this.hauteurGrille * this.tailleCase + 1); this.setOpaque(false); } /** * Accesseur en lecture de la taille d'une case. * * @return la taille d'une case. */ public final int getTailleCase() { return this.tailleCase; } /** * Accesseur en lecture de l'abscisse de la grille. * * @return l'abscisse de la grille. */ public final int getXGrille() { return this.xGrille; } /** * Accesseur en lecture de l'ordonnee de la grille. * * @return l'ordonnee de la grille. */ public final int getYGrille() { return this.yGrille; } /** * Recopie de la carte dans l'attribut carte. * * @param carte la carte a copier. */ private void copieCarte(int[][] carte) { this.carte = new int[carte.length][carte[0].length]; int i = -1; while (++i < carte.length) { int j = -1; while(++j < carte[0].length) { this.carte[i][j] = carte[i][j]; } } } }
afraisse/TinyMonkey
src/tinymonkeys/vue/VueCarte.java
Java
apache-2.0
5,524
package org.sagebionetworks.auth.services; import org.sagebionetworks.repo.manager.AuthenticationManager; import org.sagebionetworks.repo.manager.MessageManager; import org.sagebionetworks.repo.manager.UserManager; import org.sagebionetworks.repo.manager.authentication.PersonalAccessTokenManager; import org.sagebionetworks.repo.manager.oauth.AliasAndType; import org.sagebionetworks.repo.manager.oauth.OAuthManager; import org.sagebionetworks.repo.manager.oauth.OpenIDConnectManager; import org.sagebionetworks.repo.model.AuthorizationUtils; import org.sagebionetworks.repo.model.UnauthorizedException; import org.sagebionetworks.repo.model.UserInfo; import org.sagebionetworks.repo.model.auth.AccessToken; import org.sagebionetworks.repo.model.auth.AccessTokenGenerationRequest; import org.sagebionetworks.repo.model.auth.AccessTokenGenerationResponse; import org.sagebionetworks.repo.model.auth.AccessTokenRecord; import org.sagebionetworks.repo.model.auth.AccessTokenRecordList; import org.sagebionetworks.repo.model.auth.AuthenticatedOn; import org.sagebionetworks.repo.model.auth.ChangePasswordInterface; import org.sagebionetworks.repo.model.auth.LoginRequest; import org.sagebionetworks.repo.model.auth.LoginResponse; import org.sagebionetworks.repo.model.auth.NewUser; import org.sagebionetworks.repo.model.auth.PasswordResetSignedToken; import org.sagebionetworks.repo.model.oauth.OAuthAccountCreationRequest; import org.sagebionetworks.repo.model.oauth.OAuthProvider; import org.sagebionetworks.repo.model.oauth.OAuthUrlRequest; import org.sagebionetworks.repo.model.oauth.OAuthUrlResponse; import org.sagebionetworks.repo.model.oauth.OAuthValidationRequest; import org.sagebionetworks.repo.model.oauth.ProvidedUserInfo; import org.sagebionetworks.repo.model.principal.AliasType; import org.sagebionetworks.repo.model.principal.PrincipalAlias; import org.sagebionetworks.repo.transactions.WriteTransaction; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.util.ValidateArgument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AuthenticationServiceImpl implements AuthenticationService { @Autowired private UserManager userManager; @Autowired private AuthenticationManager authManager; @Autowired private OAuthManager oauthManager; @Autowired private OpenIDConnectManager oidcManager; @Autowired private MessageManager messageManager; @Autowired private PersonalAccessTokenManager personalAccessTokenManager; @WriteTransaction @Override public void changePassword(ChangePasswordInterface request) throws NotFoundException { final long userId = authManager.changePassword(request); messageManager.sendPasswordChangeConfirmationEmail(userId); } @Override @WriteTransaction public void signTermsOfUse(AccessToken accessToken) throws NotFoundException { ValidateArgument.required(accessToken, "Access token"); ValidateArgument.required(accessToken.getAccessToken(), "Access token contents"); Long principalId = Long.parseLong(oidcManager.validateAccessToken(accessToken.getAccessToken())); // Save the state of acceptance authManager.setTermsOfUseAcceptance(principalId, true); } @Override public String getSecretKey(Long principalId) throws NotFoundException { return authManager.getSecretKey(principalId); } @Override @WriteTransaction public void deleteSecretKey(Long principalId) throws NotFoundException { authManager.changeSecretKey(principalId); } @Override public boolean hasUserAcceptedTermsOfUse(Long userId) throws NotFoundException { return authManager.hasUserAcceptedTermsOfUse(userId); } @Override public void sendPasswordResetEmail(String passwordResetUrlPrefix, String usernameOrEmail) { try { PrincipalAlias principalAlias = userManager.lookupUserByUsernameOrEmail(usernameOrEmail); PasswordResetSignedToken passwordRestToken = authManager.createPasswordResetToken(principalAlias.getPrincipalId()); messageManager.sendNewPasswordResetEmail(passwordResetUrlPrefix, passwordRestToken, principalAlias); } catch (NotFoundException e) { // should not indicate that a email/user could not be found } } @Override public OAuthUrlResponse getOAuthAuthenticationUrl(OAuthUrlRequest request) { String url = oauthManager.getAuthorizationUrl(request.getProvider(), request.getRedirectUrl(), request.getState()); OAuthUrlResponse response = new OAuthUrlResponse(); response.setAuthorizationUrl(url); return response; } @Override public LoginResponse validateOAuthAuthenticationCodeAndLogin( OAuthValidationRequest request, String tokenIssuer) throws NotFoundException { // Use the authentication code to lookup the user's information. ProvidedUserInfo providedInfo = oauthManager.validateUserWithProvider( request.getProvider(), request.getAuthenticationCode(), request.getRedirectUrl()); if(providedInfo.getUsersVerifiedEmail() == null){ throw new IllegalArgumentException("OAuthProvider: "+request.getProvider().name()+" did not provide a user email"); } // This is the ID of the user within the provider's system. PrincipalAlias emailAlias = userManager.lookupUserByUsernameOrEmail(providedInfo.getUsersVerifiedEmail()); // Return the user's access token return authManager.loginWithNoPasswordCheck(emailAlias.getPrincipalId(), tokenIssuer); } @WriteTransaction public LoginResponse createAccountViaOauth(OAuthAccountCreationRequest request, String tokenIssuer) { // Use the authentication code to lookup the user's information. ProvidedUserInfo providedInfo = oauthManager.validateUserWithProvider( request.getProvider(), request.getAuthenticationCode(), request.getRedirectUrl()); if(providedInfo.getUsersVerifiedEmail() == null){ throw new IllegalArgumentException("OAuthProvider: "+request.getProvider().name()+" did not provide a user email"); } // create account with the returned user info. NewUser newUser = new NewUser(); newUser.setEmail(providedInfo.getUsersVerifiedEmail()); newUser.setFirstName(providedInfo.getFirstName()); newUser.setLastName(providedInfo.getLastName()); newUser.setUserName(request.getUserName()); long newPrincipalId = userManager.createUser(newUser); return authManager.loginWithNoPasswordCheck(newPrincipalId, tokenIssuer); } @Override public PrincipalAlias bindExternalID(Long userId, OAuthValidationRequest validationRequest) { if (AuthorizationUtils.isUserAnonymous(userId)) throw new UnauthorizedException("User ID is required."); AliasAndType providersUserId = oauthManager.retrieveProvidersId( validationRequest.getProvider(), validationRequest.getAuthenticationCode(), validationRequest.getRedirectUrl()); // now bind the ID to the user account return userManager.bindAlias(providersUserId.getAlias(), providersUserId.getType(), userId); } @Override public void unbindExternalID(Long userId, OAuthProvider provider, String aliasName) { if (AuthorizationUtils.isUserAnonymous(userId)) throw new UnauthorizedException("User ID is required."); AliasType aliasType = oauthManager.getAliasTypeForProvider(provider); userManager.unbindAlias(aliasName, aliasType, userId); } @Override public LoginResponse login(LoginRequest request, String tokenIssuer) { return authManager.login(request, tokenIssuer); } @Override public AuthenticatedOn getAuthenticatedOn(long userId) { UserInfo userInfo = userManager.getUserInfo(userId); return authManager.getAuthenticatedOn(userInfo); } @Override public PrincipalAlias lookupUserForAuthentication(String alias) { return userManager.lookupUserByUsernameOrEmail(alias); } @Override public AccessTokenGenerationResponse createPersonalAccessToken(Long userId, String accessToken, AccessTokenGenerationRequest request, String oauthEndpoint) { UserInfo userInfo = userManager.getUserInfo(userId); return personalAccessTokenManager.issueToken(userInfo, accessToken, request, oauthEndpoint); } @Override public AccessTokenRecordList getPersonalAccessTokenRecords(Long userId, String nextPageToken) { UserInfo userInfo = userManager.getUserInfo(userId); return personalAccessTokenManager.getTokenRecords(userInfo, nextPageToken); } @Override public AccessTokenRecord getPersonalAccessTokenRecord(Long userId, Long tokenId) { UserInfo userInfo = userManager.getUserInfo(userId); return personalAccessTokenManager.getTokenRecord(userInfo, tokenId.toString()); } @Override public void revokePersonalAccessToken(Long userId, Long tokenId) { UserInfo userInfo = userManager.getUserInfo(userId); personalAccessTokenManager.revokeToken(userInfo, tokenId.toString()); } }
Sage-Bionetworks/Synapse-Repository-Services
services/repository/src/main/java/org/sagebionetworks/auth/services/AuthenticationServiceImpl.java
Java
apache-2.0
8,736
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iotevents.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/UntagResource" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UntagResourceResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UntagResourceResult == false) return false; UntagResourceResult other = (UntagResourceResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public UntagResourceResult clone() { try { return (UntagResourceResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-iotevents/src/main/java/com/amazonaws/services/iotevents/model/UntagResourceResult.java
Java
apache-2.0
2,326
/* * Copyright 2020 Google LLC * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1/model_service.proto package com.google.cloud.aiplatform.v1; /** * * * <pre> * Response message of [ModelService.ExportModel][google.cloud.aiplatform.v1.ModelService.ExportModel] operation. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ExportModelResponse} */ public final class ExportModelResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ExportModelResponse) ExportModelResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ExportModelResponse.newBuilder() to construct. private ExportModelResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExportModelResponse() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ExportModelResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ExportModelResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.ModelServiceProto .internal_static_google_cloud_aiplatform_v1_ExportModelResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.ModelServiceProto .internal_static_google_cloud_aiplatform_v1_ExportModelResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ExportModelResponse.class, com.google.cloud.aiplatform.v1.ExportModelResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1.ExportModelResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.ExportModelResponse other = (com.google.cloud.aiplatform.v1.ExportModelResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ExportModelResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.aiplatform.v1.ExportModelResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message of [ModelService.ExportModel][google.cloud.aiplatform.v1.ModelService.ExportModel] operation. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ExportModelResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ExportModelResponse) com.google.cloud.aiplatform.v1.ExportModelResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.ModelServiceProto .internal_static_google_cloud_aiplatform_v1_ExportModelResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.ModelServiceProto .internal_static_google_cloud_aiplatform_v1_ExportModelResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ExportModelResponse.class, com.google.cloud.aiplatform.v1.ExportModelResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.ExportModelResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.ModelServiceProto .internal_static_google_cloud_aiplatform_v1_ExportModelResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.ExportModelResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.ExportModelResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.ExportModelResponse build() { com.google.cloud.aiplatform.v1.ExportModelResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.ExportModelResponse buildPartial() { com.google.cloud.aiplatform.v1.ExportModelResponse result = new com.google.cloud.aiplatform.v1.ExportModelResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1.ExportModelResponse) { return mergeFrom((com.google.cloud.aiplatform.v1.ExportModelResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.ExportModelResponse other) { if (other == com.google.cloud.aiplatform.v1.ExportModelResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.aiplatform.v1.ExportModelResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.aiplatform.v1.ExportModelResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ExportModelResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ExportModelResponse) private static final com.google.cloud.aiplatform.v1.ExportModelResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ExportModelResponse(); } public static com.google.cloud.aiplatform.v1.ExportModelResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExportModelResponse> PARSER = new com.google.protobuf.AbstractParser<ExportModelResponse>() { @java.lang.Override public ExportModelResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ExportModelResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ExportModelResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExportModelResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.ExportModelResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-aiplatform
proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ExportModelResponse.java
Java
apache-2.0
16,200
/* * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. */ package com.aqua.filetransfer.ftp; import java.io.File; import java.io.FileInputStream; import java.util.Properties; import jsystem.framework.JSystemProperties; import jsystem.framework.system.SystemObjectImpl; import jsystem.utils.FileUtils; import jsystem.utils.ReflectionUtils; import jsystem.utils.StringUtils; import systemobject.terminal.Cli; import systemobject.terminal.Prompt; import com.aqua.sysobj.conn.CliConnection; import com.aqua.sysobj.conn.CliConnectionImpl; import com.aqua.sysobj.conn.CliFactory; /** * <b>SystemObject for running FTP client on a remote machine.</b><br> * The main purpose of this system object is to enable file transfer * without assuming an FTP server is running on the remote machine.<br> * In a typical usage of this SystemObject, an embedded FTP server * will be activated on the local machine. * A {@link Cli} session is opened with the remote client the session * activates the FTP client on the remote machine. <br> * * <u>Using FTPRemoteClient</u><br> * SystemObject can be instantiated from sut file or directly in the code. * Once initiated copy operations can be used. * The copy operations identifies whether a connection is already open if not * a connection is opened.<br> * In many cases the remote server (telnet/ssh) limits number of connections; * use the {@link #closeFTPSession()} to close connection when needed.<br> * * Passivation: since TAS 4.9 the sys object support passivation. Please note that passivation * is only supported when the remote client is a linux machine. * In case the built-in prompts are not enough to open an FTP session * with the FTP server you are using the system object also supports adding additional FTP prompts. * To do that write a property file called {@link #FILE_TRANSFER_PROPERTIES_FILE_NAME} * (in run directory) and add to it the following properties: * {@link #FTP_LOGIN_PROMPTS} - comma seperated prompts which identifies that * the FTP server waits for the user to enter the login user name * * {@link #FTP_PASSWORD_PROMPTS} - comma seperated prompts which identifies that * the FTP server waits for the user to enter the password * * {@link #FTP_PROMPTS} - comma seperated prompts which identifies that * the FTP server is waiting for an ftp command * * Since TAS 4.9 cli connectivity parameters to can be set using CliConnection. * This can be done either by passing a CliConnection to the FtpRemoteClient constructor * or setting the <code>cliConnection</code> member through the SUT file. * When connectivity parameters are set using a CliConnection other connectivity * parameters are ignored (host,operatingSystem,protocol,port,user,password). * * FTP Server address: * ------------------- * FTP Server address is fetched as following: * If the user gave value to the member {@link #ftpServerHostName} through the SUT file * or by activating it's setter this will be the server to which the remote ftp client will * try to connect. * Next, when connecting, the system object will try to fetch the property {@value #LOCAL_HOST_ADDRESS_PROPERTY} * from the jsystem.properties file, if the property was set it will use it as server address * otherwise, the system object uses java API to get local machine host name and uses it as server address. */ public class FTPRemoteClient extends SystemObjectImpl { public static final String FILE_TRANSFER_PROPERTIES_FILE_NAME = "filetransfer.properties"; public static final String FTP_PROMPTS = "ftp.prompts"; public static final String FTP_LOGIN_PROMPTS = "ftp.login.prompts"; public static final String FTP_PASSWORD_PROMPTS = "ftp.password.prompts"; public static final String LOCAL_HOST_ADDRESS_PROPERTY = "local.host.external.name"; public CliConnection cliConnection; private Cli cli; private String host; private String operatingSystem = CliFactory.OPERATING_SYSTEM_WINDOWS; private String protocol = "telnet"; private int port = 23; private String user; private String password; private String ftpServerHostName; private String ftpUserName="aqua"; private String ftpPassword="aqua"; private boolean ascii ; private Prompt[] ftpGeneralPrompts; private Prompt[] ftpLoginPrompts; private Prompt[] ftpPasswordPrompts; private java.net.InetAddress localMachine; private boolean promptOn = true; /** */ public FTPRemoteClient(CliConnection cliConn,String ftpServerHostName) throws Exception{ cliConnection = cliConn; setFtpServerHostName(ftpServerHostName); } /** * Constructs a FTPRemoteClient for working on local machine as the remote machine.<br> * Used for testing purposes. */ public FTPRemoteClient() throws Exception{ localMachine = java.net.InetAddress.getLocalHost(); setHost(localMachine.getHostName()); } /** * Constructs a FTPRemoteClient were remote machine is this machine. * The FTPRemoteClient assumes Aqua's embedded FTP server is running on * this machine. */ public FTPRemoteClient(String user,String password) throws Exception { this(); setUser(user); setPassword(password); } /** * Constructs a FTPRemoteClient were remote machine is <code>host</code>. * The FTPRemoteClient assumes Aqua's embedded FTP server is running on * this machine. */ public FTPRemoteClient(String host,String telnetUser,String telnetPassword,String ftpServerHostName) throws Exception{ this(telnetUser,telnetPassword); setHost(host); setFtpServerHostName(ftpServerHostName); } /** * Initializes {@link FTPRemoteClient} members and verifies that * a telnet connection can be opened to the remote client and * that the remote client can open a FTP connection to the server.<br> * All connections are closed when initialization is done. * @see SystemObjectImpl#init() */ public void init() throws Exception { super.init(); initPrompts(); } /** * Closes connection to remote machine. */ public void closeFTPSession(){ closeFtp(); closeCli(); } /** * Copies a file from FTP server machine(in most cases it will be the local machine) * to the remote client.<br> * Source file path should be relative to FTP user home directory and not absolute * file path. * Destination can be either absolute destination path or relative to client's * user directory.<br> */ public void copyFileFromLocalMachineToRemoteClient(String source, String destination) throws Exception { StringBuffer stringbuffer = new StringBuffer("get "); destination = adjustPath(destination); stringbuffer.append(source); stringbuffer.append(" "); stringbuffer.append(destination); copyFileViaFTP(stringbuffer.toString()); } /** * Copies all files from FTP server machine(in most cases it will be the local machine) * to the remote client.<br> * * @param filesPath - String Array (String...) of full file path.<br> * @throws Exception */ public void copyAllFilesFromLocalMachineToLocalRemote(String... filesPath) throws Exception{ copyAllFilesViaFTP("mget ", filesPath); } /** * Copies a file from the remote client to FTP server machine(in most cases it will be * the local machine) * * Source file path can be either absolute destination path or relative to client's * user directory. * Destination should be relative to FTP user home directory and not absolute * file path. */ public void copyFileFromRemoteClientToLocalMachine(String source, String destination) throws Exception { source = adjustPath(source); StringBuffer stringbuffer = new StringBuffer("put "); stringbuffer.append(source); stringbuffer.append(" "); stringbuffer.append(destination); copyFileViaFTP(stringbuffer.toString()); } /** * Copies all files from remote client to FTP server machine(in most cases it will be * the local machine).<br> * * @param filesPath - String Array (String...) of full file path.<br> * @throws Exception */ public void copyAllFilesFromRemoteMachineToLocalMachine(String... filesPath) throws Exception{ copyAllFilesViaFTP("mput ", filesPath); } private void copyFileViaFTP(String command) throws Exception { openFTPSession(); setAsciiMode(isAscii()); setPromptMode(isPromptOn()); runCliCommand(command); } private void copyAllFilesViaFTP(String command, String... filesPath) throws Exception { StringBuffer stringBuffer = new StringBuffer(command); openFTPSession(); setAsciiMode(isAscii()); setPromptMode(isPromptOn()); for(String currentFilePath : filesPath){ String source = adjustPath(currentFilePath); stringBuffer.append(source); stringBuffer.append(" "); } runCliCommand(stringBuffer.toString()); } private void runCliCommand(String command) throws Exception{ cli.command(command , 1000 *60 * 5,true,false,null,ftpGeneralPrompts); if (cli.getResult().indexOf("226") < 0){ throw new Exception("Failed in files transfer"); } } /** * Changes ftp session mode to passive */ public void passivate(boolean isPassive) throws Exception { openFTPSession(); for (int i = 0; i < 2;i++){ cli.command("passive",1000*60,true,false,null,ftpGeneralPrompts); String result = cli.getResult().toLowerCase(); boolean on = result.indexOf("on") >= 0; boolean off = result.indexOf("off")>= 0; boolean notSupported = result.indexOf("invalid")>= 0; if (notSupported){ throw new Exception("Passivation not supported"); } if ((isPassive && on) ||(!isPassive && off) ){ break; } } } /** * Terminates FTPRemoteClient. */ public void close() { closeFTPSession(); super.close(); } /** * Opens FTP session */ private void openFTPSession() throws Exception { initCli(); ftpLogin(); } /** */ private void initCli() throws Exception { if (cli == null){ if (cliConnection != null){ initCliFromCliConnectionImpl(); return; } Prompt p = new Prompt(); p.setPrompt(">"); p.setCommandEnd(true); cli = CliFactory.createCli(getHost(),getOperatingSystem(), getProtocol(),getUser(),getPassword(),new Prompt[]{p}); } } private void initCliFromCliConnectionImpl() throws Exception{ if (!cliConnection.isConnected()){ cliConnection.connect(); } cli = (Cli)ReflectionUtils.getField("cli", CliConnectionImpl.class).get(cliConnection); } /** */ private void closeFtp(){ try { cli.command("bye", 1000 *2 ,true,false,null,new Prompt[]{new Prompt("bye.",true)}); if (cli.getResult().indexOf("221") < 0){ report.report("Did not find success code 221"); } }catch (Exception e){ report.report("Could not find prompt after closing session. " + e.getMessage()); } } /** */ private void closeCli(){ if (cli != null){ try { if (cliConnection != null){ closeCliConnectionImpl(); } cli.close(); }catch (Exception e){ report.report("Failed closing telnet connection",e); } } cli=null; } private void closeCliConnectionImpl() throws Exception{ if (cliConnection.isConnected()){ cliConnection.disconnect(); } } /** * Starts FTP client and performs login. */ private void ftpLogin() throws Exception{ cli.command(""); String result = cli.getResult(); for (String ftpPrompt:promptsToStringArray(ftpGeneralPrompts)){ if (result.indexOf(ftpPrompt) >=0 ){ //we are already logged in return; } } String serverAddress = getFTPServerAddress(); cli.command("ftp " + serverAddress, 1000*60,true,false,null,ftpLoginPrompts); if (cli.getResult().indexOf("220") < 0){ throw new Exception("Failed connecting to FTP server.("+serverAddress+"). Please verify that there is a ping between the remote client to the runner machine"); } cli.command(getFtpUserName(),1000*60,true,false,null,ftpPasswordPrompts); if (cli.getResult().indexOf("331") < 0){ throw new Exception("Failed in login process"); } cli.command(getFtpPassword(),1000*60,true,false,null,ftpGeneralPrompts); if (cli.getResult().indexOf("230") < 0){ throw new Exception("User not authorized to login"); } } /** * Changes ftp session mode (ascii/binary) */ private void setAsciiMode(boolean isAscii) throws Exception { String command = "binary"; if (isAscii){ command="ascii"; } cli.command(command,1000*60,true,false,null,ftpGeneralPrompts); if (cli.getResult().indexOf("200") < 0){ throw new Exception("Failed changing to binary mode"); } } /** * Changes the FTP session mode ( on / off ) * @param promptOn * @throws Exception */ private void setPromptMode(boolean promptOn) throws Exception{ String command = "prompt off"; if (promptOn){ command="prompt on"; } cli.command(command,1000*60,true,false,null,ftpGeneralPrompts); if (cli.getResult().indexOf("Interactive") < 0){ throw new Exception("Failed changing prompt mode"); } } public boolean isPromptOn() { return promptOn; } public void setPromptOn(boolean promptOn) { this.promptOn = promptOn; } /** * Adjusts file path to operating system. */ private String adjustPath(String path) { if (CliFactory.OPERATING_SYSTEM_WINDOWS.equals(getOperatingSystem())){ String toReturn = FileUtils.convertToWindowsPath(path); if (!toReturn.startsWith("\"")){ toReturn = "\""+toReturn+"\""; } return toReturn; }else { return FileUtils.replaceSeparator(path); } } /** * */ private void initPrompts() throws Exception { String[] defaultFTPPrompts = new String[]{"ftp>"}; String[] defaultLoginPrompts = new String[]{"):"}; String[] defaultPasswordPrompts = new String[]{"for "+getFtpUserName(),"Password:"}; if (!new File(FILE_TRANSFER_PROPERTIES_FILE_NAME).exists()){ ftpGeneralPrompts = stringArrayToPrompts(defaultFTPPrompts); ftpLoginPrompts = stringArrayToPrompts(defaultLoginPrompts); ftpPasswordPrompts = stringArrayToPrompts(defaultPasswordPrompts); return; } Properties props = new Properties(); FileInputStream stream = new FileInputStream(FILE_TRANSFER_PROPERTIES_FILE_NAME); try { props.load(stream); }finally{ try{stream.close();}catch(Exception e){}; } String ftpPrompts = props.getProperty(FTP_PROMPTS); String[] ftpPromptsAsStringArray = StringUtils.split(ftpPrompts, ";, "); ftpPromptsAsStringArray = StringUtils.mergeStringArrays(new String[][]{ftpPromptsAsStringArray,defaultFTPPrompts}); ftpGeneralPrompts = stringArrayToPrompts(ftpPromptsAsStringArray); String _ftpLoginPrompts = props.getProperty(FTP_LOGIN_PROMPTS); String[] ftpLoginPromptsAsStringArray = StringUtils.split(_ftpLoginPrompts, ";, "); ftpLoginPromptsAsStringArray = StringUtils.mergeStringArrays(new String[][]{ftpLoginPromptsAsStringArray,defaultLoginPrompts}); ftpLoginPrompts = stringArrayToPrompts(ftpLoginPromptsAsStringArray); String _ftpPasswordPrompts = props.getProperty(FTP_PASSWORD_PROMPTS); String[] ftpPasswordPromptsAsStringArray = StringUtils.split(_ftpPasswordPrompts, ";, "); ftpPasswordPromptsAsStringArray = StringUtils.mergeStringArrays(new String[][]{ftpPasswordPromptsAsStringArray,defaultPasswordPrompts}); ftpPasswordPrompts = stringArrayToPrompts(ftpPasswordPromptsAsStringArray); } private String[] promptsToStringArray(Prompt[] prompts){ if (prompts == null){ return new String[0]; } String[] res = new String[prompts.length]; int i=0; for (Prompt p:prompts){ res[i]=p.getPrompt(); i++; } return res; } private Prompt[] stringArrayToPrompts(String[] promptsAsString){ if (promptsAsString == null){ return new Prompt[0]; } Prompt[] res = new Prompt[promptsAsString.length]; int i=0; for (String s:promptsAsString){ res[i]=new Prompt(s,false); res[i].setCommandEnd(true); i++; } return res; } private String getFTPServerAddress(){ if (!StringUtils.isEmpty(getFtpServerHostName())){ return getFtpServerHostName(); } if (!StringUtils.isEmpty(JSystemProperties.getInstance().getPreference(LOCAL_HOST_ADDRESS_PROPERTY))){ return JSystemProperties.getInstance().getPreference(LOCAL_HOST_ADDRESS_PROPERTY); } return localMachine.getHostName(); } /********************************************************************** * FTPRemoteClient setters and getters *********************************************************************/ public String getHost() { return host; } public String getOperatingSystem() { return operatingSystem; } public void setOperatingSystem(String operatingSystem) { this.operatingSystem = operatingSystem; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public void setHost(String remoteHost) { this.host = remoteHost; } public String getPassword() { return password; } public void setPassword(String telnetPassword) { this.password = telnetPassword; } public int getPort() { return port; } public void setPort(int telnetPort) { this.port = telnetPort; } public String getUser() { return user; } public void setUser(String telnetUser) { this.user = telnetUser; } public String getFtpServerHostName() { return ftpServerHostName; } public void setFtpServerHostName(String ftpServerHostName) { this.ftpServerHostName = ftpServerHostName; } public String getFtpUserName() { return ftpUserName; } public void setFtpUserName(String ftpUserName) { this.ftpUserName = ftpUserName; } public String getFtpPassword() { return ftpPassword; } public void setFtpPassword(String ftpPassword) { this.ftpPassword = ftpPassword; } public boolean isAscii() { return ascii; } public void setAscii(boolean ascii) { this.ascii = ascii; } }
Top-Q/jsystem
jsystem-core-system-objects/FileTransfer-so/src/main/java/com/aqua/filetransfer/ftp/FTPRemoteClient.java
Java
apache-2.0
17,775
/******************************************************************************* * Copyright 2017 Bstek * * 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.bstek.uflo.command.impl; import java.util.List; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import com.bstek.uflo.command.Command; import com.bstek.uflo.env.Context; import com.bstek.uflo.model.HistoryTask; /** * @author Jacky.gao * @since 2013年9月12日 */ public class GetListHistoryTasksCommand implements Command<List<HistoryTask>> { private long processInstanceId; public GetListHistoryTasksCommand(long processInstanceId) { this.processInstanceId = processInstanceId; } @SuppressWarnings("unchecked") public List<HistoryTask> execute(Context context) { return context.getSession().createCriteria(HistoryTask.class) .add(Restrictions.eq("processInstanceId", processInstanceId)) .addOrder(Order.desc("endDate")).list(); } }
youseries/uflo
uflo-core/src/main/java/com/bstek/uflo/command/impl/GetListHistoryTasksCommand.java
Java
apache-2.0
1,555
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.elasticmapreduce.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DescribeClusterResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeClusterResultJsonUnmarshaller implements Unmarshaller<DescribeClusterResult, JsonUnmarshallerContext> { public DescribeClusterResult unmarshall(JsonUnmarshallerContext context) throws Exception { DescribeClusterResult describeClusterResult = new DescribeClusterResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return describeClusterResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Cluster", targetDepth)) { context.nextToken(); describeClusterResult.setCluster(ClusterJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return describeClusterResult; } private static DescribeClusterResultJsonUnmarshaller instance; public static DescribeClusterResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DescribeClusterResultJsonUnmarshaller(); return instance; } }
dagnir/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/DescribeClusterResultJsonUnmarshaller.java
Java
apache-2.0
2,841
package no.dusken.momus.model.websocket; public enum Action { CREATE, UPDATE, DELETE }
Studentmediene/Momus
src/main/java/no/dusken/momus/model/websocket/Action.java
Java
apache-2.0
91
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.demonstrations.imageprocessing; import boofcv.abst.distort.FDistort; import boofcv.alg.filter.kernel.GKernelMath; import boofcv.alg.filter.kernel.SteerableKernel; import boofcv.alg.misc.GImageStatistics; import boofcv.core.image.GeneralizedImageOps; import boofcv.gui.ListDisplayPanel; import boofcv.gui.SelectAlgorithmPanel; import boofcv.gui.image.VisualizeImageData; import boofcv.struct.convolve.Kernel2D; import boofcv.struct.image.ImageGray; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** * Visualizes steerable kernels. * * @author Peter Abeles */ public abstract class DisplaySteerableBase<T extends ImageGray<T>, K extends Kernel2D> extends SelectAlgorithmPanel { protected static int imageSize = 400; protected static int radius = 100; protected Class<T> imageType; protected Class<K> kernelType; ListDisplayPanel basisPanel = new ListDisplayPanel(); ListDisplayPanel steerPanel = new ListDisplayPanel(); T largeImg; List<DisplayGaussianKernelApp.DerivType> order = new ArrayList<>(); protected DisplaySteerableBase( Class<T> imageType, Class<K> kernelType ) { this.imageType = imageType; this.kernelType = kernelType; largeImg = GeneralizedImageOps.createSingleBand(imageType, imageSize, imageSize); addAlgorithm("Deriv X", new DisplayGaussianKernelApp.DerivType(1, 0)); addAlgorithm("Deriv XX", new DisplayGaussianKernelApp.DerivType(2, 0)); addAlgorithm("Deriv XXX", new DisplayGaussianKernelApp.DerivType(3, 0)); addAlgorithm("Deriv XXXX", new DisplayGaussianKernelApp.DerivType(4, 0)); addAlgorithm("Deriv XY", new DisplayGaussianKernelApp.DerivType(1, 1)); addAlgorithm("Deriv XXY", new DisplayGaussianKernelApp.DerivType(2, 1)); addAlgorithm("Deriv XYY", new DisplayGaussianKernelApp.DerivType(1, 2)); addAlgorithm("Deriv XXXY", new DisplayGaussianKernelApp.DerivType(3, 1)); addAlgorithm("Deriv XXYY", new DisplayGaussianKernelApp.DerivType(2, 2)); addAlgorithm("Deriv XYYY", new DisplayGaussianKernelApp.DerivType(1, 3)); JPanel content = new JPanel(new GridLayout(0, 2)); content.add(basisPanel); content.add(steerPanel); setMainGUI(content); } protected abstract SteerableKernel<K> createKernel( int orderX, int orderY ); @Override public void setActiveAlgorithm( String name, Object cookie ) { DisplayGaussianKernelApp.DerivType dt = (DisplayGaussianKernelApp.DerivType)cookie; // add basis SteerableKernel<K> steerable = createKernel(dt.orderX, dt.orderY); basisPanel.reset(); for (int i = 0; i < steerable.getBasisSize(); i++) { T smallImg = GKernelMath.convertToImage(steerable.getBasis(i)); new FDistort(smallImg, largeImg).scaleExt().interpNN().apply(); double maxValue = GImageStatistics.maxAbs(largeImg); BufferedImage out = VisualizeImageData.colorizeSign(largeImg, null, maxValue); basisPanel.addImage(out, "Basis " + i); } // add steered kernels steerPanel.reset(); for (int i = 0; i <= 20; i++) { double angle = Math.PI*i/20.0; K kernel = steerable.compute(angle); T smallImg = GKernelMath.convertToImage(kernel); new FDistort(smallImg, largeImg).scaleExt().interpNN().apply(); double maxValue = GImageStatistics.maxAbs(largeImg); BufferedImage out = VisualizeImageData.colorizeSign(largeImg, null, maxValue); steerPanel.addImage(out, String.format("%5d", (int)(180.0*angle/Math.PI))); } repaint(); } }
lessthanoptimal/BoofCV
demonstrations/src/main/java/boofcv/demonstrations/imageprocessing/DisplaySteerableBase.java
Java
apache-2.0
4,148
/** * Copyright 2011-2017 Asakusa Framework Team. * * 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.asakusafw.compiler.batch; import com.asakusafw.compiler.batch.batch.JobFlow1; import com.asakusafw.vocabulary.batch.Batch; import com.asakusafw.vocabulary.batch.BatchDescription; /** * A batch class which is not public. */ @Batch(name = "testing") class NotPublic extends BatchDescription { @Override protected void describe() { run(JobFlow1.class).soon(); } }
cocoatomo/asakusafw
mapreduce/compiler/core/src/test/java/com/asakusafw/compiler/batch/NotPublic.java
Java
apache-2.0
1,012
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for CustomTargetingValue.Status. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="CustomTargetingValue.Status"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="ACTIVE"/> * &lt;enumeration value="INACTIVE"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "CustomTargetingValue.Status") @XmlEnum public enum CustomTargetingValueStatus { /** * * The object is active. * * */ ACTIVE, /** * * The object is no longer active. * * */ INACTIVE, /** * * The value returned if the actual value is not exposed by the requested * API version. * * */ UNKNOWN; public String value() { return name(); } public static CustomTargetingValueStatus fromValue(String v) { return valueOf(v); } }
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/CustomTargetingValueStatus.java
Java
apache-2.0
1,306
/* ### * IP: GHIDRA * REVIEWED: YES * * 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 ghidra.app.plugin.core.compositeeditor; /** * Composite Viewer Model component selection change listener interface. */ public interface CompositeModelSelectionListener { /** * Called to indicate the model's component selection has changed. */ void selectionChanged(); }
NationalSecurityAgency/ghidra
Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/compositeeditor/CompositeModelSelectionListener.java
Java
apache-2.0
904
/* * This file is part of "lunisolar-magma". * * (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/). * * 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 eu.lunisolar.magma.asserts.func.function.to; import eu.lunisolar.magma.asserts.func.FunctionalAttest.AssertionsCheck; import eu.lunisolar.magma.asserts.func.FunctionalAttest.SemiEvaluation; import eu.lunisolar.magma.func.supp.Be; import eu.lunisolar.magma.asserts.func.FunctionalAttest; import eu.lunisolar.magma.asserts.func.FunctionalAttest.*; import javax.annotation.Nonnull; // NOSONAR import javax.annotation.Nullable; // NOSONAR import eu.lunisolar.magma.func.supp.check.Checks; // NOSONAR import eu.lunisolar.magma.basics.meta.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR import eu.lunisolar.magma.func.action.*; // NOSONAR import java.util.function.*; import eu.lunisolar.magma.func.function.to.*; import eu.lunisolar.magma.func.action.*; // NOSONAR import eu.lunisolar.magma.func.consumer.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR import eu.lunisolar.magma.func.function.*; // NOSONAR import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR import eu.lunisolar.magma.func.function.from.*; // NOSONAR import eu.lunisolar.magma.func.function.to.*; // NOSONAR import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR import eu.lunisolar.magma.func.predicate.*; // NOSONAR import eu.lunisolar.magma.func.supplier.*; // NOSONAR import eu.lunisolar.magma.func.function.to.LToIntBiFunction.*; /** Assert class for LToIntObj1Obj0Func. */ public final class LToIntObj1Obj0FuncAttest<T2, T1> extends FunctionalAttest.Full<LToIntObj1Obj0FuncAttest<T2, T1>, LToIntObj1Obj0Func<T2, T1>, LBiConsumer<T2, T1>, Checks.CheckInt> { public LToIntObj1Obj0FuncAttest(LToIntObj1Obj0Func<T2, T1> actual) { super(actual); } @Nonnull public static <T2, T1> LToIntObj1Obj0FuncAttest<T2, T1> attestToIntObj1Obj0Func(LToIntBiFunction.LToIntObj1Obj0Func<T2, T1> func) { return new LToIntObj1Obj0FuncAttest(func); } @Nonnull public IntEvaluation<LToIntObj1Obj0FuncAttest<T2, T1>, LBiConsumer<T2, T1>> doesApplyAsInt(T2 a2, T1 a1) { return new IntEvaluation<LToIntObj1Obj0FuncAttest<T2, T1>, LBiConsumer<T2, T1>>(this, () -> String.format("(%s,%s)", a2, a1), (desc, pc) -> { var func = value(); Checks.check(func).must(Be::notNull, "Actual function is null."); if (pc != null) { pc.accept(a2, a1); } var result = func.applyAsIntObj1Obj0(a2, a1); return Checks.attest(result, desc); }, recurringAssert); } }
lunisolar/magma
magma-asserts/src/main/java/eu/lunisolar/magma/asserts/func/function/to/LToIntObj1Obj0FuncAttest.java
Java
apache-2.0
3,567
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.glue.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/CreateCrawler" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateCrawlerRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * Name of the new crawler. * </p> */ private String name; /** * <p> * The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources. * </p> */ private String role; /** * <p> * The Glue database where results are written, such as: * <code>arn:aws:daylight:us-east-1::database/sometable/*</code>. * </p> */ private String databaseName; /** * <p> * A description of the new crawler. * </p> */ private String description; /** * <p> * A list of collection of targets to crawl. * </p> */ private CrawlerTargets targets; /** * <p> * A <code>cron</code> expression used to specify the schedule (see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for * Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify: * <code>cron(15 12 * * ? *)</code>. * </p> */ private String schedule; /** * <p> * A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a * crawl, but these custom classifiers always override the default classifiers for a given classification. * </p> */ private java.util.List<String> classifiers; /** * <p> * The table prefix used for catalog tables that are created. * </p> */ private String tablePrefix; /** * <p> * The policy for the crawler's update and deletion behavior. * </p> */ private SchemaChangePolicy schemaChangePolicy; /** * <p> * A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since * the last crawler run. * </p> */ private RecrawlPolicy recrawlPolicy; /** * <p> * Specifies data lineage configuration settings for the crawler. * </p> */ private LineageConfiguration lineageConfiguration; private LakeFormationConfiguration lakeFormationConfiguration; /** * <p> * Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's * behavior. For more information, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>. * </p> */ private String configuration; /** * <p> * The name of the <code>SecurityConfiguration</code> structure to be used by this crawler. * </p> */ private String crawlerSecurityConfiguration; /** * <p> * The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information * about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web * Services Tags in Glue</a> in the developer guide. * </p> */ private java.util.Map<String, String> tags; /** * <p> * Name of the new crawler. * </p> * * @param name * Name of the new crawler. */ public void setName(String name) { this.name = name; } /** * <p> * Name of the new crawler. * </p> * * @return Name of the new crawler. */ public String getName() { return this.name; } /** * <p> * Name of the new crawler. * </p> * * @param name * Name of the new crawler. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withName(String name) { setName(name); return this; } /** * <p> * The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources. * </p> * * @param role * The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer * resources. */ public void setRole(String role) { this.role = role; } /** * <p> * The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources. * </p> * * @return The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer * resources. */ public String getRole() { return this.role; } /** * <p> * The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources. * </p> * * @param role * The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer * resources. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withRole(String role) { setRole(role); return this; } /** * <p> * The Glue database where results are written, such as: * <code>arn:aws:daylight:us-east-1::database/sometable/*</code>. * </p> * * @param databaseName * The Glue database where results are written, such as: * <code>arn:aws:daylight:us-east-1::database/sometable/*</code>. */ public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } /** * <p> * The Glue database where results are written, such as: * <code>arn:aws:daylight:us-east-1::database/sometable/*</code>. * </p> * * @return The Glue database where results are written, such as: * <code>arn:aws:daylight:us-east-1::database/sometable/*</code>. */ public String getDatabaseName() { return this.databaseName; } /** * <p> * The Glue database where results are written, such as: * <code>arn:aws:daylight:us-east-1::database/sometable/*</code>. * </p> * * @param databaseName * The Glue database where results are written, such as: * <code>arn:aws:daylight:us-east-1::database/sometable/*</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withDatabaseName(String databaseName) { setDatabaseName(databaseName); return this; } /** * <p> * A description of the new crawler. * </p> * * @param description * A description of the new crawler. */ public void setDescription(String description) { this.description = description; } /** * <p> * A description of the new crawler. * </p> * * @return A description of the new crawler. */ public String getDescription() { return this.description; } /** * <p> * A description of the new crawler. * </p> * * @param description * A description of the new crawler. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * A list of collection of targets to crawl. * </p> * * @param targets * A list of collection of targets to crawl. */ public void setTargets(CrawlerTargets targets) { this.targets = targets; } /** * <p> * A list of collection of targets to crawl. * </p> * * @return A list of collection of targets to crawl. */ public CrawlerTargets getTargets() { return this.targets; } /** * <p> * A list of collection of targets to crawl. * </p> * * @param targets * A list of collection of targets to crawl. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withTargets(CrawlerTargets targets) { setTargets(targets); return this; } /** * <p> * A <code>cron</code> expression used to specify the schedule (see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for * Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify: * <code>cron(15 12 * * ? *)</code>. * </p> * * @param schedule * A <code>cron</code> expression used to specify the schedule (see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based * Schedules for Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would * specify: <code>cron(15 12 * * ? *)</code>. */ public void setSchedule(String schedule) { this.schedule = schedule; } /** * <p> * A <code>cron</code> expression used to specify the schedule (see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for * Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify: * <code>cron(15 12 * * ? *)</code>. * </p> * * @return A <code>cron</code> expression used to specify the schedule (see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based * Schedules for Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would * specify: <code>cron(15 12 * * ? *)</code>. */ public String getSchedule() { return this.schedule; } /** * <p> * A <code>cron</code> expression used to specify the schedule (see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for * Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify: * <code>cron(15 12 * * ? *)</code>. * </p> * * @param schedule * A <code>cron</code> expression used to specify the schedule (see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based * Schedules for Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would * specify: <code>cron(15 12 * * ? *)</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withSchedule(String schedule) { setSchedule(schedule); return this; } /** * <p> * A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a * crawl, but these custom classifiers always override the default classifiers for a given classification. * </p> * * @return A list of custom classifiers that the user has registered. By default, all built-in classifiers are * included in a crawl, but these custom classifiers always override the default classifiers for a given * classification. */ public java.util.List<String> getClassifiers() { return classifiers; } /** * <p> * A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a * crawl, but these custom classifiers always override the default classifiers for a given classification. * </p> * * @param classifiers * A list of custom classifiers that the user has registered. By default, all built-in classifiers are * included in a crawl, but these custom classifiers always override the default classifiers for a given * classification. */ public void setClassifiers(java.util.Collection<String> classifiers) { if (classifiers == null) { this.classifiers = null; return; } this.classifiers = new java.util.ArrayList<String>(classifiers); } /** * <p> * A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a * crawl, but these custom classifiers always override the default classifiers for a given classification. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setClassifiers(java.util.Collection)} or {@link #withClassifiers(java.util.Collection)} if you want to * override the existing values. * </p> * * @param classifiers * A list of custom classifiers that the user has registered. By default, all built-in classifiers are * included in a crawl, but these custom classifiers always override the default classifiers for a given * classification. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withClassifiers(String... classifiers) { if (this.classifiers == null) { setClassifiers(new java.util.ArrayList<String>(classifiers.length)); } for (String ele : classifiers) { this.classifiers.add(ele); } return this; } /** * <p> * A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a * crawl, but these custom classifiers always override the default classifiers for a given classification. * </p> * * @param classifiers * A list of custom classifiers that the user has registered. By default, all built-in classifiers are * included in a crawl, but these custom classifiers always override the default classifiers for a given * classification. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withClassifiers(java.util.Collection<String> classifiers) { setClassifiers(classifiers); return this; } /** * <p> * The table prefix used for catalog tables that are created. * </p> * * @param tablePrefix * The table prefix used for catalog tables that are created. */ public void setTablePrefix(String tablePrefix) { this.tablePrefix = tablePrefix; } /** * <p> * The table prefix used for catalog tables that are created. * </p> * * @return The table prefix used for catalog tables that are created. */ public String getTablePrefix() { return this.tablePrefix; } /** * <p> * The table prefix used for catalog tables that are created. * </p> * * @param tablePrefix * The table prefix used for catalog tables that are created. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withTablePrefix(String tablePrefix) { setTablePrefix(tablePrefix); return this; } /** * <p> * The policy for the crawler's update and deletion behavior. * </p> * * @param schemaChangePolicy * The policy for the crawler's update and deletion behavior. */ public void setSchemaChangePolicy(SchemaChangePolicy schemaChangePolicy) { this.schemaChangePolicy = schemaChangePolicy; } /** * <p> * The policy for the crawler's update and deletion behavior. * </p> * * @return The policy for the crawler's update and deletion behavior. */ public SchemaChangePolicy getSchemaChangePolicy() { return this.schemaChangePolicy; } /** * <p> * The policy for the crawler's update and deletion behavior. * </p> * * @param schemaChangePolicy * The policy for the crawler's update and deletion behavior. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withSchemaChangePolicy(SchemaChangePolicy schemaChangePolicy) { setSchemaChangePolicy(schemaChangePolicy); return this; } /** * <p> * A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since * the last crawler run. * </p> * * @param recrawlPolicy * A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were * added since the last crawler run. */ public void setRecrawlPolicy(RecrawlPolicy recrawlPolicy) { this.recrawlPolicy = recrawlPolicy; } /** * <p> * A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since * the last crawler run. * </p> * * @return A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were * added since the last crawler run. */ public RecrawlPolicy getRecrawlPolicy() { return this.recrawlPolicy; } /** * <p> * A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since * the last crawler run. * </p> * * @param recrawlPolicy * A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were * added since the last crawler run. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withRecrawlPolicy(RecrawlPolicy recrawlPolicy) { setRecrawlPolicy(recrawlPolicy); return this; } /** * <p> * Specifies data lineage configuration settings for the crawler. * </p> * * @param lineageConfiguration * Specifies data lineage configuration settings for the crawler. */ public void setLineageConfiguration(LineageConfiguration lineageConfiguration) { this.lineageConfiguration = lineageConfiguration; } /** * <p> * Specifies data lineage configuration settings for the crawler. * </p> * * @return Specifies data lineage configuration settings for the crawler. */ public LineageConfiguration getLineageConfiguration() { return this.lineageConfiguration; } /** * <p> * Specifies data lineage configuration settings for the crawler. * </p> * * @param lineageConfiguration * Specifies data lineage configuration settings for the crawler. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withLineageConfiguration(LineageConfiguration lineageConfiguration) { setLineageConfiguration(lineageConfiguration); return this; } /** * @param lakeFormationConfiguration */ public void setLakeFormationConfiguration(LakeFormationConfiguration lakeFormationConfiguration) { this.lakeFormationConfiguration = lakeFormationConfiguration; } /** * @return */ public LakeFormationConfiguration getLakeFormationConfiguration() { return this.lakeFormationConfiguration; } /** * @param lakeFormationConfiguration * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withLakeFormationConfiguration(LakeFormationConfiguration lakeFormationConfiguration) { setLakeFormationConfiguration(lakeFormationConfiguration); return this; } /** * <p> * Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's * behavior. For more information, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>. * </p> * * @param configuration * Crawler configuration information. This versioned JSON string allows users to specify aspects of a * crawler's behavior. For more information, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>. */ public void setConfiguration(String configuration) { this.configuration = configuration; } /** * <p> * Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's * behavior. For more information, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>. * </p> * * @return Crawler configuration information. This versioned JSON string allows users to specify aspects of a * crawler's behavior. For more information, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>. */ public String getConfiguration() { return this.configuration; } /** * <p> * Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's * behavior. For more information, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>. * </p> * * @param configuration * Crawler configuration information. This versioned JSON string allows users to specify aspects of a * crawler's behavior. For more information, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withConfiguration(String configuration) { setConfiguration(configuration); return this; } /** * <p> * The name of the <code>SecurityConfiguration</code> structure to be used by this crawler. * </p> * * @param crawlerSecurityConfiguration * The name of the <code>SecurityConfiguration</code> structure to be used by this crawler. */ public void setCrawlerSecurityConfiguration(String crawlerSecurityConfiguration) { this.crawlerSecurityConfiguration = crawlerSecurityConfiguration; } /** * <p> * The name of the <code>SecurityConfiguration</code> structure to be used by this crawler. * </p> * * @return The name of the <code>SecurityConfiguration</code> structure to be used by this crawler. */ public String getCrawlerSecurityConfiguration() { return this.crawlerSecurityConfiguration; } /** * <p> * The name of the <code>SecurityConfiguration</code> structure to be used by this crawler. * </p> * * @param crawlerSecurityConfiguration * The name of the <code>SecurityConfiguration</code> structure to be used by this crawler. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withCrawlerSecurityConfiguration(String crawlerSecurityConfiguration) { setCrawlerSecurityConfiguration(crawlerSecurityConfiguration); return this; } /** * <p> * The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information * about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web * Services Tags in Glue</a> in the developer guide. * </p> * * @return The tags to use with this crawler request. You may use tags to limit access to the crawler. For more * information about tags in Glue, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web Services Tags in Glue</a> * in the developer guide. */ public java.util.Map<String, String> getTags() { return tags; } /** * <p> * The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information * about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web * Services Tags in Glue</a> in the developer guide. * </p> * * @param tags * The tags to use with this crawler request. You may use tags to limit access to the crawler. For more * information about tags in Glue, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web Services Tags in Glue</a> * in the developer guide. */ public void setTags(java.util.Map<String, String> tags) { this.tags = tags; } /** * <p> * The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information * about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web * Services Tags in Glue</a> in the developer guide. * </p> * * @param tags * The tags to use with this crawler request. You may use tags to limit access to the crawler. For more * information about tags in Glue, see <a * href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web Services Tags in Glue</a> * in the developer guide. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; } /** * Add a single Tags entry * * @see CreateCrawlerRequest#withTags * @returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest addTagsEntry(String key, String value) { if (null == this.tags) { this.tags = new java.util.HashMap<String, String>(); } if (this.tags.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.tags.put(key, value); return this; } /** * Removes all the entries added into Tags. * * @return Returns a reference to this object so that method calls can be chained together. */ public CreateCrawlerRequest clearTagsEntries() { this.tags = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getRole() != null) sb.append("Role: ").append(getRole()).append(","); if (getDatabaseName() != null) sb.append("DatabaseName: ").append(getDatabaseName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getTargets() != null) sb.append("Targets: ").append(getTargets()).append(","); if (getSchedule() != null) sb.append("Schedule: ").append(getSchedule()).append(","); if (getClassifiers() != null) sb.append("Classifiers: ").append(getClassifiers()).append(","); if (getTablePrefix() != null) sb.append("TablePrefix: ").append(getTablePrefix()).append(","); if (getSchemaChangePolicy() != null) sb.append("SchemaChangePolicy: ").append(getSchemaChangePolicy()).append(","); if (getRecrawlPolicy() != null) sb.append("RecrawlPolicy: ").append(getRecrawlPolicy()).append(","); if (getLineageConfiguration() != null) sb.append("LineageConfiguration: ").append(getLineageConfiguration()).append(","); if (getLakeFormationConfiguration() != null) sb.append("LakeFormationConfiguration: ").append(getLakeFormationConfiguration()).append(","); if (getConfiguration() != null) sb.append("Configuration: ").append(getConfiguration()).append(","); if (getCrawlerSecurityConfiguration() != null) sb.append("CrawlerSecurityConfiguration: ").append(getCrawlerSecurityConfiguration()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateCrawlerRequest == false) return false; CreateCrawlerRequest other = (CreateCrawlerRequest) obj; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getRole() == null ^ this.getRole() == null) return false; if (other.getRole() != null && other.getRole().equals(this.getRole()) == false) return false; if (other.getDatabaseName() == null ^ this.getDatabaseName() == null) return false; if (other.getDatabaseName() != null && other.getDatabaseName().equals(this.getDatabaseName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getTargets() == null ^ this.getTargets() == null) return false; if (other.getTargets() != null && other.getTargets().equals(this.getTargets()) == false) return false; if (other.getSchedule() == null ^ this.getSchedule() == null) return false; if (other.getSchedule() != null && other.getSchedule().equals(this.getSchedule()) == false) return false; if (other.getClassifiers() == null ^ this.getClassifiers() == null) return false; if (other.getClassifiers() != null && other.getClassifiers().equals(this.getClassifiers()) == false) return false; if (other.getTablePrefix() == null ^ this.getTablePrefix() == null) return false; if (other.getTablePrefix() != null && other.getTablePrefix().equals(this.getTablePrefix()) == false) return false; if (other.getSchemaChangePolicy() == null ^ this.getSchemaChangePolicy() == null) return false; if (other.getSchemaChangePolicy() != null && other.getSchemaChangePolicy().equals(this.getSchemaChangePolicy()) == false) return false; if (other.getRecrawlPolicy() == null ^ this.getRecrawlPolicy() == null) return false; if (other.getRecrawlPolicy() != null && other.getRecrawlPolicy().equals(this.getRecrawlPolicy()) == false) return false; if (other.getLineageConfiguration() == null ^ this.getLineageConfiguration() == null) return false; if (other.getLineageConfiguration() != null && other.getLineageConfiguration().equals(this.getLineageConfiguration()) == false) return false; if (other.getLakeFormationConfiguration() == null ^ this.getLakeFormationConfiguration() == null) return false; if (other.getLakeFormationConfiguration() != null && other.getLakeFormationConfiguration().equals(this.getLakeFormationConfiguration()) == false) return false; if (other.getConfiguration() == null ^ this.getConfiguration() == null) return false; if (other.getConfiguration() != null && other.getConfiguration().equals(this.getConfiguration()) == false) return false; if (other.getCrawlerSecurityConfiguration() == null ^ this.getCrawlerSecurityConfiguration() == null) return false; if (other.getCrawlerSecurityConfiguration() != null && other.getCrawlerSecurityConfiguration().equals(this.getCrawlerSecurityConfiguration()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getRole() == null) ? 0 : getRole().hashCode()); hashCode = prime * hashCode + ((getDatabaseName() == null) ? 0 : getDatabaseName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getTargets() == null) ? 0 : getTargets().hashCode()); hashCode = prime * hashCode + ((getSchedule() == null) ? 0 : getSchedule().hashCode()); hashCode = prime * hashCode + ((getClassifiers() == null) ? 0 : getClassifiers().hashCode()); hashCode = prime * hashCode + ((getTablePrefix() == null) ? 0 : getTablePrefix().hashCode()); hashCode = prime * hashCode + ((getSchemaChangePolicy() == null) ? 0 : getSchemaChangePolicy().hashCode()); hashCode = prime * hashCode + ((getRecrawlPolicy() == null) ? 0 : getRecrawlPolicy().hashCode()); hashCode = prime * hashCode + ((getLineageConfiguration() == null) ? 0 : getLineageConfiguration().hashCode()); hashCode = prime * hashCode + ((getLakeFormationConfiguration() == null) ? 0 : getLakeFormationConfiguration().hashCode()); hashCode = prime * hashCode + ((getConfiguration() == null) ? 0 : getConfiguration().hashCode()); hashCode = prime * hashCode + ((getCrawlerSecurityConfiguration() == null) ? 0 : getCrawlerSecurityConfiguration().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public CreateCrawlerRequest clone() { return (CreateCrawlerRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/CreateCrawlerRequest.java
Java
apache-2.0
36,471
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.cloudwatch.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.cloudwatch.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * ListDashboardsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListDashboardsRequestMarshaller implements Marshaller<Request<ListDashboardsRequest>, ListDashboardsRequest> { public Request<ListDashboardsRequest> marshall(ListDashboardsRequest listDashboardsRequest) { if (listDashboardsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } Request<ListDashboardsRequest> request = new DefaultRequest<ListDashboardsRequest>(listDashboardsRequest, "AmazonCloudWatch"); request.addParameter("Action", "ListDashboards"); request.addParameter("Version", "2010-08-01"); request.setHttpMethod(HttpMethodName.POST); if (listDashboardsRequest.getDashboardNamePrefix() != null) { request.addParameter("DashboardNamePrefix", StringUtils.fromString(listDashboardsRequest.getDashboardNamePrefix())); } if (listDashboardsRequest.getNextToken() != null) { request.addParameter("NextToken", StringUtils.fromString(listDashboardsRequest.getNextToken())); } return request; } }
aws/aws-sdk-java
aws-java-sdk-cloudwatch/src/main/java/com/amazonaws/services/cloudwatch/model/transform/ListDashboardsRequestMarshaller.java
Java
apache-2.0
2,151
/* * Copyright 2013 Thomas Bocek * * 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 net.tomp2p.futures; /** * A generic future that can be used to set a future to complete with an attachment. * * @author Thomas Bocek * * @param <K> */ public class FutureDone<K> extends BaseFutureImpl<FutureDone<K>> { public static FutureDone<Void> SUCCESS = new FutureDone<Void>().done(); private K object; /** * Creates a new future for the shutdown operation. */ public FutureDone() { self(this); } /** * Set future as finished and notify listeners. * * @return This class */ public FutureDone<K> done() { done(null); return this; } /** * Set future as finished and notify listeners. * * @param object * An object that can be attached. * @return This class */ public FutureDone<K> done(final K object) { synchronized (lock) { if (!completedAndNotify()) { return this; } this.object = object; this.type = BaseFuture.FutureType.OK; } notifyListeners(); return this; } /** * @return The attached object */ public K object() { synchronized (lock) { return object; } } }
jonaswagner/TomP2P
core/src/main/java/net/tomp2p/futures/FutureDone.java
Java
apache-2.0
1,873
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.talend.sdk.component.api.configuration.constraint; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Collection; import org.talend.sdk.component.api.configuration.constraint.meta.Validation; import org.talend.sdk.component.api.meta.Documentation; @Validation(expectedTypes = Collection.class, name = "uniqueItems") @Target({ FIELD, PARAMETER }) @Retention(RUNTIME) @Documentation("Ensure the elements of the collection must be distinct (kind of set).") public @interface Uniques { }
chmyga/component-runtime
component-api/src/main/java/org/talend/sdk/component/api/configuration/constraint/Uniques.java
Java
apache-2.0
1,331
package de.mhu.com.morse.channel.sql; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; import java.util.Iterator; import java.util.LinkedList; import de.mhu.lib.ASql; import de.mhu.lib.dtb.Sth; import de.mhu.com.morse.aaa.IAclManager; import de.mhu.com.morse.channel.CMql; import de.mhu.com.morse.channel.IChannelDriverServer; import de.mhu.com.morse.channel.IConnectionServer; import de.mhu.com.morse.channel.IQueryFunction; import de.mhu.com.morse.channel.IQueryWhereFunction; import de.mhu.com.morse.mql.ICompiledQuery; import de.mhu.com.morse.types.IAttribute; import de.mhu.com.morse.types.IAttributeDefault; import de.mhu.com.morse.types.ITypes; import de.mhu.com.morse.usr.UserInformation; import de.mhu.com.morse.utils.AttributeUtil; import de.mhu.com.morse.utils.MorseException; public class WhereSqlListener implements WhereParser.IWhereListener { private StringBuffer sb = null; private Descriptor desc; private SqlDriver driver; private IConnectionServer con; private ITypes types; private IAclManager aclm; private UserInformation user; private ICompiledQuery code; private boolean needComma; public WhereSqlListener( SqlDriver pDriver, IConnectionServer pCon, ITypes pTypes, IAclManager pAclm, UserInformation pUser, Descriptor pDesc, ICompiledQuery pCode, StringBuffer dest ) { desc = pDesc; driver = pDriver; con = pCon; types = pTypes; aclm = pAclm; user = pUser; code = pCode; sb = dest; } public int appendTableSelect(String name, int off) throws MorseException { name = name.toLowerCase(); if ( ! AttributeUtil.isAttrName( name, true ) ) throw new MorseException( MorseException.UNKNOWN_ATTRIBUTE, name ); Object[] obj = desc.attrMap.get( name ); if ( obj == null ) throw new MorseException( MorseException.UNKNOWN_ATTRIBUTE, name ); if ( obj.length == 0 ) throw new MorseException( MorseException.ATTR_AMBIGIOUS, name ); String tName = (String)obj[3]; int pos = tName.indexOf('.'); if ( pos < 0 ) tName = IAttribute.M_ID; else tName = tName.substring( 0, pos + 1 ) + IAttribute.M_ID; sb.append( driver.getColumnName( tName ) ); sb.append( " IN ( SELECT " ); sb.append( driver.getColumnName( IAttribute.M_ID ) ); sb.append( " FROM r_" ); sb.append( ((IAttribute)obj[1]).getSourceType().getName() ).append( '_' ).append( ((IAttribute)obj[1]).getName() ); sb.append( " WHERE " ); Descriptor desc2 = new Descriptor(); Attr a = new Attr(); a.name = IAttribute.M_ID; desc2.addAttr( a ); // find all tables / types Table newTable = new Table(); newTable.name = ((IAttribute)obj[1]).getSourceType().getName() + '.' + ((IAttribute)obj[1]).getName(); desc2.addTable( newTable ); SqlUtils.checkTables( desc2, types, con, user, aclm ); SqlUtils.checkAttributes( con, desc2, user, aclm ); off+=2; off = SqlUtils.createWhereClause( con, driver, off, code, desc2, types, sb, user, aclm ); // sb.append( ')' ); off++; return off; } public void brackedClose() { sb.append( ')' ); } public void brackedOpen() { sb.append( '(' ); } public void compareEQ(String left, String right) { sb.append( left ).append( '=' ).append( right ); } public void compareGT(String left, String right) { sb.append( left ).append( '>' ).append( right ); } public void compareGTEQ(String left, String right) { sb.append( left ).append( ">=" ).append( right ); } public void compareINBegin(String left) { sb.append( left ).append( " IN (" ); needComma = false; } public void compareINEnd() { sb.append( ')' ); } public void compareINValue(String string) { if ( needComma ) sb.append( ',' ); needComma = true; sb.append( string ); } public void compareLIKE(String left, String right) { sb.append( left ).append( " LIKE " ).append( right ); } public void compareLT(String left, String right) { sb.append( left ).append( '<' ).append( right ); } public void compareLTEQ(String left, String right) { sb.append( left ).append( "<=" ).append( right ); } public void compareNOTEQ(String left, String right) { sb.append( left ).append( "!=" ).append( right ); } public int compareSubSelect(String name, int off, boolean distinct) throws MorseException { Descriptor desc2 = new Descriptor(); off = SqlUtils.findAttributes(off, code, desc2); if ( desc.attrSize == 0 ) throw new MorseException( MorseException.NO_ATTRIBUTES ); off++; // FROM // find all tables / types off = SqlUtils.findTables(off, code, desc2 ); SqlUtils.checkTables( desc2, types, con, user, aclm ); SqlUtils.checkAttributes( con, desc2, user, aclm ); SqlUtils.postCheckAttributes( desc2 ); SqlUtils.checkFunctions( con, desc2, desc2, user, driver.getAclManager() ); StringBuffer sb2 = new StringBuffer(); SqlUtils.createSelect( driver, desc2, sb2, distinct ); boolean hasWhere = false; if ( SqlUtils.needHintWhere( driver, desc2 ) ) { if ( ! hasWhere ) { sb2.append( " WHERE (" ); } else { sb2.append( " AND (" ); } SqlUtils.createHintWhereClause( con, driver, desc2, driver.getTypes(), sb2, user, aclm ); sb2.append( " ) " ); hasWhere = true; } if ( code.getInteger( off ) == CMql.WHERE ) { if ( ! hasWhere ) { sb2.append( " WHERE (" ); } else { sb2.append( " AND (" ); } off++; off = SqlUtils.createWhereClause( con, driver, off, code, desc2, types, sb2, user, aclm ); } sb.append( name ).append( " IN ( " ).append( sb2.toString() ).append( " ) "); off++; // ) return off; } public String executeFunction( IQueryFunction function, LinkedList<Object> functionAttrs ) throws MorseException { // Object[] obj = desc.attrMap.get( aName.toLowerCase() ); if ( function instanceof IQuerySqlFunction ) { String[] attrs = (String[])functionAttrs.toArray( new String[ functionAttrs.size() ] ); for ( int j = 0; j < attrs.length; j++ ) { attrs[j] = SqlUtils.checkAttribute( driver, null, attrs[j], desc, user ); } return ((IQuerySqlFunction)function).appendSqlCommand( driver, attrs ); } else { Object[] values = new Object[ functionAttrs.size() ]; Class[] classes = new Class[ functionAttrs.size() ]; int cnt = 0; for ( Iterator i = functionAttrs.iterator(); i.hasNext(); ) { values[cnt] = i.next(); classes[cnt] = values[cnt].getClass(); cnt++; } if ( function instanceof IQueryWhereFunction ) return ((IQueryWhereFunction)function).getSingleResult( values ); else { try { function.getClass().getMethod( "append", classes ).invoke( function, values ); } catch (Exception e) { throw new MorseException( MorseException.ERROR, e ); } return function.getResult(); } } } public void appendInFunction( String left, IQueryFunction function, LinkedList<Object> functionAttrs) throws MorseException { Sth sth = null; String tmpName = null; try { Object[] obj = desc.attrMap.get( left.toLowerCase() ); tmpName = "x_" + driver.getNextTmpId(); String drop = driver.getDropTmpTableSql( tmpName ); sth = driver.internatConnection.getPool().aquireStatement(); if ( drop != null ) { try { sth.executeUpdate( drop ); } catch ( SQLException sqle ) { } } String create = new StringBuffer() .append( driver.getCreateTmpTablePrefixSql() ) .append( ' ' ) .append( tmpName ) .append( " ( v " ) .append( driver.getColumnDefinition( (IAttribute)obj[1], false ) ) .append( ") ") .append( driver.getCreateTmpTableSuffixSql() ) .toString(); sth.executeUpdate( create ); sth.executeUpdate( driver.getCreateTmpIndexSql( 1, tmpName, "v" ) ); if ( ! ( function instanceof IQueryWhereFunction ) ) throw new MorseException( MorseException.FUNCTION_NOT_COMPATIBLE ); Iterator<String> res = ((IQueryWhereFunction)function).getRepeatingResult( (Object[])functionAttrs.toArray( new Object[ functionAttrs.size() ] ) ); while ( res.hasNext() ) { String insert = "INSERT INTO " + tmpName + "(v) VALUES (" + SqlUtils.getValueRepresentation(driver, (IAttribute)obj[1], res.next() ) + ")"; sth.executeUpdate( insert ); } } catch ( Exception sqle ) { if ( sqle instanceof MorseException ) throw (MorseException)sqle; throw new MorseException( MorseException.ERROR, sqle ); } finally { try { sth.release(); } catch ( Exception ex ) {} } desc.addTmpTable( tmpName ); sb.append( " IN ( SELECT v FROM " ).append( tmpName ).append( " ) "); } public void operatorAnd() { sb.append( " AND " ); } public void operatorNot() { sb.append( " NOT " ); } public void operatorOr() { sb.append( " OR " ); } public String transformAttribute(String name) throws MorseException { Object[] obj = desc.attrMap.get( name ); if ( obj == null ) throw new MorseException( MorseException.UNKNOWN_ATTRIBUTE, name ); if ( obj.length == 0 ) throw new MorseException( MorseException.ATTR_AMBIGIOUS, name ); String tName = (String)obj[3]; /* int pos = tName.indexOf('.'); if ( pos < 0 ) tName = IAttribute.M_ID; else tName = tName.substring( 0, pos + 1 ) + IAttribute.M_ID; */ return driver.getColumnName( tName ); // return SqlUtils.checkAttribute( driver, null, name, desc, user ); } public Object transformValue( String attrName, String name) throws MorseException { if ( ! AttributeUtil.isValue( name ) ) throw new MorseException( MorseException.WRONG_VALUE_FORMAT, name ); if ( attrName != null ) { Object[] obj = desc.attrMap.get( attrName.toLowerCase() ); if ( obj != null && obj.length != 0 && obj[1] != null ) { IAttribute attr = (IAttribute)obj[1]; String value = name; if ( name.length() > 1 && name.charAt( 0 ) == '\'' && name.charAt( name.length() - 1 ) == '\'' ) value = ASql.unescape( name.substring( 1, name.length() - 1 ) ); if ( ! attr.getAco().validate( value ) ) throw new MorseException( MorseException.ATTR_VALUE_NOT_VALIDE, new String[] { attrName, name } ); return SqlUtils.getValueRepresentation( driver, attr, value ); } else { IAttribute attr = IAttributeDefault.getAttribute( attrName ); if ( attr != null ) return SqlUtils.getValueRepresentation( driver, attr, name ); } } return name; } }
mhus/mhus-inka
de.mhus.app.inka.morse.server/src/de/mhu/com/morse/channel/sql/WhereSqlListener.java
Java
apache-2.0
10,620
/* * Copyright 2016 Code Above Lab LLC * * 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.codeabovelab.dm.common.utils; import java.util.function.Function; import java.util.function.IntPredicate; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; /** */ public class StringUtils { private StringUtils() { } public static String before(String s, char c) { return beforeOr(s, c, () -> { // we throw exception for preserve old behavior throw new IllegalArgumentException("String '" + s + "' must contains '" + c + "'."); }); } /** * Return part of 's' before 'c' * @param s string which may contain char 'c' * @param c char * @param ifNone supplier of value which is used when 'c' is not present in 's' (null not allowed) * @return part of 's' before 'c' or 'ifNone.get()' */ public static String beforeOr(String s, char c, Supplier<String> ifNone) { int pos = s.indexOf(c); if(pos < 0) { return ifNone.get(); } return s.substring(0, pos); } public static String after(String s, char c) { int pos = s.indexOf(c); if(pos < 0) { throw new IllegalArgumentException("String '" + s + "' must contains '" + c + "'."); } return s.substring(pos + 1); } public static String beforeLast(String s, char c) { int pos = s.lastIndexOf(c); if(pos < 0) { throw new IllegalArgumentException("String '" + s + "' must contains '" + c + "'."); } return s.substring(0, pos); } public static String afterLast(String s, char c) { int pos = s.lastIndexOf(c); if(pos < 0) { throw new IllegalArgumentException("String '" + s + "' must contains '" + c + "'."); } return s.substring(pos + 1); } /** * Split string into two pieces at last appearing of delimiter. * @param s string * @param c delimiter * @return null if string does not contains delimiter */ public static String[] splitLast(String s, char c) { int pos = s.lastIndexOf(c); if(pos < 0) { return null; } return new String[] {s.substring(0, pos), s.substring(pos + 1)}; } /** * Split string into two pieces at last appearing of delimiter. * @param s string * @param delimiter delimiter * @return null if string does not contains delimiter */ public static String[] splitLast(String s, String delimiter) { int pos = s.lastIndexOf(delimiter); if(pos < 0) { return null; } return new String[] {s.substring(0, pos), s.substring(pos + delimiter.length())}; } /** * Return string which contains only chars for which charJudge give true. * @param src source string, may be null * @param charJudge predicate which consume codePoint (not chars) * @return string, null when incoming string is null */ public static String retain(String src, IntPredicate charJudge) { if (src == null) { return null; } final int length = src.length(); StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { int cp = src.codePointAt(i); if(charJudge.test(cp)) { sb.appendCodePoint(cp); } } return sb.toString(); } /** * Retain only characters which is {@link #isAz09(int)} * @param src source string, may be null * @return string, null when incoming string is null */ public static String retainAz09(String src) { return retain(src, StringUtils::isAz09); } /** * Retain chars which is acceptable as file name or part of url on most operation systems. <p/> * It: <code>'A'-'z', '0'-'9', '_', '-', '.'</code> * @param src source string, may be null * @return string, null when incoming string is null */ public static String retainForFileName(String src) { return retain(src, StringUtils::isAz09); } /** * Test that specified codePoint is an ASCII letter or digit * @param cp codePoint * @return true for specified chars */ public static boolean isAz09(int cp) { return cp >= '0' && cp <= '9' || cp >= 'a' && cp <= 'z' || cp >= 'A' && cp <= 'Z'; } /** * Test that specified codePoint is an ASCII letter, digit or hyphen '-'. * @param cp codePoint * @return true for specified chars */ public static boolean isAz09Hyp(int cp) { return isAz09(cp) || cp == '-'; } /** * Test that specified codePoint is an ASCII letter, digit or hyphen '-', '_', ':', '.'. <p/> * It common matcher that limit alphabet acceptable for our system IDs. * @param cp codePoint * @return true for specified chars */ public static boolean isId(int cp) { return isAz09(cp) || cp == '-' || cp == '_' || cp == ':' || cp == '.'; } public static boolean isHex(int cp) { return cp >= '0' && cp <= '9' || cp >= 'a' && cp <= 'f' || cp >= 'A' && cp <= 'F'; } /** * Chars which is acceptable as file name or part of url on most operation systems. <p/> * It: <code>'A'-'z', '0'-'9', '_', '-', '.'</code> * @param cp codePoint * @return true for specified chars */ public static boolean isForFileName(int cp) { return isAz09(cp) || cp == '-' || cp == '_' || cp == '.'; } /** * Invoke {@link Object#toString()} on specified argument, if arg is null then return null. * @param o * @return null or result of o.toString() */ public static String valueOf(Object o) { return o == null? null : o.toString(); } /** * Test that each char of specified string match for predicate. <p/> * Note that it method does not support unicode, because it usual applicable only for match letters that placed under 128 code. * @param str string * @param predicate char matcher * @return true if all chars match */ public static boolean match(String str, IntPredicate predicate) { final int len = str.length(); if(len == 0) { return false; } for(int i = 0; i < len; i++) { if(!predicate.test(str.charAt(i))) { return false; } } return true; } /** * Is a <code>match(str, StringUtils::isAz09);</code>. * @param str string * @return true if string match [A-Za-z0-9]* */ public static boolean matchAz09(String str) { return match(str, StringUtils::isAz09); } /** * Is a <code>match(str, StringUtils::isAz09Hyp);</code>. * @param str string * @return true if string match [A-Za-z0-9-]* */ public static boolean matchAz09Hyp(String str) { return match(str, StringUtils::isAz09Hyp); } /** * Is a <code>match(str, StringUtils::isId);</code>. * @param str string * @return true if string match [A-Za-z0-9-_:.]* */ public static boolean matchId(String str) { return match(str, StringUtils::isId); } public static boolean matchHex(String str) { return match(str, StringUtils::isHex); } /** * Replace string with pattern obtaining replacement values through handler function. <p/> * Note that it differ from usual Pattern behavior when it process replacement for group references, * this code do nothing with replacement. * @param pattern pattern * @param src source string * @param handler function which take matched part of source string and return replacement value, must never return null * @return result string */ public static String replace(Pattern pattern, String src, Function<String, String> handler) { StringBuilder sb = null; Matcher matcher = pattern.matcher(src); int pos = 0; while(matcher.find()) { if(sb == null) { // replacement can be a very rare operation, and we not need excess string buffer sb = new StringBuilder(); } String expr = matcher.group(); String replacement = handler.apply(expr); sb.append(src, pos, matcher.start()); sb.append(replacement); pos = matcher.end(); } if(sb == null) { return src; } sb.append(src, pos, src.length()); return sb.toString(); } }
codeabovelab/haven-platform
common/common-utils/src/main/java/com/codeabovelab/dm/common/utils/StringUtils.java
Java
apache-2.0
9,252
/* * Copyright 2015 Namihiko Matsumura (https://github.com/n-i-e/) * * 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.github.n_i_e.deepfolderview; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.PojoProperties; import org.eclipse.core.databinding.observable.Realm; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.wb.swt.SWTResourceManager; import com.github.n_i_e.dirtreedb.Assertion; import com.github.n_i_e.dirtreedb.DBPathEntry; import com.github.n_i_e.dirtreedb.PathEntry; import com.github.n_i_e.dirtreedb.lazy.LazyRunnable; import com.github.n_i_e.dirtreedb.lazy.LazyUpdater; import com.github.n_i_e.dirtreedb.lazy.LazyUpdater.Dispatcher; import com.ibm.icu.text.NumberFormat; import com.ibm.icu.text.SimpleDateFormat; public class SwtFileFolderMenu extends SwtCommonFileFolderMenu { @SuppressWarnings("unused") private DataBindingContext m_bindingContext; protected Shell shell; private FormToolkit formToolkit = new FormToolkit(Display.getDefault()); private Text txtLocation; private Composite compositeToolBar; private Table table; private Label lblStatusBar; private Composite compositeStatusBar; private ProgressBar progressBar; @Override protected Shell getShell() { return shell; } @Override protected Table getTable() { return table; } @Override protected Label getLblStatusBar() { return lblStatusBar; } @Override protected ProgressBar getProgressBar() { return progressBar; } public static void main(String[] args) { final Display display = Display.getDefault(); Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() { public void run() { try { final SwtFileFolderMenu window = new SwtFileFolderMenu(); window.open(); /* display.asyncExec(new Runnable() { public void run() { TableItem tableItem = new TableItem(window.table, SWT.NONE); tableItem.setText(new String[] {"C:\\", "2015-01-01 00:00:00", "1", "2", "3"}); TableItem tableItem_1 = new TableItem(window.table, SWT.NONE); tableItem_1.setText(new String[] {"D:\\", "2014-01-01 00:00:00", "100", "200", "1"}); } });*/ } catch (Exception e) { e.printStackTrace(); } } }); } public void open() { Display display = Display.getDefault(); //createContents(); //shell.open(); //shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } public SwtFileFolderMenu() { createContents(); shell.open(); shell.layout(); location = new NavigatableList<Location>(); location.add(new Location()); } /** * Create contents of the window. */ private void createContents() { shell = new Shell(); shell.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent arg0) { Point p = shell.getSize(); PreferenceRW.setSwtFileFolderMenuWindowWidth(p.x); PreferenceRW.setSwtFileFolderMenuWindowHeight(p.y); } }); shell.setImage(SWTResourceManager.getImage(SwtFileFolderMenu.class, "/com/github/n_i_e/deepfolderview/icon/drive-harddisk.png")); shell.setMinimumSize(new Point(300, 200)); shell.setSize(PreferenceRW.getSwtFileFolderMenuWindowWidth(), PreferenceRW.getSwtFileFolderMenuWindowHeight()); GridLayout gl_shell = new GridLayout(1, false); gl_shell.verticalSpacing = 6; gl_shell.marginWidth = 3; gl_shell.marginHeight = 3; gl_shell.horizontalSpacing = 6; shell.setLayout(gl_shell); Menu menu = new Menu(shell, SWT.BAR); shell.setMenuBar(menu); MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE); mntmFile.setText(Messages.mntmFile_text); Menu menuFile = new Menu(mntmFile); mntmFile.setMenu(menuFile); MenuItem mntmOpen_1 = new MenuItem(menuFile, SWT.NONE); mntmOpen_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onOpenSelected(e); } }); mntmOpen_1.setText(Messages.mntmOpen_text); MenuItem mntmOpenInNew_1 = new MenuItem(menuFile, SWT.NONE); mntmOpenInNew_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onOpenInNewWindowSelected(e); } }); mntmOpenInNew_1.setText(Messages.mntmOpenInNewWindow_text); MenuItem mntmOpenDuplicateDetails_1 = new MenuItem(menuFile, SWT.NONE); mntmOpenDuplicateDetails_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onOpenDuplicateDetailsSelected(e); } }); mntmOpenDuplicateDetails_1.setText(Messages.mntmOpenDuplicateDetails_text); MenuItem mntmCopyTo_2 = new MenuItem(menuFile, SWT.NONE); mntmCopyTo_2.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCopyToSelected(); } }); mntmCopyTo_2.setText(Messages.mntmCopyTo_text); MenuItem mntmClose = new MenuItem(menuFile, SWT.NONE); mntmClose.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCloseSelected(); } }); mntmClose.setText(Messages.mntmClose_text); MenuItem mntmQuit = new MenuItem(menuFile, SWT.NONE); mntmQuit.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onQuitSelected(); } }); mntmQuit.setText(Messages.mntmQuit_text); MenuItem mntmEdit = new MenuItem(menu, SWT.CASCADE); mntmEdit.setText(Messages.mntmEdit_text); Menu menuEdit = new Menu(mntmEdit); mntmEdit.setMenu(menuEdit); MenuItem mntmRun_1 = new MenuItem(menuEdit, SWT.NONE); mntmRun_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onRunSelected(); } }); mntmRun_1.setText(Messages.mntmRun_text); MenuItem mntmCopyAsString_1 = new MenuItem(menuEdit, SWT.NONE); mntmCopyAsString_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCopyAsStringSelected(); } }); mntmCopyAsString_1.setText(Messages.mntmCopyAsString_text); MenuItem mntmCopyTo_1 = new MenuItem(menuEdit, SWT.NONE); mntmCopyTo_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCopyToSelected(); } }); mntmCopyTo_1.setText(Messages.mntmCopyTo_text); MenuItem mntmVisibility = new MenuItem(menu, SWT.CASCADE); mntmVisibility.setText(Messages.mntmVisibility_text); Menu menuVisibility = new Menu(mntmVisibility); mntmVisibility.setMenu(menuVisibility); final MenuItem mntmFoldersVisible = new MenuItem(menuVisibility, SWT.CHECK); mntmFoldersVisible.setSelection(true); mntmFoldersVisible.setText(Messages.mntmFoldersVisible_text); final MenuItem mntmFilesVisible = new MenuItem(menuVisibility, SWT.CHECK); mntmFilesVisible.setSelection(true); mntmFilesVisible.setText(Messages.mntmFilesVisible_text); final MenuItem mntmCompressedFoldersVisible = new MenuItem(menuVisibility, SWT.CHECK); mntmCompressedFoldersVisible.setSelection(true); mntmCompressedFoldersVisible.setText(Messages.mntmCompressedFoldersVisible_text); final MenuItem mntmCompressedFilesVisible = new MenuItem(menuVisibility, SWT.CHECK); mntmCompressedFilesVisible.setSelection(true); mntmCompressedFilesVisible.setText(Messages.mntmCompressedFilesVisible_text); MenuItem mntmHelp = new MenuItem(menu, SWT.CASCADE); mntmHelp.setText(Messages.mntmHelp_text); Menu menuHelp = new Menu(mntmHelp); mntmHelp.setMenu(menuHelp); MenuItem mntmOpenSourceLicenses = new MenuItem(menuHelp, SWT.NONE); mntmOpenSourceLicenses.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new SwtOpenSourceLicenses(shell, SWT.TITLE|SWT.MIN|SWT.MAX|SWT.CLOSE).open(); } }); mntmOpenSourceLicenses.setText(Messages.mntmOpenSourceLicenses_text); compositeToolBar = new Composite(shell, SWT.NONE); compositeToolBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); compositeToolBar.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND)); compositeToolBar.setFont(SWTResourceManager.getFont("Meiryo UI", 12, SWT.NORMAL)); GridLayout gl_compositeToolBar = new GridLayout(5, false); gl_compositeToolBar.horizontalSpacing = 0; gl_compositeToolBar.verticalSpacing = 0; gl_compositeToolBar.marginWidth = 0; gl_compositeToolBar.marginHeight = 0; compositeToolBar.setLayout(gl_compositeToolBar); formToolkit.adapt(compositeToolBar); formToolkit.paintBordersFor(compositeToolBar); Button btnLeft = new Button(compositeToolBar, SWT.NONE); btnLeft.setImage(SWTResourceManager.getImage(SwtFileFolderMenu.class, "/com/github/n_i_e/deepfolderview/icon/go-previous.png")); btnLeft.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onNavigatePreviousSelected(e); } }); btnLeft.setFont(SWTResourceManager.getFont("Meiryo UI", 11, SWT.NORMAL)); formToolkit.adapt(btnLeft, true, true); Button btnRight = new Button(compositeToolBar, SWT.NONE); btnRight.setImage(SWTResourceManager.getImage(SwtFileFolderMenu.class, "/com/github/n_i_e/deepfolderview/icon/go-next.png")); btnRight.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onNavigateNextSelected(e); } }); btnRight.setFont(SWTResourceManager.getFont("Meiryo UI", 11, SWT.NORMAL)); formToolkit.adapt(btnRight, true, true); Button btnUp = new Button(compositeToolBar, SWT.NONE); btnUp.setImage(SWTResourceManager.getImage(SwtFileFolderMenu.class, "/com/github/n_i_e/deepfolderview/icon/go-up.png")); btnUp.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onUpperFolderSelected(e); } }); formToolkit.adapt(btnUp, true, true); txtLocation = new Text(compositeToolBar, SWT.BORDER); txtLocation.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { onLocationModified(arg0); } }); GridData gd_txtLocation = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_txtLocation.widthHint = 200; txtLocation.setLayoutData(gd_txtLocation); txtLocation.setFont(SWTResourceManager.getFont("Meiryo UI", 11, SWT.NORMAL)); formToolkit.adapt(txtLocation, true, true); Button btnRefresh = new Button(compositeToolBar, SWT.NONE); btnRefresh.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { refresh(); } }); btnRefresh.setImage(SWTResourceManager.getImage(SwtFileFolderMenu.class, "/com/github/n_i_e/deepfolderview/icon/view-refresh.png")); formToolkit.adapt(btnRefresh, true, true); final TableViewer tableViewer = new TableViewer(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION | SWT.VIRTUAL); table = tableViewer.getTable(); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); //table = new Table(scrolledComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.VIRTUAL); table.setHeaderVisible(true); table.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onTableSelected(e); } @Override public void widgetDefaultSelected(SelectionEvent e) { onOpenSelected(e); } }); formToolkit.adapt(table); formToolkit.paintBordersFor(table); final TableColumn tblclmnPath = new TableColumn(table, SWT.LEFT); tblclmnPath.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setSortColumn(tblclmnPath); if (table.getSortDirection() == SWT.UP) { table.setSortDirection(SWT.DOWN); } else { table.setSortDirection(SWT.UP); } onTblclmnPathSelected(tblclmnPath, e); } }); tblclmnPath.setWidth(230); tblclmnPath.setText(Messages.tblclmnPath_text); setTableSortDirection(tblclmnPath, "path", order); final TableColumn tblclmnDateLastModified = new TableColumn(table, SWT.LEFT); tblclmnDateLastModified.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setSortColumn(tblclmnDateLastModified); if (table.getSortDirection() == SWT.UP) { table.setSortDirection(SWT.DOWN); } else { table.setSortDirection(SWT.UP); } onTblclmnDateLastModifiedSelected(tblclmnDateLastModified, e); } }); tblclmnDateLastModified.setWidth(136); tblclmnDateLastModified.setText(Messages.tblclmnDateLastModified_text); setTableSortDirection(tblclmnDateLastModified, "datelastmodified", order); final TableColumn tblclmnSize = new TableColumn(table, SWT.RIGHT); tblclmnSize.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setSortColumn(tblclmnSize); if (table.getSortDirection() == SWT.UP) { table.setSortDirection(SWT.DOWN); } else { table.setSortDirection(SWT.UP); } onTblclmnSizeSelected(tblclmnSize, e); } }); tblclmnSize.setWidth(110); tblclmnSize.setText(Messages.tblclmnSize_text); setTableSortDirection(tblclmnSize, "size", order); final TableColumn tblclmnCompressedsize = new TableColumn(table, SWT.RIGHT); tblclmnCompressedsize.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setSortColumn(tblclmnCompressedsize); if (table.getSortDirection() == SWT.UP) { table.setSortDirection(SWT.DOWN); } else { table.setSortDirection(SWT.UP); } onTblclmnCompressedsizeSelected(tblclmnCompressedsize, e); } }); tblclmnCompressedsize.setWidth(110); tblclmnCompressedsize.setText(Messages.tblclmnCompressedesize_text); setTableSortDirection(tblclmnCompressedsize, "compressedsize", order); final TableColumn tblclmnDuplicate = new TableColumn(table, SWT.NONE); tblclmnDuplicate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setSortColumn(tblclmnDuplicate); if (table.getSortDirection() == SWT.UP) { table.setSortDirection(SWT.DOWN); } else { table.setSortDirection(SWT.UP); } onTblclmnDuplicateSelected(tblclmnDuplicate, e); } }); tblclmnDuplicate.setWidth(35); tblclmnDuplicate.setText(Messages.tblclmnDuplicate_text); setTableSortDirection(tblclmnDuplicate, "duplicate", order); final TableColumn tblclmnDedupablesize = new TableColumn(table, SWT.RIGHT); tblclmnDedupablesize.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { table.setSortColumn(tblclmnDedupablesize); if (table.getSortDirection() == SWT.UP) { table.setSortDirection(SWT.DOWN); } else { table.setSortDirection(SWT.UP); } onTblclmnDedupablesizeSelected(tblclmnDedupablesize, e); } }); tblclmnDedupablesize.setWidth(110); tblclmnDedupablesize.setText(Messages.tblclmnDedupablesize_text); setTableSortDirection(tblclmnDedupablesize, "dedupablesize", order); Menu popupMenu = new Menu(table); table.setMenu(popupMenu); MenuItem mntmRun = new MenuItem(popupMenu, SWT.NONE); mntmRun.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onRunSelected(); } }); mntmRun.setText(Messages.mntmRun_text); MenuItem mntmOpen = new MenuItem(popupMenu, SWT.NONE); mntmOpen.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onOpenSelected(e); } }); mntmOpen.setText(Messages.mntmOpen_text); MenuItem mntmOpenInNew = new MenuItem(popupMenu, SWT.NONE); mntmOpenInNew.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onOpenInNewWindowSelected(e); } }); mntmOpenInNew.setText(Messages.mntmOpenInNewWindow_text); MenuItem mntmOpenDuplicateDetails = new MenuItem(popupMenu, SWT.NONE); mntmOpenDuplicateDetails.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onOpenDuplicateDetailsSelected(e); } }); mntmOpenDuplicateDetails.setText(Messages.mntmOpenDuplicateDetails_text); MenuItem mntmCopyAsString = new MenuItem(popupMenu, SWT.NONE); mntmCopyAsString.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCopyAsStringSelected(); } }); mntmCopyAsString.setText(Messages.mntmCopyAsString_text); MenuItem mntmCopyTo = new MenuItem(popupMenu, SWT.NONE); mntmCopyTo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { onCopyToSelected(); } }); mntmCopyTo.setText(Messages.mntmCopyTo_text); MenuItem menuItem = new MenuItem(popupMenu, SWT.SEPARATOR); menuItem.setText("Visibility"); final MenuItem mntmFoldersVisible_1 = new MenuItem(popupMenu, SWT.CHECK); mntmFoldersVisible_1.setSelection(true); mntmFoldersVisible_1.setText(Messages.mntmFoldersVisible_text); mntmFoldersVisible_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmFoldersVisible.setSelection(mntmFoldersVisible_1.getSelection()); onFoldersVisibleChecked(mntmFoldersVisible.getSelection()); } }); final MenuItem mntmFilesVisible_1 = new MenuItem(popupMenu, SWT.CHECK); mntmFilesVisible_1.setSelection(true); mntmFilesVisible_1.setText(Messages.mntmFilesVisible_text); mntmFilesVisible_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmFilesVisible.setSelection(mntmFilesVisible_1.getSelection()); onFilesVisibleChecked(mntmFilesVisible.getSelection()); } }); final MenuItem mntmCompressedFoldersVisible_1 = new MenuItem(popupMenu, SWT.CHECK); mntmCompressedFoldersVisible_1.setSelection(true); mntmCompressedFoldersVisible_1.setText(Messages.mntmCompressedFoldersVisible_text); mntmCompressedFoldersVisible_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmCompressedFoldersVisible.setSelection(mntmCompressedFoldersVisible_1.getSelection()); onCompressedFoldersVisibleChecked(mntmCompressedFoldersVisible.getSelection()); } }); final MenuItem mntmCompressedFilesVisible_1 = new MenuItem(popupMenu, SWT.CHECK); mntmCompressedFilesVisible_1.setSelection(true); mntmCompressedFilesVisible_1.setText(Messages.mntmCompressedFilesVisible_text); mntmCompressedFilesVisible_1.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmCompressedFilesVisible.setSelection(mntmCompressedFilesVisible_1.getSelection()); onCompressedFilesVisibleSelected(mntmCompressedFilesVisible.getSelection()); } }); mntmFoldersVisible.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmFoldersVisible_1.setSelection(mntmFoldersVisible.getSelection()); onFoldersVisibleChecked(mntmFoldersVisible.getSelection()); } }); mntmFilesVisible.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmFilesVisible_1.setSelection(mntmFilesVisible.getSelection()); onFilesVisibleChecked(mntmFilesVisible.getSelection()); } }); mntmCompressedFoldersVisible.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmCompressedFoldersVisible_1.setSelection(mntmCompressedFoldersVisible.getSelection()); onCompressedFoldersVisibleChecked(mntmCompressedFoldersVisible.getSelection()); } }); mntmCompressedFilesVisible.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { mntmCompressedFilesVisible_1.setSelection(mntmCompressedFilesVisible.getSelection()); onCompressedFilesVisibleSelected(mntmCompressedFilesVisible.getSelection()); } }); compositeStatusBar = new Composite(shell, SWT.NONE); compositeStatusBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); compositeStatusBar.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND)); GridLayout gl_compositeStatusBar = new GridLayout(2, false); gl_compositeStatusBar.marginWidth = 0; gl_compositeStatusBar.marginHeight = 0; compositeStatusBar.setLayout(gl_compositeStatusBar); formToolkit.adapt(compositeStatusBar); formToolkit.paintBordersFor(compositeStatusBar); lblStatusBar = new Label(compositeStatusBar, SWT.NONE); lblStatusBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); lblStatusBar.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_BACKGROUND)); formToolkit.adapt(lblStatusBar, true, true); lblStatusBar.setText(""); progressBar = new ProgressBar(compositeStatusBar, SWT.NONE); formToolkit.adapt(progressBar, true, true); m_bindingContext = initDataBindings(); } /* * event handlers */ protected void onCopyAsStringSelected() { ArrayList<String> s = new ArrayList<String>(); for (PathEntry p: getSelectedPathEntries()) { s.add(p.getPath()); } StringSelection ss = new StringSelection(String.join("\n", s)); Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); clip.setContents(ss, ss); } protected void onOpenSelected(SelectionEvent e) { DBPathEntry entry = getSelectedPathEntry(); if (entry != null) { setLocationAndRefresh(entry); } } protected void onOpenInNewWindowSelected(SelectionEvent e) { DBPathEntry p = getSelectedPathEntry(); if (p == null) { p = location.get().getPathEntry(); } if (p != null) { new SwtFileFolderMenu().setLocationAndRefresh(p); } else if (location.get().getPathString() != null) { new SwtFileFolderMenu().setLocationAndRefresh(location.get().getPathString()); } else if (location.get().getSearchString() != null) { new SwtFileFolderMenu().setLocationAndRefresh(location.get().getSearchString()); } else if (location.get().getPathId() != 0L) { new SwtFileFolderMenu().setLocationAndRefresh(location.get().getPathId()); } } protected void onOpenDuplicateDetailsSelected(SelectionEvent e) { DBPathEntry p = getSelectedPathEntry(); if (p == null) { p = location.get().getPathEntry(); } if (p != null) { new SwtDuplicateMenu().setLocationAndRefresh(p); } else if (location.get().getPathString() != null) { new SwtDuplicateMenu().setLocationAndRefresh(location.get().getPathString()); } else if (location.get().getSearchString() != null) { new SwtDuplicateMenu().setLocationAndRefresh(location.get().getSearchString()); } else if (location.get().getPathId() != 0L) { new SwtDuplicateMenu().setLocationAndRefresh(location.get().getPathId()); } } protected void onNavigatePreviousSelected(SelectionEvent e) { location.navigatePrevious(); setLocationAndRefresh(location.get()); } protected void onNavigateNextSelected(SelectionEvent e) { location.navigateNext(); setLocationAndRefresh(location.get()); } protected void onUpperFolderSelected(SelectionEvent e) { DBPathEntry p = location.get().getPathEntry(); if (p != null && p.getParentId() != 0L) { setLocationAndRefresh(p.getParentId()); } else { writeStatusBar("Not ready for going up operation; be patient."); } } protected void onLocationModified(ModifyEvent arg0) { String newstring = txtLocation.getText(); Assertion.assertNullPointerException(newstring != null); writeStatusBar(String.format("New path string is: %s", newstring)); shell.setText(newstring); Location oldloc = location.get(); if (newstring.equals(oldloc.getPathString())) { // noop } else if (newstring.equals(oldloc.getSearchString())) { oldloc.setPathEntry(null); oldloc.setPathId(0L); oldloc.setPathString(null); } else { Location newloc = new Location(); newloc.setPathString(newstring); location.add(newloc); } refresh(); } protected void onTableSelected(SelectionEvent e) {} private String order = PreferenceRW.getSwtFileFolderMenuSortOrder(); private boolean isFolderChecked = true; private boolean isFileChecked = true; private boolean isCompressedFolderChecked = true; private boolean isCompressedFileChecked = true; protected void onTblclmnPathSelected(TableColumn tblclmnPath, SelectionEvent e) { if (table.getSortDirection() == SWT.UP) { order = "path"; } else { order = "path DESC"; } PreferenceRW.setSwtFileFolderMenuSortOrder(order); refresh(); } protected void onTblclmnDateLastModifiedSelected(TableColumn tblclmnDateLastModified, SelectionEvent e) { if (table.getSortDirection() == SWT.UP) { order = "datelastmodified"; } else { order = "datelastmodified DESC"; } PreferenceRW.setSwtFileFolderMenuSortOrder(order); refresh(); } protected void onTblclmnSizeSelected(TableColumn tblclmnSize, SelectionEvent e) { if (table.getSortDirection() == SWT.UP) { order = "size"; } else { order = "size DESC"; } PreferenceRW.setSwtFileFolderMenuSortOrder(order); refresh(); } protected void onTblclmnCompressedsizeSelected(TableColumn tblclmnCompressedesize, SelectionEvent e) { if (table.getSortDirection() == SWT.UP) { order = "compressedsize"; } else { order = "compressedsize DESC"; } PreferenceRW.setSwtFileFolderMenuSortOrder(order); refresh(); } protected void onTblclmnDuplicateSelected(TableColumn tblclmnDuplicate, SelectionEvent e) { if (table.getSortDirection() == SWT.UP) { order = "duplicate"; } else { order = "duplicate DESC"; } PreferenceRW.setSwtFileFolderMenuSortOrder(order); refresh(); } protected void onTblclmnDedupablesizeSelected(TableColumn tblclmnDedupablesize, SelectionEvent e) { if (table.getSortDirection() == SWT.UP) { order = "dedupablesize"; } else { order = "dedupablesize DESC"; } PreferenceRW.setSwtFileFolderMenuSortOrder(order); refresh(); } protected void onFoldersVisibleChecked(boolean checked) { isFolderChecked = checked; refresh(); } protected void onFilesVisibleChecked(boolean checked) { isFileChecked = checked; refresh(); } protected void onCompressedFoldersVisibleChecked(boolean checked) { isCompressedFolderChecked = checked; refresh(); } protected void onCompressedFilesVisibleSelected(boolean checked) { isCompressedFileChecked = checked; refresh(); } public void setLocationAndRefresh(final String text) { Display.getDefault().asyncExec(new Runnable() { public void run() { txtLocation.setText(text); // onLocationModified() is automatically called here. } }); } /* * setLocationAndRefresh and related */ public void setLocationAndRefresh(final DBPathEntry entry) { Assertion.assertNullPointerException(entry != null); Assertion.assertNullPointerException(location != null); Location oldloc = location.get(); if (oldloc.getPathEntry() != null && oldloc.getPathEntry().getPathId() == entry.getPathId()) { // noop } else if (oldloc.getPathString() != null && oldloc.getPathString().equals(entry.getPath())) { oldloc.setPathEntry(entry); oldloc.setPathId(entry.getPathId()); } else { Location newloc = new Location(); newloc.setPathEntry(entry); newloc.setPathId(entry.getPathId()); newloc.setPathString(entry.getPath()); location.add(newloc); } setLocationAndRefresh(entry.getPath()); } public void setLocationAndRefresh(long id) { writeStatusBar(String.format("Starting query; new ID is: %d", id)); Location oldloc = location.get(); if (oldloc.getPathId() == id) { // null } else { Location newloc = new Location(); newloc.setPathId(id); location.add(newloc); } refresh(new LazyRunnable() { @Override public void run() throws SQLException, InterruptedException { Debug.writelog("-- SwtFileFolderMenu SetLocationAndRefresh LOCAL PATTERN (id based) --"); Location loc = location.get(); DBPathEntry p = getDB().getDBPathEntryByPathId(loc.getPathId()); if (p != null) { loc.setPathEntry(p); loc.setPathString(p.getPath()); loc.setSearchString(null); setLocationAndRefresh(loc.getPathString()); } } }); } public void setLocationAndRefresh(final Location loc) { if (loc.getPathString() != null) { setLocationAndRefresh(loc.getPathString()); } else if (loc.getPathEntry() != null) { setLocationAndRefresh(loc.getPathEntry().getPath()); } else if (loc.getSearchString() != null) { setLocationAndRefresh(loc.getSearchString()); } else { setLocationAndRefresh(""); } } /* * normal refresh */ private Scenario scenario = new Scenario(); protected synchronized void refresh() { refresh(scenario); } class Scenario extends SwtCommonFileFolderMenu.Scenario { @Override public void run() throws SQLException, InterruptedException { writeProgress(10); Location loc = location.get(); if (loc.getPathEntry() == null && loc.getSearchString() == null && (loc.getPathEntry() != null || loc.getPathId() != 0L || (loc.getPathString() != null && !"".equals(loc.getPathString())))) { writeProgress(50); if (loc.getPathString() != null) { DBPathEntry p = getDB().getDBPathEntryByPath(loc.getPathString()); if (p != null) { loc.setPathEntry(p); loc.setPathId(p.getPathId()); Debug.writelog("-- SwtFileFolderMenu PREPROCESS PATTERN 1 (path based entry detection) --"); } else { loc.setSearchString(loc.getPathString()); loc.setPathString(null); loc.setPathId(0L); loc.setPathEntry(null); Debug.writelog("-- SwtFileFolderMenu PREPROCESS PATTERN 2 (searchstring=" + loc.getSearchString() + ") --"); } } else if (loc.getPathId() != 0L) { Debug.writelog("-- SwtFileFolderMenu PREPROCESS PATTERN 3 (id based) --"); DBPathEntry p = getDB().getDBPathEntryByPathId(loc.getPathId()); assert(p != null); setLocationAndRefresh(p); return; } else { Debug.writelog("-- SwtFileFolderMenu PREPROCESS PATTERN 4 (show all paths) --"); } } try { threadWait(); cleanupTable(); ArrayList<String> typelist = new ArrayList<String> (); if (isFolderChecked) { typelist.add("type=0"); } if (isFileChecked) { typelist.add("type=1"); } if (isCompressedFolderChecked) { typelist.add("type=2"); } if (isCompressedFileChecked) { typelist.add("type=3"); } String typeWhere = typelist.size() == 0 ? "" : String.join(" OR ", typelist); threadWait(); writeStatusBar("Querying..."); writeProgress(70); String searchSubSQL; ArrayList<String> searchStringElement = new ArrayList<String> (); if (loc.getSearchString() == null || "".equals(loc.getSearchString())) { searchSubSQL = ""; } else { ArrayList<String> p = new ArrayList<String> (); for (String s: loc.getSearchString().split(" ")) { if (! "".equals(s)) { p.add("path LIKE ?"); searchStringElement.add(s); } } searchSubSQL = " AND (" + String.join(" AND ", p) + ")"; } threadWait(); DBPathEntry locationPathEntry = null; PreparedStatement ps; if (loc.getPathString() == null || "".equals(loc.getPathString())) { String sql = "SELECT * FROM directory AS d1 WHERE (" + typeWhere + ") " + searchSubSQL + " AND (parentid=0 OR EXISTS (SELECT * FROM directory AS d2 WHERE d1.parentid=d2.pathid))" + " ORDER BY " + order; Debug.writelog(sql); ps = getDB().prepareStatement(sql); int c = 1; for (String s: searchStringElement) { ps.setString(c, "%" + s + "%"); Debug.writelog(c + " %" + s + "%"); c++; } } else if ((locationPathEntry = loc.getPathEntry()) != null) { String sql = "SELECT * FROM directory AS d1 WHERE (" + typeWhere + ") " + searchSubSQL + " AND (pathid=? OR EXISTS (SELECT * FROM upperlower WHERE upper=? AND lower=pathid))" + " AND (parentid=0 OR EXISTS (SELECT * FROM directory AS d2 WHERE d1.parentid=d2.pathid))" + " ORDER BY " + order; Debug.writelog(sql); ps = getDB().prepareStatement(sql); int c = 1; for (String s: searchStringElement) { ps.setString(c, "%" + s + "%"); Debug.writelog(c + " %" + s + "%"); c++; } ps.setLong(c++, locationPathEntry.getPathId()); ps.setLong(c++, locationPathEntry.getPathId()); Debug.writelog(locationPathEntry.getPath()); } else { String sql = "SELECT * FROM directory AS d1 WHERE (" + typeWhere + ") " + searchSubSQL + " AND path LIKE ?" + " AND (parentid=0 OR EXISTS (SELECT * FROM directory AS d2 WHERE d1.parentid=d2.pathid))" + " ORDER BY " + order; Debug.writelog(sql); ps = getDB().prepareStatement(sql); int c = 1; for (String s: searchStringElement) { ps.setString(c, "%" + s + "%"); Debug.writelog(c + " %" + s + "%"); c++; } ps.setString(c++, loc.getPathString() + "%"); Debug.writelog(loc.getPathString()); } try { LazyUpdater.Dispatcher disp = getDB().getDispatcher(); disp.setList(Dispatcher.NONE); disp.setCsum(Dispatcher.NONE); ResultSet rs = ps.executeQuery(); try { threadWait(); Debug.writelog("QUERY FINISHED"); writeStatusBar("Listing..."); writeProgress(90); int count = 0; while (rs.next()) { threadWait(); DBPathEntry p1 = getDB().rsToPathEntry(rs); Assertion.assertAssertionError(p1 != null); Assertion.assertAssertionError(p1.getPath() != null); if (locationPathEntry != null) { Assertion.assertAssertionError(locationPathEntry.getPath() != null); Assertion.assertAssertionError(p1.getPath().startsWith(locationPathEntry.getPath()), p1.getPath() + " does not start with " + locationPathEntry.getPath() ); } PathEntry p2; try { p2 = disp.dispatch(p1); } catch (IOException e) { p2 = null; } if (p2 == null) { addRow(p1, rs.getInt("duplicate"), rs.getLong("dedupablesize"), true); getDB().unsetClean(p1.getParentId()); } else { Assertion.assertAssertionError(p1.getPath().equals(p2.getPath()), "!! " + p1.getPath() + " != " + p2.getPath()); if (!PathEntry.dscMatch(p1, p2)) { p1.setDateLastModified(p2.getDateLastModified()); p1.setSize(p2.getSize()); p1.setCompressedSize(p2.getCompressedSize()); p1.clearCsum(); getDB().unsetClean(p1.getParentId()); } addRow(p1, rs.getInt("duplicate"), rs.getLong("dedupablesize"), false); } count ++; } writeStatusBar(String.format("%d items", count)); } finally { rs.close(); } } finally { ps.close(); } writeProgress(0); } catch (WindowDisposedException e) {} } protected void cleanupTable() throws WindowDisposedException { if (table.isDisposed()) { throw new WindowDisposedException("!! Window disposed at cleanupTable"); } Display.getDefault().asyncExec(new Runnable() { public void run() { pathentrylist.clear(); table.removeAll();; } }); } protected void addRow(final DBPathEntry entry, final int duplicate, final long dedupablesize, final boolean grayout) throws WindowDisposedException { if (table.isDisposed()) { throw new WindowDisposedException("!! Window disposed at addRow"); } Display.getDefault().asyncExec(new Runnable() { public void run() { pathentrylist.add(entry); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); final NumberFormat numf = NumberFormat.getNumberInstance(); Date d = new Date(entry.getDateLastModified()); String[] row = { entry.getPath(), sdf.format(d), numf.format(entry.getSize()), numf.format(entry.getCompressedSize()), (duplicate > 0 ? numf.format(duplicate) : null), (dedupablesize > 0 ? numf.format(dedupablesize) : null), }; final Display display = Display.getDefault(); final Color blue = new Color(display, 0, 0, 255); final Color red = new Color(display, 255, 0, 0); final Color black = new Color(display, 0, 0, 0); final Color gray = new Color(display, 127, 127, 127); try { TableItem tableItem = new TableItem(table, SWT.NONE); tableItem.setText(row); if (grayout) { tableItem.setForeground(gray); } else if (entry.isNoAccess()) { tableItem.setForeground(red); } else if (entry.isFile() && entry.getSize() != entry.getCompressedSize()) { tableItem.setForeground(blue); } else { tableItem.setForeground(black); } } catch (Exception e) { if (!table.isDisposed()) { e.printStackTrace(); } } } }); } } protected DataBindingContext initDataBindings() { DataBindingContext bindingContext = new DataBindingContext(); // IObservableValue observeBackgroundCompositeObserveWidget = WidgetProperties.background().observe(compositeToolBar); IObservableValue backgroundShellObserveValue = PojoProperties.value("background").observe(shell); bindingContext.bindValue(observeBackgroundCompositeObserveWidget, backgroundShellObserveValue, null, null); // IObservableValue observeBackgroundLblStatusBarObserveWidget = WidgetProperties.background().observe(lblStatusBar); bindingContext.bindValue(observeBackgroundLblStatusBarObserveWidget, backgroundShellObserveValue, null, null); // IObservableValue observeBackgroundCompositeStatusBarObserveWidget = WidgetProperties.background().observe(compositeStatusBar); bindingContext.bindValue(observeBackgroundCompositeStatusBarObserveWidget, backgroundShellObserveValue, null, null); // return bindingContext; } }
n-i-e/deepfolderview
src/main/java/com/github/n_i_e/deepfolderview/SwtFileFolderMenu.java
Java
apache-2.0
41,340
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.medialive.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * Settings for the action to deactivate the image in a specific layer. * * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/StaticImageDeactivateScheduleActionSettings" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class StaticImageDeactivateScheduleActionSettings implements Serializable, Cloneable, StructuredPojo { /** The time in milliseconds for the image to fade out. Default is 0 (no fade-out). */ private Integer fadeOut; /** The image overlay layer to deactivate, 0 to 7. Default is 0. */ private Integer layer; /** * The time in milliseconds for the image to fade out. Default is 0 (no fade-out). * * @param fadeOut * The time in milliseconds for the image to fade out. Default is 0 (no fade-out). */ public void setFadeOut(Integer fadeOut) { this.fadeOut = fadeOut; } /** * The time in milliseconds for the image to fade out. Default is 0 (no fade-out). * * @return The time in milliseconds for the image to fade out. Default is 0 (no fade-out). */ public Integer getFadeOut() { return this.fadeOut; } /** * The time in milliseconds for the image to fade out. Default is 0 (no fade-out). * * @param fadeOut * The time in milliseconds for the image to fade out. Default is 0 (no fade-out). * @return Returns a reference to this object so that method calls can be chained together. */ public StaticImageDeactivateScheduleActionSettings withFadeOut(Integer fadeOut) { setFadeOut(fadeOut); return this; } /** * The image overlay layer to deactivate, 0 to 7. Default is 0. * * @param layer * The image overlay layer to deactivate, 0 to 7. Default is 0. */ public void setLayer(Integer layer) { this.layer = layer; } /** * The image overlay layer to deactivate, 0 to 7. Default is 0. * * @return The image overlay layer to deactivate, 0 to 7. Default is 0. */ public Integer getLayer() { return this.layer; } /** * The image overlay layer to deactivate, 0 to 7. Default is 0. * * @param layer * The image overlay layer to deactivate, 0 to 7. Default is 0. * @return Returns a reference to this object so that method calls can be chained together. */ public StaticImageDeactivateScheduleActionSettings withLayer(Integer layer) { setLayer(layer); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFadeOut() != null) sb.append("FadeOut: ").append(getFadeOut()).append(","); if (getLayer() != null) sb.append("Layer: ").append(getLayer()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof StaticImageDeactivateScheduleActionSettings == false) return false; StaticImageDeactivateScheduleActionSettings other = (StaticImageDeactivateScheduleActionSettings) obj; if (other.getFadeOut() == null ^ this.getFadeOut() == null) return false; if (other.getFadeOut() != null && other.getFadeOut().equals(this.getFadeOut()) == false) return false; if (other.getLayer() == null ^ this.getLayer() == null) return false; if (other.getLayer() != null && other.getLayer().equals(this.getLayer()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFadeOut() == null) ? 0 : getFadeOut().hashCode()); hashCode = prime * hashCode + ((getLayer() == null) ? 0 : getLayer().hashCode()); return hashCode; } @Override public StaticImageDeactivateScheduleActionSettings clone() { try { return (StaticImageDeactivateScheduleActionSettings) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.medialive.model.transform.StaticImageDeactivateScheduleActionSettingsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
jentfoo/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/StaticImageDeactivateScheduleActionSettings.java
Java
apache-2.0
5,899
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * 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.alibaba.rocketmq.broker.client; import io.netty.channel.Channel; import java.util.List; /** * @author shijia.wxr<vintage.wang@gmail.com> * @since 2013-6-24 */ public interface ConsumerIdsChangeListener { public void consumerIdsChanged(final String group, final List<Channel> channels); }
dingjun84/mq-backup
rocketmq-broker/src/main/java/com/alibaba/rocketmq/broker/client/ConsumerIdsChangeListener.java
Java
apache-2.0
963
package com.bjorktech.cayman.idea.designpattern.structure.proxy; public class TargetClass implements TargetInterface { @Override public long add(long a, long b) { long temp = a + b; System.out.println(temp); return temp; } @Override public long sub(long a, long b) { long temp = a - b; System.out.println(temp); return temp; } }
wanliwang/cayman
cm-idea/src/main/java/com/bjorktech/cayman/idea/designpattern/structure/proxy/TargetClass.java
Java
apache-2.0
351
package com.badlogic.gdx.ingenuity.scene2d; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.ingenuity.GdxData; import com.badlogic.gdx.ingenuity.helper.PixmapHelper; import com.badlogic.gdx.ingenuity.utils.GdxUtilities; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Disposable; /** * @作者 Mitkey * @时间 2017年3月24日 下午3:09:56 * @类说明: * @版本 xx */ public class Loading implements Disposable { private Group root = new Group(); private Image imgOut; private Image imgInner; public Loading() { root.setSize(GdxData.WIDTH, GdxData.HEIGHT); Image imgBg = new Image(PixmapHelper.getInstance().newTranslucentDrawable(5, 5)); imgBg.setFillParent(true); root.addActor(imgBg); imgOut = new Image(PixmapHelper.getInstance().newRectangleDrawable(Color.YELLOW, 40, 40)); imgOut.setOrigin(Align.center); imgInner = new Image(PixmapHelper.getInstance().newCircleDrawable(Color.RED, 18)); imgInner.setOrigin(Align.center); GdxUtilities.center(imgOut); GdxUtilities.center(imgInner); root.addActor(imgOut); root.addActor(imgInner); } public void show(Stage stage) { stage.addActor(root); root.toFront(); imgOut.clearActions(); imgOut.addAction(Actions.forever(Actions.rotateBy(-360, 1f))); imgInner.clearActions(); imgInner.addAction(Actions.forever(Actions.rotateBy(360, 2f))); } public void hide() { root.remove(); } @Override public void dispose() { hide(); } }
mitkey/libgdx-ingenuity
depot/src/com/badlogic/gdx/ingenuity/scene2d/Loading.java
Java
apache-2.0
1,675
package com.concavenp.nanodegree.shared; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
concaveNP/GoUbiquitous
shared/src/test/java/com/concavenp/nanodegree/shared/ExampleUnitTest.java
Java
apache-2.0
324
/* * Copyright (c) 2013-2015 Josef Hardi <josef.hardi@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.obidea.semantika.datatype; import com.obidea.semantika.datatype.exception.InvalidLexicalFormException; import com.obidea.semantika.datatype.primitive.XsdDecimal; public abstract class AbstractDerivedDecimalType extends AbstractXmlType<Number> { protected AbstractDerivedDecimalType(String name) { super(name); } @Override public IDatatype<?> getPrimitiveDatatype() { return XsdDecimal.getInstance(); } @Override public Number getValue(String lexicalForm) { return parseLexicalForm(lexicalForm); } @Override public boolean isPrimitive() { return false; } /** * Parse and validate a lexical form of the literal. * * @param lexicalForm * the typing form of the literal. * @return A <code>Number</code> representation of the literal * @throws InvalidLexicalFormException * if the literal form is invalid or the value is out of range */ protected abstract Number parseLexicalForm(String lexicalForm) throws InvalidLexicalFormException; }
obidea/semantika
src/main/java/com/obidea/semantika/datatype/AbstractDerivedDecimalType.java
Java
apache-2.0
1,709
/* Copyright (C) 2013-2020 Expedia 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 com.hotels.styx.support.matchers; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.Objects; import java.util.Optional; /** * Provides matchers around the {@code Optional} class. * * @param <T> * @author john.butler * @see Optional */ public final class IsOptional<T> extends TypeSafeMatcher<Optional<? extends T>> { /** * Checks that the passed Optional is not present. */ public static IsOptional<Object> isAbsent() { return new IsOptional<>(false); } /** * Checks that the passed Optional is present. */ public static IsOptional<Object> isPresent() { return new IsOptional<>(true); } public static <T> IsOptional<T> isValue(T value) { return new IsOptional<>(value); } public static <T> IsOptional<T> matches(Matcher<T> matcher) { return new IsOptional<>(matcher); } public static <T extends Iterable> IsOptional<T> isIterable(Matcher<? extends Iterable> matcher) { return new IsOptional<>((Matcher) matcher); } private final boolean someExpected; private final Optional<T> expected; private final Optional<Matcher<T>> matcher; private IsOptional(boolean someExpected) { this.someExpected = someExpected; this.expected = Optional.empty(); this.matcher = Optional.empty(); } private IsOptional(T value) { this.someExpected = true; this.expected = Optional.of(value); this.matcher = Optional.empty(); } private IsOptional(Matcher<T> matcher) { this.someExpected = true; this.expected = Optional.empty(); this.matcher = Optional.of(matcher); } @Override public void describeTo(Description description) { if (!someExpected) { description.appendText("<Absent>"); } else if (expected.isPresent()) { description.appendValue(expected); } else if (matcher.isPresent()) { description.appendText("a present value matching "); matcher.get().describeTo(description); } else { description.appendText("<Present>"); } } @Override public boolean matchesSafely(Optional<? extends T> item) { if (!someExpected) { return !item.isPresent(); } else if (expected.isPresent()) { return item.isPresent() && Objects.equals(item.get(), expected.get()); } else if (matcher.isPresent()) { return item.isPresent() && matcher.get().matches(item.get()); } else { return item.isPresent(); } } }
mikkokar/styx
support/testsupport/src/main/java/com/hotels/styx/support/matchers/IsOptional.java
Java
apache-2.0
3,272
/* * Copyright (C) 2016 Google 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 com.googlecode.android_scripting.language; import com.googlecode.android_scripting.rpc.ParameterDescriptor; /** * Represents the BeanShell programming language. * * @author igor.v.karp@gmail.com (Igor Karp) */ public class BeanShellLanguage extends Language { @Override protected String getImportStatement() { // FIXME(igor.v.karp): this is interpreter specific return "source(\"/sdcard/com.googlecode.bshforandroid/extras/bsh/android.bsh\");\n"; } @Override protected String getRpcReceiverDeclaration(String rpcReceiver) { return rpcReceiver + " = Android();\n"; } @Override protected String getMethodCallText(String receiver, String method, ParameterDescriptor[] parameters) { StringBuilder result = new StringBuilder().append(getApplyReceiverText(receiver)).append(getApplyOperatorText()) .append(method); if (parameters.length > 0) { result.append(getLeftParametersText()); } else { result.append(getQuote()); } String separator = ""; for (ParameterDescriptor parameter : parameters) { result.append(separator).append(getValueText(parameter)); separator = getParameterSeparator(); } result.append(getRightParametersText()); return result.toString(); } @Override protected String getApplyOperatorText() { return ".call(\""; } @Override protected String getLeftParametersText() { return "\", "; } @Override protected String getRightParametersText() { return ")"; } }
kuri65536/sl4a
android/Common/src/com/googlecode/android_scripting/language/BeanShellLanguage.java
Java
apache-2.0
2,132
/* * Copyright [2017] * * 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.netpet.spools.book.insidethejavavirtualmachine.chapter18; /** * @Desc javap -verbose / javap -c Hello.class 查看字节码文件 * Created by woncz on 2017/8/18. */ public class Hello { }
WindsorWang/Spools
spools-book/src/main/java/com/netpet/spools/book/insidethejavavirtualmachine/chapter18/Hello.java
Java
apache-2.0
789
package com.ctrip.xpipe.redis.checker.alert.manager; import com.ctrip.xpipe.redis.checker.alert.ALERT_TYPE; import com.ctrip.xpipe.redis.checker.alert.AlertChannel; import com.ctrip.xpipe.redis.checker.alert.AlertConfig; import com.ctrip.xpipe.redis.checker.alert.AlertEntity; import com.ctrip.xpipe.redis.checker.alert.message.AlertEntityHolderManager; import com.ctrip.xpipe.redis.checker.alert.policy.channel.ChannelSelector; import com.ctrip.xpipe.redis.checker.alert.policy.channel.DefaultChannelSelector; import com.ctrip.xpipe.redis.checker.alert.policy.receiver.*; import com.ctrip.xpipe.redis.checker.alert.policy.timing.RecoveryTimeSlotControl; import com.ctrip.xpipe.redis.checker.alert.policy.timing.TimeSlotControl; import com.ctrip.xpipe.redis.checker.config.CheckerDbConfig; import com.ctrip.xpipe.redis.core.meta.MetaCache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.LongSupplier; /** * @author chen.zhu * <p> * Oct 18, 2017 */ @Component public class AlertPolicyManager { @Autowired private AlertConfig alertConfig; @Autowired private CheckerDbConfig checkerDbConfig; @Autowired private MetaCache metaCache; private EmailReceiver emailReceiver; private GroupEmailReceiver groupEmailReceiver; private ChannelSelector channelSelector; private TimeSlotControl recoveryTimeController; @PostConstruct public void initPolicies() { emailReceiver = new DefaultEmailReceiver(alertConfig, checkerDbConfig, metaCache); groupEmailReceiver = new DefaultGroupEmailReceiver(alertConfig, checkerDbConfig, metaCache); channelSelector = new DefaultChannelSelector(); if(recoveryTimeController == null) { recoveryTimeController = new RecoveryTimeSlotControl(alertConfig); } } public List<AlertChannel> queryChannels(AlertEntity alert) { return channelSelector.alertChannels(alert); } public long queryRecoverMilli(AlertEntity alert) { return recoveryTimeController.durationMilli(alert); } public long querySuspendMilli(AlertEntity alert) { return TimeUnit.MINUTES.toMillis(alertConfig.getAlertSystemSuspendMinute()); } public EmailReceiverModel queryEmailReceivers(AlertEntity alert) { return emailReceiver.receivers(alert); } public void markCheckInterval(ALERT_TYPE alertType, LongSupplier checkInterval) { if(recoveryTimeController == null) { recoveryTimeController = new RecoveryTimeSlotControl(alertConfig); } recoveryTimeController.mark(alertType, checkInterval); } public Map<EmailReceiverModel, Map<ALERT_TYPE, Set<AlertEntity>>> queryGroupedEmailReceivers( AlertEntityHolderManager alerts) { return groupEmailReceiver.getGroupedEmailReceiver(alerts); } }
ctripcorp/x-pipe
redis/redis-checker/src/main/java/com/ctrip/xpipe/redis/checker/alert/manager/AlertPolicyManager.java
Java
apache-2.0
3,064
package com.coolweather.android.util; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by fengj on 2017/1/27. */ public class HttpUtil { public static void sendOkHttpRequest(String address,okhttp3.Callback callback){ OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } }
cabbagemaoyi/coolweather
app/src/main/java/com/coolweather/android/util/HttpUtil.java
Java
apache-2.0
419
/* * Copyright 2013 * * 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.openntf.domino.iterators; import java.util.Iterator; import org.openntf.domino.Base; import org.openntf.domino.Database; import org.openntf.domino.DocumentCollection; import org.openntf.domino.Session; import org.openntf.domino.View; import org.openntf.domino.ViewEntryCollection; import org.openntf.domino.utils.DominoUtils; import org.openntf.domino.utils.Factory; // TODO: Auto-generated Javadoc /** * The Class AbstractDominoIterator. * * @param <T> * the generic type */ public abstract class AbstractDominoIterator<T> implements Iterator<T> { /** The server name_. */ private String serverName_; /** The file path_. */ private String filePath_; /** The collection_. */ private Base<?> collection_; /** The session_. */ private transient Session session_; /** The database_. */ private transient Database database_; /** * Instantiates a new abstract domino iterator. * * @param collection * the collection */ protected AbstractDominoIterator(final Base<?> collection) { setCollection(collection); } /** * Gets the session. * * @return the session */ protected Session getSession() { if (session_ == null) { try { session_ = Factory.getSession(); } catch (Throwable e) { DominoUtils.handleException(e); return null; } } return session_; } /** * Gets the database. * * @return the database */ protected Database getDatabase() { if (database_ == null) { Session session = getSession(); try { database_ = session.getDatabase(getServerName(), getFilePath()); } catch (Throwable e) { DominoUtils.handleException(e); return null; } } return database_; } /** * Gets the file path. * * @return the file path */ protected String getFilePath() { return filePath_; } /** * Gets the server name. * * @return the server name */ protected String getServerName() { return serverName_; } /** * Sets the database. * * @param database * the new database */ protected void setDatabase(final Database database) { if (database != null) { try { setFilePath(database.getFilePath()); setServerName(database.getServer()); } catch (Throwable e) { DominoUtils.handleException(e); } } } /** * Sets the file path. * * @param filePath * the new file path */ protected void setFilePath(final String filePath) { filePath_ = filePath; } /** * Sets the server name. * * @param serverName * the new server name */ protected void setServerName(final String serverName) { serverName_ = serverName; } /** * Gets the collection. * * @return the collection */ public Base<?> getCollection() { return collection_; } /** * Sets the collection. * * @param collection * the new collection */ public void setCollection(final Base<?> collection) { if (collection != null) { if (collection instanceof DocumentCollection) { org.openntf.domino.Database parent = ((org.openntf.domino.DocumentCollection) collection).getParent(); session_ = Factory.fromLotus(parent.getParent(), Session.SCHEMA, null); // FIXME NTF - this is suboptimal, database_ = Factory.fromLotus(parent, Database.SCHEMA, session_); // but we still need to // sort out the parent/child pattern } else if (collection instanceof ViewEntryCollection) { View vw = ((ViewEntryCollection) collection).getParent(); database_ = vw.getParent(); session_ = Factory.getSession(database_); } if (database_ != null) { setDatabase(database_); } } collection_ = collection; } }
mariusj/org.openntf.domino
domino/core/archive/AbstractDominoIterator.java
Java
apache-2.0
4,458
/* * Copyright (c) 2015 IRCCloud, Ltd. * * 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.irccloud.android.fragment; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.method.ScrollingMovementMethod; import android.text.style.TabStopSpan; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment; import com.irccloud.android.R; import com.irccloud.android.activity.MainActivity; public class TextListFragment extends DialogFragment { private TextView textView; private String title = null; private String text = null; public boolean dismissed = false; public String type; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Context ctx = getActivity(); if(ctx == null) return null; LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.dialog_textlist, null); textView = v.findViewById(R.id.textView); textView.setHorizontallyScrolling(true); textView.setMovementMethod(new ScrollingMovementMethod()); if (savedInstanceState != null && savedInstanceState.containsKey("text")) { text = savedInstanceState.getString("text"); } if(text != null) { setText(text); } Dialog d = new AlertDialog.Builder(ctx) .setView(v) .setTitle(title) .setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); return d; } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); dismissed = true; if(getActivity() != null && ((MainActivity)getActivity()).help_fragment == this) ((MainActivity)getActivity()).help_fragment = null; } @Override public void onCancel(DialogInterface dialog) { super.onCancel(dialog); dismissed = true; if(getActivity() != null && ((MainActivity)getActivity()).help_fragment == this) ((MainActivity)getActivity()).help_fragment = null; } @Override public void onSaveInstanceState(Bundle state) { state.putString("text", text); } public void refresh() { Bundle args = getArguments(); if(args.containsKey("title")) { title = args.getString("title"); if(getDialog() != null) getDialog().setTitle(title); } if(args.containsKey("text")) { text = args.getString("text"); if(textView != null) setText(text); } } private void setText(String text) { SpannableStringBuilder sb = new SpannableStringBuilder(text); for (int i = 0; i < 100; i++) sb.setSpan(new TabStopSpan.Standard(i * 300), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(sb, TextView.BufferType.SPANNABLE); } @Override public void setArguments(Bundle args) { super.setArguments(args); refresh(); } @Override public void onPause() { super.onPause(); } }
irccloud/android
src/com/irccloud/android/fragment/TextListFragment.java
Java
apache-2.0
4,169
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2010 Oracle. All rights reserved. * * $Id: ReplicaSyncupReader.java,v 1.4 2010/01/11 20:00:48 linda Exp $ */ package com.sleepycat.je.rep.stream; import static com.sleepycat.je.utilint.DbLsn.NULL_LSN; import java.io.IOException; import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.EnvironmentFailureException; import com.sleepycat.je.dbi.EnvironmentImpl; import com.sleepycat.je.log.LogEntryType; import com.sleepycat.je.log.entry.LogEntry; import com.sleepycat.je.recovery.CheckpointEnd; import com.sleepycat.je.rep.impl.node.NameIdPair; import com.sleepycat.je.rep.vlsn.VLSNIndex; import com.sleepycat.je.rep.vlsn.VLSNRange; import com.sleepycat.je.txn.TxnCommit; import com.sleepycat.je.utilint.LoggerUtils; import com.sleepycat.je.utilint.VLSN; /** * The ReplicaSyncupReader scans the log backwards for requested log entries. * The reader must track whether it has passed a checkpoint, and therefore * can not used the vlsn index to skip over entries. * * The ReplicaSyncupReader is not thread safe, and can only be used * serially. It will stop at the finishLsn, which should be set using the * GlobalCBVLSN. */ public class ReplicaSyncupReader extends VLSNReader { /* True if this particular record retrieval is for a syncable record. */ private boolean syncableSearch; private final LogEntry ckptEndLogEntry = LogEntryType.LOG_CKPT_END.getNewLogEntry(); private final LogEntry commitLogEntry = LogEntryType.LOG_TXN_COMMIT.getNewLogEntry(); /* * SearchResults retains the information as to whether the found * matchpoint is valid. */ private final MatchpointSearchResults searchResults; private final Logger logger; public ReplicaSyncupReader(EnvironmentImpl envImpl, VLSNIndex vlsnIndex, long endOfLogLsn, int readBufferSize, NameIdPair nameIdPair, VLSN startVLSN, long finishLsn, MatchpointSearchResults searchResults) throws IOException, DatabaseException { /* * If we go backwards, endOfFileLsn and startLsn must not be null. * Make them the same, so we always start at the same very end. */ super(envImpl, vlsnIndex, false, // forward endOfLogLsn, readBufferSize, nameIdPair, finishLsn); initScan(startVLSN, endOfLogLsn); this.searchResults = searchResults; logger = LoggerUtils.getLogger(getClass()); } /** * Set up the ReplicaSyncupReader to start scanning from this VLSN. * @throws IOException */ private void initScan(VLSN startVLSN, long endOfLogLsn) throws IOException { if (startVLSN.equals(VLSN.NULL_VLSN)) { throw EnvironmentFailureException.unexpectedState ("ReplicaSyncupReader start can't be NULL_VLSN"); } startLsn = endOfLogLsn; assert startLsn != NULL_LSN; /* * Flush the log so that syncup can assume that all log entries that * are represented in the VLSNIndex are safely out of the log buffers * and on disk. Simplifies this reader, so it can use the regular * ReadWindow, which only works on a file. */ envImpl.getLogManager().flush(); window.initAtFileStart(startLsn); currentEntryPrevOffset = window.getEndOffset(); currentEntryOffset = window.getEndOffset(); currentVLSN = startVLSN; } /** * Backward scanning for the replica's part in syncup. */ public OutputWireRecord scanBackwards(VLSN vlsn) throws DatabaseException { syncableSearch = false; VLSNRange range = vlsnIndex.getRange(); if (vlsn.compareTo(range.getFirst()) < 0) { /* * The requested VLSN is before the start of our range, we don't * have this record. */ return null; } currentVLSN = vlsn; if (readNextEntry()) { return currentFeedRecord; } return null; } /** * Backward scanning for finding an earlier candidate syncup matchpoint. */ public OutputWireRecord findPrevSyncEntry() throws DatabaseException { currentFeedRecord = null; syncableSearch = true; /* Start by looking at the entry before the current record. */ currentVLSN = currentVLSN.getPrev(); VLSNRange range = vlsnIndex.getRange(); if (currentVLSN.compareTo(range.getFirst()) < 0) { /* * We've walked off the end of the contiguous VLSN range. */ return null; } if (readNextEntry() == false) { /* * We scanned all the way to the front of the log, no * other sync-able entry found. */ return null; } assert LogEntryType.isSyncPoint(currentFeedRecord.getEntryType()) : "Unexpected log type= " + currentFeedRecord; return currentFeedRecord; } /** * @throw an EnvironmentFailureException if we were scanning for a * particular VLSN and we have passed it by. */ private void checkForPassingTarget(int compareResult) { if (compareResult < 0) { /* Hey, we passed the VLSN we wanted. */ throw EnvironmentFailureException.unexpectedState ("want to read " + currentVLSN + " but reader at " + currentEntryHeader.getVLSN()); } } /** * Return true for ckpt entries, for syncable entries, and if we're in * specific vlsn scan mode, any replicated entry. There is an additional * level of filtering in processEntry. */ @Override protected boolean isTargetEntry() throws DatabaseException { if (logger.isLoggable(Level.FINEST)) { LoggerUtils.finest(logger, envImpl, " isTargetEntry " + currentEntryHeader); } nScanned++; /* Skip invisible entries. */ if (currentEntryHeader.isInvisible()) { return false; } byte currentType = currentEntryHeader.getType(); /* * Return true if this entry is replicated. All entries need to be * perused by processEntry, when we are doing a vlsn based search, * even if they are not a sync point, because: * (a) If this is a vlsn-based search, it's possible that the replica * and feeder are mismatched. The feeder will only propose a sync type * entry as a matchpoint but it might be that the replica has a non- * sync entry at that vlsn. * (b) We need to note passed commits in processEntry. */ if (entryIsReplicated()) { if (syncableSearch) { if (LogEntryType.isSyncPoint(currentType)) { return true; } currentVLSN = currentEntryHeader.getVLSN().getPrev(); } else { return true; } } /* * We'll also need to read checkpoint end records to record their * presence. */ if (LogEntryType.LOG_CKPT_END.equalsType(currentType)) { return true; } return false; } /** * ProcessEntry does additional filtering before deciding whether to * return an entry as a candidate for matching. * * If this is a record we are submitting as a matchpoint candidate, * instantiate a WireRecord to house this log entry. If this is a * non-replicated entry or a txn end that follows the candidate matchpoint, * record whatever status we need to, but don't use it for comparisons. * * For example, suppose the log is like this:f * * VLSN entry * 10 LN * 11 commit * 12 LN * -- ckpt end * 13 commit * 14 abort * * And that the master only has VLSNs 1-12. The replica will suggest vlsn * 14 as the first matchpoint. The feeder will counter with a suggestion * of vlsn 11, since it doe not have vlsn 14. * * At that point, the ReplicaSyncupReader will scan backwards in the log, * looking for vlsn 11. Although the reader should only return an entry * when it gets to vlsn 11. the reader must process commits and ckpts that * follow 11, so that they can be recorded in the searchResults, so the * number of rolled back commits can be accurately reported. */ @Override protected boolean processEntry(ByteBuffer entryBuffer) { if (logger.isLoggable(Level.FINEST)) { LoggerUtils.finest(logger, envImpl, " syncup reader saw " + currentEntryHeader); } byte currentType = currentEntryHeader.getType(); /* * CheckpointEnd entries are tracked in order to see if a rollback * must be done, but are not returned as possible matchpoints. */ if (LogEntryType.LOG_CKPT_END.equalsType(currentType)) { /* * Read the entry, which both lets us decipher its contents and * also advances the file reader position. */ ckptEndLogEntry.readEntry(currentEntryHeader, entryBuffer, true /*readFullItem*/); if (logger.isLoggable(Level.FINEST)) { LoggerUtils.finest(logger, envImpl, " syncup reader read " + currentEntryHeader + ckptEndLogEntry); } if (((CheckpointEnd) ckptEndLogEntry.getMainItem()). getCleanedFilesToDelete()) { searchResults.notePassedCheckpointEnd(); } return false; } /* * Setup the log entry as a wire record so we can compare it to * the entry from the feeder as we look for a matchpoint. Do this * before we change positions on the entry buffer by reading it. */ ByteBuffer buffer = entryBuffer.slice(); buffer.limit(currentEntryHeader.getItemSize()); currentFeedRecord = new OutputWireRecord(currentEntryHeader, buffer); /* * All commit records must be tracked to figure out if we've exceeded * the txn rollback limit. For reporting reasons, we'll need to * unmarshal the log entry, so we can read the timestamp in the commit * record. */ if (LogEntryType.LOG_TXN_COMMIT.equalsType(currentType)) { commitLogEntry.readEntry(currentEntryHeader, entryBuffer, true /*readFullItem*/); TxnCommit commit = (TxnCommit) commitLogEntry.getMainItem(); searchResults.notePassedCommits(commit.getTime(), commit.getId(), currentEntryHeader.getVLSN(), getLastLsn()); if (logger.isLoggable(Level.FINEST)) { LoggerUtils.finest(logger, envImpl, "syncup reader read " + currentEntryHeader + commitLogEntry); } } else { entryBuffer.position(entryBuffer.position() + currentEntryHeader.getItemSize()); } if (syncableSearch) { return true; } /* We're looking for a particular VLSN. */ int compareResult = currentEntryHeader.getVLSN().compareTo(currentVLSN); checkForPassingTarget(compareResult); /* return true if this is the entry we want. */ return (compareResult == 0); } }
bjorndm/prebake
code/third_party/bdb/src/com/sleepycat/je/rep/stream/ReplicaSyncupReader.java
Java
apache-2.0
12,355
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jsecurity.authz.aop; import org.jsecurity.aop.AnnotationMethodInterceptor; import org.jsecurity.aop.MethodInvocation; import org.jsecurity.authz.AuthorizationException; import java.lang.annotation.Annotation; /** * An <tt>AnnotationMethodInterceptor</tt> that asserts the calling code is authorized to execute the method * before allowing the invocation to continue. * * @author Les Hazlewood * @since 0.1 */ public abstract class AuthorizingAnnotationMethodInterceptor extends AnnotationMethodInterceptor { public AuthorizingAnnotationMethodInterceptor(Class<? extends Annotation> annotationClass) { super(annotationClass); } public Object invoke(MethodInvocation methodInvocation) throws Throwable { assertAuthorized(methodInvocation); return methodInvocation.proceed(); } public abstract void assertAuthorized(MethodInvocation mi) throws AuthorizationException; }
apache/jsecurity
src/org/jsecurity/authz/aop/AuthorizingAnnotationMethodInterceptor.java
Java
apache-2.0
1,745
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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 com.tle.web.workflow.soap; public interface TaskListSoapInterface { String getTaskFilterCounts(boolean ignoreZero); String[] getTaskFilterNames(); String getTaskList(String filterName, int start, int numResults) throws Exception; }
equella/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/web/workflow/soap/TaskListSoapInterface.java
Java
apache-2.0
1,054
package com.soulkey.calltalent.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.soulkey.calltalent.db.model.SettingModel; import com.soulkey.calltalent.db.populator.SettingPopulator; public final class DbOpenHelper extends SQLiteOpenHelper { public static final String DB_NAME = "calltalent.db"; private static final int DB_VERSION = 1; private static DbOpenHelper instance; public static DbOpenHelper getInstance(Context context) { if (null == instance) { instance = new DbOpenHelper(context); } return instance; } private DbOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SettingModel.CREATE_TABLE); populateDb(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } private void populateDb(SQLiteDatabase db) { SettingPopulator.populate(db); } }
wpcfan/calltalent
app/src/main/java/com/soulkey/calltalent/db/DbOpenHelper.java
Java
apache-2.0
1,109
package com.splinter.graphing; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class SplinterLogTest { @Test public void testDisableLogs() { try { SLog.setEnabled(false); String expected = ""; Assert.assertEquals(expected, new SLogStop("Coffee Time", "coffeeComplete") .withOperationAlias("ensureCapacity") .withComponentOverride("WaterReservoir") .withUserData("size", "large") .withInstrumentationOverride(0, null) .toString()); } finally { SLog.setEnabled(true); } } @Test public void testStaticUtilsVarArgs() { String expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", null)); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;_MISSING_KEY_0=null;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", null, null)); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", "size")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;size=null;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", "size", null)); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;_MISSING_KEY_0=large;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", null, "large")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;_MISSING_KEY_0=large;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", null, "large", "newkey")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;size=large;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", "size", "large")); } @Test public void testStaticUtils() { String expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;size=large;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize", "size", "large")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;"; Assert.assertEquals(expected, SLogCall.log("Coffee Time", "selectCupSize")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=A;size=large;"; Assert.assertEquals(expected, SLogStart.log("Coffee Time", "selectCupSize", "size", "large")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=A;"; Assert.assertEquals(expected, SLogStart.log("Coffee Time", "selectCupSize")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=F;size=large;"; Assert.assertEquals(expected, SLogStop.log("Coffee Time", "selectCupSize", "size", "large")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=F;"; Assert.assertEquals(expected, SLogStop.log("Coffee Time", "selectCupSize")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;+MC=1;size=large;"; Assert.assertEquals(expected, SLogBroadcastSend.log("Coffee Time", "selectCupSize", "size", "large")); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;+MC=1;"; Assert.assertEquals(expected, SLogBroadcastSend.log("Coffee Time", "selectCupSize")); expected = "$SPG$+T=Coffee Time;+O=bcastId;+M=A;+OA=selectCupSize;size=large;"; Assert.assertEquals(expected, SLogBroadcastStart.log("Coffee Time", "bcastId", "selectCupSize","size", "large")); expected = "$SPG$+T=Coffee Time;+O=bcastId;+M=A;+OA=selectCupSize;"; Assert.assertEquals(expected, SLogBroadcastStart.log("Coffee Time", "bcastId", "selectCupSize")); expected = "$SPG$+T=Coffee Time;+O=bcastId;+M=F;+OA=selectCupSize;size=large;"; Assert.assertEquals(expected, SLogBroadcastStop.log("Coffee Time", "bcastId", "selectCupSize","size", "large")); expected = "$SPG$+T=Coffee Time;+O=bcastId;+M=F;+OA=selectCupSize;"; Assert.assertEquals(expected, SLogBroadcastStop.log("Coffee Time", "bcastId", "selectCupSize")); } @Test public void testSunnyDay() { String expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;size=large;"; Assert.assertEquals(expected, new SLogCall("Coffee Time", "selectCupSize") .withUserData("size", "large").toString()); Map<String, String> userData = new HashMap<String, String>(); userData.put("size", "large"); Assert.assertEquals(expected, new SLogCall("Coffee Time", "selectCupSize") .withUserData(userData).toString()); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;size=large;size1=large;size2=large;size3=large;size4=large;size5=large;"; Assert.assertEquals(expected, new SLogCall("Coffee Time", "selectCupSize") .withUserData("size", "large") .withUserData("size1", "large") .withUserData("size2", "large") .withUserData("size3", "large") .withUserData("size4", "large") .withUserData("size5", "large").toString()); } @Test public void testOptionalParams() { String expected = "$SPG$+T=Coffee Time;+O=pumpWater;+M=A;+I^=100ms;"; Assert.assertEquals(expected, new SLogStart("Coffee Time", "pumpWater") .withInstrumentationOverride(100, SLog.TimeNotation.MILLIS) .toString()); expected = "$SPG$+T=Coffee Time;+O=coffeeComplete;+M=F;+OA=ensureCapacity;+C^=WaterReservoir;"; Assert.assertEquals(expected, new SLogStop("Coffee Time", "coffeeComplete") .withOperationAlias("ensureCapacity") .withComponentOverride("WaterReservoir") .toString()); } @Test public void testMissingParams() { String expected = "$SPG$+T=_MISSING_TASK_;+O=_MISSING_OPERATION_;+M=S;"; Assert.assertEquals(expected, new SLog(null, null, null) .toString()); expected = "$SPG$+T=Coffee Time;+O=selectCupSize;+M=S;_MISSING_KEY_0=large;"; Assert.assertEquals(expected, new SLogCall("Coffee Time", "selectCupSize") .withUserData(null, "large").toString()); } @Test public void testEscaping() { Assert.assertEquals("abcd", SLog.escape("abcd")); Assert.assertEquals("ab\\ncd", SLog.escape("ab\ncd")); Assert.assertNull(SLog.escape(null)); Assert.assertEquals("", SLog.escape("")); Assert.assertEquals("ab\\=cd", SLog.escape("ab=cd")); Assert.assertEquals("ab\\;cd", SLog.escape("ab;cd")); Assert.assertEquals("ab\\\\cd", SLog.escape("ab\\cd")); } @Test public void testEscapingLog() { String expected = "$SPG$+T=file\\; opened;+O=\\\\open;+M=S;+OA=\\=1;r\\=sr=/Users/dimitarz/\\;filename.log;"; Assert.assertEquals(expected, new SLog(null, null, null) .withUserData("r=sr", "/Users/dimitarz/;filename.log") .withOperation("\\open") .withOperationAlias("=1") .withTask("file; opened") .toString()); } }
dimitarz/splinter
src/test/java/com/splinter/graphing/SplinterLogTest.java
Java
apache-2.0
7,294
package io.zrz.graphql.core.decl; import java.util.List; import org.eclipse.jdt.annotation.Nullable; import io.zrz.graphql.core.doc.GQLDirective; import io.zrz.graphql.core.parser.GQLSourceLocation; public interface GQLDeclaration { @Nullable String description(); <R> R apply(GQLDeclarationVisitor<R> visitor); List<GQLDirective> directives(); @Nullable GQLSourceLocation location(); GQLDeclaration withDescription(String value); GQLDeclaration withDirectives(GQLDirective... elements); GQLDeclaration withDirectives(Iterable<? extends GQLDirective> elements); GQLDeclaration withLocation(GQLSourceLocation value); }
zourzouvillys/graphql
graphql-core/src/main/java/io/zrz/graphql/core/decl/GQLDeclaration.java
Java
apache-2.0
651
/* * Copyright © 2016 - 2017 Dominik Szalai (emptulik@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cz.muni.fi.editor.support; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; import org.springframework.security.test.context.support.WithSecurityContext; /** * @author Dominik Szalai - emptulik at gmail.com on 10.8.2016. */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @WithSecurityContext( factory = TestSecurityContextFactory.class ) public @interface WithEditorUser { // the owner is always user with ID 1 @AliasFor("value") long id() default 1L; @AliasFor("id") long value() default 1L; boolean mock() default false; }
empt-ak/meditor
editor-backend/src/test/java/cz/muni/fi/editor/support/WithEditorUser.java
Java
apache-2.0
1,489
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.ui.admin.tree.editablePanel; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; @SuppressWarnings("serial") public class EditablePanel extends Panel { public EditablePanel(String id, IModel<String> inputModel) { super(id); TextField<String> field = new TextField<String>("textfield", inputModel); add(field); field.add(new AjaxFormComponentUpdatingBehavior("onblur") { @Override protected void onUpdate(AjaxRequestTarget target) { } }); } }
openengsb/openengsb
ui/admin/src/main/java/org/openengsb/ui/admin/tree/editablePanel/EditablePanel.java
Java
apache-2.0
1,593
package org.devocative.demeter.service.template; import groovy.lang.Binding; import groovy.lang.Script; import org.devocative.demeter.iservice.template.BaseStringTemplate; import java.util.Map; public class GroovyScript extends BaseStringTemplate<Script> { private Script script; public GroovyScript(Script script) { this.script = script; } @Override public Object process(Map<String, Object> params) { Binding binding = new Binding(); for (Map.Entry<String, Object> entry : params.entrySet()) { binding.setVariable(entry.getKey(), entry.getValue()); } script.setBinding(binding); return script.run(); } @Override public Script unwrap() { return script; } }
mbizhani/Demeter
service/src/main/java/org/devocative/demeter/service/template/GroovyScript.java
Java
apache-2.0
690
/** * * ThingBench - Things and Devices Simulator * * http://github.com/frapu78/thingbench * * @author Frank Puhlmann * */ package thingbench; import java.util.HashMap; import net.frapu.code.visualization.ProcessNode; /** * This class provides an operation on a thing. * * @author fpu */ public abstract class ThingOperation { private ProcessNode thingNode; private String operationName; public ThingOperation(ProcessNode thingNode, String operationName) { this.thingNode = thingNode; this.operationName = operationName; } public ProcessNode getThingNode() { return thingNode; } public String getOperationName() { return operationName; } /** * This class executes the Operation. Each operation has a set of properties * of the type <String, String> as input and output. What the operation * does with it remains to the operation. * @param properties * @return * @throws thingbench.ThingExecutionException */ public abstract HashMap<String, String> execute(HashMap<String, String> properties) throws ThingExecutionException; }
frapu78/thingbench
src/thingbench/ThingOperation.java
Java
apache-2.0
1,167
package lan.dk.podcastserver.manager.worker.selector; import lan.dk.podcastserver.manager.worker.selector.update.*; import lan.dk.podcastserver.manager.worker.updater.*; import org.junit.Before; import org.junit.Test; import java.util.HashSet; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; public class UpdaterSelectorTest { Set<UpdaterCompatibility> updaterSelectors = new HashSet<>(); @Before public void setUp() throws Exception { updaterSelectors.add(new YoutubeUpdaterCompatibility()); updaterSelectors.add(new RssUpdaterCompatibility()); updaterSelectors.add(new BeInSportUpdaterCompatibility()); updaterSelectors.add(new CanalPlusUpdaterCompatibility()); updaterSelectors.add(new JeuxVideoFrCompatibility()); updaterSelectors.add(new JeuxVideoComCompatibility()); updaterSelectors.add(new ParleysCompatibility()); updaterSelectors.add(new PluzzCompatibility()); } @Test public void should_return_an_RssUpdater () { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("www.link.to.rss/feeds"); /* Then */ assertThat(updaterClass).isEqualTo(RSSUpdater.class); } @Test public void should_return_a_YoutubeUpdater () { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("http://www.youtube.com/user/fakeUser"); /* Then */ assertThat(updaterClass).isEqualTo(YoutubeUpdater.class); } @Test public void should_return_a_BeInSportUpdater () { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("http://www.beinsports.fr/replay/category/3361/name/lexpresso"); /* Then */ assertThat(updaterClass).isEqualTo(BeInSportsUpdater.class); } @Test public void should_return_a_CanalPlusUpdater() { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("http://www.canalplus.fr/show/for/dummies"); /* Then */ assertThat(updaterClass).isEqualTo(CanalPlusUpdater.class); } @Test public void should_return_a_JeuxVideoFrUpdater() { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("http://www.jeuxvideo.fr/show/for/dummies"); /* Then */ assertThat(updaterClass).isEqualTo(JeuxVideoFRUpdater.class); } @Test public void should_return_a_JeuxVideoComUpdater() { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("http://www.jeuxvideo.com/show/for/dummies"); /* Then */ assertThat(updaterClass).isEqualTo(JeuxVideoComUpdater.class); } @Test public void should_return_a_ParleysUpdater() { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("http://www.parleys.com/show/for/dummies"); /* Then */ assertThat(updaterClass).isEqualTo(ParleysUpdater.class); } @Test public void should_return_a_PluzzUpdater() { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ Class updaterClass = updaterSelector.of("http://www.pluzz.francetv.fr/show/for/dummies"); /* Then */ assertThat(updaterClass).isEqualTo(PluzzUpdater.class); } @Test(expected = RuntimeException.class) public void should_reject_empty_url() { /* Given */ UpdaterSelector updaterSelector = new UpdaterSelector().setUpdaterCompatibilities(updaterSelectors); /* When */ updaterSelector.of(""); } }
radut/Podcast-Server
src/test/java/lan/dk/podcastserver/manager/worker/selector/UpdaterSelectorTest.java
Java
apache-2.0
4,263
/* * #%L * fujion * %% * Copyright (C) 2021 Fujion Framework * %% * 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. * * #L% */ package org.fujion.highcharts; import org.fujion.ancillary.OptionMap; import org.fujion.ancillary.Options; import org.fujion.annotation.Option; import java.util.ArrayList; import java.util.List; /** * Base class for all plot types. * <p> * PlotOptions is a wrapper for config objects for each series type. The config objects for each * series can also be overridden for each series item as given in the series array. Configuration * options for the series are given in three levels. Options for all series in a chart are given in * the plotOptions.series object. Then options for all series of a specific type are given in the * plotOptions of that type, for example plotOptions.line. Next, options for one single series are * given in the series array. */ public abstract class PlotOptions extends Options { /** * The text identifier of the plot type. */ @Option(ignore = true) protected String type; /** * Allow this series' points to be selected by clicking on the markers, bars or pie slices. * Defaults to false. */ @Option public Boolean allowPointSelect; /** * Enable or disable the initial animation when a series is displayed. Since version 2.1, the * animation can be set as a configuration object. Please note that this option only applies to * the initial animation of the series itself. For other animations, see #chart.animation and * the animation parameter under the API methods. */ @Option public final AnimationOptions animation = new AnimationOptions(); /** * For some series, there is a limit that shuts down initial animation by default when the total * number of points in the chart is too high. For example, for a column chart and its * derivatives, animation doesn't run if there is more than 250 points totally. To disable this * cap, set animationLimit to Infinity. */ @Option public Integer animationLimit; /** * Set the point threshold for when a series should enter boost mode. Setting it to e.g. 2000 * will cause the series to enter boost mode when there are 2000 or more points in the series. * To disable boosting on the series, set the boostThreshold to 0. Setting it to 1 will force * boosting. Requires modules/boost.js. */ @Option public Integer boostThreshold; /** * A CSS class name to apply to the series' graphical elements. */ @Option public String className; /** * The main color or the series. In line type series it applies to the line and the point * markers unless otherwise specified. In bar type series it applies to the bars unless a color * is specified per point. The default value is pulled from the options.colors array. */ @Option public String color; /** * Styled mode only. A specific color index to use for the series, so its graphic * representations are given the class name highcharts-color-{n}. Defaults to undefined. */ @Option public Integer colorIndex; /** * When using automatic point colors pulled from the options.colors collection, this option * determines whether the chart should receive one color per series or one color per point. * Defaults to false. */ @Option public Boolean colorByPoint; /** * A series specific or series type specific color set to apply instead of the global colors * when colorByPoint is true. */ @Option public List<String> colors = new ArrayList<>(); /** * Polar charts only. Whether to connect the ends of a line series plot across the extremes. * Defaults to true. */ @Option public Boolean connectEnds; /** * Whether to connect a graph line across null points. Defaults to false. */ @Option public Boolean connectNulls; /** * When the series contains less points than the crop threshold, all points are drawn, event if * the points fall outside the visible plot area at the current zoom. The advantage of drawing * all points (including markers and columns), is that animation is performed on updates. On the * other hand, when the series contains more points than the crop threshold, the series data is * cropped to only contain points that fall within the plot area. The advantage of cropping away * invisible points is to increase performance on large series. . Defaults to 300. */ @Option public Double cropThreshold; /** * You can set the cursor to "pointer" if you have click events attached to the series, to * signal to the user that the points and lines can be clicked. Defaults to ''. */ @Option public String cursor; /** * A name for the dash style to use for the graph. Applies only to series type having a graph, * like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle * include: * <ul> * <li>Solid</li> * <li>ShortDash</li> * <li>ShortDot</li> * <li>ShortDashDot</li> * <li>ShortDashDotDot</li> * <li>Dot</li> * <li>Dash</li> * <li>LongDash</li> * <li>DashDot</li> * <li>LongDashDot</li> * <li>LongDashDotDot</li> * </ul> * Defaults to null. */ @Option public DashStyle dashStyle; /** * Options for data labels. * * @see DataLabelOptions */ @Option public final DataLabelOptions dataLabels = new DataLabelOptions(); /** * Requires the Accessibility module. A description of the series to add to the screen reader * information about the series. Defaults to undefined. */ @Option public String description; /** * Enable or disable the mouse tracking for a specific series. This includes point tooltips and * click events on graphs and points. For large datasets it improves performance. Defaults to * true. */ @Option public Boolean enableMouseTracking; /** * Requires the Accessibility module. By default, series are exposed to screen readers as * regions. By enabling this option, the series element itself will be exposed in the same way * as the data points. This is useful if the series is not used as a grouping entity in the * chart, but you still want to attach a description to the series. Defaults to undefined. */ @Option public Boolean exposeElementToA11y; /** * Determines whether the series should look for the nearest point in both dimensions or just * the x-dimension when hovering the series. Defaults to 'xy' for scatter series and 'x' for * most other series. If the data has duplicate x-values, it is recommended to set this to 'xy' * to allow hovering over all points. Applies only to series types using nearest neighbor search * (not direct hover) for tooltip. Defaults to x. */ @Option public String findNearestPointBy; /** * Whether to use the Y extremes of the total chart width or only the zoomed area when zooming * in on parts of the X axis. By default, the Y axis adjusts to the min and max of the visible * data. Cartesian series only. Defaults to false. */ @Option public Boolean getExtremesFromAll; /** * An id for the series. Defaults to null. */ @Option public String id; /** * An array specifying which option maps to which key in the data point array. This makes it * convenient to work with unstructured data arrays from different sources. Defaults to * undefined. */ @Option public final List<String> keys = new ArrayList<>(); /** * Text labels for the plot bands. */ @Option public final PlotLabelOptions label = new PlotLabelOptions(); /** * The line cap used for line ends and line joins on the graph. Defaults to round. */ @Option public String linecap; /** * Pixel with of the graph line. Defaults to 2. */ @Option public Integer lineWidth; /** * The id of another series to link to. Additionally, the value can be ":previous" to link to * the previous series. When two series are linked, only the first one appears in the legend. * Toggling the visibility of this also toggles the linked series. */ @Option public String linkedTo; /** * Options for point markers. * * @see MarkerOptions */ @Option public final MarkerOptions marker = new MarkerOptions(); /** * The color for the parts of the graph or points that are below the threshold. Defaults to * null. */ @Option public String negativeColor; /** * If no x values are given for the points in a series, pointInterval defines the interval of * the x values. For example, if a series contains one value every decade starting from year 0, * set pointInterval to 10. Defaults to 1. */ @Option public Double pointInterval; /** * On datetime series, this allows for setting the pointInterval to irregular time units, day, * month and year. A day is usually the same as 24 hours, but pointIntervalUnit also takes the * DST crossover into consideration when dealing with local time. Combine this option with * pointInterval to draw weeks, quarters, 6 months, 10 years etc. Please note that this options * applies to the series data, not the interval of the axis ticks, which is independent. * Defaults to undefined. */ @Option public String pointIntervalUnit; /** * Possible values: null, "on", "between". In a column chart, when pointPlacement is "on", the * point will not create any padding of the X axis. In a polar column chart this means that the * first column points directly north. If the pointPlacement is "between", the columns will be * laid out between ticks. This is useful for example for visualising an amount between two * points in time or in a certain sector of a polar chart. Defaults to null in cartesian charts, * "between" in polar charts. */ @Option public String pointPlacement; /** * If no x values are given for the points in a series, pointStart defines on what value to * start. For example, if a series contains one yearly value starting from 1945, set pointStart * to 1945. Defaults to 0. */ @Option public Double pointStart; /** * Whether to select the series initially. If showCheckbox is true, the checkbox next to the * series name will be checked for a selected series. Defaults to false. */ @Option public Boolean selected; /** * Boolean value whether to apply a drop shadow to the graph line. Optionally can be a * ShadowOptions object. Defaults to true. * * @see ShadowOptions */ @Option public Object shadow; /** * If true, a checkbox is displayed next to the legend item to allow selecting the series. The * state of the checkbox is determined by the selected option. Defaults to false. */ @Option public Boolean showCheckbox; /** * Whether to display this particular series or series type in the legend. Defaults to true. */ @Option public Boolean showInLegend; /** * If set to True, the accessibility module will skip past the points in this series for * keyboard navigation. Defaults to undefined. */ @Option public Boolean skipKeyboardNavigation; /** * When this is true, the series will not cause the Y axis to cross the zero plane (or threshold * option) unless the data actually crosses the plane. For example, if softThreshold is false, a * series of 0, 1, 2, 3 will make the Y axis show negative values according to the minPadding * option. If softThreshold is true, the Y axis starts at 0. Defaults to true. */ @Option public Boolean softThreshold; /** * Whether to stack the values of each series on top of each other. Possible values are null to * disable, "normal" to stack by value or "percent". Defaults to null. */ @Option public String stacking; /** * Whether to apply steps to the line. Possible values are left, center and right. Defaults to * undefined. */ @Option public AlignHorizontal step; /** * Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered * until the mouse moves over another series, or out of the plot area. When false, the mouseOut * event on a series is triggered when the mouse leaves the area around the series' graph or * markers. This also implies the tooltip. When stickyTracking is false and tooltip.shared is * false, the tooltip will be hidden when moving the mouse between series. Defaults to true. */ @Option public Boolean stickyTracking; /** * The threshold, also called zero level or base level. For line type series this is only used * in conjunction with negativeColor. Defaults to 0. */ @Option public Double threshold; /** * A configuration object for the tooltip rendering of each single series. */ @Option public final TooltipOptions tooltip = new TooltipOptions(); /** * When a series contains a data array that is longer than this, only one dimensional arrays of * numbers, or two dimensional arrays with x and y values are allowed. Also, only the first * point is tested, and the rest are assumed to be the same format. This saves expensive data * checking and indexing in long series. Defaults to 1000. */ @Option public Integer turboThreshold; /** * Set the initial visibility of the series. Defaults to true. */ @Option public Boolean visible; /** * Defines the axis on which the zones are applied. Defaults to y. */ @Option public String zoneAxis; /** * An array defining zones within a series. Zones can be applied to the X axis, Y axis or Z axis * for bubbles, according to the zoneAxis option. In styled mode, the color zones are styled * with the .highcharts-zone-{n} class, or custom classed from the className option. */ @Option public final List<Zone> zones = new ArrayList<>(); /** * If type is not null, place options under a submap indexed by the type id. */ @Override public OptionMap toMap() { OptionMap map = super.toMap(); if (type != null) { OptionMap newMap = new OptionMap(); newMap.put(type, map); map = newMap; } return map; } }
fujion/fujion-framework
fujion-highcharts/src/main/java/org/fujion/highcharts/PlotOptions.java
Java
apache-2.0
15,646
package grok.core; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; @AutoValue public abstract class Image { @JsonCreator public static Image of(@JsonProperty("id") String id, @JsonProperty("title") String title, @JsonProperty("url") String url) { return builder().id(id) .title(title) .url(url) .build(); } public static Builder builder() { return new AutoValue_Image.Builder(); } Image() {} @JsonProperty public abstract String id(); @JsonProperty public abstract String title(); @JsonProperty public abstract String url(); @AutoValue.Builder public abstract static class Builder { Builder() {} public abstract Builder id(String value); @JsonProperty public abstract Builder title(String value); @JsonProperty public abstract Builder url(String value); public abstract Image build(); } }
achaphiv/grok-core
grok-core-api/src/main/java/grok/core/Image.java
Java
apache-2.0
1,076
package com.mgaetan89.showsrage.fragment; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @RunWith(Parameterized.class) public class ShowsFragment_OnQueryTextChangeTest { @Parameterized.Parameter(0) public String newText; private ShowsFragment fragment; @Before public void before() { this.fragment = spy(new ShowsFragment()); } @Test public void onQueryTextChange() { try { assertTrue(this.fragment.onQueryTextChange(this.newText)); } catch (NullPointerException exception) { // LocalBroadcastManager.getInstance(Context) returns null in tests } verify(this.fragment).sendFilterMessage(); } @After public void after() { this.fragment = null; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {null}, {""}, {" "}, {"Search Query"}, }); } }
phaseburn/ShowsRage
app/src/test/java/com/mgaetan89/showsrage/fragment/ShowsFragment_OnQueryTextChangeTest.java
Java
apache-2.0
1,137
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Maarten De Weerdt */ @Entity @Table(name = "Product") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p") , @NamedQuery(name = "Product.findById", query = "SELECT p FROM Product p WHERE p.id = :id") , @NamedQuery(name = "Product.findByPrijs", query = "SELECT p FROM Product p WHERE p.prijs = :prijs") , @NamedQuery(name = "Product.findByCategorie", query = "SELECT p FROM Product p WHERE p.categorieNaam = :categorieNaam") }) public class Product implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "ID") private Integer id; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 65535) @Column(name = "Naam") private String naam; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 65535) @Column(name = "Omschrijving") private String omschrijving; @Basic(optional = false) @NotNull @Column(name = "Prijs") private double prijs; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 65535) @Column(name = "Afbeelding") private String afbeelding; @Lob @Size(max = 65535) @Column(name = "Informatie") private String informatie; @JoinColumn(name = "CategorieNaam", referencedColumnName = "CategorieNaam") @ManyToOne(optional = false) private Categorie categorieNaam; public Product() { } public Product(Integer id) { this.id = id; } public Product(Integer id, String naam, String omschrijving, double prijs, String afbeelding) { this.id = id; this.naam = naam; this.omschrijving = omschrijving; this.prijs = prijs; this.afbeelding = afbeelding; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } public String getOmschrijving() { return omschrijving; } public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } public double getPrijs() { return prijs; } public void setPrijs(double prijs) { this.prijs = prijs; } public String getAfbeelding() { return afbeelding; } public void setAfbeelding(String afbeelding) { this.afbeelding = afbeelding; } public String getInformatie() { return informatie; } public void setInformatie(String informatie) { this.informatie = informatie; } public Categorie getCategorieNaam() { return categorieNaam; } public void setCategorieNaam(Categorie categorieNaam) { this.categorieNaam = categorieNaam; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Product)) { return false; } Product other = (Product) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "entities.Product[ id=" + id + " ]"; } }
MaartenDeWeerdt/TomEnJerry
TomEnJerry-ejb/src/java/entities/Product.java
Java
apache-2.0
4,620
/* * Copyright (C) 2018 The Dagger 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 dagger.internal.codegen.validation; import static com.google.auto.common.MoreTypes.asDeclared; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.in; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Iterables.getOnlyElement; import static dagger.internal.codegen.base.ComponentAnnotation.rootComponentAnnotation; import static dagger.internal.codegen.base.DiagnosticFormatting.stripCommonTypePrefixes; import static dagger.internal.codegen.base.Formatter.INDENT; import static dagger.internal.codegen.base.Scopes.getReadableSource; import static dagger.internal.codegen.base.Scopes.scopesOf; import static dagger.internal.codegen.base.Scopes.singletonScope; import static dagger.internal.codegen.base.Util.reentrantComputeIfAbsent; import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSet; import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSetMultimap; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static javax.tools.Diagnostic.Kind.ERROR; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.google.common.base.Equivalence.Wrapper; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import dagger.internal.codegen.binding.ComponentCreatorDescriptor; import dagger.internal.codegen.binding.ComponentDescriptor; import dagger.internal.codegen.binding.ComponentRequirement; import dagger.internal.codegen.binding.ComponentRequirement.NullPolicy; import dagger.internal.codegen.binding.ContributionBinding; import dagger.internal.codegen.binding.ErrorMessages; import dagger.internal.codegen.binding.ErrorMessages.ComponentCreatorMessages; import dagger.internal.codegen.binding.MethodSignatureFormatter; import dagger.internal.codegen.binding.ModuleDescriptor; import dagger.internal.codegen.compileroption.CompilerOptions; import dagger.internal.codegen.compileroption.ValidationType; import dagger.internal.codegen.langmodel.DaggerElements; import dagger.internal.codegen.langmodel.DaggerTypes; import dagger.model.Scope; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.StringJoiner; import javax.inject.Inject; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic; /** * Reports errors in the component hierarchy. * * <ul> * <li>Validates scope hierarchy of component dependencies and subcomponents. * <li>Reports errors if there are component dependency cycles. * <li>Reports errors if any abstract modules have non-abstract instance binding methods. * <li>Validates component creator types. * </ul> */ // TODO(dpb): Combine with ComponentHierarchyValidator. public final class ComponentDescriptorValidator { private final DaggerElements elements; private final DaggerTypes types; private final CompilerOptions compilerOptions; private final MethodSignatureFormatter methodSignatureFormatter; private final ComponentHierarchyValidator componentHierarchyValidator; @Inject ComponentDescriptorValidator( DaggerElements elements, DaggerTypes types, CompilerOptions compilerOptions, MethodSignatureFormatter methodSignatureFormatter, ComponentHierarchyValidator componentHierarchyValidator) { this.elements = elements; this.types = types; this.compilerOptions = compilerOptions; this.methodSignatureFormatter = methodSignatureFormatter; this.componentHierarchyValidator = componentHierarchyValidator; } public ValidationReport<TypeElement> validate(ComponentDescriptor component) { ComponentValidation validation = new ComponentValidation(component); validation.visitComponent(component); validation.report(component).addSubreport(componentHierarchyValidator.validate(component)); return validation.buildReport(); } private final class ComponentValidation { final ComponentDescriptor rootComponent; final Map<ComponentDescriptor, ValidationReport.Builder<TypeElement>> reports = new LinkedHashMap<>(); ComponentValidation(ComponentDescriptor rootComponent) { this.rootComponent = checkNotNull(rootComponent); } /** Returns a report that contains all validation messages found during traversal. */ ValidationReport<TypeElement> buildReport() { ValidationReport.Builder<TypeElement> report = ValidationReport.about(rootComponent.typeElement()); reports.values().forEach(subreport -> report.addSubreport(subreport.build())); return report.build(); } /** Returns the report builder for a (sub)component. */ private ValidationReport.Builder<TypeElement> report(ComponentDescriptor component) { return reentrantComputeIfAbsent( reports, component, descriptor -> ValidationReport.about(descriptor.typeElement())); } private void reportComponentItem( Diagnostic.Kind kind, ComponentDescriptor component, String message) { report(component) .addItem(message, kind, component.typeElement(), component.annotation().annotation()); } private void reportComponentError(ComponentDescriptor component, String error) { reportComponentItem(ERROR, component, error); } void visitComponent(ComponentDescriptor component) { validateDependencyScopes(component); validateComponentDependencyHierarchy(component); validateModules(component); validateCreators(component); component.childComponents().forEach(this::visitComponent); } /** Validates that component dependencies do not form a cycle. */ private void validateComponentDependencyHierarchy(ComponentDescriptor component) { validateComponentDependencyHierarchy(component, component.typeElement(), new ArrayDeque<>()); } /** Recursive method to validate that component dependencies do not form a cycle. */ private void validateComponentDependencyHierarchy( ComponentDescriptor component, TypeElement dependency, Deque<TypeElement> dependencyStack) { if (dependencyStack.contains(dependency)) { // Current component has already appeared in the component chain. StringBuilder message = new StringBuilder(); message.append(component.typeElement().getQualifiedName()); message.append(" contains a cycle in its component dependencies:\n"); dependencyStack.push(dependency); appendIndentedComponentsList(message, dependencyStack); dependencyStack.pop(); reportComponentItem( compilerOptions.scopeCycleValidationType().diagnosticKind().get(), component, message.toString()); } else { rootComponentAnnotation(dependency) .ifPresent( componentAnnotation -> { dependencyStack.push(dependency); for (TypeElement nextDependency : componentAnnotation.dependencies()) { validateComponentDependencyHierarchy( component, nextDependency, dependencyStack); } dependencyStack.pop(); }); } } /** * Validates that among the dependencies are at most one scoped dependency, that there are no * cycles within the scoping chain, and that singleton components have no scoped dependencies. */ private void validateDependencyScopes(ComponentDescriptor component) { ImmutableSet<Scope> scopes = component.scopes(); ImmutableSet<TypeElement> scopedDependencies = scopedTypesIn( component .dependencies() .stream() .map(ComponentRequirement::typeElement) .collect(toImmutableSet())); if (!scopes.isEmpty()) { Scope singletonScope = singletonScope(elements); // Dagger 1.x scope compatibility requires this be suppress-able. if (compilerOptions.scopeCycleValidationType().diagnosticKind().isPresent() && scopes.contains(singletonScope)) { // Singleton is a special-case representing the longest lifetime, and therefore // @Singleton components may not depend on scoped components if (!scopedDependencies.isEmpty()) { StringBuilder message = new StringBuilder( "This @Singleton component cannot depend on scoped components:\n"); appendIndentedComponentsList(message, scopedDependencies); reportComponentItem( compilerOptions.scopeCycleValidationType().diagnosticKind().get(), component, message.toString()); } } else if (scopedDependencies.size() > 1) { // Scoped components may depend on at most one scoped component. StringBuilder message = new StringBuilder(); for (Scope scope : scopes) { message.append(getReadableSource(scope)).append(' '); } message .append(component.typeElement().getQualifiedName()) .append(" depends on more than one scoped component:\n"); appendIndentedComponentsList(message, scopedDependencies); reportComponentError(component, message.toString()); } else { // Dagger 1.x scope compatibility requires this be suppress-able. if (!compilerOptions.scopeCycleValidationType().equals(ValidationType.NONE)) { validateDependencyScopeHierarchy( component, component.typeElement(), new ArrayDeque<>(), new ArrayDeque<>()); } } } else { // Scopeless components may not depend on scoped components. if (!scopedDependencies.isEmpty()) { StringBuilder message = new StringBuilder(component.typeElement().getQualifiedName()) .append(" (unscoped) cannot depend on scoped components:\n"); appendIndentedComponentsList(message, scopedDependencies); reportComponentError(component, message.toString()); } } } private void validateModules(ComponentDescriptor component) { for (ModuleDescriptor module : component.modules()) { if (module.moduleElement().getModifiers().contains(Modifier.ABSTRACT)) { for (ContributionBinding binding : module.bindings()) { if (binding.requiresModuleInstance()) { report(component).addError(abstractModuleHasInstanceBindingMethodsError(module)); break; } } } } } private String abstractModuleHasInstanceBindingMethodsError(ModuleDescriptor module) { String methodAnnotations; switch (module.kind()) { case MODULE: methodAnnotations = "@Provides"; break; case PRODUCER_MODULE: methodAnnotations = "@Provides or @Produces"; break; default: throw new AssertionError(module.kind()); } return String.format( "%s is abstract and has instance %s methods. Consider making the methods static or " + "including a non-abstract subclass of the module instead.", module.moduleElement(), methodAnnotations); } private void validateCreators(ComponentDescriptor component) { if (!component.creatorDescriptor().isPresent()) { // If no builder, nothing to validate. return; } ComponentCreatorDescriptor creator = component.creatorDescriptor().get(); ComponentCreatorMessages messages = ErrorMessages.creatorMessagesFor(creator.annotation()); // Requirements for modules and dependencies that the creator can set Set<ComponentRequirement> creatorModuleAndDependencyRequirements = creator.moduleAndDependencyRequirements(); // Modules and dependencies the component requires Set<ComponentRequirement> componentModuleAndDependencyRequirements = component.dependenciesAndConcreteModules(); // Requirements that the creator can set that don't match any requirements that the component // actually has. Set<ComponentRequirement> inapplicableRequirementsOnCreator = Sets.difference( creatorModuleAndDependencyRequirements, componentModuleAndDependencyRequirements); DeclaredType container = asDeclared(creator.typeElement().asType()); if (!inapplicableRequirementsOnCreator.isEmpty()) { Collection<Element> excessElements = Multimaps.filterKeys( creator.unvalidatedRequirementElements(), in(inapplicableRequirementsOnCreator)) .values(); String formatted = excessElements.stream() .map(element -> formatElement(element, container)) .collect(joining(", ", "[", "]")); report(component) .addError(String.format(messages.extraSetters(), formatted), creator.typeElement()); } // Component requirements that the creator must be able to set Set<ComponentRequirement> mustBePassed = Sets.filter( componentModuleAndDependencyRequirements, input -> input.nullPolicy(elements, types).equals(NullPolicy.THROW)); // Component requirements that the creator must be able to set, but can't Set<ComponentRequirement> missingRequirements = Sets.difference(mustBePassed, creatorModuleAndDependencyRequirements); if (!missingRequirements.isEmpty()) { report(component) .addError( String.format( messages.missingSetters(), missingRequirements.stream().map(ComponentRequirement::type).collect(toList())), creator.typeElement()); } // Validate that declared creator requirements (modules, dependencies) have unique types. ImmutableSetMultimap<Wrapper<TypeMirror>, Element> declaredRequirementsByType = Multimaps.filterKeys( creator.unvalidatedRequirementElements(), creatorModuleAndDependencyRequirements::contains) .entries().stream() .collect( toImmutableSetMultimap(entry -> entry.getKey().wrappedType(), Entry::getValue)); declaredRequirementsByType .asMap() .forEach( (typeWrapper, elementsForType) -> { if (elementsForType.size() > 1) { TypeMirror type = typeWrapper.get(); // TODO(cgdecker): Attach this error message to the factory method rather than // the component type if the elements are factory method parameters AND the // factory method is defined by the factory type itself and not by a supertype. report(component) .addError( String.format( messages.multipleSettersForModuleOrDependencyType(), type, transform( elementsForType, element -> formatElement(element, container))), creator.typeElement()); } }); // TODO(cgdecker): Duplicate binding validation should handle the case of multiple elements // that set the same bound-instance Key, but validating that here would make it fail faster // for subcomponents. } private String formatElement(Element element, DeclaredType container) { // TODO(cgdecker): Extract some or all of this to another class? // But note that it does different formatting for parameters than // DaggerElements.elementToString(Element). switch (element.getKind()) { case METHOD: return methodSignatureFormatter.format( MoreElements.asExecutable(element), Optional.of(container)); case PARAMETER: return formatParameter(MoreElements.asVariable(element), container); default: // This method shouldn't be called with any other type of element. throw new AssertionError(); } } private String formatParameter(VariableElement parameter, DeclaredType container) { // TODO(cgdecker): Possibly leave the type (and annotations?) off of the parameters here and // just use their names, since the type will be redundant in the context of the error message. StringJoiner joiner = new StringJoiner(" "); parameter.getAnnotationMirrors().stream().map(Object::toString).forEach(joiner::add); TypeMirror parameterType = resolveParameterType(parameter, container); return joiner .add(stripCommonTypePrefixes(parameterType.toString())) .add(parameter.getSimpleName()) .toString(); } private TypeMirror resolveParameterType(VariableElement parameter, DeclaredType container) { ExecutableElement method = MoreElements.asExecutable(parameter.getEnclosingElement()); int parameterIndex = method.getParameters().indexOf(parameter); ExecutableType methodType = MoreTypes.asExecutable(types.asMemberOf(container, method)); return methodType.getParameterTypes().get(parameterIndex); } /** * Validates that scopes do not participate in a scoping cycle - that is to say, scoped * components are in a hierarchical relationship terminating with Singleton. * * <p>As a side-effect, this means scoped components cannot have a dependency cycle between * themselves, since a component's presence within its own dependency path implies a cyclical * relationship between scopes. However, cycles in component dependencies are explicitly checked * in {@link #validateComponentDependencyHierarchy(ComponentDescriptor)}. */ private void validateDependencyScopeHierarchy( ComponentDescriptor component, TypeElement dependency, Deque<ImmutableSet<Scope>> scopeStack, Deque<TypeElement> scopedDependencyStack) { ImmutableSet<Scope> scopes = scopesOf(dependency); if (stackOverlaps(scopeStack, scopes)) { scopedDependencyStack.push(dependency); // Current scope has already appeared in the component chain. StringBuilder message = new StringBuilder(); message.append(component.typeElement().getQualifiedName()); message.append(" depends on scoped components in a non-hierarchical scope ordering:\n"); appendIndentedComponentsList(message, scopedDependencyStack); if (compilerOptions.scopeCycleValidationType().diagnosticKind().isPresent()) { reportComponentItem( compilerOptions.scopeCycleValidationType().diagnosticKind().get(), component, message.toString()); } scopedDependencyStack.pop(); } else { // TODO(beder): transitively check scopes of production components too. rootComponentAnnotation(dependency) .filter(componentAnnotation -> !componentAnnotation.isProduction()) .ifPresent( componentAnnotation -> { ImmutableSet<TypeElement> scopedDependencies = scopedTypesIn(componentAnnotation.dependencies()); if (scopedDependencies.size() == 1) { // empty can be ignored (base-case), and > 1 is a separately-reported error. scopeStack.push(scopes); scopedDependencyStack.push(dependency); validateDependencyScopeHierarchy( component, getOnlyElement(scopedDependencies), scopeStack, scopedDependencyStack); scopedDependencyStack.pop(); scopeStack.pop(); } }); // else: we skip component dependencies which are not components } } private <T> boolean stackOverlaps(Deque<ImmutableSet<T>> stack, ImmutableSet<T> set) { for (ImmutableSet<T> entry : stack) { if (!Sets.intersection(entry, set).isEmpty()) { return true; } } return false; } /** Appends and formats a list of indented component types (with their scope annotations). */ private void appendIndentedComponentsList(StringBuilder message, Iterable<TypeElement> types) { for (TypeElement scopedComponent : types) { message.append(INDENT); for (Scope scope : scopesOf(scopedComponent)) { message.append(getReadableSource(scope)).append(' '); } message .append(stripCommonTypePrefixes(scopedComponent.getQualifiedName().toString())) .append('\n'); } } /** * Returns a set of type elements containing only those found in the input set that have a * scoping annotation. */ private ImmutableSet<TypeElement> scopedTypesIn(Collection<TypeElement> types) { return types.stream().filter(type -> !scopesOf(type).isEmpty()).collect(toImmutableSet()); } } }
cgruber/dagger
java/dagger/internal/codegen/validation/ComponentDescriptorValidator.java
Java
apache-2.0
22,500
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.route53.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.route53.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * GetHealthCheckLastFailureReasonResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetHealthCheckLastFailureReasonResultStaxUnmarshaller implements Unmarshaller<GetHealthCheckLastFailureReasonResult, StaxUnmarshallerContext> { public GetHealthCheckLastFailureReasonResult unmarshall(StaxUnmarshallerContext context) throws Exception { GetHealthCheckLastFailureReasonResult getHealthCheckLastFailureReasonResult = new GetHealthCheckLastFailureReasonResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return getHealthCheckLastFailureReasonResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("HealthCheckObservations", targetDepth)) { getHealthCheckLastFailureReasonResult.withHealthCheckObservations(new ArrayList<HealthCheckObservation>()); continue; } if (context.testExpression("HealthCheckObservations/HealthCheckObservation", targetDepth)) { getHealthCheckLastFailureReasonResult.withHealthCheckObservations(HealthCheckObservationStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return getHealthCheckLastFailureReasonResult; } } } } private static GetHealthCheckLastFailureReasonResultStaxUnmarshaller instance; public static GetHealthCheckLastFailureReasonResultStaxUnmarshaller getInstance() { if (instance == null) instance = new GetHealthCheckLastFailureReasonResultStaxUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/transform/GetHealthCheckLastFailureReasonResultStaxUnmarshaller.java
Java
apache-2.0
3,038
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.cache.store.jdbc; import java.nio.ByteBuffer; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.cache.Cache; import javax.cache.CacheException; import javax.cache.integration.CacheLoaderException; import javax.cache.integration.CacheWriterException; import javax.sql.DataSource; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.cache.CacheTypeFieldMetadata; import org.apache.ignite.cache.CacheTypeMetadata; import org.apache.ignite.cache.store.CacheStore; import org.apache.ignite.cache.store.CacheStoreSession; import org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect; import org.apache.ignite.cache.store.jdbc.dialect.DB2Dialect; import org.apache.ignite.cache.store.jdbc.dialect.H2Dialect; import org.apache.ignite.cache.store.jdbc.dialect.JdbcDialect; import org.apache.ignite.cache.store.jdbc.dialect.MySQLDialect; import org.apache.ignite.cache.store.jdbc.dialect.OracleDialect; import org.apache.ignite.cache.store.jdbc.dialect.SQLServerDialect; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.typedef.C1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteBiInClosure; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.resources.CacheStoreSessionResource; import org.apache.ignite.resources.IgniteInstanceResource; import org.apache.ignite.resources.LoggerResource; import org.apache.ignite.transactions.Transaction; import org.jetbrains.annotations.Nullable; import static java.sql.Statement.EXECUTE_FAILED; import static java.sql.Statement.SUCCESS_NO_INFO; /** * Implementation of {@link CacheStore} backed by JDBC. * <p> * Store works with database via SQL dialect. Ignite ships with dialects for most popular databases: * <ul> * <li>{@link DB2Dialect} - dialect for IBM DB2 database.</li> * <li>{@link OracleDialect} - dialect for Oracle database.</li> * <li>{@link SQLServerDialect} - dialect for Microsoft SQL Server database.</li> * <li>{@link MySQLDialect} - dialect for Oracle MySQL database.</li> * <li>{@link H2Dialect} - dialect for H2 database.</li> * <li>{@link BasicJdbcDialect} - dialect for any database via plain JDBC.</li> * </ul> * <p> * <h2 class="header">Configuration</h2> * <ul> * <li>Data source (see {@link #setDataSource(DataSource)}</li> * <li>Dialect (see {@link #setDialect(JdbcDialect)}</li> * <li>Maximum batch size for writeAll and deleteAll operations. (see {@link #setBatchSize(int)})</li> * <li>Max workers thread count. These threads are responsible for load cache. (see {@link #setMaximumPoolSize(int)})</li> * <li>Parallel load cache minimum threshold. (see {@link #setParallelLoadCacheMinimumThreshold(int)})</li> * </ul> * <h2 class="header">Java Example</h2> * <pre name="code" class="java"> * ... * CacheConfiguration ccfg = new CacheConfiguration&lt;&gt;(); * * // Configure cache store. * ccfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(ConfigurationSnippet.store())); * ccfg.setReadThrough(true); * ccfg.setWriteThrough(true); * * // Configure cache types metadata. * ccfg.setTypeMetadata(ConfigurationSnippet.typeMetadata()); * * cfg.setCacheConfiguration(ccfg); * ... * </pre> */ public abstract class CacheAbstractJdbcStore<K, V> implements CacheStore<K, V>, LifecycleAware { /** Max attempt write count. */ protected static final int MAX_ATTEMPT_WRITE_COUNT = 2; /** Default batch size for put and remove operations. */ protected static final int DFLT_BATCH_SIZE = 512; /** Default batch size for put and remove operations. */ protected static final int DFLT_PARALLEL_LOAD_CACHE_MINIMUM_THRESHOLD = 512; /** Connection attribute property name. */ protected static final String ATTR_CONN_PROP = "JDBC_STORE_CONNECTION"; /** Empty column value. */ protected static final Object[] EMPTY_COLUMN_VALUE = new Object[] { null }; /** Auto-injected store session. */ @CacheStoreSessionResource private CacheStoreSession ses; /** Auto injected ignite instance. */ @IgniteInstanceResource private Ignite ignite; /** Auto-injected logger instance. */ @LoggerResource protected IgniteLogger log; /** Lock for metadata cache. */ @GridToStringExclude private final Lock cacheMappingsLock = new ReentrantLock(); /** Data source. */ protected DataSource dataSrc; /** Cache with entry mapping description. (cache name, (key id, mapping description)). */ protected volatile Map<String, Map<Object, EntryMapping>> cacheMappings = Collections.emptyMap(); /** Database dialect. */ protected JdbcDialect dialect; /** Max workers thread count. These threads are responsible for load cache. */ private int maxPoolSz = Runtime.getRuntime().availableProcessors(); /** Maximum batch size for writeAll and deleteAll operations. */ private int batchSz = DFLT_BATCH_SIZE; /** Parallel load cache minimum threshold. If {@code 0} then load sequentially. */ private int parallelLoadCacheMinThreshold = DFLT_PARALLEL_LOAD_CACHE_MINIMUM_THRESHOLD; /** * Get field value from object for use as query parameter. * * @param cacheName Cache name. * @param typeName Type name. * @param fieldName Field name. * @param obj Cache object. * @return Field value from object. * @throws CacheException in case of error. */ @Nullable protected abstract Object extractParameter(@Nullable String cacheName, String typeName, String fieldName, Object obj) throws CacheException; /** * Construct object from query result. * * @param <R> Type of result object. * @param cacheName Cache name. * @param typeName Type name. * @param fields Fields descriptors. * @param loadColIdxs Select query columns index. * @param rs ResultSet. * @return Constructed object. * @throws CacheLoaderException If failed to construct cache object. */ protected abstract <R> R buildObject(@Nullable String cacheName, String typeName, Collection<CacheTypeFieldMetadata> fields, Map<String, Integer> loadColIdxs, ResultSet rs) throws CacheLoaderException; /** * Extract key type id from key object. * * @param key Key object. * @return Key type id. * @throws CacheException If failed to get type key id from object. */ protected abstract Object keyTypeId(Object key) throws CacheException; /** * Extract key type id from key class name. * * @param type String description of key type. * @return Key type id. * @throws CacheException If failed to get type key id from object. */ protected abstract Object keyTypeId(String type) throws CacheException; /** * Prepare internal store specific builders for provided types metadata. * * @param cacheName Cache name to prepare builders for. * @param types Collection of types. * @throws CacheException If failed to prepare internal builders for types. */ protected abstract void prepareBuilders(@Nullable String cacheName, Collection<CacheTypeMetadata> types) throws CacheException; /** * Perform dialect resolution. * * @return The resolved dialect. * @throws CacheException Indicates problems accessing the metadata. */ protected JdbcDialect resolveDialect() throws CacheException { Connection conn = null; String dbProductName = null; try { conn = openConnection(false); dbProductName = conn.getMetaData().getDatabaseProductName(); } catch (SQLException e) { throw new CacheException("Failed access to metadata for detect database dialect.", e); } finally { U.closeQuiet(conn); } if ("H2".equals(dbProductName)) return new H2Dialect(); if ("MySQL".equals(dbProductName)) return new MySQLDialect(); if (dbProductName.startsWith("Microsoft SQL Server")) return new SQLServerDialect(); if ("Oracle".equals(dbProductName)) return new OracleDialect(); if (dbProductName.startsWith("DB2/")) return new DB2Dialect(); U.warn(log, "Failed to resolve dialect (BasicJdbcDialect will be used): " + dbProductName); return new BasicJdbcDialect(); } /** {@inheritDoc} */ @Override public void start() throws IgniteException { if (dataSrc == null) throw new IgniteException("Failed to initialize cache store (data source is not provided)."); if (dialect == null) { dialect = resolveDialect(); if (log.isDebugEnabled() && dialect.getClass() != BasicJdbcDialect.class) log.debug("Resolved database dialect: " + U.getSimpleName(dialect.getClass())); } } /** {@inheritDoc} */ @Override public void stop() throws IgniteException { // No-op. } /** * Gets connection from a pool. * * @param autocommit {@code true} If connection should use autocommit mode. * @return Pooled connection. * @throws SQLException In case of error. */ protected Connection openConnection(boolean autocommit) throws SQLException { Connection conn = dataSrc.getConnection(); conn.setAutoCommit(autocommit); return conn; } /** * @return Connection. * @throws SQLException In case of error. */ protected Connection connection() throws SQLException { CacheStoreSession ses = session(); if (ses.transaction() != null) { Map<String, Connection> prop = ses.properties(); Connection conn = prop.get(ATTR_CONN_PROP); if (conn == null) { conn = openConnection(false); // Store connection in session to used it for other operations in the same session. prop.put(ATTR_CONN_PROP, conn); } return conn; } // Transaction can be null in case of simple load operation. else return openConnection(true); } /** * Closes connection. * * @param conn Connection to close. */ protected void closeConnection(@Nullable Connection conn) { CacheStoreSession ses = session(); // Close connection right away if there is no transaction. if (ses.transaction() == null) U.closeQuiet(conn); } /** * Closes allocated resources depending on transaction status. * * @param conn Allocated connection. * @param st Created statement, */ protected void end(@Nullable Connection conn, @Nullable Statement st) { U.closeQuiet(st); closeConnection(conn); } /** {@inheritDoc} */ @Override public void sessionEnd(boolean commit) throws CacheWriterException { CacheStoreSession ses = session(); Transaction tx = ses.transaction(); if (tx != null) { Map<String, Connection> sesProps = ses.properties(); Connection conn = sesProps.get(ATTR_CONN_PROP); if (conn != null) { sesProps.remove(ATTR_CONN_PROP); try { if (commit) conn.commit(); else conn.rollback(); } catch (SQLException e) { throw new CacheWriterException( "Failed to end transaction [xid=" + tx.xid() + ", commit=" + commit + ']', e); } finally { U.closeQuiet(conn); } } if (log.isDebugEnabled()) log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']'); } } /** * Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object and * will convert to the requested Java data type. * * @param rs Result set. * @param colIdx Column index in result set. * @param type Class representing the Java data type to convert the designated column to. * @return Value in column. * @throws SQLException If a database access error occurs or this method is called. */ protected Object getColumnValue(ResultSet rs, int colIdx, Class<?> type) throws SQLException { Object val = rs.getObject(colIdx); if (val == null) return null; if (type == int.class) return rs.getInt(colIdx); if (type == long.class) return rs.getLong(colIdx); if (type == double.class) return rs.getDouble(colIdx); if (type == boolean.class || type == Boolean.class) return rs.getBoolean(colIdx); if (type == byte.class) return rs.getByte(colIdx); if (type == short.class) return rs.getShort(colIdx); if (type == float.class) return rs.getFloat(colIdx); if (type == Integer.class || type == Long.class || type == Double.class || type == Byte.class || type == Short.class || type == Float.class) { Number num = (Number)val; if (type == Integer.class) return num.intValue(); else if (type == Long.class) return num.longValue(); else if (type == Double.class) return num.doubleValue(); else if (type == Byte.class) return num.byteValue(); else if (type == Short.class) return num.shortValue(); else if (type == Float.class) return num.floatValue(); } if (type == UUID.class) { if (val instanceof UUID) return val; if (val instanceof byte[]) { ByteBuffer bb = ByteBuffer.wrap((byte[])val); long most = bb.getLong(); long least = bb.getLong(); return new UUID(most, least); } if (val instanceof String) return UUID.fromString((String)val); } return val; } /** * Construct load cache from range. * * @param em Type mapping description. * @param clo Closure that will be applied to loaded values. * @param lowerBound Lower bound for range. * @param upperBound Upper bound for range. * @return Callable for pool submit. */ private Callable<Void> loadCacheRange(final EntryMapping em, final IgniteBiInClosure<K, V> clo, @Nullable final Object[] lowerBound, @Nullable final Object[] upperBound) { return new Callable<Void>() { @Override public Void call() throws Exception { Connection conn = null; PreparedStatement stmt = null; try { conn = openConnection(true); stmt = conn.prepareStatement(lowerBound == null && upperBound == null ? em.loadCacheQry : em.loadCacheRangeQuery(lowerBound != null, upperBound != null)); int ix = 1; if (lowerBound != null) for (int i = lowerBound.length; i > 0; i--) for (int j = 0; j < i; j++) stmt.setObject(ix++, lowerBound[j]); if (upperBound != null) for (int i = upperBound.length; i > 0; i--) for (int j = 0; j < i; j++) stmt.setObject(ix++, upperBound[j]); ResultSet rs = stmt.executeQuery(); while (rs.next()) { K key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), em.loadColIdxs, rs); V val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs); clo.apply(key, val); } } catch (SQLException e) { throw new IgniteCheckedException("Failed to load cache", e); } finally { U.closeQuiet(stmt); U.closeQuiet(conn); } return null; } }; } /** * Construct load cache in one select. * * @param m Type mapping description. * @param clo Closure for loaded values. * @return Callable for pool submit. */ private Callable<Void> loadCacheFull(EntryMapping m, IgniteBiInClosure<K, V> clo) { return loadCacheRange(m, clo, null, null); } /** * Object is a simple type. * * @param cls Class. * @return {@code True} if object is a simple type. */ protected static boolean simpleType(Class<?> cls) { return (Number.class.isAssignableFrom(cls) || String.class.isAssignableFrom(cls) || java.util.Date.class.isAssignableFrom(cls) || Boolean.class.isAssignableFrom(cls) || UUID.class.isAssignableFrom(cls)); } /** * @param cacheName Cache name to check mapping for. * @param clsName Class name. * @param fields Fields descriptors. * @throws CacheException If failed to check type metadata. */ private static void checkMapping(@Nullable String cacheName, String clsName, Collection<CacheTypeFieldMetadata> fields) throws CacheException { try { Class<?> cls = Class.forName(clsName); if (simpleType(cls)) { if (fields.size() != 1) throw new CacheException("More than one field for simple type [cache name=" + cacheName + ", type=" + clsName + " ]"); CacheTypeFieldMetadata field = F.first(fields); if (field.getDatabaseName() == null) throw new CacheException("Missing database name in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); field.setJavaType(cls); } else for (CacheTypeFieldMetadata field : fields) { if (field.getDatabaseName() == null) throw new CacheException("Missing database name in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); if (field.getJavaName() == null) throw new CacheException("Missing field name in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); if (field.getJavaType() == null) throw new CacheException("Missing field type in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); } } catch (ClassNotFoundException e) { throw new CacheException("Failed to find class: " + clsName, e); } } /** * @param cacheName Cache name to check mappings for. * @return Type mappings for specified cache name. * @throws CacheException If failed to initialize cache mappings. */ private Map<Object, EntryMapping> cacheMappings(@Nullable String cacheName) throws CacheException { Map<Object, EntryMapping> entryMappings = cacheMappings.get(cacheName); if (entryMappings != null) return entryMappings; cacheMappingsLock.lock(); try { entryMappings = cacheMappings.get(cacheName); if (entryMappings != null) return entryMappings; CacheConfiguration ccfg = ignite().cache(cacheName).getConfiguration(CacheConfiguration.class); Collection<CacheTypeMetadata> types = ccfg.getTypeMetadata(); entryMappings = U.newHashMap(types.size()); for (CacheTypeMetadata type : types) { Object keyTypeId = keyTypeId(type.getKeyType()); if (entryMappings.containsKey(keyTypeId)) throw new CacheException("Key type must be unique in type metadata [cache name=" + cacheName + ", key type=" + type.getKeyType() + "]"); checkMapping(cacheName, type.getKeyType(), type.getKeyFields()); checkMapping(cacheName, type.getValueType(), type.getValueFields()); entryMappings.put(keyTypeId(type.getKeyType()), new EntryMapping(cacheName, dialect, type)); } Map<String, Map<Object, EntryMapping>> mappings = new HashMap<>(cacheMappings); mappings.put(cacheName, entryMappings); prepareBuilders(cacheName, types); cacheMappings = mappings; return entryMappings; } finally { cacheMappingsLock.unlock(); } } /** * @param cacheName Cache name. * @param keyTypeId Key type id. * @param key Key object. * @return Entry mapping. * @throws CacheException If mapping for key was not found. */ private EntryMapping entryMapping(String cacheName, Object keyTypeId, Object key) throws CacheException { EntryMapping em = cacheMappings(cacheName).get(keyTypeId); if (em == null) { String maskedCacheName = U.maskName(cacheName); throw new CacheException("Failed to find mapping description [key=" + key + ", cache=" + maskedCacheName + "]. Please configure CacheTypeMetadata to associate '" + maskedCacheName + "' with JdbcPojoStore."); } return em; } /** {@inheritDoc} */ @Override public void loadCache(final IgniteBiInClosure<K, V> clo, @Nullable Object... args) throws CacheLoaderException { ExecutorService pool = null; String cacheName = session().cacheName(); try { pool = Executors.newFixedThreadPool(maxPoolSz); Collection<Future<?>> futs = new ArrayList<>(); if (args != null && args.length > 0) { if (args.length % 2 != 0) throw new CacheLoaderException("Expected even number of arguments, but found: " + args.length); if (log.isDebugEnabled()) log.debug("Start loading entries from db using user queries from arguments"); for (int i = 0; i < args.length; i += 2) { String keyType = args[i].toString(); String selQry = args[i + 1].toString(); EntryMapping em = entryMapping(cacheName, keyTypeId(keyType), keyType); futs.add(pool.submit(new LoadCacheCustomQueryWorker<>(em, selQry, clo))); } } else { Collection<EntryMapping> entryMappings = cacheMappings(session().cacheName()).values(); for (EntryMapping em : entryMappings) { if (parallelLoadCacheMinThreshold > 0) { log.debug("Multithread loading entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + " ]"); Connection conn = null; try { conn = connection(); PreparedStatement stmt = conn.prepareStatement(em.loadCacheSelRangeQry); stmt.setInt(1, parallelLoadCacheMinThreshold); ResultSet rs = stmt.executeQuery(); if (rs.next()) { int keyCnt = em.keyCols.size(); Object[] upperBound = new Object[keyCnt]; for (int i = 0; i < keyCnt; i++) upperBound[i] = rs.getObject(i + 1); futs.add(pool.submit(loadCacheRange(em, clo, null, upperBound))); while (rs.next()) { Object[] lowerBound = upperBound; upperBound = new Object[keyCnt]; for (int i = 0; i < keyCnt; i++) upperBound[i] = rs.getObject(i + 1); futs.add(pool.submit(loadCacheRange(em, clo, lowerBound, upperBound))); } futs.add(pool.submit(loadCacheRange(em, clo, upperBound, null))); } else futs.add(pool.submit(loadCacheFull(em, clo))); } catch (SQLException ignored) { futs.add(pool.submit(loadCacheFull(em, clo))); } finally { U.closeQuiet(conn); } } else { if (log.isDebugEnabled()) log.debug("Single thread loading entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + " ]"); futs.add(pool.submit(loadCacheFull(em, clo))); } } } for (Future<?> fut : futs) U.get(fut); if (log.isDebugEnabled()) log.debug("Cache loaded from db: " + cacheName); } catch (IgniteCheckedException e) { throw new CacheLoaderException("Failed to load cache: " + cacheName, e.getCause()); } finally { U.shutdownNow(getClass(), pool, log); } } /** {@inheritDoc} */ @Nullable @Override public V load(K key) throws CacheLoaderException { assert key != null; EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key); if (log.isDebugEnabled()) log.debug("Load value from db [table= " + em.fullTableName() + ", key=" + key + "]"); Connection conn = null; PreparedStatement stmt = null; try { conn = connection(); stmt = conn.prepareStatement(em.loadQrySingle); fillKeyParameters(stmt, em, key); ResultSet rs = stmt.executeQuery(); if (rs.next()) return buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs); } catch (SQLException e) { throw new CacheLoaderException("Failed to load object [table=" + em.fullTableName() + ", key=" + key + "]", e); } finally { end(conn, stmt); } return null; } /** {@inheritDoc} */ @Override public Map<K, V> loadAll(Iterable<? extends K> keys) throws CacheLoaderException { assert keys != null; Connection conn = null; try { conn = connection(); String cacheName = session().cacheName(); Map<Object, LoadWorker<K, V>> workers = U.newHashMap(cacheMappings(cacheName).size()); Map<K, V> res = new HashMap<>(); for (K key : keys) { Object keyTypeId = keyTypeId(key); EntryMapping em = entryMapping(cacheName, keyTypeId, key); LoadWorker<K, V> worker = workers.get(keyTypeId); if (worker == null) workers.put(keyTypeId, worker = new LoadWorker<>(conn, em)); worker.keys.add(key); if (worker.keys.size() == em.maxKeysPerStmt) res.putAll(workers.remove(keyTypeId).call()); } for (LoadWorker<K, V> worker : workers.values()) res.putAll(worker.call()); return res; } catch (Exception e) { throw new CacheWriterException("Failed to load entries from database", e); } finally { closeConnection(conn); } } /** * @param insStmt Insert statement. * @param updStmt Update statement. * @param em Entry mapping. * @param entry Cache entry. * @throws CacheWriterException If failed to update record in database. */ private void writeUpsert(PreparedStatement insStmt, PreparedStatement updStmt, EntryMapping em, Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException { try { CacheWriterException we = null; for (int attempt = 0; attempt < MAX_ATTEMPT_WRITE_COUNT; attempt++) { int paramIdx = fillValueParameters(updStmt, 1, em, entry.getValue()); fillKeyParameters(updStmt, paramIdx, em, entry.getKey()); if (updStmt.executeUpdate() == 0) { paramIdx = fillKeyParameters(insStmt, em, entry.getKey()); fillValueParameters(insStmt, paramIdx, em, entry.getValue()); try { insStmt.executeUpdate(); if (attempt > 0) U.warn(log, "Entry was inserted in database on second try [table=" + em.fullTableName() + ", entry=" + entry + "]"); } catch (SQLException e) { String sqlState = e.getSQLState(); SQLException nested = e.getNextException(); while (sqlState == null && nested != null) { sqlState = nested.getSQLState(); nested = nested.getNextException(); } // The error with code 23505 or 23000 is thrown when trying to insert a row that // would violate a unique index or primary key. if ("23505".equals(sqlState) || "23000".equals(sqlState)) { if (we == null) we = new CacheWriterException("Failed insert entry in database, violate a unique" + " index or primary key [table=" + em.fullTableName() + ", entry=" + entry + "]"); we.addSuppressed(e); U.warn(log, "Failed insert entry in database, violate a unique index or primary key" + " [table=" + em.fullTableName() + ", entry=" + entry + "]"); continue; } throw new CacheWriterException("Failed insert entry in database [table=" + em.fullTableName() + ", entry=" + entry, e); } } if (attempt > 0) U.warn(log, "Entry was updated in database on second try [table=" + em.fullTableName() + ", entry=" + entry + "]"); return; } throw we; } catch (SQLException e) { throw new CacheWriterException("Failed update entry in database [table=" + em.fullTableName() + ", entry=" + entry + "]", e); } } /** {@inheritDoc} */ @Override public void write(Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException { assert entry != null; K key = entry.getKey(); EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key); if (log.isDebugEnabled()) log.debug("Start write entry to database [table=" + em.fullTableName() + ", entry=" + entry + "]"); Connection conn = null; try { conn = connection(); if (dialect.hasMerge()) { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(em.mergeQry); int i = fillKeyParameters(stmt, em, key); fillValueParameters(stmt, i, em, entry.getValue()); int updCnt = stmt.executeUpdate(); if (updCnt != 1) U.warn(log, "Unexpected number of updated entries [table=" + em.fullTableName() + ", entry=" + entry + "expected=1, actual=" + updCnt + "]"); } finally { U.closeQuiet(stmt); } } else { PreparedStatement insStmt = null; PreparedStatement updStmt = null; try { insStmt = conn.prepareStatement(em.insQry); updStmt = conn.prepareStatement(em.updQry); writeUpsert(insStmt, updStmt, em, entry); } finally { U.closeQuiet(insStmt); U.closeQuiet(updStmt); } } } catch (SQLException e) { throw new CacheWriterException("Failed to write entry to database [table=" + em.fullTableName() + ", entry=" + entry + "]", e); } finally { closeConnection(conn); } } /** {@inheritDoc} */ @Override public void writeAll(final Collection<Cache.Entry<? extends K, ? extends V>> entries) throws CacheWriterException { assert entries != null; Connection conn = null; try { conn = connection(); String cacheName = session().cacheName(); Object currKeyTypeId = null; if (dialect.hasMerge()) { PreparedStatement mergeStmt = null; try { EntryMapping em = null; LazyValue<Object[]> lazyEntries = new LazyValue<Object[]>() { @Override public Object[] create() { return entries.toArray(); } }; int fromIdx = 0, prepared = 0; for (Cache.Entry<? extends K, ? extends V> entry : entries) { K key = entry.getKey(); Object keyTypeId = keyTypeId(key); em = entryMapping(cacheName, keyTypeId, key); if (currKeyTypeId == null || !currKeyTypeId.equals(keyTypeId)) { if (mergeStmt != null) { if (log.isDebugEnabled()) log.debug("Write entries to db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries); U.closeQuiet(mergeStmt); } mergeStmt = conn.prepareStatement(em.mergeQry); currKeyTypeId = keyTypeId; fromIdx += prepared; prepared = 0; } int i = fillKeyParameters(mergeStmt, em, key); fillValueParameters(mergeStmt, i, em, entry.getValue()); mergeStmt.addBatch(); if (++prepared % batchSz == 0) { if (log.isDebugEnabled()) log.debug("Write entries to db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries); fromIdx += prepared; prepared = 0; } } if (mergeStmt != null && prepared % batchSz != 0) { if (log.isDebugEnabled()) log.debug("Write entries to db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries); } } finally { U.closeQuiet(mergeStmt); } } else { log.debug("Write entries to db one by one using update and insert statements [cache name=" + cacheName + ", count=" + entries.size() + "]"); PreparedStatement insStmt = null; PreparedStatement updStmt = null; try { for (Cache.Entry<? extends K, ? extends V> entry : entries) { K key = entry.getKey(); Object keyTypeId = keyTypeId(key); EntryMapping em = entryMapping(cacheName, keyTypeId, key); if (currKeyTypeId == null || !currKeyTypeId.equals(keyTypeId)) { U.closeQuiet(insStmt); insStmt = conn.prepareStatement(em.insQry); U.closeQuiet(updStmt); updStmt = conn.prepareStatement(em.updQry); currKeyTypeId = keyTypeId; } writeUpsert(insStmt, updStmt, em, entry); } } finally { U.closeQuiet(insStmt); U.closeQuiet(updStmt); } } } catch (SQLException e) { throw new CacheWriterException("Failed to write entries in database", e); } finally { closeConnection(conn); } } /** {@inheritDoc} */ @Override public void delete(Object key) throws CacheWriterException { assert key != null; EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key); if (log.isDebugEnabled()) log.debug("Remove value from db [table=" + em.fullTableName() + ", key=" + key + "]"); Connection conn = null; PreparedStatement stmt = null; try { conn = connection(); stmt = conn.prepareStatement(em.remQry); fillKeyParameters(stmt, em, key); int delCnt = stmt.executeUpdate(); if (delCnt != 1) U.warn(log, "Unexpected number of deleted entries [table=" + em.fullTableName() + ", key=" + key + ", expected=1, actual=" + delCnt + "]"); } catch (SQLException e) { throw new CacheWriterException("Failed to remove value from database [table=" + em.fullTableName() + ", key=" + key + "]", e); } finally { end(conn, stmt); } } /** * @param em Entry mapping. * @param stmt Statement. * @param desc Statement description for error message. * @param fromIdx Objects in batch start from index. * @param prepared Expected objects in batch. * @param lazyObjs All objects used in batch statement as array. * @throws SQLException If failed to execute batch statement. */ private void executeBatch(EntryMapping em, Statement stmt, String desc, int fromIdx, int prepared, LazyValue<Object[]> lazyObjs) throws SQLException { try { int[] rowCounts = stmt.executeBatch(); int numOfRowCnt = rowCounts.length; if (numOfRowCnt != prepared) U.warn(log, "Unexpected number of updated rows [table=" + em.fullTableName() + ", expected=" + prepared + ", actual=" + numOfRowCnt + "]"); for (int i = 0; i < numOfRowCnt; i++) { int cnt = rowCounts[i]; if (cnt != 1 && cnt != SUCCESS_NO_INFO) { Object[] objs = lazyObjs.value(); U.warn(log, "Batch " + desc + " returned unexpected updated row count [table=" + em.fullTableName() + ", entry=" + objs[fromIdx + i] + ", expected=1, actual=" + cnt + "]"); } } } catch (BatchUpdateException be) { int[] rowCounts = be.getUpdateCounts(); for (int i = 0; i < rowCounts.length; i++) { if (rowCounts[i] == EXECUTE_FAILED) { Object[] objs = lazyObjs.value(); U.warn(log, "Batch " + desc + " failed on execution [table=" + em.fullTableName() + ", entry=" + objs[fromIdx + i] + "]"); } } throw be; } } /** {@inheritDoc} */ @Override public void deleteAll(final Collection<?> keys) throws CacheWriterException { assert keys != null; Connection conn = null; try { conn = connection(); LazyValue<Object[]> lazyKeys = new LazyValue<Object[]>() { @Override public Object[] create() { return keys.toArray(); } }; String cacheName = session().cacheName(); Object currKeyTypeId = null; EntryMapping em = null; PreparedStatement delStmt = null; int fromIdx = 0, prepared = 0; for (Object key : keys) { Object keyTypeId = keyTypeId(key); em = entryMapping(cacheName, keyTypeId, key); if (delStmt == null) { delStmt = conn.prepareStatement(em.remQry); currKeyTypeId = keyTypeId; } if (!currKeyTypeId.equals(keyTypeId)) { if (log.isDebugEnabled()) log.debug("Delete entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys); fromIdx += prepared; prepared = 0; currKeyTypeId = keyTypeId; } fillKeyParameters(delStmt, em, key); delStmt.addBatch(); if (++prepared % batchSz == 0) { if (log.isDebugEnabled()) log.debug("Delete entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys); fromIdx += prepared; prepared = 0; } } if (delStmt != null && prepared % batchSz != 0) { if (log.isDebugEnabled()) log.debug("Delete entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys); } } catch (SQLException e) { throw new CacheWriterException("Failed to remove values from database", e); } finally { closeConnection(conn); } } /** * Sets the value of the designated parameter using the given object. * * @param stmt Prepare statement. * @param i Index for parameters. * @param field Field descriptor. * @param fieldVal Field value. * @throws CacheException If failed to set statement parameter. */ protected void fillParameter(PreparedStatement stmt, int i, CacheTypeFieldMetadata field, @Nullable Object fieldVal) throws CacheException { try { if (fieldVal != null) { if (field.getJavaType() == UUID.class) { switch (field.getDatabaseType()) { case Types.BINARY: fieldVal = U.uuidToBytes((UUID)fieldVal); break; case Types.CHAR: case Types.VARCHAR: fieldVal = fieldVal.toString(); break; } } stmt.setObject(i, fieldVal); } else stmt.setNull(i, field.getDatabaseType()); } catch (SQLException e) { throw new CacheException("Failed to set statement parameter name: " + field.getDatabaseName(), e); } } /** * @param stmt Prepare statement. * @param idx Start index for parameters. * @param em Entry mapping. * @param key Key object. * @return Next index for parameters. * @throws CacheException If failed to set statement parameters. */ protected int fillKeyParameters(PreparedStatement stmt, int idx, EntryMapping em, Object key) throws CacheException { for (CacheTypeFieldMetadata field : em.keyColumns()) { Object fieldVal = extractParameter(em.cacheName, em.keyType(), field.getJavaName(), key); fillParameter(stmt, idx++, field, fieldVal); } return idx; } /** * @param stmt Prepare statement. * @param m Type mapping description. * @param key Key object. * @return Next index for parameters. * @throws CacheException If failed to set statement parameters. */ protected int fillKeyParameters(PreparedStatement stmt, EntryMapping m, Object key) throws CacheException { return fillKeyParameters(stmt, 1, m, key); } /** * @param stmt Prepare statement. * @param idx Start index for parameters. * @param em Type mapping description. * @param val Value object. * @return Next index for parameters. * @throws CacheException If failed to set statement parameters. */ protected int fillValueParameters(PreparedStatement stmt, int idx, EntryMapping em, Object val) throws CacheWriterException { for (CacheTypeFieldMetadata field : em.uniqValFields) { Object fieldVal = extractParameter(em.cacheName, em.valueType(), field.getJavaName(), val); fillParameter(stmt, idx++, field, fieldVal); } return idx; } /** * @return Data source. */ public DataSource getDataSource() { return dataSrc; } /** * @param dataSrc Data source. */ public void setDataSource(DataSource dataSrc) { this.dataSrc = dataSrc; } /** * Get database dialect. * * @return Database dialect. */ public JdbcDialect getDialect() { return dialect; } /** * Set database dialect. * * @param dialect Database dialect. */ public void setDialect(JdbcDialect dialect) { this.dialect = dialect; } /** * Get Max workers thread count. These threads are responsible for execute query. * * @return Max workers thread count. */ public int getMaximumPoolSize() { return maxPoolSz; } /** * Set Max workers thread count. These threads are responsible for execute query. * * @param maxPoolSz Max workers thread count. */ public void setMaximumPoolSize(int maxPoolSz) { this.maxPoolSz = maxPoolSz; } /** * Get maximum batch size for delete and delete operations. * * @return Maximum batch size. */ public int getBatchSize() { return batchSz; } /** * Set maximum batch size for write and delete operations. * * @param batchSz Maximum batch size. */ public void setBatchSize(int batchSz) { this.batchSz = batchSz; } /** * Parallel load cache minimum row count threshold. * * @return If {@code 0} then load sequentially. */ public int getParallelLoadCacheMinimumThreshold() { return parallelLoadCacheMinThreshold; } /** * Parallel load cache minimum row count threshold. * * @param parallelLoadCacheMinThreshold Minimum row count threshold. If {@code 0} then load sequentially. */ public void setParallelLoadCacheMinimumThreshold(int parallelLoadCacheMinThreshold) { this.parallelLoadCacheMinThreshold = parallelLoadCacheMinThreshold; } /** * @return Ignite instance. */ protected Ignite ignite() { return ignite; } /** * @return Store session. */ protected CacheStoreSession session() { return ses; } /** * Entry mapping description. */ protected static class EntryMapping { /** Cache name. */ private final String cacheName; /** Database dialect. */ private final JdbcDialect dialect; /** Select border for range queries. */ private final String loadCacheSelRangeQry; /** Select all items query. */ private final String loadCacheQry; /** Select item query. */ private final String loadQrySingle; /** Select items query. */ private final String loadQry; /** Merge item(s) query. */ private final String mergeQry; /** Update item query. */ private final String insQry; /** Update item query. */ private final String updQry; /** Remove item(s) query. */ private final String remQry; /** Max key count for load query per statement. */ private final int maxKeysPerStmt; /** Database key columns. */ private final Collection<String> keyCols; /** Database unique value columns. */ private final Collection<String> cols; /** Select query columns index. */ private final Map<String, Integer> loadColIdxs; /** Unique value fields. */ private final Collection<CacheTypeFieldMetadata> uniqValFields; /** Type metadata. */ private final CacheTypeMetadata typeMeta; /** Full table name. */ private final String fullTblName; /** * @param cacheName Cache name. * @param dialect JDBC dialect. * @param typeMeta Type metadata. */ public EntryMapping(@Nullable String cacheName, JdbcDialect dialect, CacheTypeMetadata typeMeta) { this.cacheName = cacheName; this.dialect = dialect; this.typeMeta = typeMeta; Collection<CacheTypeFieldMetadata> keyFields = typeMeta.getKeyFields(); Collection<CacheTypeFieldMetadata> valFields = typeMeta.getValueFields(); keyCols = databaseColumns(keyFields); uniqValFields = F.view(valFields, new IgnitePredicate<CacheTypeFieldMetadata>() { @Override public boolean apply(CacheTypeFieldMetadata col) { return !keyCols.contains(col.getDatabaseName()); } }); String schema = typeMeta.getDatabaseSchema(); String tblName = typeMeta.getDatabaseTable(); fullTblName = F.isEmpty(schema) ? tblName : schema + "." + tblName; Collection<String> uniqValCols = databaseColumns(uniqValFields); cols = F.concat(false, keyCols, uniqValCols); loadColIdxs = U.newHashMap(cols.size()); int idx = 1; for (String col : cols) loadColIdxs.put(col, idx++); loadCacheQry = dialect.loadCacheQuery(fullTblName, cols); loadCacheSelRangeQry = dialect.loadCacheSelectRangeQuery(fullTblName, keyCols); loadQrySingle = dialect.loadQuery(fullTblName, keyCols, cols, 1); maxKeysPerStmt = dialect.getMaxParameterCount() / keyCols.size(); loadQry = dialect.loadQuery(fullTblName, keyCols, cols, maxKeysPerStmt); insQry = dialect.insertQuery(fullTblName, keyCols, uniqValCols); updQry = dialect.updateQuery(fullTblName, keyCols, uniqValCols); mergeQry = dialect.mergeQuery(fullTblName, keyCols, uniqValCols); remQry = dialect.removeQuery(fullTblName, keyCols); } /** * Extract database column names from {@link CacheTypeFieldMetadata}. * * @param dsc collection of {@link CacheTypeFieldMetadata}. * @return Collection with database column names. */ private static Collection<String> databaseColumns(Collection<CacheTypeFieldMetadata> dsc) { return F.transform(dsc, new C1<CacheTypeFieldMetadata, String>() { /** {@inheritDoc} */ @Override public String apply(CacheTypeFieldMetadata col) { return col.getDatabaseName(); } }); } /** * Construct query for select values with key count less or equal {@code maxKeysPerStmt} * * @param keyCnt Key count. * @return Load query statement text. */ protected String loadQuery(int keyCnt) { assert keyCnt <= maxKeysPerStmt; if (keyCnt == maxKeysPerStmt) return loadQry; if (keyCnt == 1) return loadQrySingle; return dialect.loadQuery(fullTblName, keyCols, cols, keyCnt); } /** * Construct query for select values in range. * * @param appendLowerBound Need add lower bound for range. * @param appendUpperBound Need add upper bound for range. * @return Query with range. */ protected String loadCacheRangeQuery(boolean appendLowerBound, boolean appendUpperBound) { return dialect.loadCacheRangeQuery(fullTblName, keyCols, cols, appendLowerBound, appendUpperBound); } /** * @return Key type. */ protected String keyType() { return typeMeta.getKeyType(); } /** * @return Value type. */ protected String valueType() { return typeMeta.getValueType(); } /** * Gets key columns. * * @return Key columns. */ protected Collection<CacheTypeFieldMetadata> keyColumns() { return typeMeta.getKeyFields(); } /** * Gets value columns. * * @return Value columns. */ protected Collection<CacheTypeFieldMetadata> valueColumns() { return typeMeta.getValueFields(); } /** * Get full table name. * * @return &lt;schema&gt;.&lt;table name&gt */ protected String fullTableName() { return fullTblName; } } /** * Worker for load cache using custom user query. * * @param <K1> Key type. * @param <V1> Value type. */ private class LoadCacheCustomQueryWorker<K1, V1> implements Callable<Void> { /** Entry mapping description. */ private final EntryMapping em; /** User query. */ private final String qry; /** Closure for loaded values. */ private final IgniteBiInClosure<K1, V1> clo; /** * @param em Entry mapping description. * @param qry User query. * @param clo Closure for loaded values. */ private LoadCacheCustomQueryWorker(EntryMapping em, String qry, IgniteBiInClosure<K1, V1> clo) { this.em = em; this.qry = qry; this.clo = clo; } /** {@inheritDoc} */ @Override public Void call() throws Exception { if (log.isDebugEnabled()) log.debug("Load cache using custom query [cache name= " + em.cacheName + ", key type=" + em.keyType() + ", query=" + qry + "]"); Connection conn = null; PreparedStatement stmt = null; try { conn = openConnection(true); stmt = conn.prepareStatement(qry); ResultSet rs = stmt.executeQuery(); ResultSetMetaData meta = rs.getMetaData(); Map<String, Integer> colIdxs = U.newHashMap(meta.getColumnCount()); for (int i = 1; i <= meta.getColumnCount(); i++) colIdxs.put(meta.getColumnLabel(i), i); while (rs.next()) { K1 key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), colIdxs, rs); V1 val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), colIdxs, rs); clo.apply(key, val); } return null; } catch (SQLException e) { throw new CacheLoaderException("Failed to execute custom query for load cache", e); } finally { U.closeQuiet(stmt); U.closeQuiet(conn); } } } /** * Lazy initialization of value. * * @param <T> Cached object type */ private abstract static class LazyValue<T> { /** Cached value. */ private T val; /** * @return Construct value. */ protected abstract T create(); /** * @return Value. */ public T value() { if (val == null) val = create(); return val; } } /** * Worker for load by keys. * * @param <K1> Key type. * @param <V1> Value type. */ private class LoadWorker<K1, V1> implements Callable<Map<K1, V1>> { /** Connection. */ private final Connection conn; /** Keys for load. */ private final Collection<K1> keys; /** Entry mapping description. */ private final EntryMapping em; /** * @param conn Connection. * @param em Entry mapping description. */ private LoadWorker(Connection conn, EntryMapping em) { this.conn = conn; this.em = em; keys = new ArrayList<>(em.maxKeysPerStmt); } /** {@inheritDoc} */ @Override public Map<K1, V1> call() throws Exception { if (log.isDebugEnabled()) log.debug("Load values from db [table= " + em.fullTableName() + ", key count=" + keys.size() + "]"); PreparedStatement stmt = null; try { stmt = conn.prepareStatement(em.loadQuery(keys.size())); int idx = 1; for (Object key : keys) for (CacheTypeFieldMetadata field : em.keyColumns()) { Object fieldVal = extractParameter(em.cacheName, em.keyType(), field.getJavaName(), key); fillParameter(stmt, idx++, field, fieldVal); } ResultSet rs = stmt.executeQuery(); Map<K1, V1> entries = U.newHashMap(keys.size()); while (rs.next()) { K1 key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), em.loadColIdxs, rs); V1 val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs); entries.put(key, val); } return entries; } finally { U.closeQuiet(stmt); } } } }
vsisko/incubator-ignite
modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheAbstractJdbcStore.java
Java
apache-2.0
62,015
package de.jungblut.math.squashing; import de.jungblut.math.DoubleMatrix; import de.jungblut.math.MathUtils; /** * Logistic error function implementation. * * @author thomas.jungblut * */ public final class LogisticErrorFunction implements ErrorFunction { @Override public double calculateError(DoubleMatrix y, DoubleMatrix hypothesis) { return (y.multiply(-1d) .multiplyElementWise(MathUtils.logMatrix(hypothesis)).subtract((y .subtractBy(1.0d)).multiplyElementWise(MathUtils.logMatrix(hypothesis .subtractBy(1d))))).sum(); } }
sourcewarehouse/thomasjungblut
src/de/jungblut/math/squashing/LogisticErrorFunction.java
Java
apache-2.0
574
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.geolocation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollFunction; import org.appcelerator.kroll.KrollModule; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollRuntime; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiBaseActivity; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.analytics.TiAnalyticsEventFactory; import org.appcelerator.titanium.util.TiConvert; import ti.modules.titanium.geolocation.TiLocation.GeocodeResponseHandler; import ti.modules.titanium.geolocation.android.AndroidModule; import ti.modules.titanium.geolocation.android.LocationProviderProxy; import ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener; import ti.modules.titanium.geolocation.android.LocationRuleProxy; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Build; import android.os.Handler; import android.os.Message; /** * GeolocationModule exposes all common methods and properties relating to geolocation behavior * associated with Ti.Geolocation to the Titanium developer. Only cross platform API points should * be exposed through this class as Android-only API points or types should be put in a Android module * under this module. * * The GeolocationModule provides management for 3 different location behavior modes (detailed * descriptions will follow below): * <ul> * <li>legacy - existing behavior found in Titanium Mobile 1.7 and 1.8. <b>DEPRECATED</b></li> * <li>simple - replacement for the old legacy mode that allows for better parity across platforms</li> * <li>manual - Android-specific mode that exposes full control over the providers and rules</li> * </ul> * * <p> * <b>Legacy location mode</b>:<br> * This mode operates on receiving location updates from a single active provider at a time. Settings * used to pick and register a provider with the OS are pulled from the PROPERTY_ACCURACY, PROPERTY_FREQUENCY * and PROPERTY_PREFERRED_PROVIDER properties on the module. * <p> * The valid accuracy properties for this location mode are ACCURACY_BEST, ACCURACY_NEAREST_TEN_METERS, * ACCURACY_HUNDRED_METERS, ACCURACY_KILOMETER and ACCURACY_THREE_KILOMETERS. The accuracy property is a * double value that will be used by the OS as a way to determine how many meters should change in location * before a new update is sent. Accuracy properties other than this will either be ignored or change the * current location behavior mode. The frequency property is a double value that is used by the OS to determine * how much time in milliseconds should pass before a new update is sent. * <p> * The OS uses some fuzzy logic to determine the update frequency and these values are treated as no more than * suggestions. For example: setting the frequency to 0 milliseconds and the accuracy to 10 meters may not * result in a update being sent as fast as possible which is what frequency of 0 ms indicates. This is due to * the OS not sending updates till the accuracy property is satisfied. If the desired behavior is to get updates * purely based on time then the suggested mechanism would be to set the accuracy to 0 meters and then set the * frequency to the desired update interval in milliseconds. * * <p> * <b>Simple location mode</b>:<br> * This mode operates on receiving location updates from multiple sources. The simple mode has two states - high * accuracy and low accuracy. The difference in these two modes is that low accuracy has the passive and network * providers registered by default where the high accuracy state enables the gps provider in addition to the passive * and network providers. The simple mode utilizes location rules for filtering location updates to try and fall back * gracefully (when in high accuracy state) to the network and passive providers if a gps update has not been received * recently. * <p> * No specific controls for time or distance (better terminology in line with native Android docs but these * are called frequency and accuracy in legacy mode) are exposed to the Titanium developer as the details of this mode * are supposed to be driven by Appcelerator based on our observations. If greater control on the part of the Titanium * developer is needed then the manual behavior mode can and should be used. * * <p> * <b>Manual location mode</b>:<br> * This mode puts full control over providers and rules in the hands of the Titanium developer. The developer will be * responsible for registering location providers, setting time and distance settings per provider and defining the rule * set if any rules are desired. * <p> * In this mode, the developer would create a Ti.Geolocation.Android.LocationProvider object for each provider they want * to use and add this to the list of manual providers via addLocationProvider(LocationProviderProxy). In order to set * rules, the developer will have to create a Ti.Geolocation.Android.LocationRule object per rule and then add those * rules via addLocationRule(LocationRuleProxy). These rules will be applied to any location updates that come from the * registered providers. Further information on the LocationProvider and LocationRule objects can be found by looking at * those specific classes. * * <p> * <b>General location behavior</b>:<br> * The GeolocationModule is capable of switching modes at any time and keeping settings per mode separated. Changing modes * is done by updating the Ti.Geolocation.accuracy property. Based on the new value of the accuracy property, the * legacy or simple modes may be enabled (and the previous mode may be turned off). Enabling or disabling the manual mode * is done by setting the AndroidModule.manualMode (Ti.Geolocation.Android.manualMode) value. NOTE: updating the location * rules will not update the mode. Simply setting the Ti.Geolocation.accuracy property will not enable the legacy/simple * modes if you are currently in the manual mode - you must disable the manual mode before the simple/legacy modes are used * <p> * In regards to actually "turning on" the providers by registering them with the OS - this is triggered by the presence of * "location" event listeners on the GeolocationModule. When the first listener is added, providers start being registered * with the OS. When there are no listeners then all the providers are de-registered. Changes made to location providers or * accuracy, frequency properties or even changing modes are respected and kept but don't actually get applied on the OS until * the listener count is greater than 0. */ // TODO deprecate the frequency and preferredProvider property @Kroll.module(propertyAccessors={ TiC.PROPERTY_ACCURACY, TiC.PROPERTY_FREQUENCY, TiC.PROPERTY_PREFERRED_PROVIDER }) public class GeolocationModule extends KrollModule implements Handler.Callback, LocationProviderListener { // TODO move these to the AndroidModule namespace since they will only be used when creating // manual location providers @Kroll.constant @Deprecated public static final String PROVIDER_PASSIVE = LocationManager.PASSIVE_PROVIDER; @Kroll.constant @Deprecated public static final String PROVIDER_NETWORK = LocationManager.NETWORK_PROVIDER; @Kroll.constant @Deprecated public static final String PROVIDER_GPS = LocationManager.GPS_PROVIDER; @Kroll.constant public static final int ACCURACY_LOW = 0; @Kroll.constant public static final int ACCURACY_HIGH = 1; @Kroll.constant @Deprecated public static final int ACCURACY_BEST = 2; @Kroll.constant @Deprecated public static final int ACCURACY_NEAREST_TEN_METERS = 3; @Kroll.constant @Deprecated public static final int ACCURACY_HUNDRED_METERS = 4; @Kroll.constant @Deprecated public static final int ACCURACY_KILOMETER = 5; @Kroll.constant @Deprecated public static final int ACCURACY_THREE_KILOMETERS = 6; public TiLocation tiLocation; public AndroidModule androidModule; public int numLocationListeners = 0; public HashMap<String, LocationProviderProxy> simpleLocationProviders = new HashMap<String, LocationProviderProxy>(); @Deprecated public HashMap<String, LocationProviderProxy> legacyLocationProviders = new HashMap<String, LocationProviderProxy>(); public boolean legacyModeActive = true; protected static final int MSG_ENABLE_LOCATION_PROVIDERS = KrollModule.MSG_LAST_ID + 100; protected static final int MSG_LAST_ID = MSG_ENABLE_LOCATION_PROVIDERS; private static final String TAG = "GeolocationModule"; private static final double SIMPLE_LOCATION_PASSIVE_DISTANCE = 0.0; private static final double SIMPLE_LOCATION_PASSIVE_TIME = 0; private static final double SIMPLE_LOCATION_NETWORK_DISTANCE = 10.0; private static final double SIMPLE_LOCATION_NETWORK_TIME = 10000; private static final double SIMPLE_LOCATION_GPS_DISTANCE = 3.0; private static final double SIMPLE_LOCATION_GPS_TIME = 3000; private static final double SIMPLE_LOCATION_NETWORK_DISTANCE_RULE = 200; private static final double SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE = 60000; private static final double SIMPLE_LOCATION_GPS_MIN_AGE_RULE = 30000; private TiCompass tiCompass; private boolean compassListenersRegistered = false; private boolean sentAnalytics = false; private ArrayList<LocationRuleProxy> simpleLocationRules = new ArrayList<LocationRuleProxy>(); private LocationRuleProxy simpleLocationGpsRule; private LocationRuleProxy simpleLocationNetworkRule; private int simpleLocationAccuracyProperty = ACCURACY_LOW; private Location currentLocation; //currentLocation is conditionally updated. lastLocation is unconditionally updated //since currentLocation determines when to send out updates, and lastLocation is passive private Location lastLocation; @Deprecated private HashMap<Integer, Double> legacyLocationAccuracyMap = new HashMap<Integer, Double>(); @Deprecated private int legacyLocationAccuracyProperty = ACCURACY_NEAREST_TEN_METERS; @Deprecated private double legacyLocationFrequency = 5000; @Deprecated private String legacyLocationPreferredProvider = PROVIDER_NETWORK; /** * Constructor */ public GeolocationModule() { super("geolocation"); tiLocation = new TiLocation(); tiCompass = new TiCompass(this, tiLocation); // initialize the legacy location accuracy map legacyLocationAccuracyMap.put(ACCURACY_BEST, 0.0); // this needs to be 0.0 to work for only time based updates legacyLocationAccuracyMap.put(ACCURACY_NEAREST_TEN_METERS, 10.0); legacyLocationAccuracyMap.put(ACCURACY_HUNDRED_METERS, 100.0); legacyLocationAccuracyMap.put(ACCURACY_KILOMETER, 1000.0); legacyLocationAccuracyMap.put(ACCURACY_THREE_KILOMETERS, 3000.0); legacyLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, 10.0f, legacyLocationFrequency, this)); simpleLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE, SIMPLE_LOCATION_NETWORK_TIME, this)); simpleLocationProviders.put(PROVIDER_PASSIVE, new LocationProviderProxy(PROVIDER_PASSIVE, SIMPLE_LOCATION_PASSIVE_DISTANCE, SIMPLE_LOCATION_PASSIVE_TIME, this)); // create these now but we don't want to include these in the rule set unless the simple GPS provider is enabled simpleLocationGpsRule = new LocationRuleProxy(PROVIDER_GPS, null, SIMPLE_LOCATION_GPS_MIN_AGE_RULE, null); simpleLocationNetworkRule = new LocationRuleProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE_RULE, SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE, null); } /** * @see org.appcelerator.kroll.KrollProxy#handleMessage(android.os.Message) */ @Override public boolean handleMessage(Message message) { switch (message.what) { case MSG_ENABLE_LOCATION_PROVIDERS: { Object locationProviders = message.obj; doEnableLocationProviders((HashMap<String, LocationProviderProxy>) locationProviders); return true; } } return super.handleMessage(message); } private void doAnalytics(Location location) { if (!sentAnalytics) { tiLocation.doAnalytics(location); sentAnalytics = true; } } /** * Called by a registered location provider when a location update is received * * @param location location update that was received * * @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onLocationChanged(android.location.Location) */ public void onLocationChanged(Location location) { lastLocation = location; if (shouldUseUpdate(location)) { fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(location, tiLocation.locationManager.getProvider(location.getProvider()))); currentLocation = location; doAnalytics(location); } } /** * Called by a registered location provider when its state changes * * @param providerName name of the provider whose state has changed * @param state new state of the provider * * @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderStateChanged(java.lang.String, int) */ public void onProviderStateChanged(String providerName, int state) { String message = providerName; // TODO this is trash. deprecate the existing mechanism of bundling status updates with the // location event and create a new "locationState" (or whatever) event. for the time being, // this solution kills my soul slightly less than the previous one switch (state) { case LocationProviderProxy.STATE_DISABLED: message += " is disabled"; Log.i(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; case LocationProviderProxy.STATE_ENABLED: message += " is enabled"; Log.d(TAG, message, Log.DEBUG_MODE); break; case LocationProviderProxy.STATE_OUT_OF_SERVICE: message += " is out of service"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; case LocationProviderProxy.STATE_UNAVAILABLE: message += " is unavailable"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; case LocationProviderProxy.STATE_AVAILABLE: message += " is available"; Log.d(TAG, message, Log.DEBUG_MODE); break; case LocationProviderProxy.STATE_UNKNOWN: message += " is in a unknown state [" + state + "]"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; default: message += " is in a unknown state [" + state + "]"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; } } /** * Called when the location provider has had one of it's properties updated and thus needs to be re-registered with the OS * * @param locationProvider the location provider that needs to be re-registered * * @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderUpdated(ti.modules.titanium.geolocation.android.LocationProviderProxy) */ public void onProviderUpdated(LocationProviderProxy locationProvider) { if (getManualMode() && (numLocationListeners > 0)) { tiLocation.locationManager.removeUpdates(locationProvider); registerLocationProvider(locationProvider); } } /** * @see org.appcelerator.kroll.KrollModule#propertyChanged(java.lang.String, java.lang.Object, java.lang.Object, org.appcelerator.kroll.KrollProxy) */ @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_ACCURACY)) { // accuracy property is what triggers a shift between simple and legacy modes. the // android only manual mode is indicated by the AndroidModule.manualMode value which // has no impact on the legacyModeActive flag. IE: when determining the current mode, // both flags must be checked propertyChangedAccuracy(newValue); } else if (key.equals(TiC.PROPERTY_FREQUENCY)) { propertyChangedFrequency(newValue); } else if (key.equals(TiC.PROPERTY_PREFERRED_PROVIDER)) { propertyChangedPreferredProvider(newValue); } } /** * Handles property change for Ti.Geolocation.accuracy * * @param newValue new accuracy value */ private void propertyChangedAccuracy(Object newValue) { // is legacy mode enabled (registered with OS, not just selected via the accuracy property) boolean legacyModeEnabled = false; if (legacyModeActive && (!getManualMode()) && (numLocationListeners > 0)) { legacyModeEnabled = true; } // is simple mode enabled (registered with OS, not just selected via the accuracy property) boolean simpleModeEnabled = false; if (!legacyModeActive && !(getManualMode()) && (numLocationListeners > 0)) { simpleModeEnabled = true; } int accuracyProperty = TiConvert.toInt(newValue); // is this a legacy accuracy property? Double accuracyLookupResult = legacyLocationAccuracyMap.get(accuracyProperty); if (accuracyLookupResult != null) { // has the value changed from the last known good value? if (accuracyProperty != legacyLocationAccuracyProperty) { legacyLocationAccuracyProperty = accuracyProperty; for (String providerKey : legacyLocationProviders.keySet()) { LocationProviderProxy locationProvider = legacyLocationProviders.get(providerKey); locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_DISTANCE, accuracyLookupResult); } if (legacyModeEnabled) { enableLocationProviders(legacyLocationProviders); } } if (simpleModeEnabled) { enableLocationProviders(legacyLocationProviders); } legacyModeActive = true; // is this a simple accuracy property? } else if ((accuracyProperty == ACCURACY_HIGH) || (accuracyProperty == ACCURACY_LOW)) { // has the value changed from the last known good value? if (accuracyProperty != simpleLocationAccuracyProperty) { simpleLocationAccuracyProperty = accuracyProperty; LocationProviderProxy gpsProvider = simpleLocationProviders.get(PROVIDER_GPS); if ((accuracyProperty == ACCURACY_HIGH) && (gpsProvider == null)) { gpsProvider = new LocationProviderProxy(PROVIDER_GPS, SIMPLE_LOCATION_GPS_DISTANCE, SIMPLE_LOCATION_GPS_TIME, this); simpleLocationProviders.put(PROVIDER_GPS, gpsProvider); simpleLocationRules.add(simpleLocationNetworkRule); simpleLocationRules.add(simpleLocationGpsRule); if (simpleModeEnabled) { registerLocationProvider(gpsProvider); } } else if ((accuracyProperty == ACCURACY_LOW) && (gpsProvider != null)) { simpleLocationProviders.remove(PROVIDER_GPS); simpleLocationRules.remove(simpleLocationNetworkRule); simpleLocationRules.remove(simpleLocationGpsRule); if (simpleModeEnabled) { tiLocation.locationManager.removeUpdates(gpsProvider); } } } if (legacyModeEnabled) { enableLocationProviders(simpleLocationProviders); } legacyModeActive = false; } } /** * Handles property change for Ti.Geolocation.frequency * * @param newValue new frequency value */ private void propertyChangedFrequency(Object newValue) { // is legacy mode enabled (registered with OS, not just selected via the accuracy property) boolean legacyModeEnabled = false; if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) { legacyModeEnabled = true; } double frequencyProperty = TiConvert.toDouble(newValue) * 1000; if (frequencyProperty != legacyLocationFrequency) { legacyLocationFrequency = frequencyProperty; Iterator<String> iterator = legacyLocationProviders.keySet().iterator(); while(iterator.hasNext()) { LocationProviderProxy locationProvider = legacyLocationProviders.get(iterator.next()); locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_TIME, legacyLocationFrequency); } if (legacyModeEnabled) { enableLocationProviders(legacyLocationProviders); } } } /** * Handles property change for Ti.Geolocation.preferredProvider * * @param newValue new preferredProvider value */ private void propertyChangedPreferredProvider(Object newValue) { // is legacy mode enabled (registered with OS, not just selected via the accuracy property) boolean legacyModeEnabled = false; if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) { legacyModeEnabled = true; } String preferredProviderProperty = TiConvert.toString(newValue); if (!(preferredProviderProperty.equals(PROVIDER_NETWORK)) && (!(preferredProviderProperty.equals(PROVIDER_GPS)))) { return; } if (!(preferredProviderProperty.equals(legacyLocationPreferredProvider))) { LocationProviderProxy oldProvider = legacyLocationProviders.get(legacyLocationPreferredProvider); LocationProviderProxy newProvider = legacyLocationProviders.get(preferredProviderProperty); if (oldProvider != null) { legacyLocationProviders.remove(legacyLocationPreferredProvider); if (legacyModeEnabled) { tiLocation.locationManager.removeUpdates(oldProvider); } } if (newProvider == null) { newProvider = new LocationProviderProxy(preferredProviderProperty, legacyLocationAccuracyMap.get(legacyLocationAccuracyProperty), legacyLocationFrequency, this); legacyLocationProviders.put(preferredProviderProperty, newProvider); if (legacyModeEnabled) { registerLocationProvider(newProvider); } } legacyLocationPreferredProvider = preferredProviderProperty; } } /** * @see org.appcelerator.kroll.KrollProxy#eventListenerAdded(java.lang.String, int, org.appcelerator.kroll.KrollProxy) */ @Override protected void eventListenerAdded(String event, int count, KrollProxy proxy) { if (TiC.EVENT_HEADING.equals(event)) { if (!compassListenersRegistered) { tiCompass.registerListener(); compassListenersRegistered = true; } } else if (TiC.EVENT_LOCATION.equals(event)) { numLocationListeners++; if (numLocationListeners == 1) { HashMap<String, LocationProviderProxy> locationProviders = legacyLocationProviders; if (getManualMode()) { locationProviders = androidModule.manualLocationProviders; } else if (!legacyModeActive) { locationProviders = simpleLocationProviders; } enableLocationProviders(locationProviders); // fire off an initial location fix if one is available if (!hasLocationPermissions()) { Log.e(TAG, "Location permissions missing"); return; } lastLocation = tiLocation.getLastKnownLocation(); if (lastLocation != null) { fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(lastLocation, tiLocation.locationManager.getProvider(lastLocation.getProvider()))); doAnalytics(lastLocation); } } } super.eventListenerAdded(event, count, proxy); } /** * @see org.appcelerator.kroll.KrollProxy#eventListenerRemoved(java.lang.String, int, org.appcelerator.kroll.KrollProxy) */ @Override protected void eventListenerRemoved(String event, int count, KrollProxy proxy) { if (TiC.EVENT_HEADING.equals(event)) { if (compassListenersRegistered) { tiCompass.unregisterListener(); compassListenersRegistered = false; } } else if (TiC.EVENT_LOCATION.equals(event)) { numLocationListeners--; if (numLocationListeners == 0) { disableLocationProviders(); } } super.eventListenerRemoved(event, count, proxy); } /** * Checks if the device has a compass sensor * * @return <code>true</code> if the device has a compass, <code>false</code> if not */ @Kroll.method @Kroll.getProperty public boolean getHasCompass() { return tiCompass.getHasCompass(); } /** * Retrieves the current compass heading and returns it to the specified Javascript function * * @param listener Javascript function that will be invoked with the compass heading */ @Kroll.method public void getCurrentHeading(final KrollFunction listener) { tiCompass.getCurrentHeading(listener); } /** * Retrieves the last obtained location and returns it as JSON. * * @return String representing the last geolocation event */ @Kroll.method @Kroll.getProperty public String getLastGeolocation() { return TiAnalyticsEventFactory.locationToJSONString(lastLocation); } /** * Checks if the Android manual location behavior mode is currently enabled * * @return <code>true</code> if currently in manual mode, <code> * false</code> if the Android module has not been registered * yet with the OS or manual mode is not enabled */ private boolean getManualMode() { if (androidModule == null) { return false; } else { return androidModule.manualMode; } } @Kroll.method public boolean hasLocationPermissions() { if (Build.VERSION.SDK_INT < 23) { return true; } Activity currentActivity = TiApplication.getInstance().getCurrentActivity(); if (currentActivity.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { return true; } return false; } @Kroll.method public void requestLocationPermissions(@Kroll.argument(optional=true) Object type, @Kroll.argument(optional=true) KrollFunction permissionCallback) { if (hasLocationPermissions()) { return; } KrollFunction permissionCB; if (type instanceof KrollFunction && permissionCallback == null) { permissionCB = (KrollFunction) type; } else { permissionCB = permissionCallback; } TiBaseActivity.registerPermissionRequestCallback(TiC.PERMISSION_CODE_LOCATION, permissionCB, getKrollObject()); Activity currentActivity = TiApplication.getInstance().getCurrentActivity(); currentActivity.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, TiC.PERMISSION_CODE_LOCATION); } /** * Registers the specified location provider with the OS. Once the provider is registered, the OS * will begin to provider location updates as they are available * * @param locationProvider location provider to be registered */ public void registerLocationProvider(LocationProviderProxy locationProvider) { if (!hasLocationPermissions()) { Log.e(TAG, "Location permissions missing", Log.DEBUG_MODE); return; } String provider = TiConvert.toString(locationProvider.getProperty(TiC.PROPERTY_NAME)); try { tiLocation.locationManager.requestLocationUpdates( provider, (long) locationProvider.getMinUpdateTime(), (float) locationProvider.getMinUpdateDistance(), locationProvider); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to register [" + provider + "], provider is null"); } catch (SecurityException e) { Log.e(TAG, "Unable to register [" + provider + "], permission denied"); } } /** * Wrapper to ensure task executes on the runtime thread * * @param locationProviders list of location providers to enable by registering * the providers with the OS */ public void enableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders) { if (KrollRuntime.getInstance().isRuntimeThread()) { doEnableLocationProviders(locationProviders); } else { Message message = getRuntimeHandler().obtainMessage(MSG_ENABLE_LOCATION_PROVIDERS, locationProviders); message.sendToTarget(); } } /** * Enables the specified location behavior mode by registering the associated * providers with the OS. Even if the specified mode is currently active, the * current mode will be disabled by de-registering all the associated providers * for that mode with the OS and then registering * them again. This can be useful in cases where the properties for all the * providers have been updated and they need to be re-registered in order for the * change to take effect. Modification of the list of providers for any mode * should occur on the runtime thread in order to make sure threading issues are * avoiding * * @param locationProviders */ private void doEnableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders) { if (numLocationListeners > 0) { disableLocationProviders(); Iterator<String> iterator = locationProviders.keySet().iterator(); while(iterator.hasNext()) { LocationProviderProxy locationProvider = locationProviders.get(iterator.next()); registerLocationProvider(locationProvider); } } } /** * Disables the current mode by de-registering all the associated providers * for that mode with the OS. Providers are just de-registered with the OS, * not removed from the list of providers we associate with the behavior mode. */ private void disableLocationProviders() { for (LocationProviderProxy locationProvider : legacyLocationProviders.values()) { tiLocation.locationManager.removeUpdates(locationProvider); } for (LocationProviderProxy locationProvider : simpleLocationProviders.values()) { tiLocation.locationManager.removeUpdates(locationProvider); } if (androidModule != null) { for (LocationProviderProxy locationProvider : androidModule.manualLocationProviders.values()) { tiLocation.locationManager.removeUpdates(locationProvider); } } } /** * Checks if the device has a valid location service present. The passive location service * is not counted. * * @return <code>true</code> if a valid location service is available on the device, * <code>false</code> if not */ @Kroll.getProperty @Kroll.method public boolean getLocationServicesEnabled() { return tiLocation.getLocationServicesEnabled(); } /** * Retrieves the last known location and returns it to the specified Javascript function * * @param callback Javascript function that will be invoked with the last known location */ @Kroll.method public void getCurrentPosition(KrollFunction callback) { if (!hasLocationPermissions()) { Log.e(TAG, "Location permissions missing"); return; } if (callback != null) { Location latestKnownLocation = tiLocation.getLastKnownLocation(); if (latestKnownLocation != null) { callback.call(this.getKrollObject(), new Object[] { buildLocationEvent(latestKnownLocation, tiLocation.locationManager.getProvider(latestKnownLocation.getProvider())) }); } else { Log.e(TAG, "Unable to get current position, location is null"); callback.call(this.getKrollObject(), new Object[] { buildLocationErrorEvent(TiLocation.ERR_POSITION_UNAVAILABLE, "location is currently unavailable.") }); } } } /** * Converts the specified address to coordinates and returns the value to the specified * Javascript function * * @param address address to be converted * @param callback Javascript function that will be invoked with the coordinates * for the specified address if available */ @Kroll.method public void forwardGeocoder(String address, KrollFunction callback) { tiLocation.forwardGeocode(address, createGeocodeResponseHandler(callback)); } /** * Converts the specified latitude and longitude to a human readable address and returns * the value to the specified Javascript function * * @param latitude latitude to be used in looking up the associated address * @param longitude longitude to be used in looking up the associated address * @param callback Javascript function that will be invoked with the address * for the specified latitude and longitude if available */ @Kroll.method public void reverseGeocoder(double latitude, double longitude, KrollFunction callback) { tiLocation.reverseGeocode(latitude, longitude, createGeocodeResponseHandler(callback)); } /** * Convenience method for creating a response handler that is used when doing a * geocode lookup. * * @param callback Javascript function that the response handler will invoke * once the geocode response is ready * @return the geocode response handler */ private GeocodeResponseHandler createGeocodeResponseHandler(final KrollFunction callback) { final GeolocationModule geolocationModule = this; return new GeocodeResponseHandler() { @Override public void handleGeocodeResponse(KrollDict geocodeResponse) { geocodeResponse.put(TiC.EVENT_PROPERTY_SOURCE, geolocationModule); callback.call(getKrollObject(), new Object[] { geocodeResponse }); } }; } /** * Called to determine if the specified location is "better" than the current location. * This is determined by comparing the new location to the current location according * to the location rules (if any are set) for the current behavior mode. If no rules * are set for the current behavior mode, the new location is always accepted. * * @param newLocation location to evaluate * @return <code>true</code> if the location has been deemed better than * the current location based on the existing rules set for the * current behavior mode, <code>false</code> if not */ private boolean shouldUseUpdate(Location newLocation) { boolean passed = false; if (getManualMode()) { if (androidModule.manualLocationRules.size() > 0) { for(LocationRuleProxy rule : androidModule.manualLocationRules) { if (rule.check(currentLocation, newLocation)) { passed = true; break; } } } else { passed = true; // no rules set, always accept } } else if (!legacyModeActive) { for(LocationRuleProxy rule : simpleLocationRules) { if (rule.check(currentLocation, newLocation)) { passed = true; break; } } // TODO remove this block when legacy mode is removed } else { // the legacy mode will fall here, don't filter the results passed = true; } return passed; } /** * Convenience method used to package a location from a location provider into a * consumable form for the Titanium developer before it is fire back to Javascript. * * @param location location that needs to be packaged into consumable form * @param locationProvider location provider that provided the location update * @return map of property names and values that contain information * pulled from the specified location */ private KrollDict buildLocationEvent(Location location, LocationProvider locationProvider) { KrollDict coordinates = new KrollDict(); coordinates.put(TiC.PROPERTY_LATITUDE, location.getLatitude()); coordinates.put(TiC.PROPERTY_LONGITUDE, location.getLongitude()); coordinates.put(TiC.PROPERTY_ALTITUDE, location.getAltitude()); coordinates.put(TiC.PROPERTY_ACCURACY, location.getAccuracy()); coordinates.put(TiC.PROPERTY_ALTITUDE_ACCURACY, null); // Not provided coordinates.put(TiC.PROPERTY_HEADING, location.getBearing()); coordinates.put(TiC.PROPERTY_SPEED, location.getSpeed()); coordinates.put(TiC.PROPERTY_TIMESTAMP, location.getTime()); KrollDict event = new KrollDict(); event.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null); event.put(TiC.PROPERTY_COORDS, coordinates); if (locationProvider != null) { KrollDict provider = new KrollDict(); provider.put(TiC.PROPERTY_NAME, locationProvider.getName()); provider.put(TiC.PROPERTY_ACCURACY, locationProvider.getAccuracy()); provider.put(TiC.PROPERTY_POWER, locationProvider.getPowerRequirement()); event.put(TiC.PROPERTY_PROVIDER, provider); } return event; } /** * Convenience method used to package a error into a consumable form * for the Titanium developer before it is fired back to Javascript. * * @param code Error code identifying the error * @param msg Error message describing the event * @return map of property names and values that contain information * regarding the error */ private KrollDict buildLocationErrorEvent(int code, String msg) { KrollDict d = new KrollDict(3); d.putCodeAndMessage(code, msg); return d; } @Override public String getApiName() { return "Ti.Geolocation"; } @Override public void onDestroy(Activity activity) { //clean up event listeners if (compassListenersRegistered) { tiCompass.unregisterListener(); compassListenersRegistered = false; } disableLocationProviders(); super.onDestroy(activity); } }
ashcoding/titanium_mobile
android/modules/geolocation/src/java/ti/modules/titanium/geolocation/GeolocationModule.java
Java
apache-2.0
36,967
package org.xmlcml.ami.visitor; import java.io.File; import java.util.List; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.xmlcml.ami.util.AMIUtil; import org.xmlcml.ami.visitable.VisitableInput; /** manages the output. * * Decides whether to create files or directories. May map the structure onto the input structure. * * @author pm286 * */ public class VisitorOutput { private static final Logger LOG = Logger.getLogger(VisitorOutput.class); private static final String DEFAULT_OUTPUT_LOCATION = "target/"; private static final String DEFAULT_BASENAME = "dummy"; private static final String DEFAULT_OUTPUT_SUFFIX = ".xml"; private String outputLocation; // private VisitableInput visitableInput; private List<VisitableInput> visitableInputList; private String extension; private boolean isDirectory; private File outputDirectory; /** reads outputLocation and ducktypes the type (File, Directory, etc.). * * @param outputLocation */ public VisitorOutput(String outputLocation) { setDefaults(); this.outputLocation = outputLocation; generateOutputDirectoryName(); } /** this creates a default outputLocation * */ public VisitorOutput() { setDefaults(); } private void setDefaults() { outputLocation = DEFAULT_OUTPUT_LOCATION; extension = DEFAULT_OUTPUT_SUFFIX; outputDirectory = new File(DEFAULT_OUTPUT_LOCATION); } /** not yet used * * @param visitableInput */ public void setVisitableInputList(List<VisitableInput> visitableInputList) { this.visitableInputList = visitableInputList; } private void generateOutputDirectoryName() { if (outputLocation.startsWith(AMIUtil.HTTP)) { throw new RuntimeException("Cannot output to URL: "+outputLocation); } if (outputLocation.startsWith(AMIUtil.DOI)) { throw new RuntimeException("Cannot output to DOI: "+outputLocation); } if (outputLocation == null) { LOG.info("No explicit output location"); } else { outputLocation = FilenameUtils.normalize(new File(outputLocation).getAbsolutePath()); extension = FilenameUtils.getExtension(outputLocation); isDirectory = AMIUtil.endsWithSeparator(outputLocation) || extension == null || extension.equals(""); outputDirectory = new File(outputLocation); } } protected String getOutputLocation() { return outputLocation; } protected String getExtension() { return extension; } protected boolean isDirectory() { return isDirectory; } public File getOutputDirectoryFile() { if (outputDirectory != null) { LOG.trace("outputDirectory: "+outputDirectory); if (outputDirectory.exists() && !outputDirectory.isDirectory()) { LOG.info("existing file is not a directory: "+outputDirectory); } else { ifNotEndsWithSlashUseParentAsOutputDirectory(); outputDirectory.mkdirs(); String baseName = (visitableInputList == null || visitableInputList.size() == 0) ? DEFAULT_BASENAME : visitableInputList.get(0).getBaseName(); LOG.trace("basename "+baseName); outputDirectory = new File(outputDirectory, baseName+"."+extension); } } else { throw new RuntimeException("Null output directory"); } return outputDirectory; } private void ifNotEndsWithSlashUseParentAsOutputDirectory() { if (!outputDirectory.toString().endsWith("/")) { File parent = outputDirectory.getParentFile(); outputDirectory = (parent == null) ? outputDirectory : parent; } } public void setExtension(String extension) { this.extension = extension; } }
tarrow/ami
src/main/java/org/xmlcml/ami/visitor/VisitorOutput.java
Java
apache-2.0
3,654
/* Copyright 2006 Jerry Huxtable Copyright 2009 Martin Davis Copyright 2012 Antoine Gourlay 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.jproj; import java.text.DecimalFormat; /** * Stores a the coordinates for a position * defined relative to some {@link CoordinateReferenceSystem}. * The coordinate is defined via X, Y, and optional Z ordinates. * Provides utility methods for comparing the ordinates of two positions and * for creating positions from Strings/storing positions as strings. * <p> * The primary use of this class is to represent coordinate * values which are to be transformed * by a {@link CoordinateTransform}. */ public class ProjCoordinate { private static final String DECIMAL_FORMAT_PATTERN = "0.0###############"; // a DecimalFormat is not ThreadSafe, hence the ThreadLocal variable. private static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { return new DecimalFormat(DECIMAL_FORMAT_PATTERN); } }; /** * The X ordinate for this point. * <p> * Note: This member variable * can be accessed directly. In the future this direct access should * be replaced with getter and setter methods. This will require * refactoring of the Proj4J code base. */ public double x; /** * The Y ordinate for this point. * <p> * Note: This member variable * can be accessed directly. In the future this direct access should * be replaced with getter and setter methods. This will require * refactoring of the Proj4J code base. */ public double y; /** * The Z ordinate for this point. * If this variable has the value <tt>Double.NaN</tt> * then this coordinate does not have a Z value. * <p> * Note: This member variable * can be accessed directly. In the future this direct access should * be replaced with getter and setter methods. This will require * refactoring of the Proj4J code base. */ public double z; /** * Creates a ProjCoordinate with default ordinate values. * */ public ProjCoordinate() { this(0.0, 0.0); } /** * Creates a ProjCoordinate with values copied from the given coordinate object. * @param pt a ProjCoordinate to copy */ public ProjCoordinate(ProjCoordinate pt) { this(pt.x, pt.y, pt.z); } /** * Creates a ProjCoordinate using the provided double parameters. * The first double parameter is the x ordinate (or easting), * the second double parameter is the y ordinate (or northing), * and the third double parameter is the z ordinate (elevation or height). * * Valid values should be passed for all three (3) double parameters. If * you want to create a horizontal-only point without a valid Z value, use * the constructor defined in this class that only accepts two (2) double * parameters. * * @param argX * @param argY * @param argZ * @see #ProjCoordinate(double argX, double argY) */ public ProjCoordinate(double argX, double argY, double argZ) { this.x = argX; this.y = argY; this.z = argZ; } /** * Creates a ProjCoordinate using the provided double parameters. * The first double parameter is the x ordinate (or easting), * the second double parameter is the y ordinate (or northing). * This constructor is used to create a "2D" point, so the Z ordinate * is automatically set to Double.NaN. * @param argX * @param argY */ public ProjCoordinate(double argX, double argY) { this.x = argX; this.y = argY; this.z = Double.NaN; } /** * Create a ProjCoordinate by parsing a String in the same format as returned * by the toString method defined by this class. * * @param argToParse the string to parse */ public ProjCoordinate(String argToParse) { // Make sure the String starts with "ProjCoordinate: ". if (!argToParse.startsWith("ProjCoordinate: ")) { throw new IllegalArgumentException("The input string was not in the proper format."); } // 15 characters should cut out "ProjCoordinate: ". String chomped = argToParse.substring(16); // Get rid of the starting and ending square brackets. String withoutFrontBracket = chomped.substring(1); // Calc the position of the last bracket. int length = withoutFrontBracket.length(); int positionOfCharBeforeLast = length - 2; String withoutBackBracket = withoutFrontBracket.substring(0, positionOfCharBeforeLast); // We should be left with just the ordinate values as strings, // separated by spaces. Split them into an array of Strings. String[] parts = withoutBackBracket.split(" "); // Get number of elements in Array. There should be two (2) elements // or three (3) elements. // If we don't have an array with two (2) or three (3) elements, // then we need to throw an exception. if (parts.length != 2 && parts.length != 3) { throw new IllegalArgumentException("The input string was not in the proper format."); } // Convert strings to doubles. this.x = "NaN".equals(parts[0]) ? Double.NaN : Double.parseDouble(parts[0]); this.y = "NaN".equals(parts[1]) ? Double.NaN : Double.parseDouble(parts[1]); // You might not always have a Z ordinate. If you do, set it. if (parts.length == 3) { this.z = "NaN".equals(parts[2]) ? Double.NaN : Double.parseDouble(parts[2]); } else { this.z = Double.NaN; } } /** * Sets the value of this coordinate to * be equal to the given coordinate's ordinates. * * @param p the coordinate to copy */ public void setValue(ProjCoordinate p) { this.x = p.x; this.y = p.y; this.z = p.z; } /** * Returns a boolean indicating if the X ordinate value of the * ProjCoordinate provided as an ordinate is equal to the X ordinate * value of this ProjCoordinate. Because we are working with floating * point numbers the ordinates are considered equal if the difference * between them is less than the specified tolerance. * @param argToCompare * @param argTolerance * @return */ public boolean areXOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) { // Subtract the x ordinate values and then see if the difference // between them is less than the specified tolerance. If the difference // is less, return true. return argToCompare.x - this.x <= argTolerance; } /** * Returns a boolean indicating if the Y ordinate value of the * ProjCoordinate provided as an ordinate is equal to the Y ordinate * value of this ProjCoordinate. Because we are working with floating * point numbers the ordinates are considered equal if the difference * between them is less than the specified tolerance. * @param argToCompare * @param argTolerance * @return */ public boolean areYOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) { // Subtract the y ordinate values and then see if the difference // between them is less than the specified tolerance. If the difference // is less, return true. return argToCompare.y - this.y <= argTolerance; } /** * Returns a boolean indicating if the Z ordinate value of the * ProjCoordinate provided as an ordinate is equal to the Z ordinate * value of this ProjCoordinate. Because we are working with floating * point numbers the ordinates are considered equal if the difference * between them is less than the specified tolerance. * * If both Z ordinate values are Double.NaN this method will return * true. If one Z ordinate value is a valid double value and one is * Double.Nan, this method will return false. * @param argToCompare * @param argTolerance * @return */ public boolean areZOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) { // We have to handle Double.NaN values here, because not every // ProjCoordinate will have a valid Z Value. if (Double.isNaN(z)) { return Double.isNaN(argToCompare.z); // if true, both the z ordinate values are Double.Nan. // else, We've got one z ordinate with a valid value and one with // a Double.NaN value. } // We have a valid z ordinate value in this ProjCoordinate object. else { if (Double.isNaN(argToCompare.z)) { // We've got one z ordinate with a valid value and one with // a Double.NaN value. Return false. return false; } // If we get to this point in the method execution, we have to // z ordinates with valid values, and we need to do a regular // comparison. This is done in the remainder of the method. } // Subtract the z ordinate values and then see if the difference // between them is less than the specified tolerance. If the difference // is less, return true. return argToCompare.z - this.z <= argTolerance; } /** * Returns a string representing the ProjPoint in the format: * <tt>ProjCoordinate[X Y Z]</tt>. * <p> * Example: * <pre> * ProjCoordinate[6241.11 5218.25 12.3] * </pre> */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ProjCoordinate["); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(x); } builder.append(" "); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(y); } builder.append(" "); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(z); } builder.append("]"); return builder.toString(); } /** * Returns a string representing the ProjPoint in the format: * <tt>[X Y]</tt> * or <tt>[X, Y, Z]</tt>. * Z is not displayed if it is NaN. * <p> * Example: * <pre> * [6241.11, 5218.25, 12.3] * </pre> * @return */ public String toShortString() { StringBuilder builder = new StringBuilder(); builder.append("["); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(DECIMAL_FORMAT.get().format(x)); } builder.append(", "); if (Double.isNaN(y)) { builder.append("NaN"); } else { builder.append(DECIMAL_FORMAT.get().format(y)); } if (!Double.isNaN(z)) { builder.append(", "); builder.append(this.z); } builder.append("]"); return builder.toString(); } public boolean hasValidZOrdinate() { return !Double.isNaN(z); } /** * Indicates if this ProjCoordinate has valid X ordinate and Y ordinate * values. Values are considered invalid if they are Double.NaN or * positive/negative infinity. * @return */ public boolean hasValidXandYOrdinates() { return !Double.isNaN(x) && !Double.isInfinite(x) && !Double.isNaN(y) && !Double.isInfinite(y); } }
ebocher/jproj
src/main/java/org/jproj/ProjCoordinate.java
Java
apache-2.0
14,438
package interviews; public class Yahoo { } Run Length Encoding for byte array Input byte array [10, 10, 10, 255, 255, 0, 10] ==> output byte array [3, 10, 2, 255, 1, 0, 1, 10] Class ByteArrayEncodeDecode { public byte[] encodeByteArray(byte[] input) { int n = input.length; if (n == 0) return new byte[]; Arraylist<Byte> out = Arraylist<Byte>(); byte prevByte = input[0]; byte prevCount = 1; for (int i = 1; i < n; i++) { if(prevByte == input[i] && prevCount != 255){ // prevCount++; } else { out.add(prevCount); out.add(prevByte); prevByte = input[i]; prevCount = 1; } } out.add(prevCount); out.add(prevByte); return out.toArray(); } public static void main() { } } // [] ==> [] // [1] ==> [1, 1] // [1, 1, 1, 2, 2, 3] ==> [3, 1, 2, 2, 1, 3] // [1 ... 300.....1] ==> [255, 1, 45, 1]
rezaur86/Coding-competitions
Java/interviews/Yahoo.java
Java
apache-2.0
1,011
/* * Copyright 2013-2017 Grzegorz Ligas <ligasgr@gmail.com> and other contributors * (see the CONTRIBUTORS file). * * 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. */ // This is a generated file. Not intended for manual editing. package org.intellij.xquery.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface XQueryContextItemDecl extends XQueryPsiElement { @Nullable XQueryItemType getItemType(); @Nullable XQuerySeparator getSeparator(); @Nullable XQueryVarDefaultValue getVarDefaultValue(); @Nullable XQueryVarValue getVarValue(); }
ligasgr/intellij-xquery
gen/org/intellij/xquery/psi/XQueryContextItemDecl.java
Java
apache-2.0
1,132
/* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * 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 net.duckling.vmt.domain; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import org.apache.log4j.Logger; public class HttpGet { private static final Logger LOG=Logger.getLogger(HttpGet.class); private String path; private String encode="UTF-8"; public HttpGet(String url,String encode){ this.path=url; this.encode=encode; } public HttpGet(String url){ this.path=url; } public String connect(){ URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { LOG.error(e.getMessage()+",can't touch this url="+path, e); return null; } try (InputStream ins = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ins, encode));) { String line; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } catch (IOException e) { LOG.error(e.getMessage(), e); return null; } } }
duckling-falcon/vmt
src/main/java/net/duckling/vmt/domain/HttpGet.java
Java
apache-2.0
1,845
/* * Copyright 2011 Jon S Akhtar (Sylvanaar) * * 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.sylvanaar.idea.Lua.lang.psi.impl.symbols; import com.intellij.lang.ASTNode; import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaParameter; import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaSymbol; import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaUpvalueIdentifier; /** * Created by IntelliJ IDEA. * User: Jon S Akhtar * Date: 1/26/11 * Time: 9:23 PM */ public class LuaUpvalueIdentifierImpl extends LuaLocalIdentifierImpl implements LuaUpvalueIdentifier { public LuaUpvalueIdentifierImpl(ASTNode node) { super(node); } @Override public boolean isSameKind(LuaSymbol symbol) { return symbol instanceof LuaLocalDeclarationImpl || symbol instanceof LuaParameter; } @Override public String toString() { return "Upvalue: " + getText(); } }
consulo/consulo-lua
src/main/java/com/sylvanaar/idea/Lua/lang/psi/impl/symbols/LuaUpvalueIdentifierImpl.java
Java
apache-2.0
1,415
package com.buschmais.xo.neo4j.test.id; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import java.util.Collection; import com.buschmais.xo.api.XOManager; import com.buschmais.xo.api.bootstrap.XOUnit; import com.buschmais.xo.neo4j.test.AbstractNeo4JXOManagerIT; import com.buschmais.xo.neo4j.test.id.composite.A; import com.buschmais.xo.neo4j.test.id.composite.A2B; import com.buschmais.xo.neo4j.test.id.composite.B; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class EqualsHashcodeIT extends AbstractNeo4JXOManagerIT { public EqualsHashcodeIT(XOUnit xoUnit) { super(xoUnit); } @Parameterized.Parameters public static Collection<Object[]> getXOUnits() { return xoUnits(A.class, B.class, A2B.class); } @Test public void equalsHashcode() { XOManager xoManager = getXOManager(); xoManager.currentTransaction().begin(); A a = xoManager.create(A.class); int aHashCode = a.hashCode(); B b = xoManager.create(B.class); int bHashCode = b.hashCode(); A2B a2b = xoManager.create(a, A2B.class, b); int a2bHashCode = a2b.hashCode(); xoManager.currentTransaction().commit(); xoManager.currentTransaction().begin(); assertThat(a.equals(a), equalTo(true)); assertThat(b.equals(b), equalTo(true)); assertThat(a2b.equals(a2b), equalTo(true)); assertThat(a.hashCode(), equalTo(aHashCode)); assertThat(b.hashCode(), equalTo(bHashCode)); assertThat(a2b.hashCode(), equalTo(a2bHashCode)); xoManager.currentTransaction().commit(); } }
buschmais/extended-objects
neo4j/test/src/test/java/com/buschmais/xo/neo4j/test/id/EqualsHashcodeIT.java
Java
apache-2.0
1,744
package com.tle.configmanager; import com.dytech.gui.ComponentHelper; import com.thoughtworks.xstream.XStream; import com.tle.common.Check; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JSeparator; import net.miginfocom.swing.MigLayout; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.io.FileUtils; // Author: Andrew Gibb @SuppressWarnings({"serial", "nls"}) public class ConfigLauncherGUI extends JFrame implements ActionListener { public static final String MANDATORY_CONFIG = "mandatory-config.properties"; public static final String OPTIONAL_CONFIG = "optional-config.properties"; public static final String HIBERNATE_CONFIG = "hibernate.properties"; public static final String LOGGING_CONFIG = "learningedge-log4j.properties"; public static final String IMAGEMAGICK_CONFIG = "plugins/com.tle.core.imagemagick/config.properties.unresolved"; public static final String HIKARI_CONFIG = "hikari.properties"; private final String TITLE = "TLE Configuration Manager"; private final String PATH = "./configs/"; private final String ORACLE = "oracle"; private final String POSTGRESQL = "postgresql"; private final String MSSQL = "ms sql"; private final String source; private final String destination; private JLabel lblConfig; private JComboBox<ConfigProfile> cmbConfigs; private JButton btnNew, btnEdit, btnApply, btnDelete; private JSeparator sep; private List<ConfigProfile> configs; public ConfigLauncherGUI(String source, String destination) { setTitle(TITLE); setupGUI(); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); this.source = source; this.destination = destination; // Set a minimum width...leave the height to the pack... setMinimumSize(new Dimension(300, 0)); pack(); ComponentHelper.centreOnScreen(this); // Updated combo box containing profiles updateConfigs(); } // Sets up the GUI for managing/loading the configuration profiles private void setupGUI() { Container contents = getContentPane(); contents.setLayout(new MigLayout("wrap 3", "[grow][grow][grow]")); configs = new ArrayList<ConfigProfile>(); lblConfig = new JLabel("Configurations: "); cmbConfigs = new JComboBox<ConfigProfile>(); btnNew = new JButton("New"); btnNew.addActionListener(this); btnApply = new JButton("Apply Configuration"); btnApply.addActionListener(this); btnEdit = new JButton("Edit"); btnEdit.addActionListener(this); sep = new JSeparator(); btnDelete = new JButton("Delete"); btnDelete.addActionListener(this); contents.add(lblConfig, "growx, spanx 3"); contents.add(cmbConfigs, "growx, spanx 3"); contents.add(btnNew, "growx, center"); contents.add(btnEdit, "growx, center"); contents.add(btnDelete, "growx, center"); contents.add(sep, "growx, spanx 3"); contents.add(btnApply, "center, growx, spanx 3"); } // Updates the available configuration profiles public void updateConfigs() { File srcDir = new File(PATH); File[] configFiles = srcDir.listFiles(); Reader rdr; cmbConfigs.removeAllItems(); configs.clear(); if (configFiles != null) { for (File f : configFiles) { if (f.isFile()) { XStream xstream = new XStream(); try { rdr = new BufferedReader(new FileReader(f)); ConfigProfile prof = (ConfigProfile) xstream.fromXML(rdr); configs.add(prof); rdr.close(); } catch (IOException e) { throw new RuntimeException(e); } } } Collections.sort( configs, new Comparator<ConfigProfile>() { @Override public int compare(ConfigProfile o1, ConfigProfile o2) { return o1.getProfName().compareToIgnoreCase(o2.getProfName()); } }); for (ConfigProfile prof : configs) { cmbConfigs.addItem(prof); } } if (configs.isEmpty()) { btnEdit.setEnabled(false); btnApply.setEnabled(false); btnDelete.setEnabled(false); } else { btnEdit.setEnabled(true); btnApply.setEnabled(true); btnDelete.setEnabled(true); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnNew) { addProfile(); } else if (e.getSource() == btnEdit) { editProfile(); } else if (e.getSource() == btnDelete) { deleteProfile(); } else if (e.getSource() == btnApply) { try { loadProfile(); } catch (Exception ex) { JOptionPane.showMessageDialog( null, "Error loading configuration: \n" + ex.getMessage(), "Load Failed", JOptionPane.ERROR_MESSAGE); } } } // Adds a new profile which is either a clone of an existing profile or is // blank private void addProfile() { ConfigEditorGUI confEd = null; if (configs != null && cmbConfigs.getSelectedItem() != null) { ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); int result = JOptionPane.showConfirmDialog( null, "Do you want to clone the currently selected configuration?: " + selectedProf.getProfName(), "Clone Confirmation", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { confEd = new ConfigEditorGUI(selectedProf, "copy"); } else { confEd = new ConfigEditorGUI(); } } else { confEd = new ConfigEditorGUI(); } confEd.setModal(true); confEd.setVisible(true); if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) { updateConfigs(); } } // Edits and existing profile private void editProfile() { int index = cmbConfigs.getSelectedIndex(); ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); ConfigEditorGUI confEd = new ConfigEditorGUI(selectedProf); confEd.setModal(true); confEd.setVisible(true); if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) { updateConfigs(); cmbConfigs.setSelectedIndex(index); } } // Deletes a configuration profile private void deleteProfile() { ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); File toDel = new File(PATH + selectedProf.getProfName() + ".xml"); int result = JOptionPane.showConfirmDialog( null, "Are you sure you want to delete this configuration?: " + selectedProf.getProfName(), "Delete Confirmation", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { boolean success = toDel.delete(); if (!success) { JOptionPane.showMessageDialog( null, "Unable to delete configuration: " + selectedProf.getProfName(), "Delete Failed", JOptionPane.ERROR_MESSAGE); } } updateConfigs(); } // Loads a profile (SUPER HACKISH) private void loadProfile() throws FileNotFoundException, IOException, ConfigurationException { ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); File srcDir = new File(source); // Remove Current Configuration Files File destDir = new File(destination); FileUtils.deleteDirectory(destDir); // Create Destination destDir.mkdir(); // Copy Required Files (Database Specific) boolean oracleSelected = selectedProf.getDbtype().equalsIgnoreCase(ORACLE); if (oracleSelected) { org.apache.commons.io.FileUtils.copyFile( new File(srcDir + "/hibernate.properties.oracle"), new File(destDir + "/hibernate.properties")); } else if (selectedProf.getDbtype().equalsIgnoreCase(POSTGRESQL)) { FileUtils.copyFile( new File(srcDir + "/hibernate.properties.postgresql"), new File(destDir + "/hibernate.properties")); } else if (selectedProf.getDbtype().equalsIgnoreCase(MSSQL)) { FileUtils.copyFile( new File(srcDir + "/hibernate.properties.sqlserver"), new File(destDir + "/hibernate.properties")); } // Mandatory / Optional / Logging FileUtils.copyFile( new File(srcDir + "/mandatory-config.properties"), new File(destDir + "/mandatory-config.properties")); FileUtils.copyFile( new File(srcDir + "/optional-config.properties"), new File(destDir + "/optional-config.properties")); // Copy custom development logging file FileUtils.copyFile( new File("./learningedge-log4j.properties"), new File(destDir + "/learningedge-log4j.properties")); // Other Miscellaneous Files FileUtils.copyFile( new File(srcDir + "/en-stopWords.txt"), new File(destDir + "/en-stopWords.txt")); FileUtils.copyFile( new File(srcDir + "/" + HIKARI_CONFIG), new File(destDir + "/" + HIKARI_CONFIG)); // Plugins Folder FileUtils.copyDirectoryToDirectory(new File(srcDir + "/plugins"), destDir); // Edit Hibernate Properties String hibProp = readFile(destination + "/" + HIBERNATE_CONFIG); hibProp = hibProp.replace("${datasource/host}", selectedProf.getHost()); hibProp = hibProp.replace("${datasource/port}", selectedProf.getPort()); hibProp = hibProp.replace("${datasource/database}", selectedProf.getDatabase()); hibProp = hibProp.replace("${datasource/username}", selectedProf.getUsername()); hibProp = hibProp.replace("${datasource/password}", selectedProf.getPassword()); hibProp = hibProp.replace( "${datasource/schema}", oracleSelected ? "hibernate.default_schema = " + selectedProf.getUsername() : ""); writeFile(destination + "/hibernate.properties", hibProp); // Edit Mandatory Properties PropertyEditor mandProps = new PropertyEditor(); mandProps.load(new File(destination + "/" + MANDATORY_CONFIG)); String http = selectedProf.getHttp(); String portFromUrl = selectedProf.getAdminurl().split(":")[1]; mandProps.setProperty( "http.port", !Check.isEmpty(http) ? http : !Check.isEmpty(portFromUrl) ? portFromUrl : "80"); String https = selectedProf.getHttps(); if (!Check.isEmpty(https)) { mandProps.setProperty("https.port", https); } String ajp = selectedProf.getAjp(); if (!Check.isEmpty(https)) { mandProps.setProperty("ajp.port", ajp); } mandProps.setProperty("filestore.root", selectedProf.getFilestore()); mandProps.setProperty("java.home", selectedProf.getJavahome()); mandProps.setProperty("admin.url", selectedProf.getAdminurl()); mandProps.setProperty("freetext.index.location", selectedProf.getFreetext()); mandProps.setProperty("freetext.stopwords.file", selectedProf.getStopwords()); String reporting = selectedProf.getReporting(); if (!Check.isEmpty(reporting)) { mandProps.setProperty("reporting.workspace.location", reporting); } mandProps.setProperty("plugins.location", selectedProf.getPlugins()); mandProps.save(new File(destination + "/" + MANDATORY_CONFIG)); // Edit Optional Properties String optProp = readFile(destination + "/" + OPTIONAL_CONFIG); if (selectedProf.isDevinst()) { optProp = optProp.replace( "#conversionService.disableConversion = false", "conversionService.disableConversion = true"); optProp = optProp.replace( "conversionService.conversionServicePath = ${install.path#t\\/}/conversion/conversion-service.jar", "#conversionService.conversionServicePath ="); optProp = optProp.replace("#pluginPathResolver.wrappedClass", "pluginPathResolver.wrappedClass"); } else { optProp = optProp.replace( "${install.path#t\\/}/conversion/conversion-service.jar", selectedProf.getConversion()); } writeFile(destination + "/optional-config.properties", optProp); // Edit ImageMagik Properties (MORE HAX...) File imgmgk = new File(destination + "/" + IMAGEMAGICK_CONFIG); PropertyEditor magickProps = new PropertyEditor(); magickProps.load(imgmgk); magickProps.setProperty("imageMagick.path", selectedProf.getImagemagick()); magickProps.save(new File((destination + "/" + IMAGEMAGICK_CONFIG).replace(".unresolved", ""))); imgmgk.delete(); JOptionPane.showMessageDialog( null, "The configuration: " + selectedProf.getProfName() + " has been successfully loaded.", "Load Success", JOptionPane.INFORMATION_MESSAGE); } // Reads a file into a string private String readFile(String path) throws IOException { StringBuilder contents = new StringBuilder(); BufferedReader br = new BufferedReader(new FileReader(path)); String line = null; while ((line = br.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } br.close(); return contents.toString(); } // Writes a file from String private void writeFile(String path, String contents) throws IOException { BufferedWriter output = null; output = new BufferedWriter(new FileWriter(new File(path))); output.write(contents); output.close(); } }
equella/Equella
Source/Tools/ConfigManager/src/com/tle/configmanager/ConfigLauncherGUI.java
Java
apache-2.0
13,989
package com.krealid.starter.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.krealid.starter.R; import butterknife.ButterKnife; /** * Created by Maxime on 26/08/2015. */ public class ActuExpendedAdapter extends RecyclerView.Adapter<ActuExpendedAdapter.ViewHolder> { private String text; private Context context; private View view; public ActuExpendedAdapter(String text, Context context){ this.text = text; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { view = LayoutInflater .from(parent.getContext()) .inflate(R.layout.actu_text, parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { String iframeLink; if(this.text.contains("<iframe")){ String iframeStart = "<iframe src=\""; String iframeEnd = "\" width="; int indexToStartIframe = this.text.indexOf(iframeStart); int indexToEndIframe = (this.text.substring(indexToStartIframe)).indexOf(iframeEnd); String iframeHeight = "height=\""; int indexToStartHeightIframe= this.text.indexOf(iframeHeight); String iframeHeightValue = this.text.substring(indexToStartHeightIframe + iframeHeight.length(), this.text.indexOf('"', indexToStartHeightIframe + iframeHeight.length())); iframeLink = this.text.substring(indexToStartIframe + iframeStart.length(), indexToStartIframe + indexToEndIframe); String articleText = this.text.substring(0, indexToStartIframe); holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" + articleText + "</font>", "text/html; charset=UTF-8", null); final RelativeLayout layout = new RelativeLayout(this.context); RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT); layout.setLayoutParams(lprams); WebView web1 = new WebView(this.context); web1.setWebChromeClient(new WebChromeClient()); web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); web1.getSettings().setJavaScriptEnabled(true); web1.getSettings().setPluginState(WebSettings.PluginState.ON); web1.loadUrl(iframeLink); web1.setId(R.id.myWebView); int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Integer.parseInt(iframeHeightValue), this.context.getResources().getDisplayMetrics()); final RelativeLayout.LayoutParams webViewParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, height); layout.addView(web1, webViewParams); holder.articleContainer.addView(layout); } else { holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" + this.text + "</font>", "text/html; charset=UTF-8", null); } } @Override public int getItemCount() { return 1; } public void stopVideo(){ ViewHolder holder = new ViewHolder(view); WebView mWebView = (WebView) holder.articleContainer.findViewById(R.id.myWebView); if(mWebView != null) mWebView.loadUrl("about:blank"); } public static class ViewHolder extends RecyclerView.ViewHolder { public WebView text; public LinearLayout articleContainer; public ViewHolder(View itemView) { super(itemView); text = ButterKnife.findById(itemView, R.id.articleContent); articleContainer = ButterKnife.findById(itemView, R.id.article_container); } } }
max02100/paroisse
ParseStarterProject/src/main/java/com/krealid/starter/adapters/ActuExpendedAdapter.java
Java
apache-2.0
4,384
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ package org.webrtc; @JNINamespace("webrtc::jni") class VP8Decoder extends WrappedNativeVideoDecoder { @Override long createNativeDecoder() { return nativeCreateDecoder(); } static native long nativeCreateDecoder(); }
wangcy6/storm_app
frame/c++/webrtc-master/sdk/android/src/java/org/webrtc/VP8Decoder.java
Java
apache-2.0
645
/* * Copyright (C) 2013 The Android Open Source Project * * 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.android.inputmethod.keyboard.internal; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.os.Message; import android.util.SparseArray; import android.view.View; import com.android.inputmethod.keyboard.PointerTracker; import com.android.inputmethod.keyboard.internal.GestureTrail.Params; import com.android.inputmethod.latin.CollectionUtils; import com.android.inputmethod.latin.StaticInnerHandlerWrapper; /** * Draw gesture trail preview graphics during gesture. */ public final class GestureTrailsPreview extends AbstractDrawingPreview { private final SparseArray<GestureTrail> mGestureTrails = CollectionUtils.newSparseArray(); private final Params mGestureTrailParams; private final Paint mGesturePaint; private int mOffscreenWidth; private int mOffscreenHeight; private int mOffscreenOffsetY; private Bitmap mOffscreenBuffer; private final Canvas mOffscreenCanvas = new Canvas(); private final Rect mOffscreenSrcRect = new Rect(); private final Rect mDirtyRect = new Rect(); private final Rect mGestureTrailBoundsRect = new Rect(); // per trail private final DrawingHandler mDrawingHandler; private static final class DrawingHandler extends StaticInnerHandlerWrapper<GestureTrailsPreview> { private static final int MSG_UPDATE_GESTURE_TRAIL = 0; private final Params mGestureTrailParams; public DrawingHandler(final GestureTrailsPreview outerInstance, final Params gestureTrailParams) { super(outerInstance); mGestureTrailParams = gestureTrailParams; } @Override public void handleMessage(final Message msg) { final GestureTrailsPreview preview = getOuterInstance(); if (preview == null) return; switch (msg.what) { case MSG_UPDATE_GESTURE_TRAIL: preview.getDrawingView().invalidate(); break; } } public void postUpdateGestureTrailPreview() { removeMessages(MSG_UPDATE_GESTURE_TRAIL); sendMessageDelayed(obtainMessage(MSG_UPDATE_GESTURE_TRAIL), mGestureTrailParams.mUpdateInterval); } } public GestureTrailsPreview(final View drawingView, final TypedArray mainKeyboardViewAttr) { super(drawingView); mGestureTrailParams = new Params(mainKeyboardViewAttr); mDrawingHandler = new DrawingHandler(this, mGestureTrailParams); final Paint gesturePaint = new Paint(); gesturePaint.setAntiAlias(true); gesturePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); mGesturePaint = gesturePaint; } @Override public void setKeyboardGeometry(final int[] originCoords, final int width, final int height) { mOffscreenOffsetY = (int)( height * GestureStroke.EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO); mOffscreenWidth = width; mOffscreenHeight = mOffscreenOffsetY + height; } @Override public void onDetachFromWindow() { freeOffscreenBuffer(); } private void freeOffscreenBuffer() { if (mOffscreenBuffer != null) { mOffscreenBuffer.recycle(); mOffscreenBuffer = null; } } private void mayAllocateOffscreenBuffer() { if (mOffscreenBuffer != null && mOffscreenBuffer.getWidth() == mOffscreenWidth && mOffscreenBuffer.getHeight() == mOffscreenHeight) { return; } freeOffscreenBuffer(); mOffscreenBuffer = Bitmap.createBitmap( mOffscreenWidth, mOffscreenHeight, Bitmap.Config.ARGB_8888); mOffscreenCanvas.setBitmap(mOffscreenBuffer); mOffscreenCanvas.translate(0, mOffscreenOffsetY); } private boolean drawGestureTrails(final Canvas offscreenCanvas, final Paint paint, final Rect dirtyRect) { // Clear previous dirty rectangle. if (!dirtyRect.isEmpty()) { paint.setColor(Color.TRANSPARENT); paint.setStyle(Paint.Style.FILL); offscreenCanvas.drawRect(dirtyRect, paint); } dirtyRect.setEmpty(); boolean needsUpdatingGestureTrail = false; // Draw gesture trails to offscreen buffer. synchronized (mGestureTrails) { // Trails count == fingers count that have ever been active. final int trailsCount = mGestureTrails.size(); for (int index = 0; index < trailsCount; index++) { final GestureTrail trail = mGestureTrails.valueAt(index); needsUpdatingGestureTrail |= trail.drawGestureTrail(offscreenCanvas, paint, mGestureTrailBoundsRect, mGestureTrailParams); // {@link #mGestureTrailBoundsRect} has bounding box of the trail. dirtyRect.union(mGestureTrailBoundsRect); } } return needsUpdatingGestureTrail; } /** * Draws the preview * @param canvas The canvas where the preview is drawn. */ @Override public void drawPreview(final Canvas canvas) { if (!isPreviewEnabled()) { return; } mayAllocateOffscreenBuffer(); // Draw gesture trails to offscreen buffer. final boolean needsUpdatingGestureTrail = drawGestureTrails( mOffscreenCanvas, mGesturePaint, mDirtyRect); if (needsUpdatingGestureTrail) { mDrawingHandler.postUpdateGestureTrailPreview(); } // Transfer offscreen buffer to screen. if (!mDirtyRect.isEmpty()) { mOffscreenSrcRect.set(mDirtyRect); mOffscreenSrcRect.offset(0, mOffscreenOffsetY); canvas.drawBitmap(mOffscreenBuffer, mOffscreenSrcRect, mDirtyRect, null); // Note: Defer clearing the dirty rectangle here because we will get cleared // rectangle on the canvas. } } /** * Set the position of the preview. * @param tracker The new location of the preview is based on the points in PointerTracker. */ @Override public void setPreviewPosition(final PointerTracker tracker) { if (!isPreviewEnabled()) { return; } GestureTrail trail; synchronized (mGestureTrails) { trail = mGestureTrails.get(tracker.mPointerId); if (trail == null) { trail = new GestureTrail(); mGestureTrails.put(tracker.mPointerId, trail); } } trail.addStroke(tracker.getGestureStrokeWithPreviewPoints(), tracker.getDownTime()); // TODO: Should narrow the invalidate region. getDrawingView().invalidate(); } }
slightfoot/android-kioskime
src/com/android/inputmethod/keyboard/internal/GestureTrailsPreview.java
Java
apache-2.0
7,627
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package org.glassfish.admingui.devtests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.Select; public class JavaMessageServiceTest extends BaseSeleniumTestClass { public static final String DEFAULT_JMS_HOST = "default_JMS_host"; @Test public void testJmsService() { gotoDasPage(); final String timeout = Integer.toString(generateRandomNumber(90)); final String interval = Integer.toString(generateRandomNumber(10)); final String attempts = Integer.toString(generateRandomNumber(10)); clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsConfiguration_link"); setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:timeoutProp:Timeout", timeout); setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:intervalProp:Interval", interval); setFieldValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:attemptsProp:Attempts", attempts); Select select = new Select(driver.findElement(By.id("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:behaviorProp:Behavior"))); select.selectByVisibleText("priority"); int count = addTableRow("propertyForm:propertyContentPage:basicTable", "propertyForm:propertyContentPage:basicTable:topActionsGroup1:addSharedTableButton"); sleep(500); setFieldValue("propertyForm:propertyContentPage:basicTable:rowGroup1:0:col2:col1St", "property" + generateRandomString()); sleep(500); setFieldValue("propertyForm:propertyContentPage:basicTable:rowGroup1:0:col3:col1St", "value"); clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton"); assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved.")); gotoDasPage(); clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsConfiguration_link"); assertEquals(timeout, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:timeoutProp:Timeout", "value")); assertEquals(interval, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:intervalProp:Interval", "value")); assertEquals(attempts, getValue("propertyForm:propertyContentPage:propertySheet:propertSectionTextField:attemptsProp:Attempts", "value")); assertTableRowCount("propertyForm:propertyContentPage:basicTable", count); //delete the property used to test clickByIdAction("propertyForm:propertyContentPage:basicTable:_tableActionsTop:_selectMultipleButton:_selectMultipleButton_image"); clickByIdAction("propertyForm:propertyContentPage:basicTable:topActionsGroup1:button1"); waitforBtnDisable("propertyForm:propertyContentPage:basicTable:topActionsGroup1:button1"); clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton"); assertTrue(isElementSaveSuccessful("label_sun4","New values successfully saved.")); } @Test public void testJmsHosts() { gotoDasPage(); String hostText = "host" + generateRandomString(); String host = "somemachine" + generateRandomNumber(1000); String port = Integer.toString(generateRandomNumber(32768)); clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsHosts:jmsHosts_link"); clickAndWait("propertyForm:configs:topActionsGroup1:newButton"); setFieldValue("propertyForm:propertySheet:propertSectionTextField:JmsHostTextProp:JmsHostText", hostText); setFieldValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", host); setFieldValue("propertyForm:propertySheet:propertSectionTextField:PortProp:Port", port); setFieldValue("propertyForm:propertySheet:propertSectionTextField:AdminUserProp:AdminUser", "admin"); setFieldValue("propertyForm:propertySheet:propertSectionTextField:newPasswordProp:NewPassword", "admin"); setFieldValue("propertyForm:propertySheet:propertSectionTextField:confirmPasswordProp:ConfirmPassword", "admin"); clickAndWait("propertyForm:propertyContentPage:topButtons:newButton"); String prefix = getTableRowByValue("propertyForm:configs", hostText, "colName"); assertEquals(hostText, getText(prefix + "colName:link")); String clickId = prefix + "colName:link"; clickByIdAction(clickId); assertEquals(host, getValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", "value")); clickAndWait("propertyForm:propertyContentPage:topButtons:cancelButton"); //delete related jms host String deleteRow = prefix + "col0:select"; clickByIdAction(deleteRow); clickByIdAction("propertyForm:configs:topActionsGroup1:button1"); closeAlertAndGetItsText(); waitForAlertProcess("modalBody"); } @Test public void testJmsHostInNonServerConfig() { String hostText = "host" + generateRandomString(); String instanceName = "in" + generateRandomString(); final String LINK_HOSTS = "treeForm:tree:configurations:" + instanceName + "-config:jmsConfiguration:jmsHosts:jmsHosts_link"; StandaloneTest sat = new StandaloneTest(); sat.createStandAloneInstance(instanceName); sat.startInstance(instanceName); // Create new JMS Host for the standalone instance's config clickAndWait(LINK_HOSTS); clickAndWait("propertyForm:configs:topActionsGroup1:newButton"); setFieldValue("propertyForm:propertySheet:propertSectionTextField:JmsHostTextProp:JmsHostText", hostText); setFieldValue("propertyForm:propertySheet:propertSectionTextField:HostProp:Host", "localhost"); clickAndWait("propertyForm:propertyContentPage:topButtons:newButton"); // Delete the default host for the SA instance gotoDasPage(); clickAndWait(LINK_HOSTS); String prefix = getTableRowByValue("propertyForm:configs", DEFAULT_JMS_HOST, "colName"); String deleteRow = prefix + "col0:select"; clickByIdAction(deleteRow); clickByIdAction("propertyForm:configs:topActionsGroup1:button1"); closeAlertAndGetItsText(); waitForAlertProcess("modalBody"); // Verify that the DAS still has the default JMS Host gotoDasPage(); clickAndWait("treeForm:tree:configurations:server-config:jmsConfiguration:jmsHosts:jmsHosts_link"); assertEquals(DEFAULT_JMS_HOST, getText(prefix + "colName:link")); // Delete SA config's new host gotoDasPage(); clickAndWait(LINK_HOSTS); String prefix1 = getTableRowByValue("propertyForm:configs", hostText, "colName"); String deleteRow1 = prefix1 + "col0:select"; clickByIdAction(deleteRow1); clickByIdAction("propertyForm:configs:topActionsGroup1:button1"); closeAlertAndGetItsText(); waitForAlertProcess("modalBody"); sat.deleteAllStandaloneInstances(); } // //This tests need to be rewrite and retested after the issue has been resolved // @Test // public void testJmsPhysicalDestinations() { // gotoDasPage(); // final String name = "dest" + generateRandomString(); // final String maxUnconsumed = Integer.toString(generateRandomNumber(100)); // final String maxMessageSize = Integer.toString(generateRandomNumber(100)); // final String maxTotalMemory = Integer.toString(generateRandomNumber(100)); // final String maxProducers = Integer.toString(generateRandomNumber(500)); // final String consumerFlowLimit = Integer.toString(generateRandomNumber(5000)); // // clickAndWait("treeForm:tree:applicationServer:applicationServer_link"); // clickAndWait("propertyForm:serverInstTabs:jmsPhysDest"); // clickAndWait("propertyForm:configs:topActionsGroup1:newButton"); // // setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:NameTextProp:NameText", name); // setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumMsgsProp:maxNumMsgs", maxUnconsumed); // setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxBytesPerMsgProp:maxBytesPerMsg", maxMessageSize); // setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxTotalMsgBytesProp:maxTotalMsgBytes", maxTotalMemory); // Select select = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:typeProp:type"))); // select.selectByVisibleText("javax.jms.Queue"); // setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumProducersProp:maxNumProducers", maxProducers); // setFieldValue("jmsPhysDestForm:propertySheet:propertSectionTextField:consumerFlowLimitProp:consumerFlowLimit", consumerFlowLimit); // Select select1 = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:useDmqProp:useDmq"))); // select1.selectByVisibleText("false"); // Select select2 = new Select(driver.findElement(By.id("jmsPhysDestForm:propertySheet:propertSectionTextField:validateSchemaProp:validateXMLSchemaEnabled"))); // select2.selectByVisibleText("true"); // clickAndWait("jmsPhysDestForm:propertyContentPage:topButtons:newButton"); // // String prefix = getTableRowByValue("propertyForm:configs", name, "col1"); // assertEquals(name, getText(prefix + "col1:nameCol")); // // String clickId = prefix + "col1:nameCol"; // clickByIdAction(clickId); // // assertEquals(maxUnconsumed, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxNumMsgsProp:maxNumMsgs", "value")); // assertEquals(maxMessageSize, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxBytesPerMsgProp:maxBytesPerMsg", "value")); // assertEquals(maxTotalMemory, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:maxTotalMsgBytesProp:maxTotalMsgBytes", "value")); // // assertEquals(consumerFlowLimit, getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:consumerFlowLimitProp:consumerFlowLimit", "value")); // assertEquals("true", getValue("jmsPhysDestForm:propertySheet:propertSectionTextField:validateSchemaProp:validateXMLSchemaEnabled", "value")); // clickAndWait("jmsPhysDestForm:propertyContentPage:topButtons:cancelButton"); // // String selectId = prefix + "col0:select"; // clickByIdAction(selectId);; // clickAndWait("propertyForm:configs:topActionsGroup1:flushButton"); // // gotoDasPage(); // clickAndWait("treeForm:tree:applicationServer:applicationServer_link"); // clickAndWait("propertyForm:serverInstTabs:jmsPhysDest"); // deleteRow("propertyForm:configs:topActionsGroup1:deleteButton", "propertyForm:configs", name); // } @Test public void testMasterBroker() { ClusterTest ct = new ClusterTest(); try { final String FIELD_MASTER_BROKER = "propertyForm:propertyContentPage:propertySheet:propertSectionTextField:maseterBrokerProp:MasterBroker"; String clusterName = "clusterName" + generateRandomString(); ct.deleteAllCluster(); final String instance1 = clusterName + generateRandomString(); final String instance2 = clusterName + generateRandomString(); ct.createCluster(clusterName, instance1, instance2); final String ELEMENT_JMS_LINK = "treeForm:tree:configurations:" + clusterName + "-config:jmsConfiguration:jmsConfiguration_link"; clickAndWait(ELEMENT_JMS_LINK); Select select = new Select(driver.findElement(By.id(FIELD_MASTER_BROKER))); select.selectByVisibleText(instance2); clickAndWait("propertyForm:propertyContentPage:topButtons:saveButton"); clickAndWait(ELEMENT_JMS_LINK); assertEquals(instance2, getValue(FIELD_MASTER_BROKER, "value")); } finally { ct.deleteAllCluster(); } } }
LvSongping/GLASSFISH_ADMIN_CONSOLE_DEVTESTS
auto-test/src/test/java/org/glassfish/admingui/devtests/JavaMessageServiceTest.java
Java
apache-2.0
14,315
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v3beta1.model; /** * Metadata for a ConversationDatasets.ImportConversationData operation. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowV2ImportConversationDataOperationMetadata extends com.google.api.client.json.GenericJson { /** * The resource name of the imported conversation dataset. Format: * `projects//locations//conversationDatasets/` * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String conversationDataset; /** * Timestamp when import conversation data request was created. The time is measured on server * side. * The value may be {@code null}. */ @com.google.api.client.util.Key private String createTime; /** * Partial failures are failures that don't fail the whole long running operation, e.g. single * files that couldn't be read. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleRpcStatus> partialFailures; /** * The resource name of the imported conversation dataset. Format: * `projects//locations//conversationDatasets/` * @return value or {@code null} for none */ public java.lang.String getConversationDataset() { return conversationDataset; } /** * The resource name of the imported conversation dataset. Format: * `projects//locations//conversationDatasets/` * @param conversationDataset conversationDataset or {@code null} for none */ public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setConversationDataset(java.lang.String conversationDataset) { this.conversationDataset = conversationDataset; return this; } /** * Timestamp when import conversation data request was created. The time is measured on server * side. * @return value or {@code null} for none */ public String getCreateTime() { return createTime; } /** * Timestamp when import conversation data request was created. The time is measured on server * side. * @param createTime createTime or {@code null} for none */ public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setCreateTime(String createTime) { this.createTime = createTime; return this; } /** * Partial failures are failures that don't fail the whole long running operation, e.g. single * files that couldn't be read. * @return value or {@code null} for none */ public java.util.List<GoogleRpcStatus> getPartialFailures() { return partialFailures; } /** * Partial failures are failures that don't fail the whole long running operation, e.g. single * files that couldn't be read. * @param partialFailures partialFailures or {@code null} for none */ public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setPartialFailures(java.util.List<GoogleRpcStatus> partialFailures) { this.partialFailures = partialFailures; return this; } @Override public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata set(String fieldName, Object value) { return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.set(fieldName, value); } @Override public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata clone() { return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-dialogflow/v3beta1/1.31.0/com/google/api/services/dialogflow/v3beta1/model/GoogleCloudDialogflowV2ImportConversationDataOperationMetadata.java
Java
apache-2.0
4,520
package org.jboss.resteasy.test; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.util.PortProvider; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import javax.ws.rs.client.ClientBuilder; /** * Test utility class * * @author <a href="justin@justinedelson.com">Justin Edelson</a> * @version $Revision$ */ public class TestPortProvider { /** * Creates a ResteasyWebTarget using base request path. */ public static ResteasyWebTarget createTarget(String path) { return (ResteasyWebTarget) ClientBuilder.newClient().target(generateURL(path)); } /** * Create a Resteasy client proxy with an empty base request path. * * @param clazz the client interface class * @return the proxy object */ public static <T> T createProxy(Class<T> clazz) { return createProxy(clazz, generateBaseUrl()); } /** * Create a Resteasy client proxy. * * @param clazz the client interface class * @return the proxy object * @path the base request path */ public static <T> T createProxy(Class<T> clazz, String url) { ResteasyWebTarget target = (ResteasyWebTarget) ResteasyClientBuilder.newClient().target(url); return target.proxy(clazz); } /** * Create a URI for the provided path, using the configured port * * @param path the request path * @return a full URI */ public static URI createURI(String path) { return URI.create(generateURL(path)); } /** * Create a URL for the provided path, using the configured port * * @param path the request path * @return a full URL */ public static URL createURL(String path) throws MalformedURLException { return new URL(generateURL(path)); } /** * Generate a base URL incorporating the configured port. * * @return a full URL */ public static String generateBaseUrl() { return generateURL(""); } /** * Generate a URL incorporating the configured port. * * @param path the path * @return a full URL */ public static String generateURL(String path) { return String.format("http://%s:%d%s", getHost(), getPort(), path); } /** * Look up the configured port number, first checking an environment variable (RESTEASY_PORT), * then a system property (org.jboss.resteasy.port), and finally the default port (8081). * * @return the port number specified in either the environment or system properties */ public static int getPort() { return PortProvider.getPort(); } /** * Look up the configured hostname, first checking an environment variable (RESTEASY_HOST), * then a system property (org.jboss.resteasy.host), and finally the default hostname (localhost). * * @return the host specified in either the environment or system properties */ public static String getHost() { return PortProvider.getHost(); } }
awhitford/Resteasy
resteasy-client/src/main/java/org/jboss/resteasy/test/TestPortProvider.java
Java
apache-2.0
3,100
package com.xiaochen.progressroundbutton; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.animation.PathInterpolatorCompat; import android.util.AttributeSet; import android.widget.TextView; /** * Created by tanfujun on 15/9/4. */ public class AnimDownloadProgressButton extends TextView { private Context mContext; //背景画笔 private Paint mBackgroundPaint; //按钮文字画笔 private volatile Paint mTextPaint; //第一个点画笔 private Paint mDot1Paint; //第二个点画笔 private Paint mDot2Paint; //背景颜色 private int[] mBackgroundColor; private int[] mOriginBackgroundColor; //下载中后半部分后面背景颜色 private int mBackgroundSecondColor; //文字颜色 private int mTextColor; //覆盖后颜色 private int mTextCoverColor; //文字大小 private float mAboveTextSize = 50; private float mProgress = -1; private float mToProgress; private int mMaxProgress; private int mMinProgress; private float mProgressPercent; private float mButtonRadius; //两个点向右移动距离 private float mDot1transX; private float mDot2transX; private RectF mBackgroundBounds; private LinearGradient mFillBgGradient; private LinearGradient mProgressBgGradient; private LinearGradient mProgressTextGradient; //点运动动画 private AnimatorSet mDotAnimationSet; //下载平滑动画 private ValueAnimator mProgressAnimation; //记录当前文字 private CharSequence mCurrentText; //普通状态 public static final int NORMAL = 0; //下载中 public static final int DOWNLOADING = 1; //有点运动状态 public static final int INSTALLING = 2; private ButtonController mDefaultController; private ButtonController mCustomerController; private int mState; public AnimDownloadProgressButton(Context context) { this(context, null); } public AnimDownloadProgressButton(Context context, AttributeSet attrs) { super(context, attrs); if (!isInEditMode()) { mContext = context; initController(); initAttrs(context, attrs); init(); setupAnimations(); }else { initController(); } } private void initController() { mDefaultController = new DefaultButtonController(); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); ButtonController buttonController = switchController(); if (buttonController.enablePress()) { if (mOriginBackgroundColor == null) { mOriginBackgroundColor = new int[2]; mOriginBackgroundColor[0] = mBackgroundColor[0]; mOriginBackgroundColor[1] = mBackgroundColor[1]; } if (this.isPressed()) { int pressColorleft = buttonController.getPressedColor(mBackgroundColor[0]); int pressColorright = buttonController.getPressedColor(mBackgroundColor[1]); if (buttonController.enableGradient()) { initGradientColor(pressColorleft, pressColorright); } else { initGradientColor(pressColorleft, pressColorleft); } } else { if (buttonController.enableGradient()) { initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[1]); } else { initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[0]); } } invalidate(); } } private void initAttrs(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimDownloadProgressButton); int bgColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_color, Color.parseColor("#6699ff")); //初始化背景颜色数组 initGradientColor(bgColor, bgColor); mBackgroundSecondColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_second_color, Color.LTGRAY); mButtonRadius = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_radius, getMeasuredHeight() / 2); mAboveTextSize = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_text_size, 50); mTextColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_color, bgColor); mTextCoverColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_covercolor, Color.WHITE); boolean enableGradient = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_gradient, false); boolean enablePress = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_press, false); ((DefaultButtonController) mDefaultController).setEnableGradient(enableGradient).setEnablePress(enablePress); if (enableGradient){ initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]); } a.recycle(); } private void init() { mMaxProgress = 100; mMinProgress = 0; mProgress = 0; //设置背景画笔 mBackgroundPaint = new Paint(); mBackgroundPaint.setAntiAlias(true); mBackgroundPaint.setStyle(Paint.Style.FILL); //设置文字画笔 mTextPaint = new Paint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(mAboveTextSize); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //解决文字有时候画不出问题 setLayerType(LAYER_TYPE_SOFTWARE, mTextPaint); } //设置第一个点画笔 mDot1Paint = new Paint(); mDot1Paint.setAntiAlias(true); mDot1Paint.setTextSize(mAboveTextSize); //设置第二个点画笔 mDot2Paint = new Paint(); mDot2Paint.setAntiAlias(true); mDot2Paint.setTextSize(mAboveTextSize); //初始化状态设为NORMAL mState = NORMAL; invalidate(); } //初始化渐变色 private int[] initGradientColor(int leftColor, int rightColor) { mBackgroundColor = new int[2]; mBackgroundColor[0] = leftColor; mBackgroundColor[1] = rightColor; return mBackgroundColor; } private void setupAnimations() { //两个点向右移动动画 ValueAnimator dotMoveAnimation = ValueAnimator.ofFloat(0, 20); TimeInterpolator pathInterpolator = PathInterpolatorCompat.create(0.11f, 0f, 0.12f, 1f); dotMoveAnimation.setInterpolator(pathInterpolator); dotMoveAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float transX = (float) animation.getAnimatedValue(); mDot1transX = transX; mDot2transX = transX; invalidate(); } }); dotMoveAnimation.setDuration(1243); dotMoveAnimation.setRepeatMode(ValueAnimator.RESTART); dotMoveAnimation.setRepeatCount(ValueAnimator.INFINITE); //两个点渐显渐隐动画 final ValueAnimator dotAlphaAnim = ValueAnimator.ofInt(0, 1243).setDuration(1243); dotAlphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int time = (int) dotAlphaAnim.getAnimatedValue(); int dot1Alpha = calculateDot1AlphaByTime(time); int dot2Alpha = calculateDot2AlphaByTime(time); mDot1Paint.setColor(mTextCoverColor); mDot2Paint.setColor(mTextCoverColor); mDot1Paint.setAlpha(dot1Alpha); mDot2Paint.setAlpha(dot2Alpha); } }); dotAlphaAnim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { mDot1Paint.setAlpha(0); mDot2Paint.setAlpha(0); } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); dotAlphaAnim.setRepeatMode(ValueAnimator.RESTART); dotAlphaAnim.setRepeatCount(ValueAnimator.INFINITE); //两个点的动画集合 mDotAnimationSet = new AnimatorSet(); mDotAnimationSet.playTogether(dotAlphaAnim, dotMoveAnimation); //ProgressBar的动画 mProgressAnimation = ValueAnimator.ofFloat(0, 1).setDuration(500); mProgressAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float timepercent = (float) animation.getAnimatedValue(); mProgress = ((mToProgress - mProgress) * timepercent + mProgress); invalidate(); } }); } //第一个点透明度计算函数 private int calculateDot2AlphaByTime(int time) { int alpha; if (0 <= time && time <= 83) { double DAlpha = 255.0 / 83.0 * time; alpha = (int) DAlpha; } else if (83 < time && time <= 1000) { alpha = 255; } else if (1000 < time && time <= 1083) { double DAlpha = -255.0 / 83.0 * (time - 1083); alpha = (int) DAlpha; } else if (1083 < time && time <= 1243) { alpha = 0; } else { alpha = 255; } return alpha; } //第二个点透明度计算函数 private int calculateDot1AlphaByTime(int time) { int alpha; if (0 <= time && time <= 160) { alpha = 0; } else if (160 < time && time <= 243) { double DAlpha = 255.0 / 83.0 * (time - 160); alpha = (int) DAlpha; } else if (243 < time && time <= 1160) { alpha = 255; } else if (1160 < time && time <= 1243) { double DAlpha = -255.0 / 83.0 * (time - 1243); alpha = (int) DAlpha; } else { alpha = 255; } return alpha; } private ValueAnimator createDotAlphaAnimation(int i, Paint mDot1Paint, int i1, int i2, int i3) { return new ValueAnimator(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!isInEditMode()) { drawing(canvas); } } private void drawing(Canvas canvas) { drawBackground(canvas); drawTextAbove(canvas); } private void drawBackground(Canvas canvas) { mBackgroundBounds = new RectF(); if (mButtonRadius == 0) { mButtonRadius = getMeasuredHeight() / 2; } mBackgroundBounds.left = 2; mBackgroundBounds.top = 2; mBackgroundBounds.right = getMeasuredWidth() - 2; mBackgroundBounds.bottom = getMeasuredHeight() - 2; ButtonController buttonController = switchController(); //color switch (mState) { case NORMAL: if (buttonController.enableGradient()) { mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2, mBackgroundColor, null, Shader.TileMode.CLAMP); mBackgroundPaint.setShader(mFillBgGradient); } else { if (mBackgroundPaint.getShader() != null) { mBackgroundPaint.setShader(null); } mBackgroundPaint.setColor(mBackgroundColor[0]); } canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint); break; case DOWNLOADING: if (buttonController.enableGradient()) { mProgressPercent = mProgress / (mMaxProgress + 0f); int[] colorList = new int[]{mBackgroundColor[0], mBackgroundColor[1], mBackgroundSecondColor}; mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0, colorList, new float[]{0, mProgressPercent, mProgressPercent + 0.001f}, Shader.TileMode.CLAMP ); mBackgroundPaint.setShader(mProgressBgGradient); } else { mProgressPercent = mProgress / (mMaxProgress + 0f); mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0, new int[]{mBackgroundColor[0], mBackgroundSecondColor}, new float[]{mProgressPercent, mProgressPercent + 0.001f}, Shader.TileMode.CLAMP ); mBackgroundPaint.setColor(mBackgroundColor[0]); mBackgroundPaint.setShader(mProgressBgGradient); } canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint); break; case INSTALLING: if (buttonController.enableGradient()) { mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2, mBackgroundColor, null, Shader.TileMode.CLAMP); mBackgroundPaint.setShader(mFillBgGradient); } else { mBackgroundPaint.setShader(null); mBackgroundPaint.setColor(mBackgroundColor[0]); } canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint); break; } } private void drawTextAbove(Canvas canvas) { final float y = canvas.getHeight() / 2 - (mTextPaint.descent() / 2 + mTextPaint.ascent() / 2); if (mCurrentText == null) { mCurrentText = ""; } final float textWidth = mTextPaint.measureText(mCurrentText.toString()); //color switch (mState) { case NORMAL: mTextPaint.setShader(null); mTextPaint.setColor(mTextCoverColor); canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint); break; case DOWNLOADING: //进度条压过距离 float coverlength = getMeasuredWidth() * mProgressPercent; //开始渐变指示器 float indicator1 = getMeasuredWidth() / 2 - textWidth / 2; //结束渐变指示器 float indicator2 = getMeasuredWidth() / 2 + textWidth / 2; //文字变色部分的距离 float coverTextLength = textWidth / 2 - getMeasuredWidth() / 2 + coverlength; float textProgress = coverTextLength / textWidth; if (coverlength <= indicator1) { mTextPaint.setShader(null); mTextPaint.setColor(mTextColor); } else if (indicator1 < coverlength && coverlength <= indicator2) { mProgressTextGradient = new LinearGradient((getMeasuredWidth() - textWidth) / 2, 0, (getMeasuredWidth() + textWidth) / 2, 0, new int[]{mTextCoverColor, mTextColor}, new float[]{textProgress, textProgress + 0.001f}, Shader.TileMode.CLAMP); mTextPaint.setColor(mTextColor); mTextPaint.setShader(mProgressTextGradient); } else { mTextPaint.setShader(null); mTextPaint.setColor(mTextCoverColor); } canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint); break; case INSTALLING: mTextPaint.setColor(mTextCoverColor); canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint); canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 4 + mDot1transX, y, 4, mDot1Paint); canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 24 + mDot2transX, y, 4, mDot2Paint); break; } } private ButtonController switchController() { if (mCustomerController != null) { return mCustomerController; } else { return mDefaultController; } } public int getState() { return mState; } public void setState(int state) { if (mState != state) {//状态确实有改变 this.mState = state; invalidate(); if (state == AnimDownloadProgressButton.INSTALLING) { //开启两个点动画 mDotAnimationSet.start(); } else if (state == NORMAL) { mDotAnimationSet.cancel(); } else if (state == DOWNLOADING) { mDotAnimationSet.cancel(); } } } /** * 设置按钮文字 */ public void setCurrentText(CharSequence charSequence) { mCurrentText = charSequence; invalidate(); } /** * 设置带下载进度的文字 */ @TargetApi(Build.VERSION_CODES.KITKAT) public void setProgressText(String text, float progress) { if (progress >= mMinProgress && progress < mMaxProgress) { mCurrentText = text + getResources().getString(R.string.downloaded, (int) progress); mToProgress = progress; if (mProgressAnimation.isRunning()) { mProgressAnimation.start(); } else { mProgressAnimation.start(); } } else if (progress < mMinProgress) { mProgress = 0; } else if (progress >= mMaxProgress) { mProgress = 100; mCurrentText = text + getResources().getString(R.string.downloaded, (int) mProgress); invalidate(); } } public float getProgress() { return mProgress; } public void setProgress(float progress) { this.mProgress = progress; } /** * Sometimes you should use the method to avoid memory leak */ public void removeAllAnim() { mDotAnimationSet.cancel(); mDotAnimationSet.removeAllListeners(); mProgressAnimation.cancel(); mProgressAnimation.removeAllListeners(); } public void setProgressBtnBackgroundColor(int color){ initGradientColor(color, color); } public void setProgressBtnBackgroundSecondColor(int color){ mBackgroundSecondColor = color; } public float getButtonRadius() { return mButtonRadius; } public void setButtonRadius(float buttonRadius) { mButtonRadius = buttonRadius; } public int getTextColor() { return mTextColor; } @Override public void setTextColor(int textColor) { mTextColor = textColor; } public int getTextCoverColor() { return mTextCoverColor; } public void setTextCoverColor(int textCoverColor) { mTextCoverColor = textCoverColor; } public int getMinProgress() { return mMinProgress; } public void setMinProgress(int minProgress) { mMinProgress = minProgress; } public int getMaxProgress() { return mMaxProgress; } public void setMaxProgress(int maxProgress) { mMaxProgress = maxProgress; } public void enabelDefaultPress(boolean enable) { if (mDefaultController != null) { ((DefaultButtonController) mDefaultController).setEnablePress(enable); } } public void enabelDefaultGradient(boolean enable) { if (mDefaultController != null) { ((DefaultButtonController) mDefaultController).setEnableGradient(enable); initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]); } } @Override public void setTextSize(float size) { mAboveTextSize = size; mTextPaint.setTextSize(size); } @Override public float getTextSize() { return mAboveTextSize; } public AnimDownloadProgressButton setCustomerController(ButtonController customerController) { mCustomerController = customerController; return this; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mState = ss.state; mProgress = ss.progress; mCurrentText = ss.currentText; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); return new SavedState(superState, (int) mProgress, mState, mCurrentText.toString()); } public static class SavedState extends BaseSavedState { private int progress; private int state; private String currentText; public SavedState(Parcelable parcel, int progress, int state, String currentText) { super(parcel); this.progress = progress; this.state = state; this.currentText = currentText; } private SavedState(Parcel in) { super(in); progress = in.readInt(); state = in.readInt(); currentText = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(progress); out.writeInt(state); out.writeString(currentText); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
Ernest-su/ProgressRoundButton
library/src/main/java/com/xiaochen/progressroundbutton/AnimDownloadProgressButton.java
Java
apache-2.0
23,449
/* * 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. * * Copyright 2012-2020 the original author or authors. */ package org.assertj.core.api.long_; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.test.AlwaysEqualComparator.alwaysEqual; import org.assertj.core.api.LongAssert; import org.assertj.core.api.LongAssertBaseTest; import org.assertj.core.internal.Longs; import org.assertj.core.internal.Objects; import org.junit.jupiter.api.DisplayName; /** * Tests for <code>{@link LongAssert#usingDefaultComparator()}</code>. * * @author Joel Costigliola */ @DisplayName("LongAssert usingDefaultComparator") class LongAssert_usingDefaultComparator_Test extends LongAssertBaseTest { @Override protected LongAssert invoke_api_method() { return assertions.usingComparator(alwaysEqual()).usingDefaultComparator(); } @Override protected void verify_internal_effects() { assertThat(getObjects(assertions)).isSameAs(Objects.instance()); assertThat(getLongs(assertions)).isSameAs(Longs.instance()); } }
joel-costigliola/assertj-core
src/test/java/org/assertj/core/api/long_/LongAssert_usingDefaultComparator_Test.java
Java
apache-2.0
1,561
/* * Copyright (c) 2010-2017 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.testing.sanity; import static com.evolveum.midpoint.prism.util.PrismAsserts.assertEqualsPolyString; import static com.evolveum.midpoint.prism.util.PrismAsserts.assertParentConsistency; import static com.evolveum.midpoint.test.IntegrationTestTools.assertAttributeNotNull; import static com.evolveum.midpoint.test.IntegrationTestTools.assertNoRepoCache; import static com.evolveum.midpoint.test.IntegrationTestTools.assertNotEmpty; import static com.evolveum.midpoint.test.IntegrationTestTools.displayJaxb; import static com.evolveum.midpoint.test.IntegrationTestTools.getAttributeValues; import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import javax.xml.ws.Holder; import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.*; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.xnode.MapXNode; import com.evolveum.midpoint.prism.xnode.XNode; import com.evolveum.midpoint.util.exception.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.opends.server.core.ModifyOperation; import org.opends.server.protocols.internal.InternalSearchOperation; import org.opends.server.types.*; import org.opends.server.types.ModificationType; import org.opends.server.util.ChangeRecordEntry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; import com.evolveum.midpoint.prism.crypto.EncryptionException; import com.evolveum.midpoint.prism.match.MatchingRule; import com.evolveum.midpoint.prism.match.MatchingRuleRegistry; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.schema.SchemaRegistry; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.CapabilityUtil; import com.evolveum.midpoint.schema.DeltaConvertor; import com.evolveum.midpoint.schema.ResultHandler; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; import com.evolveum.midpoint.schema.util.SchemaDebugUtil; import com.evolveum.midpoint.schema.util.SchemaTestConstants; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.test.Checker; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.ObjectChecker; import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.DerbyController; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.JAXBUtil; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.PropertyReferenceListType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectDeltaOperationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectShadowChangeDescriptionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectTypeDefinitionType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SchemaHandlingType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SelectorQualifiedGetOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultType; import com.evolveum.midpoint.xml.ns._public.common.fault_3.ObjectAlreadyExistsFaultType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType; import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType; import com.evolveum.prism.xml.ns._public.query_3.QueryType; import com.evolveum.prism.xml.ns._public.types_3.ChangeTypeType; import com.evolveum.prism.xml.ns._public.types_3.EncryptedDataType; import com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; import com.evolveum.prism.xml.ns._public.types_3.ModificationTypeType; import com.evolveum.prism.xml.ns._public.types_3.ObjectDeltaType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; import com.evolveum.prism.xml.ns._public.types_3.RawType; /** * Sanity test suite. * <p/> * It tests the very basic representative test cases. It does not try to be * complete. It rather should be quick to execute and pass through the most * representative cases. It should test all the system components except for * GUI. Therefore the test cases are selected to pass through most of the * components. * <p/> * It is using embedded H2 repository and embedded OpenDJ instance as a testing * resource. The repository is instantiated from the Spring context in the * same way as all other components. OpenDJ instance is started explicitly using * BeforeClass method. Appropriate resource definition to reach the OpenDJ * instance is provided in the test data and is inserted in the repository as * part of test initialization. * * @author Radovan Semancik */ @ContextConfiguration(locations = {"classpath:ctx-sanity-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSanity extends AbstractModelIntegrationTest { private static final String REPO_DIR_NAME = "src/test/resources/repo/"; private static final String REQUEST_DIR_NAME = "src/test/resources/request/"; private static final File REQUEST_DIR = new File(REQUEST_DIR_NAME); private static final String SYSTEM_CONFIGURATION_FILENAME = REPO_DIR_NAME + "system-configuration.xml"; private static final String SYSTEM_CONFIGURATION_OID = "00000000-0000-0000-0000-000000000001"; private static final String ROLE_SUPERUSER_FILENAME = REPO_DIR_NAME + "role-superuser.xml"; private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004"; private static final String RESOURCE_OPENDJ_FILENAME = REPO_DIR_NAME + "resource-opendj.xml"; private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; protected static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS,"inetOrgPerson"); private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID"; private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn"; private static final String RESOURCE_DERBY_FILENAME = REPO_DIR_NAME + "resource-derby.xml"; private static final String RESOURCE_DERBY_OID = "ef2bc95b-76e0-59e2-86d6-999902d3abab"; private static final String RESOURCE_BROKEN_FILENAME = REPO_DIR_NAME + "resource-broken.xml"; private static final String RESOURCE_BROKEN_OID = "ef2bc95b-76e0-59e2-ffff-ffffffffffff"; private static final String RESOURCE_DUMMY_FILENAME = REPO_DIR_NAME + "resource-dummy.xml"; private static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000004"; private static final String CONNECTOR_LDAP_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector"; private static final String CONNECTOR_DBTABLE_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-databasetable/org.identityconnectors.databasetable.DatabaseTableConnector"; private static final String CONNECTOR_BROKEN_FILENAME = REPO_DIR_NAME + "connector-broken.xml"; private static final String CONNECTOR_BROKEN_OID = "cccccccc-76e0-59e2-ffff-ffffffffffff"; private static final String TASK_OPENDJ_SYNC_FILENAME = REPO_DIR_NAME + "task-opendj-sync.xml"; private static final String TASK_OPENDJ_SYNC_OID = "91919191-76e0-59e2-86d6-3d4f02d3ffff"; private static final String TASK_USER_RECOMPUTE_FILENAME = REPO_DIR_NAME + "task-user-recompute.xml"; private static final String TASK_USER_RECOMPUTE_OID = "91919191-76e0-59e2-86d6-3d4f02d3aaaa"; private static final String TASK_OPENDJ_RECON_FILENAME = REPO_DIR_NAME + "task-opendj-reconciliation.xml"; private static final String TASK_OPENDJ_RECON_OID = "91919191-76e0-59e2-86d6-3d4f02d30000"; private static final String SAMPLE_CONFIGURATION_OBJECT_FILENAME = REPO_DIR_NAME + "sample-configuration-object.xml"; private static final String SAMPLE_CONFIGURATION_OBJECT_OID = "c0c010c0-d34d-b33f-f00d-999111111111"; private static final String USER_TEMPLATE_FILENAME = REPO_DIR_NAME + "user-template.xml"; private static final String USER_TEMPLATE_OID = "c0c010c0-d34d-b33f-f00d-777111111111"; private static final String USER_ADMINISTRATOR_FILENAME = REPO_DIR_NAME + "user-administrator.xml"; private static final String USER_ADMINISTRATOR_NAME = "administrator"; private static final String USER_ADMINISTRATOR_OID = "00000000-0000-0000-0000-000000000002"; private static final String USER_JACK_FILENAME = REPO_DIR_NAME + "user-jack.xml"; private static final File USER_JACK_FILE = new File(USER_JACK_FILENAME); private static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; private static final String USER_JACK_LDAP_UID = "jack"; private static final String USER_JACK_LDAP_DN = "uid=" + USER_JACK_LDAP_UID + "," + OPENDJ_PEOPLE_SUFFIX; private static final String USER_GUYBRUSH_FILENAME = REPO_DIR_NAME + "user-guybrush.xml"; private static final File USER_GUYBRUSH_FILE = new File(USER_GUYBRUSH_FILENAME); private static final String USER_GUYBRUSH_OID = "c0c010c0-d34d-b33f-f00d-111111111222"; private static final String USER_GUYBRUSH_USERNAME = "guybrush"; private static final String USER_GUYBRUSH_LDAP_UID = "guybrush"; private static final String USER_GUYBRUSH_LDAP_DN = "uid=" + USER_GUYBRUSH_LDAP_UID + "," + OPENDJ_PEOPLE_SUFFIX; private static final String USER_E_LINK_ACTION_FILENAME = REPO_DIR_NAME + "user-e.xml"; private static final File USER_E_LINK_ACTION_FILE = new File(USER_E_LINK_ACTION_FILENAME); private static final String LDIF_E_FILENAME_LINK = "src/test/resources/request/e-create.ldif"; private static final String ROLE_PIRATE_FILENAME = REPO_DIR_NAME + "role-pirate.xml"; private static final String ROLE_PIRATE_OID = "12345678-d34d-b33f-f00d-987987987988"; private static final String ROLE_SAILOR_FILENAME = REPO_DIR_NAME + "role-sailor.xml"; private static final String ROLE_SAILOR_OID = "12345678-d34d-b33f-f00d-987955553535"; private static final String ROLE_CAPTAIN_FILENAME = REPO_DIR_NAME + "role-captain.xml"; private static final String ROLE_CAPTAIN_OID = "12345678-d34d-b33f-f00d-987987cccccc"; private static final String ROLE_JUDGE_FILENAME = REPO_DIR_NAME + "role-judge.xml"; private static final String ROLE_JUDGE_OID = "12345111-1111-2222-1111-121212111111"; private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account.xml"; private static final String REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME = REQUEST_DIR_NAME + "user-modify-add-account-derby.xml"; private static final String USER_JACK_DERBY_LOGIN = "jsparrow"; private static final String REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME = REQUEST_DIR_NAME + "user-modify-fullname-locality.xml"; private static final String REQUEST_USER_MODIFY_GIVENNAME_FILENAME = REQUEST_DIR_NAME + "user-modify-givenname.xml"; private static final String REQUEST_USER_MODIFY_PASSWORD_FILENAME = REQUEST_DIR_NAME + "user-modify-password.xml"; private static final String REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-disable.xml"; private static final String REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME = REQUEST_DIR_NAME + "user-modify-activation-enable.xml"; private static final String REQUEST_USER_MODIFY_NAME_FILENAME = REQUEST_DIR_NAME + "user-modify-name.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-pirate.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-1.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-captain-2.xml"; private static final String REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME = REQUEST_DIR_NAME + "user-modify-add-role-judge.xml"; private static final String REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-pirate.xml"; private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-1.xml"; private static final String REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME = REQUEST_DIR_NAME + "user-modify-delete-role-captain-2.xml"; private static final File REQUEST_ACCOUNT_MODIFY_ATTRS_FILE = new File(REQUEST_DIR, "account-modify-attrs.xml"); private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE = new File(REQUEST_DIR, "account-modify-roomnumber.xml"); private static final File REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE = new File(REQUEST_DIR, "account-modify-roomnumber-explicit-type.xml"); private static final File REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE = new File(REQUEST_DIR, "account-modify-bad-path.xml"); private static final String LDIF_WILL_FILENAME = REQUEST_DIR_NAME + "will.ldif"; private static final File LDIF_WILL_MODIFY_FILE = new File (REQUEST_DIR_NAME, "will-modify.ldif"); private static final String LDIF_WILL_WITHOUT_LOCATION_FILENAME = REQUEST_DIR_NAME + "will-without-location.ldif"; private static final String WILL_NAME = "wturner"; private static final String LDIF_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "angelika.ldif"; private static final String ANGELIKA_NAME = "angelika"; private static final String ACCOUNT_ANGELIKA_FILENAME = REQUEST_DIR_NAME + "account-angelika.xml"; private static final String LDIF_ELAINE_FILENAME = REQUEST_DIR_NAME + "elaine.ldif"; private static final String ELAINE_NAME = "elaine"; private static final File LDIF_GIBBS_MODIFY_FILE = new File (REQUEST_DIR_NAME, "gibbs-modify.ldif"); private static final String LDIF_HERMAN_FILENAME = REQUEST_DIR_NAME + "herman.ldif"; private static final Trace LOGGER = TraceManager.getTrace(TestSanity.class); private static final String NS_MY = "http://whatever.com/my"; private static final ItemName MY_SHIP_STATE = new ItemName(NS_MY, "shipState"); private static final ItemName MY_DEAD = new ItemName(NS_MY, "dead"); private static final long WAIT_FOR_LOOP_SLEEP_MILIS = 1000; /** * Unmarshalled resource definition to reach the embedded OpenDJ instance. * Used for convenience - the tests method may find it handy. */ private static ResourceType resourceTypeOpenDjrepo; private static ResourceType resourceDerby; private static String accountShadowOidOpendj; private static String accountShadowOidDerby; private static String accountShadowOidGuybrushOpendj; private static String accountGuybrushOpendjEntryUuuid = null; private static String originalJacksLdapPassword; private static String lastJacksLdapPassword = null; private int lastSyncToken; @Autowired(required = true) private MatchingRuleRegistry matchingRuleRegistry; // This will get called from the superclass to init the repository // It will be called only once public void initSystem(Task initTask, OperationResult initResult) throws Exception { LOGGER.trace("initSystem"); try{ super.initSystem(initTask, initResult); repoAddObjectFromFile(ROLE_SUPERUSER_FILENAME, initResult); repoAddObjectFromFile(USER_ADMINISTRATOR_FILENAME, initResult); // This should discover the connectors LOGGER.trace("initSystem: trying modelService.postInit()"); modelService.postInit(initResult); LOGGER.trace("initSystem: modelService.postInit() done"); login(USER_ADMINISTRATOR_NAME); // We need to add config after calling postInit() so it will not be applied. // we want original logging configuration from the test logback config file, not // the one from the system config. repoAddObjectFromFile(SYSTEM_CONFIGURATION_FILENAME, initResult); // Add broken connector before importing resources repoAddObjectFromFile(CONNECTOR_BROKEN_FILENAME, initResult); // Need to import instead of add, so the (dynamic) connector reference // will be resolved // correctly importObjectFromFile(RESOURCE_OPENDJ_FILENAME, initResult); importObjectFromFile(RESOURCE_BROKEN_FILENAME, initResult); repoAddObjectFromFile(SAMPLE_CONFIGURATION_OBJECT_FILENAME, initResult); repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult); repoAddObjectFromFile(ROLE_SAILOR_FILENAME, initResult); repoAddObjectFromFile(ROLE_PIRATE_FILENAME, initResult); repoAddObjectFromFile(ROLE_CAPTAIN_FILENAME, initResult); repoAddObjectFromFile(ROLE_JUDGE_FILENAME, initResult); } catch (Exception ex){ LOGGER.error("erro: {}", ex); throw ex; } } /** * Initialize embedded OpenDJ instance Note: this is not in the abstract * superclass so individual tests may avoid starting OpenDJ. */ @Override public void startResources() throws Exception { openDJController.startCleanServer(); derbyController.startCleanServer(); } /** * Shutdown embedded OpenDJ instance Note: this is not in the abstract * superclass so individual tests may avoid starting OpenDJ. */ @AfterClass public static void stopResources() throws Exception { openDJController.stop(); derbyController.stop(); } /** * Test integrity of the test setup. * * @throws SchemaException * @throws ObjectNotFoundException * @throws CommunicationException */ @Test public void test000Integrity() throws Exception { final String TEST_NAME = "test000Integrity"; TestUtil.displayTestTitle(this, TEST_NAME); assertNotNull(modelWeb); assertNotNull(modelService); assertNotNull(repositoryService); assertTrue(isSystemInitialized()); assertNotNull(taskManager); assertNotNull(prismContext); SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry(); assertNotNull(schemaRegistry); // This is defined in extra schema. So this effectively checks whether the extra schema was loaded PrismPropertyDefinition shipStateDefinition = schemaRegistry.findPropertyDefinitionByElementName(MY_SHIP_STATE); assertNotNull("No my:shipState definition", shipStateDefinition); assertEquals("Wrong maxOccurs in my:shipState definition", 1, shipStateDefinition.getMaxOccurs()); assertNoRepoCache(); Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test000Integrity"); OperationResult result = task.getResult(); // Check if OpenDJ resource was imported correctly PrismObject<ResourceType> openDjResource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); display("Imported OpenDJ resource (repository)", openDjResource); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, openDjResource.getOid()); assertNoRepoCache(); String ldapConnectorOid = openDjResource.asObjectable().getConnectorRef().getOid(); PrismObject<ConnectorType> ldapConnector = repositoryService.getObject(ConnectorType.class, ldapConnectorOid, null, result); display("LDAP Connector: ", ldapConnector); // TODO: test if OpenDJ and Derby are running repositoryService.getObject(GenericObjectType.class, SAMPLE_CONFIGURATION_OBJECT_OID, null, result); } /** * Repeat self-test when we have all the dependencies on the classpath. */ @Test public void test001SelfTests() throws Exception { final String TEST_NAME = "test001SelfTests"; displayTestTitle(TEST_NAME); // GIVEN Task task = taskManager.createTaskInstance(TestSanity.class.getName()+"."+TEST_NAME); // WHEN OperationResult repositorySelfTestResult = modelDiagnosticService.repositorySelfTest(task); // THEN assertSuccess("Repository self test", repositorySelfTestResult); // WHEN OperationResult provisioningSelfTestResult = modelDiagnosticService.provisioningSelfTest(task); // THEN display("Repository self test result", provisioningSelfTestResult); // There may be warning about illegal key size on some platforms. As far as it is warning and not error we are OK // the system will fall back to a interoperable key size if (provisioningSelfTestResult.getStatus() != OperationResultStatus.SUCCESS && provisioningSelfTestResult.getStatus() != OperationResultStatus.WARNING) { AssertJUnit.fail("Provisioning self-test failed: "+provisioningSelfTestResult); } } /** * Test the testResource method. Expect a complete success for now. */ @Test public void test001TestConnectionOpenDJ() throws Exception { final String TEST_NAME = "test001TestConnectionOpenDJ"; displayTestTitle(TEST_NAME); // GIVEN try{ assertNoRepoCache(); // WHEN OperationResultType result = modelWeb.testResource(RESOURCE_OPENDJ_OID); // THEN assertNoRepoCache(); displayJaxb("testResource result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("testResource has failed", result); OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test001TestConnectionOpenDJ"); PrismObject<ResourceType> resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult); resourceTypeOpenDjrepo = resourceOpenDjRepo.asObjectable(); assertNoRepoCache(); assertEquals(RESOURCE_OPENDJ_OID, resourceTypeOpenDjrepo.getOid()); display("Initialized OpenDJ resource (respository)", resourceTypeOpenDjrepo); assertNotNull("Resource schema was not generated", resourceTypeOpenDjrepo.getSchema()); Element resourceOpenDjXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceTypeOpenDjrepo); assertNotNull("Resource schema was not generated", resourceOpenDjXsdSchemaElement); PrismObject<ResourceType> openDjResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult); display("Initialized OpenDJ resource resource (provisioning)", openDjResourceProvisioninig); PrismObject<ResourceType> openDjResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, null, opResult); display("Initialized OpenDJ resource OpenDJ resource (model)", openDjResourceModel); checkOpenDjResource(resourceTypeOpenDjrepo, "repository"); System.out.println("------------------------------------------------------------------"); display("OpenDJ resource schema (repo XML)", DOMUtil.serializeDOMToString(ResourceTypeUtil.getResourceXsdSchema(resourceOpenDjRepo))); System.out.println("------------------------------------------------------------------"); checkOpenDjResource(openDjResourceProvisioninig.asObjectable(), "provisioning"); checkOpenDjResource(openDjResourceModel.asObjectable(), "model"); // TODO: model web } catch (Exception ex){ LOGGER.info("exception: " + ex); throw ex; } } private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoOpenDjResource"); PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); checkOpenDjResource(resource.asObjectable(), "repository"); } /** * Checks if the resource is internally consistent, if it has everything it should have. * * @throws SchemaException */ private void checkOpenDjResource(ResourceType resource, String source) throws SchemaException { assertNotNull("Resource from " + source + " is null", resource); ObjectReferenceType connectorRefType = resource.getConnectorRef(); assertNotNull("Resource from " + source + " has null connectorRef", connectorRefType); assertFalse("Resource from " + source + " has no OID in connectorRef", StringUtils.isBlank(connectorRefType.getOid())); assertNotNull("Resource from " + source + " has null description in connectorRef", connectorRefType.getDescription()); assertNotNull("Resource from " + source + " has null filter in connectorRef", connectorRefType.getFilter()); assertNotNull("Resource from " + source + " has null filter element in connectorRef", connectorRefType.getFilter().getFilterClauseXNode()); assertNotNull("Resource from " + source + " has null configuration", resource.getConnectorConfiguration()); assertNotNull("Resource from " + source + " has null schema", resource.getSchema()); checkOpenDjSchema(resource, source); assertNotNull("Resource from " + source + " has null schemahandling", resource.getSchemaHandling()); checkOpenDjSchemaHandling(resource, source); if (!source.equals("repository")) { // This is generated on the fly in provisioning assertNotNull("Resource from " + source + " has null nativeCapabilities", resource.getCapabilities().getNative()); assertFalse("Resource from " + source + " has empty nativeCapabilities", resource.getCapabilities().getNative().getAny().isEmpty()); } assertNotNull("Resource from " + source + " has null configured capabilities", resource.getCapabilities().getConfigured()); assertFalse("Resource from " + source + " has empty capabilities", resource.getCapabilities().getConfigured().getAny().isEmpty()); assertNotNull("Resource from " + source + " has null synchronization", resource.getSynchronization()); checkOpenDjConfiguration(resource.asPrismObject(), source); } private void checkOpenDjSchema(ResourceType resource, String source) throws SchemaException { ResourceSchema schema = RefinedResourceSchemaImpl.getResourceSchema(resource, prismContext); ObjectClassComplexTypeDefinition accountDefinition = schema.findObjectClassDefinition(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS); assertNotNull("Schema does not define any account (resource from " + source + ")", accountDefinition); Collection<? extends ResourceAttributeDefinition> identifiers = accountDefinition.getPrimaryIdentifiers(); assertFalse("No account identifiers (resource from " + source + ")", identifiers == null || identifiers.isEmpty()); // TODO: check for naming attributes and display names, etc ActivationCapabilityType capActivation = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class); if (capActivation != null && capActivation.getStatus() != null && capActivation.getStatus().getAttribute() != null) { // There is simulated activation capability, check if the attribute is in schema. QName enableAttrName = capActivation.getStatus().getAttribute(); ResourceAttributeDefinition enableAttrDef = accountDefinition.findAttributeDefinition(enableAttrName); display("Simulated activation attribute definition", enableAttrDef); assertNotNull("No definition for enable attribute " + enableAttrName + " in account (resource from " + source + ")", enableAttrDef); assertTrue("Enable attribute " + enableAttrName + " is not ignored (resource from " + source + ")", enableAttrDef.isIgnored()); } } private void checkOpenDjSchemaHandling(ResourceType resource, String source) { SchemaHandlingType schemaHandling = resource.getSchemaHandling(); for (ResourceObjectTypeDefinitionType resObjectTypeDef: schemaHandling.getObjectType()) { if (resObjectTypeDef.getKind() == ShadowKindType.ACCOUNT) { String name = resObjectTypeDef.getIntent(); assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig account definition without intent", name); assertNotNull("Account type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass()); } if (resObjectTypeDef.getKind() == ShadowKindType.ENTITLEMENT) { String name = resObjectTypeDef.getIntent(); assertNotNull("Resource "+resource+" from "+source+" has an schemaHandlig entitlement definition without intent", name); assertNotNull("Entitlement type "+name+" in "+resource+" from "+source+" does not have object class", resObjectTypeDef.getObjectClass()); } } } private void checkOpenDjConfiguration(PrismObject<ResourceType> resource, String source) { checkOpenResourceConfiguration(resource, CONNECTOR_LDAP_NAMESPACE, "bindPassword", 8, source); } private void checkOpenResourceConfiguration(PrismObject<ResourceType> resource, String connectorNamespace, String credentialsPropertyName, int numConfigProps, String source) { PrismContainer<Containerable> configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertNotNull("No configuration container in "+resource+" from "+source, configurationContainer); PrismContainer<Containerable> configPropsContainer = configurationContainer.findContainer(SchemaTestConstants.ICFC_CONFIGURATION_PROPERTIES); assertNotNull("No configuration properties container in "+resource+" from "+source, configPropsContainer); Collection<? extends Item<?,?>> configProps = configPropsContainer.getValue().getItems(); assertEquals("Wrong number of config properties in "+resource+" from "+source, numConfigProps, configProps.size()); PrismProperty<Object> credentialsProp = configPropsContainer.findProperty(new ItemName(connectorNamespace,credentialsPropertyName)); if (credentialsProp == null) { // The is the heisenbug we are looking for. Just dump the entire damn thing. display("Configuration with the heisenbug", configurationContainer.debugDump()); } assertNotNull("No "+credentialsPropertyName+" property in "+resource+" from "+source, credentialsProp); assertEquals("Wrong number of "+credentialsPropertyName+" property value in "+resource+" from "+source, 1, credentialsProp.getValues().size()); PrismPropertyValue<Object> credentialsPropertyValue = credentialsProp.getValues().iterator().next(); assertNotNull("No "+credentialsPropertyName+" property value in "+resource+" from "+source, credentialsPropertyValue); if (credentialsPropertyValue.isRaw()) { Object rawElement = credentialsPropertyValue.getRawElement(); assertTrue("Wrong element class "+rawElement.getClass()+" in "+resource+" from "+source, rawElement instanceof MapXNode); // Element rawDomElement = (Element)rawElement; MapXNode xmap = (MapXNode) rawElement; try{ ProtectedStringType protectedType = new ProtectedStringType(); prismContext.hacks().parseProtectedType(protectedType, xmap, prismContext, prismContext.getDefaultParsingContext()); // display("LDAP credentials raw element", DOMUtil.serializeDOMToString(rawDomElement)); // assertEquals("Wrong credentials element namespace in "+resource+" from "+source, connectorNamespace, rawDomElement.getNamespaceURI()); // assertEquals("Wrong credentials element local name in "+resource+" from "+source, credentialsPropertyName, rawDomElement.getLocalName()); // Element encryptedDataElement = DOMUtil.getChildElement(rawDomElement, new QName(DOMUtil.NS_XML_ENC, "EncryptedData")); EncryptedDataType encryptedDataType = protectedType.getEncryptedDataType(); assertNotNull("No EncryptedData element", encryptedDataType); } catch (SchemaException ex){ throw new IllegalArgumentException(ex); } // assertEquals("Wrong EncryptedData element namespace in "+resource+" from "+source, DOMUtil.NS_XML_ENC, encryptedDataType.getNamespaceURI()); // assertEquals("Wrong EncryptedData element local name in "+resource+" from "+source, "EncryptedData", encryptedDataType.getLocalName()); } else { Object credentials = credentialsPropertyValue.getValue(); assertTrue("Wrong type of credentials configuration property in "+resource+" from "+source+": "+credentials.getClass(), credentials instanceof ProtectedStringType); ProtectedStringType credentialsPs = (ProtectedStringType)credentials; EncryptedDataType encryptedData = credentialsPs.getEncryptedDataType(); assertNotNull("No EncryptedData element", encryptedData); } } @Test public void test002AddDerbyResource() throws Exception { final String TEST_NAME = "test002AddDerbyResource"; displayTestTitle(TEST_NAME); // GIVEN OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); checkRepoOpenDjResource(); assertNoRepoCache(); PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DERBY_FILENAME)); assertParentConsistency(resource); fillInConnectorRef(resource, IntegrationTestTools.DBTABLE_CONNECTOR_TYPE, result); OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<String> oidHolder = new Holder<>(); display("Adding Derby Resource", resource); // WHEN addObjectViaModelWS(resource.asObjectable(), null, oidHolder, resultHolder); // THEN // Check if Derby resource was imported correctly PrismObject<ResourceType> derbyResource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); AssertJUnit.assertEquals(RESOURCE_DERBY_OID, derbyResource.getOid()); assertNoRepoCache(); String dbConnectorOid = derbyResource.asObjectable().getConnectorRef().getOid(); PrismObject<ConnectorType> dbConnector = repositoryService.getObject(ConnectorType.class, dbConnectorOid, null, result); display("DB Connector: ", dbConnector); // Check if password was encrypted during import // via JAXB Object configurationPropertiesElement = JAXBUtil.findElement(derbyResource.asObjectable().getConnectorConfiguration().getAny(), new QName(dbConnector.asObjectable().getNamespace(), "configurationProperties")); Object passwordElement = JAXBUtil.findElement(JAXBUtil.listChildElements(configurationPropertiesElement), new QName(dbConnector.asObjectable().getNamespace(), "password")); System.out.println("Password element: " + passwordElement); // via prisms PrismContainerValue configurationProperties = derbyResource.findContainer( ItemPath.create( ResourceType.F_CONNECTOR_CONFIGURATION, new QName("configurationProperties"))) .getValue(); PrismProperty password = configurationProperties.findProperty(new ItemName(dbConnector.asObjectable().getNamespace(), "password")); System.out.println("Password property: " + password); } private void addObjectViaModelWS(ObjectType objectType, ModelExecuteOptionsType options, Holder<String> oidHolder, Holder<OperationResultType> resultHolder) throws FaultMessage { ObjectDeltaListType deltaList = new ObjectDeltaListType(); ObjectDeltaType objectDelta = new ObjectDeltaType(); objectDelta.setObjectToAdd(objectType); QName type = objectType.asPrismObject().getDefinition().getTypeName(); objectDelta.setObjectType(type); objectDelta.setChangeType(ChangeTypeType.ADD); deltaList.getDelta().add(objectDelta); ObjectDeltaOperationListType objectDeltaOperationListType = modelWeb.executeChanges(deltaList, options); ObjectDeltaOperationType objectDeltaOperationType = getOdoFromDeltaOperationList(objectDeltaOperationListType, objectDelta); resultHolder.value = objectDeltaOperationType.getExecutionResult(); oidHolder.value = ((ObjectType) objectDeltaOperationType.getObjectDelta().getObjectToAdd()).getOid(); } // ugly hack... private static ObjectDeltaOperationType getOdoFromDeltaOperationList(ObjectDeltaOperationListType operationListType, ObjectDeltaType originalDelta) { Validate.notNull(operationListType); Validate.notNull(originalDelta); for (ObjectDeltaOperationType operationType : operationListType.getDeltaOperation()) { ObjectDeltaType objectDeltaType = operationType.getObjectDelta(); if (originalDelta.getChangeType() == ChangeTypeType.ADD) { if (objectDeltaType.getChangeType() == originalDelta.getChangeType() && objectDeltaType.getObjectToAdd() != null) { ObjectType objectAdded = (ObjectType) objectDeltaType.getObjectToAdd(); if (objectAdded.getClass().equals(originalDelta.getObjectToAdd().getClass())) { return operationType; } } } else { if (objectDeltaType.getChangeType() == originalDelta.getChangeType() && originalDelta.getOid().equals(objectDeltaType.getOid())) { return operationType; } } } throw new IllegalStateException("No suitable ObjectDeltaOperationType found"); } private void checkRepoDerbyResource() throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(TestSanity.class.getName()+".checkRepoDerbyResource"); PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, result); checkDerbyResource(resource, "repository"); } private void checkDerbyResource(PrismObject<ResourceType> resource, String source) { checkDerbyConfiguration(resource, source); } private void checkDerbyConfiguration(PrismObject<ResourceType> resource, String source) { checkOpenResourceConfiguration(resource, CONNECTOR_DBTABLE_NAMESPACE, "password", 10, source); } /** * Test the testResource method. Expect a complete success for now. */ @Test public void test003TestConnectionDerby() throws Exception { TestUtil.displayTestTitle("test003TestConnectionDerby"); // GIVEN checkRepoDerbyResource(); assertNoRepoCache(); // WHEN OperationResultType result = modelWeb.testResource(RESOURCE_DERBY_OID); // THEN assertNoRepoCache(); displayJaxb("testResource result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("testResource has failed", result.getPartialResults().get(0)); OperationResult opResult = new OperationResult(TestSanity.class.getName() + ".test002TestConnectionDerby"); PrismObject<ResourceType> rObject = repositoryService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, opResult); resourceDerby = rObject.asObjectable(); checkDerbyResource(rObject, "repository(after test)"); assertNoRepoCache(); assertEquals(RESOURCE_DERBY_OID, resourceDerby.getOid()); display("Initialized Derby resource (respository)", resourceDerby); assertNotNull("Resource schema was not generated", resourceDerby.getSchema()); Element resourceDerbyXsdSchemaElement = ResourceTypeUtil.getResourceXsdSchema(resourceDerby); assertNotNull("Resource schema was not generated", resourceDerbyXsdSchemaElement); PrismObject<ResourceType> derbyResourceProvisioninig = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, null, opResult); display("Initialized Derby resource (provisioning)", derbyResourceProvisioninig); PrismObject<ResourceType> derbyResourceModel = provisioningService.getObject(ResourceType.class, RESOURCE_DERBY_OID, null, null, opResult); display("Initialized Derby resource (model)", derbyResourceModel); // TODO: check // checkOpenDjResource(resourceOpenDj,"repository"); // checkOpenDjResource(openDjResourceProvisioninig,"provisioning"); // checkOpenDjResource(openDjResourceModel,"model"); // TODO: model web } @Test public void test004Capabilities() throws ObjectNotFoundException, CommunicationException, SchemaException, FaultMessage { TestUtil.displayTestTitle("test004Capabilities"); // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.getObject(ObjectTypes.RESOURCE.getTypeQName(), RESOURCE_OPENDJ_OID, options , objectHolder, resultHolder); ResourceType resource = (ResourceType) objectHolder.value; // THEN display("Resource", resource); assertNoRepoCache(); CapabilityCollectionType nativeCapabilities = resource.getCapabilities().getNative(); List<Object> capabilities = nativeCapabilities.getAny(); assertFalse("Empty capabilities returned", capabilities.isEmpty()); for (Object capability : nativeCapabilities.getAny()) { System.out.println("Native Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } if (resource.getCapabilities() != null) { for (Object capability : resource.getCapabilities().getConfigured().getAny()) { System.out.println("Configured Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } } List<Object> effectiveCapabilities = ResourceTypeUtil.getEffectiveCapabilities(resource); for (Object capability : effectiveCapabilities) { System.out.println("Efective Capability: " + CapabilityUtil.getCapabilityDisplayName(capability) + " : " + capability); } CredentialsCapabilityType capCred = CapabilityUtil.getCapability(capabilities, CredentialsCapabilityType.class); assertNotNull("password capability not present", capCred.getPassword()); // Connector cannot do activation, this should be null ActivationCapabilityType capAct = CapabilityUtil.getCapability(capabilities, ActivationCapabilityType.class); assertNull("Found activation capability while not expecting it", capAct); capCred = ResourceTypeUtil.getEffectiveCapability(resource, CredentialsCapabilityType.class); assertNotNull("password capability not found", capCred.getPassword()); // Although connector does not support activation, the resource specifies a way how to simulate it. // Therefore the following should succeed capAct = ResourceTypeUtil.getEffectiveCapability(resource, ActivationCapabilityType.class); assertNotNull("activation capability not found", capAct); } @Test public void test005resolveConnectorRef() throws Exception{ TestUtil.displayTestTitle("test005resolveConnectorRef"); PrismObject<ResourceType> resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); ModelExecuteOptionsType options = new ModelExecuteOptionsType(); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>()); OperationResult repoResult = new OperationResult("getObject"); PrismObject<ResourceType> uObject = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); assertNotNull(uObject); ResourceType resourceType = uObject.asObjectable(); assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); } @Test public void test006reimportResourceDummy() throws Exception{ TestUtil.displayTestTitle("test006reimportResourceDummy"); //get object from repo (with version set and try to add it - it should be re-added, without error) OperationResult repoResult = new OperationResult("getObject"); PrismObject<ResourceType> resource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, repoResult); assertNotNull(resource); ModelExecuteOptionsType options = new ModelExecuteOptionsType(); options.setOverwrite(Boolean.TRUE); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), new Holder<>()); //TODO: add some asserts //parse object from file again and try to add it - this should fail, becasue the same object already exists) resource = PrismTestUtil.parseObject(new File(RESOURCE_DUMMY_FILENAME)); try { Holder<OperationResultType> resultHolder = new Holder<>(); options = new ModelExecuteOptionsType(); options.setIsImport(Boolean.TRUE); addObjectViaModelWS(resource.asObjectable(), options, new Holder<>(), resultHolder); OperationResultType result = resultHolder.value; TestUtil.assertFailure(result); fail("Expected object already exists exception, but haven't got one."); } catch (FaultMessage ex) { LOGGER.info("fault {}", ex.getFaultInfo()); LOGGER.info("fault {}", ex.getCause()); if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType) { // this is OK, we expect this } else{ fail("Expected object already exists exception, but got: " + ex.getFaultInfo()); } } // ResourceType resourceType = uObject.asObjectable(); // assertNotNull("Reference on the connector must not be null in resource.",resourceType.getConnectorRef()); // assertNotNull("Missing oid reference on the connector",resourceType.getConnectorRef().getOid()); } /** * Attempt to add new user. It is only added to the repository, so check if * it is in the repository after the operation. */ @Test public void test010AddUser() throws Exception { final String TEST_NAME = "test010AddUser"; displayTestTitle(TEST_NAME); // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); PrismObject<UserType> user = PrismTestUtil.parseObject(USER_JACK_FILE); UserType userType = user.asObjectable(); assertParentConsistency(user); // Encrypt Jack's password protector.encrypt(userType.getCredentials().getPassword().getValue()); assertParentConsistency(user); OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<String> oidHolder = new Holder<>(); display("Adding user object", userType); // WHEN addObjectViaModelWS(userType, null, oidHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("addObject has failed", resultHolder.value); // AssertJUnit.assertEquals(USER_JACK_OID, oid); OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("repository.getObject result", repoResult); TestUtil.assertSuccess("getObject has failed", repoResult); AssertJUnit.assertEquals(USER_JACK_OID, repoUser.getOid()); assertEqualsPolyString("fullName", userType.getFullName(), repoUser.getFullName()); // TODO: better checks } /** * Add account to user. This should result in account provisioning. Check if * that happens in repo and in LDAP. */ @Test public void test013AddOpenDjAccountToUser() throws Exception { final String TEST_NAME = "test013AddOpenDjAccountToUser"; displayTestTitle(TEST_NAME); try{ // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); // IMPORTANT! SWITCHING OFF ASSIGNMENT ENFORCEMENT HERE! setAssignmentEnforcement(AssignmentPolicyEnforcementType.NONE); // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.NONE); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class); // WHEN displayWhen(TEST_NAME); OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals("No accountRefs", 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidOpendj = accountRef.getOid(); assertFalse(accountShadowOidOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); assertNotNull("Shadow stored in repository has no name", repoShadowType.getName()); // Check the "name" property, it should be set to DN, not entryUUID assertEquals("Wrong name property", USER_JACK_LDAP_DN.toLowerCase(), repoShadowType.getName().getOrig().toLowerCase()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(uid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "jack"); OpenDJController.assertAttribute(entry, "givenName", "Jack"); OpenDJController.assertAttribute(entry, "sn", "Sparrow"); OpenDJController.assertAttribute(entry, "cn", "Jack Sparrow"); OpenDJController.assertAttribute(entry, "displayName", "Jack Sparrow"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Black Pearl"); assertTrue("LDAP account is not enabled", openDJController.isAccountEnabled(entry)); originalJacksLdapPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", originalJacksLdapPassword); System.out.println("password after create: " + originalJacksLdapPassword); // Use getObject to test fetch of complete shadow assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, options, objectHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "Black Pearl"); assertNull("carLicense attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "carLicense")); assertNull("postalAddress attribute sneaked to LDAP", OpenDJController.getAttributeValue(entry, "postalAddress")); assertNotNull("Activation is null (model)", modelShadow.getActivation()); assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); } catch (Exception ex){ LOGGER.info("ERROR: {}", ex); throw ex; } } private OperationResultType modifyObjectViaModelWS(ObjectDeltaType objectChange) throws FaultMessage { ObjectDeltaListType deltaList = new ObjectDeltaListType(); deltaList.getDelta().add(objectChange); ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null); return getOdoFromDeltaOperationList(list, objectChange).getExecutionResult(); } /** * Add Derby account to user. This should result in account provisioning. Check if * that happens in repo and in Derby. */ @Test public void test014AddDerbyAccountToUser() throws IOException, JAXBException, FaultMessage, ObjectNotFoundException, SchemaException, DirectoryException, SQLException { TestUtil.displayTestTitle("test014AddDerbyAccountToUser"); // GIVEN checkRepoDerbyResource(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); // OpenDJ account was added in previous test, hence 2 accounts assertEquals(2, accountRefs.size()); ObjectReferenceType accountRef = null; for (ObjectReferenceType ref : accountRefs) { if (!ref.getOid().equals(accountShadowOidOpendj)) { accountRef = ref; } } accountShadowOidDerby = accountRef.getOid(); assertFalse(accountShadowOidDerby.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidDerby, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("addObject has failed", repoResult); display("Shadow (repository)", repoShadowType); assertNotNull(repoShadowType); assertEquals(RESOURCE_DERBY_OID, repoShadowType.getResourceRef().getOid()); // Check the "name" property, it should be set to DN, not entryUUID assertEquals("Wrong name property", PrismTestUtil.createPolyStringType(USER_JACK_DERBY_LOGIN), repoShadowType.getName()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // check if account was created in DB Table Statement stmt = derbyController.getExecutedStatementWhereLoginName(uid); ResultSet rs = stmt.getResultSet(); System.out.println("RS: " + rs); assertTrue("No records found for login name " + uid, rs.next()); assertEquals(USER_JACK_DERBY_LOGIN, rs.getString(DerbyController.COLUMN_LOGIN)); assertEquals("Cpt. Jack Sparrow", rs.getString(DerbyController.COLUMN_FULL_NAME)); // TODO: check password //assertEquals("3lizab3th",rs.getString(DerbyController.COLUMN_PASSWORD)); System.out.println("Password: " + rs.getString(DerbyController.COLUMN_PASSWORD)); assertFalse("Too many records found for login name " + uid, rs.next()); rs.close(); stmt.close(); // Use getObject to test fetch of complete shadow assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType (); // WHEN modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby, options, objectHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_DERBY_OID, modelShadow.getResourceRef().getOid()); assertAttribute(modelShadow, SchemaConstants.ICFS_UID, USER_JACK_DERBY_LOGIN); assertAttribute(modelShadow, SchemaConstants.ICFS_NAME, USER_JACK_DERBY_LOGIN); assertAttribute(resourceDerby, modelShadow, "FULL_NAME", "Cpt. Jack Sparrow"); } @Test public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException, JAXBException { TestUtil.displayTestTitle("test015AccountOwner"); // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<UserType> userHolder = new Holder<>(); // WHEN modelWeb.findShadowOwner(accountShadowOidOpendj, userHolder, resultHolder); // THEN display("listAccountShadowOwner result", resultHolder.value); TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value); UserType user = userHolder.value; assertNotNull("No owner", user); assertEquals(USER_JACK_OID, user.getOid()); System.out.println("Account " + accountShadowOidOpendj + " has owner " + ObjectTypeUtil.toShortString(user)); } @Test public void test016ProvisioningSearchAccountsIterative() throws Exception { TestUtil.displayTestTitle("test016ProvisioningSearchAccountsIterative"); // GIVEN OperationResult result = new OperationResult(TestSanity.class.getName() + ".test016ProvisioningSearchAccountsIterative"); RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceTypeOpenDjrepo, prismContext); final RefinedObjectClassDefinition refinedAccountDefinition = refinedSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); QName objectClass = refinedAccountDefinition.getObjectClassDefinition().getTypeName(); ObjectQuery q = ObjectQueryUtil.createResourceAndObjectClassQuery(resourceTypeOpenDjrepo.getOid(), objectClass, prismContext); final Collection<ObjectType> objects = new HashSet<>(); final MatchingRule caseIgnoreMatchingRule = matchingRuleRegistry.getMatchingRule(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME, DOMUtil.XSD_STRING); ResultHandler handler = new ResultHandler<ObjectType>() { @Override public boolean handle(PrismObject<ObjectType> prismObject, OperationResult parentResult) { ObjectType objectType = prismObject.asObjectable(); objects.add(objectType); display("Found object", objectType); assertTrue(objectType instanceof ShadowType); ShadowType shadow = (ShadowType) objectType; assertNotNull(shadow.getOid()); assertNotNull(shadow.getName()); assertEquals(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS, shadow.getObjectClass()); assertEquals(RESOURCE_OPENDJ_OID, shadow.getResourceRef().getOid()); String icfUid = getAttributeValue(shadow, getOpenDjPrimaryIdentifierQName()); assertNotNull("No ICF UID", icfUid); String icfName = getNormalizedAttributeValue(shadow, refinedAccountDefinition, getOpenDjSecondaryIdentifierQName()); assertNotNull("No ICF NAME", icfName); try { PrismAsserts.assertEquals("Wrong shadow name", caseIgnoreMatchingRule, shadow.getName().getOrig(), icfName); } catch (SchemaException e) { throw new IllegalArgumentException(e.getMessage(),e); } assertNotNull("Missing LDAP uid", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "uid"))); assertNotNull("Missing LDAP cn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "cn"))); assertNotNull("Missing LDAP sn", getAttributeValue(shadow, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "sn"))); assertNotNull("Missing activation", shadow.getActivation()); assertNotNull("Missing activation status", shadow.getActivation().getAdministrativeStatus()); return true; } }; // WHEN provisioningService.searchObjectsIterative(ShadowType.class, q, null, handler, null, result); // THEN display("Count", objects.size()); } /** * We are going to modify the user. As the user has an account, the user * changes should be also applied to the account (by schemaHandling). */ @Test public void test020ModifyUser() throws Exception { final String TEST_NAME = "test020ModifyUser"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); PrismAsserts.assertEqualsPolyString("wrong value for locality", "somewhere", repoUserType.getLocality()); assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { assertTrue("No OID in "+accountRef+" in "+repoUserType, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated assertOpenDJAccountJack(uid, "jack"); } private Entry assertOpenDJAccountJack(String entryUuid, String uid) throws DirectoryException { Entry entry = openDJController.searchAndAssertByEntryUuid(entryUuid); return assertOpenDJAccountJack(entry, uid); } private Entry assertOpenDJAccountJack(Entry entry, String uid) throws DirectoryException { return assertOpenDJAccountJack(entry, uid, "Jack"); } private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) throws DirectoryException { display(entry); OpenDJController.assertDn(entry, "uid="+uid+",ou=people,dc=example,dc=com"); OpenDJController.assertAttribute(entry, "uid", uid); if (givenName == null) { OpenDJController.assertAttribute(entry, "givenName"); } else { OpenDJController.assertAttribute(entry, "givenName", givenName); } OpenDJController.assertAttribute(entry, "sn", "Sparrow"); // These two should be assigned from the User modification by // schemaHandling OpenDJController.assertAttribute(entry, "cn", "Cpt. Jack Sparrow"); OpenDJController.assertAttribute(entry, "displayName", "Cpt. Jack Sparrow"); // This will get translated from "somewhere" to this (outbound // expression in schemeHandling) -> this is not more supported...we // don't support complex run-time properties. the value will be // evaluated from outbound expression OpenDJController.assertAttribute(entry, "l", "somewhere"); OpenDJController.assertAttribute(entry, "postalAddress", "Number 1"); return entry; } /** * We are going to change user's password. As the user has an account, the password change * should be also applied to the account (by schemaHandling). */ @Test public void test022ChangeUserPassword() throws Exception { final String TEST_NAME = "test022ChangeUserPassword"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_PASSWORD_FILENAME, ObjectDeltaType.class); System.out.println("In modification: " + objectChange.getItemDelta().get(0).getValue().get(0)); assertNoRepoCache(); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertUserPasswordChange("butUnd3dM4yT4lkAL0t", result); } /** * Similar to previous test just the request is constructed a bit differently. */ @Test public void test023ChangeUserPasswordJAXB() throws Exception { final String TEST_NAME = "test023ChangeUserPasswordJAXB"; displayTestTitle(TEST_NAME); // GIVEN final String NEW_PASSWORD = "abandonSHIP"; Document doc = ModelClientUtil.getDocumnent(); ObjectDeltaType userDelta = new ObjectDeltaType(); userDelta.setOid(USER_JACK_OID); userDelta.setChangeType(ChangeTypeType.MODIFY); userDelta.setObjectType(UserType.COMPLEX_TYPE); ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext)); ProtectedStringType pass = new ProtectedStringType(); pass.setClearValue(NEW_PASSWORD); XNode passValue = prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(pass).getSubnode(); System.out.println("PASSWORD VALUE: " + passValue.debugDump()); RawType passwordValue = new RawType(passValue, prismContext); passwordDelta.getValue().add(passwordValue); userDelta.getItemDelta().add(passwordDelta); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(userDelta); // THEN assertUserPasswordChange(NEW_PASSWORD, result); } private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws JAXBException, ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException { assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); // Check if nothing else was modified PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality()); // Check if appropriate accountRef is still there assertLinks(repoUser, 2); assertLinked(repoUser, accountShadowOidOpendj); assertLinked(repoUser, accountShadowOidDerby); assertPassword(repoUser, expectedUserPassword); // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); display("repository shadow", repoShadow); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertNotNull(repoShadowType); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry entry = assertOpenDJAccountJack(uid, "jack"); String ldapPasswordAfter = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull(ldapPasswordAfter); display("LDAP password after change", ldapPasswordAfter); assertFalse("No change in password (original)", ldapPasswordAfter.equals(originalJacksLdapPassword)); if (lastJacksLdapPassword != null) { assertFalse("No change in password (last)", ldapPasswordAfter.equals(lastJacksLdapPassword)); } lastJacksLdapPassword = ldapPasswordAfter; } @Test public void test027ModifyAccountDj() throws Exception { final String TEST_NAME = "test027ModifyAccountDj"; testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck"); } @Test public void test028ModifyAccountDjExplicitType() throws Exception { final String TEST_NAME = "test028ModifyAccountDjExplicitType"; testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck"); } public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, String expectedVal) throws Exception { displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile(reqFile, ObjectDeltaType.class); objectChange.setOid(accountShadowOidOpendj); // WHEN OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); OperationResult repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack"); OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", expectedVal); } @Test public void test029ModifyAccountDjBadPath() throws Exception { final String TEST_NAME = "test029ModifyAccountDjBadPath"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidOpendj); OperationResultType result; try { // WHEN result = modifyObjectViaModelWS(objectChange); AssertJUnit.fail("Unexpected success"); } catch (FaultMessage f) { // this is expected FaultType faultInfo = f.getFaultInfo(); result = faultInfo.getOperationResult(); } // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertFailure(result); OperationResult repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry jackLdapEntry = assertOpenDJAccountJack(uid, "jack"); OpenDJController.assertAttribute(jackLdapEntry, "roomNumber", "upperdeck"); } /** * Try to disable user. As the user has an account, the account should be disabled as well. */ @Test public void test030DisableUser() throws Exception { final String TEST_NAME = "test030DisableUser"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME, ObjectDeltaType.class); Entry entry = openDJController.searchByUid("jack"); assertOpenDJAccountJack(entry, "jack"); String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled"); display("ds-pwp-account-disabled before change", pwpAccountDisabled); assertTrue("LDAP account is not enabled (precondition)", openDJController.isAccountEnabled(entry)); assertNoRepoCache(); // WHEN displayWhen(TEST_NAME); OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); display("repository user", repoUser); UserType repoUserType = repoUser.asObjectable(); // Check if nothing else was modified assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); assertEqualsPolyString("wrong repo locality", "somewhere", repoUserType.getLocality()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { assertTrue("No OID in "+accountRef+" in "+repoUserType, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); display("repo shadow", repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); AssertJUnit.assertNotNull(repoShadowType); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated entry = openDJController.searchAndAssertByEntryUuid(uid); assertOpenDJAccountJack(entry, "jack"); pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled"); display("ds-pwp-account-disabled after change", pwpAccountDisabled); assertFalse("LDAP account was not disabled", openDJController.isAccountEnabled(entry)); // Use getObject to test fetch of complete shadow Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); assertNoRepoCache(); // WHEN displayWhen(TEST_NAME); modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, options, objectHolder, resultHolder); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere"); assertNotNull("The account activation is null in the shadow", modelShadow.getActivation()); assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus()); assertEquals("The account was not disabled in the shadow", ActivationStatusType.DISABLED, modelShadow.getActivation().getAdministrativeStatus()); } /** * Try to enable user after it has been disabled. As the user has an account, the account should be enabled as well. */ @Test public void test031EnableUser() throws Exception { final String TEST_NAME = "test031EnableUser"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class); assertNoRepoCache(); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); display("repo user", repoUser); // Check if nothing else was modified PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Cpt. Jack Sparrow", repoUser.getFullName()); PrismAsserts.assertEqualsPolyString("wrong repo locality", "somewhere", repoUser.getLocality()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(2, accountRefs.size()); for (ObjectReferenceType accountRef : accountRefs) { assertTrue("No OID in "+accountRef+" in "+repoUser, accountRef.getOid().equals(accountShadowOidOpendj) || accountRef.getOid().equals(accountShadowOidDerby)); } // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repo shadow", repoShadowType); AssertJUnit.assertNotNull(repoShadowType); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Use getObject to test fetch of complete shadow Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); assertNoRepoCache(); // WHEN modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidOpendj, options, objectHolder, resultHolder); // THEN assertNoRepoCache(); displayJaxb("getObject result", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("getObject has failed", resultHolder.value); ShadowType modelShadow = (ShadowType) objectHolder.value; display("Shadow (model)", modelShadow); AssertJUnit.assertNotNull(modelShadow); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, modelShadow.getResourceRef().getOid()); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "uid", "jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "givenName", "Jack"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "sn", "Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "cn", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "displayName", "Cpt. Jack Sparrow"); assertAttribute(resourceTypeOpenDjrepo, modelShadow, "l", "somewhere"); assertNotNull("The account activation is null in the shadow", modelShadow.getActivation()); assertNotNull("The account activation status was not present in shadow", modelShadow.getActivation().getAdministrativeStatus()); assertEquals("The account was not enabled in the shadow", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); // Check if LDAP account was updated Entry entry = openDJController.searchAndAssertByEntryUuid(uid); assertOpenDJAccountJack(entry, "jack"); // The value of ds-pwp-account-disabled should have been removed String pwpAccountDisabled = OpenDJController.getAttributeValue(entry, "ds-pwp-account-disabled"); System.out.println("ds-pwp-account-disabled after change: " + pwpAccountDisabled); assertTrue("LDAP account was not enabled", openDJController.isAccountEnabled(entry)); } /** * Unlink account by removing the accountRef from the user. * The account will not be deleted, just the association to user will be broken. */ @Test public void test040UnlinkDerbyAccountFromUser() throws FileNotFoundException, JAXBException, FaultMessage, ObjectNotFoundException, SchemaException, DirectoryException, SQLException { TestUtil.displayTestTitle("test040UnlinkDerbyAccountFromUser"); // GIVEN ObjectDeltaType objectChange = new ObjectDeltaType(); objectChange.setOid(USER_JACK_OID); ItemDeltaType modificationDeleteAccountRef = new ItemDeltaType(); modificationDeleteAccountRef.setModificationType(ModificationTypeType.DELETE); ObjectReferenceType accountRefToDelete = new ObjectReferenceType(); accountRefToDelete.setOid(accountShadowOidDerby); RawType modificationValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(accountRefToDelete).getSubnode(), prismContext); modificationDeleteAccountRef.getValue().add(modificationValue); modificationDeleteAccountRef.setPath(new ItemPathType(UserType.F_LINK_REF)); objectChange.getItemDelta().add(modificationDeleteAccountRef); objectChange.setChangeType(ChangeTypeType.MODIFY); objectChange.setObjectType(UserType.COMPLEX_TYPE); displayJaxb("modifyObject input", objectChange, new QName(SchemaConstants.NS_C, "change")); assertNoRepoCache(); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); // only OpenDJ account should be left now assertEquals(1, accountRefs.size()); ObjectReferenceType ref = accountRefs.get(0); assertEquals("Wrong OID in accountRef in "+repoUser, accountShadowOidOpendj, ref.getOid()); } /** * Delete the shadow which will cause deletion of associated account. * The account was unlinked in the previous test, therefore no operation with user is needed. */ @Test public void test041DeleteDerbyAccount() throws FileNotFoundException, JAXBException, FaultMessage, ObjectNotFoundException, SchemaException, DirectoryException, SQLException { TestUtil.displayTestTitle("test041DeleteDerbyAccount"); // GIVEN assertNoRepoCache(); // WHEN OperationResultType result = deleteObjectViaModelWS(ObjectTypes.SHADOW.getTypeQName(), accountShadowOidDerby); // THEN assertNoRepoCache(); displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("deleteObject has failed", result); // Check if shadow was deleted OperationResult repoResult = new OperationResult("getObject"); try { repositoryService.getObject(ShadowType.class, accountShadowOidDerby, null, repoResult); AssertJUnit.fail("Shadow was not deleted"); } catch (ObjectNotFoundException ex) { display("Caught expected exception from getObject(shadow): " + ex); } // check if account was deleted in DB Table Statement stmt = derbyController.getExecutedStatementWhereLoginName(USER_JACK_DERBY_LOGIN); ResultSet rs = stmt.getResultSet(); System.out.println("RS: " + rs); assertFalse("Account was not deleted in database", rs.next()); } private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) throws FaultMessage { ObjectDeltaListType deltaList = new ObjectDeltaListType(); ObjectDeltaType objectDelta = new ObjectDeltaType(); objectDelta.setOid(oid); objectDelta.setObjectType(typeQName); objectDelta.setChangeType(ChangeTypeType.DELETE); deltaList.getDelta().add(objectDelta); ObjectDeltaOperationListType list = modelWeb.executeChanges(deltaList, null); return getOdoFromDeltaOperationList(list, objectDelta).getExecutionResult(); } @Test public void test047RenameUser() throws Exception { final String TEST_NAME = "test047RenameUser"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_NAME_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for User name", "jsparrow", repoUserType.getName()); PrismAsserts.assertEqualsPolyString("wrong value for User fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); PrismAsserts.assertEqualsPolyString("wrong value for User locality", "somewhere", repoUserType.getLocality()); assertEquals("wrong value for employeeNumber", "1", repoUserType.getEmployeeNumber()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.iterator().next(); assertEquals("Wrong OID in "+accountRef+" in "+repoUserType, accountShadowOidOpendj, accountRef.getOid()); // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated assertOpenDJAccountJack(uid, "jsparrow"); } /** * We are going to modify the user. As the user has an account, the user * changes should be also applied to the account (by schemaHandling). * * @throws DirectoryException */ @Test public void test048ModifyUserRemoveGivenName() throws Exception { final String TEST_NAME = "test048ModifyUserRemoveGivenName"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_GIVENNAME_FILENAME, ObjectDeltaType.class); displayJaxb("objectChange:", objectChange, SchemaConstants.T_OBJECT_DELTA); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); display("repository user", repoUser); PrismAsserts.assertEqualsPolyString("wrong value for fullName", "Cpt. Jack Sparrow", repoUserType.getFullName()); assertNull("Value for givenName still present", repoUserType.getGivenName()); // Check if appropriate accountRef is still there List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.iterator().next(); accountRef.getOid().equals(accountShadowOidOpendj); // Check if shadow is still in the repo and that it is untouched repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); repoResult.computeStatus(); TestUtil.assertSuccess("getObject(repo) has failed", repoResult); display("repository shadow", repoShadow); AssertJUnit.assertNotNull(repoShadow); ShadowType repoShadowType = repoShadow.asObjectable(); AssertJUnit.assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check attributes in the shadow: should be only identifiers (ICF UID) String uid = checkRepoShadow(repoShadow); // Check if LDAP account was updated Entry entry = openDJController.searchAndAssertByEntryUuid(uid); assertOpenDJAccountJack(entry, "jsparrow", null); } /** * The user should have an account now. Let's try to delete the user. The * account should be gone as well. * * @throws JAXBException */ @Test public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryException, JAXBException { TestUtil.displayTestTitle("test049DeleteUser"); // GIVEN assertNoRepoCache(); // WHEN OperationResultType result = deleteObjectViaModelWS(ObjectTypes.USER.getTypeQName(), USER_JACK_OID); // THEN assertNoRepoCache(); displayJaxb("deleteObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("deleteObject has failed", result); // User should be gone from the repository OperationResult repoResult = new OperationResult("getObject"); try { repositoryService.getObject(UserType.class, USER_JACK_OID, null, repoResult); AssertJUnit.fail("User still exists in repo after delete"); } catch (ObjectNotFoundException e) { // This is expected } // Account shadow should be gone from the repository repoResult = new OperationResult("getObject"); try { repositoryService.getObject(ShadowType.class, accountShadowOidOpendj, null, repoResult); AssertJUnit.fail("Shadow still exists in repo after delete"); } catch (ObjectNotFoundException e) { // This is expected, but check also the result AssertJUnit.assertFalse("getObject failed as expected, but the result indicates success", repoResult.isSuccess()); } // Account should be deleted from LDAP InternalSearchOperation op = openDJController.getInternalConnection().processSearch( "dc=example,dc=com", SearchScope.WHOLE_SUBTREE, DereferencePolicy.NEVER_DEREF_ALIASES, 100, 100, false, "(uid=" + USER_JACK_LDAP_UID + ")", null); AssertJUnit.assertEquals(0, op.getEntriesSent()); } @Test public void test100AssignRolePirate() throws Exception { final String TEST_NAME = "test100AssignRolePirate"; displayTestTitle(TEST_NAME); // GIVEN // IMPORTANT! Assignment enforcement is FULL now setAssignmentEnforcement(AssignmentPolicyEnforcementType.FULL); // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.FULL); PrismObject<UserType> user = PrismTestUtil.parseObject(USER_GUYBRUSH_FILE); UserType userType = user.asObjectable(); // Encrypt the password protector.encrypt(userType.getCredentials().getPassword().getValue()); OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<String> oidHolder = new Holder<>(); assertNoRepoCache(); addObjectViaModelWS(userType, null, oidHolder, resultHolder); assertNoRepoCache(); TestUtil.assertSuccess("addObject has failed", resultHolder.value); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidGuybrushOpendj = accountRef.getOid(); assertFalse(accountShadowOidGuybrushOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadowType); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", guybrushPassword); // TODO: Derby } @Test public void test101AccountOwnerAfterRole() throws Exception { final String TEST_NAME = "test101AccountOwnerAfterRole"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); Holder<OperationResultType> resultHolder = new Holder<>(); Holder<UserType> userHolder = new Holder<>(); // WHEN modelWeb.findShadowOwner(accountShadowOidGuybrushOpendj, userHolder, resultHolder); // THEN TestUtil.assertSuccess("listAccountShadowOwner has failed (result)", resultHolder.value); UserType user = userHolder.value; assertNotNull("No owner", user); assertEquals(USER_GUYBRUSH_OID, user.getOid()); System.out.println("Account " + accountShadowOidGuybrushOpendj + " has owner " + ObjectTypeUtil.toShortString(user)); } @Test public void test102AssignRoleCaptain() throws Exception { final String TEST_NAME = "test102AssignRoleCaptain"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadow = aObject.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadow); assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignment OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } /** * Assign the same "captain" role again, this time with a slightly different assignment parameters. */ @Test public void test103AssignRoleCaptainAgain() throws Exception { final String TEST_NAME = "test103AssignRoleCaptainAgain"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadow = aObject.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadow); assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } @Test public void test105ModifyAccount() throws Exception { final String TEST_NAME = "test105ModifyAccount"; displayTestTitle(TEST_NAME); // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidGuybrushOpendj); // WHEN ObjectTypes.SHADOW.getTypeQName(), OperationResultType result = modifyObjectViaModelWS(objectChange); Task task = taskManager.createTaskInstance(); OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify"); PrismObject<ShadowType> shadow= modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult); assertNotNull("shadow must not be null", shadow); ShadowType shadowType = shadow.asObjectable(); QName employeeTypeQName = new QName(resourceTypeOpenDjrepo.getNamespace(), "employeeType"); ItemPath employeeTypePath = ItemPath.create(ShadowType.F_ATTRIBUTES, employeeTypeQName); PrismProperty item = shadow.findProperty(employeeTypePath); PropertyDelta deleteDelta = prismContext.deltaFactory().property().create(ShadowType.F_ATTRIBUTES, item.getDefinition().getItemName(), item.getDefinition()); // PropertyDelta deleteDelta = PropertyDelta.createDelta(employeeTypePath, shadow.getDefinition()); // PrismPropertyValue valToDelte = new PrismPropertyValue("A"); // valToDelte.setParent(deleteDelta); Collection<PrismPropertyValue> values= item.getValues(); for (PrismPropertyValue val : values){ if ("A".equals(val.getValue())){ deleteDelta.addValueToDelete(val.clone()); } } ObjectDelta delta = prismContext.deltaFactory().object().create(ShadowType.class, ChangeType.MODIFY); delta.addModification(deleteDelta); delta.setOid(accountShadowOidGuybrushOpendj); Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>(); deltas.add(delta); LOGGER.info("-------->>EXECUTE DELETE MODIFICATION<<------------"); modelService.executeChanges(deltas, null, task, parentResult); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // check if LDAP account was modified Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); OpenDJController.assertAttribute(entry, "roomNumber", "captain's cabin"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Bloody Pirate", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "loot", "murder", "cruise", "fighting", "capsize"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); } /** * Judge role excludes pirate role. This assignment should fail. */ @Test public void test104AssignRoleJudge() throws Exception { final String TEST_NAME = "test104AssignRoleJudge"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<String> oidHolder = new Holder<>(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME, ObjectDeltaType.class); try { // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN AssertJUnit.fail("Expected a failure after assigning conflicting roles but nothing happened and life goes on"); } catch (FaultMessage f) { // This is expected // TODO: check if the fault is the right one } assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object remain unmodified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals("Unexpected number or accountRefs", 1, accountRefs.size()); } @Test public void test107UnassignRolePirate() throws Exception { final String TEST_NAME = "test107UnassignRolePirate"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> aObject = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadow = aObject.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadow); assertEquals(RESOURCE_OPENDJ_OID, repoShadow.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Sea Monkey", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } @Test public void test108UnassignRoleCaptain() throws Exception { final String TEST_NAME = "test108UnassignRoleCaptain"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUser); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); assertEquals(accountShadowOidGuybrushOpendj, accountRef.getOid()); // Check if shadow is still in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); display("Shadow (repository)", repoShadow); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); // check if account is still in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise", "fighting", "capsize"); // Expression in the role taking that from the user OpenDJController.assertAttribute(entry, "destinationIndicator", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "departmentNumber", "Department of Guybrush"); // Expression in the role taking that from the assignments (both of them) OpenDJController.assertAttribute(entry, "physicalDeliveryOfficeName", "The Dainty Lady"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword disappeared", guybrushPassword); // TODO: Derby } /** * Captain role was assigned twice. It has to also be unassigned twice. */ @Test public void test109UnassignRoleCaptainAgain() throws Exception { final String TEST_NAME = "test109UnassignRoleCaptainAgain"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); displayJaxb("modifyObject result", result, SchemaConstants.C_RESULT); //TODO TODO TODO TODO operation result from repostiory.getObject is unknown...find out why.. // assertSuccess("modifyObject has failed", result); // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PropertyReferenceListType resolve = new PropertyReferenceListType(); PrismObject<UserType> repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); repoResult.computeStatus(); display("User (repository)", repoUserType); List<ObjectReferenceType> accountRefs = repoUserType.getLinkRef(); assertEquals(0, accountRefs.size()); // Check if shadow was deleted from the repo repoResult = new OperationResult("getObject"); try { PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); AssertJUnit.fail("Account shadow was not deleted from repo"); } catch (ObjectNotFoundException ex) { // This is expected } // check if account was deleted from LDAP Entry entry = openDJController.searchByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); assertNull("LDAP account was not deleted", entry); // TODO: Derby } // Synchronization tests /** * Test initialization of synchronization. It will create a cycle task and * check if the cycle executes No changes are synchronized yet. */ @Test public void test300LiveSyncInit() throws Exception { final String TEST_NAME = "test300LiveSyncInit"; displayTestTitle(TEST_NAME); // Now it is the right time to add task definition to the repository // We don't want it there any sooner, as it may interfere with the // previous tests checkAllShadows(); // IMPORTANT! Assignment enforcement is POSITIVE now setAssignmentEnforcement(AssignmentPolicyEnforcementType.POSITIVE); // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE); final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); repoAddObjectFromFile(TASK_OPENDJ_SYNC_FILENAME, result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task waitFor("Waiting for task manager to pick up the task", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); display("Task while waiting for task manager to pick up the task", task); // wait until the task is picked up return task.getLastRunFinishTimestamp() != null; // if (TaskExclusivityStatus.CLAIMED == task.getExclusivityStatus()) { // // wait until the first run is finished // if (task.getLastRunFinishTimestamp() == null) { // return false; // } // return true; // } // return false; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 20000); // Check task status Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, retrieveTaskResult(), result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); AssertJUnit.assertNotNull(task); display("Task after pickup", task); PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_SYNC_OID, null, result); display("Task after pickup in the repository", o.asObjectable()); // .. it should be running AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); // .. and claimed // AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus()); // .. and last run should not be zero assertNotNull("No lastRunStartTimestamp", task.getLastRunStartTimestamp()); assertFalse("Zero lastRunStartTimestamp", task.getLastRunStartTimestamp().longValue() == 0); assertNotNull("No lastRunFinishedTimestamp", task.getLastRunFinishTimestamp()); assertFalse("Zero lastRunFinishedTimestamp", task.getLastRunFinishTimestamp().longValue() == 0); // Test for extension. This will also roughly test extension processor // and schema processor PrismContainer<?> taskExtension = task.getExtensionOrClone(); AssertJUnit.assertNotNull(taskExtension); display("Task extension", taskExtension); PrismProperty<String> shipStateProp = taskExtension.findProperty(MY_SHIP_STATE); AssertJUnit.assertEquals("Wrong 'shipState' property value", "capsized", shipStateProp.getValue().getValue()); PrismProperty<Integer> deadProp = taskExtension.findProperty(MY_DEAD); PrismPropertyValue<Integer> deadPVal = deadProp.getValues().iterator().next(); AssertJUnit.assertEquals("Wrong 'dead' property class", Integer.class, deadPVal.getValue().getClass()); AssertJUnit.assertEquals("Wrong 'dead' property value", Integer.valueOf(42), deadPVal.getValue()); // The progress should be 0, as there were no changes yet AssertJUnit.assertEquals(0, task.getProgress()); // Test for presence of a result. It should be there and it should // indicate success OperationResult taskResult = task.getResult(); AssertJUnit.assertNotNull(taskResult); assertTrue("Task result is not a success, it is "+taskResult, taskResult.isSuccess()); final Object tokenAfter = findSyncToken(task); display("Sync token after", tokenAfter.toString()); lastSyncToken = (Integer)tokenAfter; checkAllShadows(); // Try without options. The results should NOT be there // MID-4670 task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, null, result); taskResult = task.getResult(); AssertJUnit.assertNull("Unexpected task result", taskResult); } /** * Create LDAP object. That should be picked up by liveSync and a user * should be created in repo. */ @Test public void test301LiveSyncCreate() throws Exception { final String TEST_NAME = "test301LiveSyncCreate"; displayTestTitle(TEST_NAME); // Sync task should be running (tested in previous test), so just create // new LDAP object. final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); final Object tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore.toString()); // WHEN displayWhen(TEST_NAME); Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_FILENAME); display("Entry from LDIF", entry); // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 2, result); // THEN displayThen(TEST_NAME); // Search for the user that should be created now UserType user = searchUserByName(WILL_NAME); PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); assertNotNull(user.getLinkRef()); assertFalse(user.getLinkRef().isEmpty()); // AssertJUnit.assertEquals(user.getName(), WILL_NAME); // TODO: more checks assertAndStoreSyncTokenIncrement(syncCycle, 2); checkAllShadows(); } @Test public void test302LiveSyncModify() throws Exception { final String TEST_NAME = "test302LiveSyncModify"; displayTestTitle(TEST_NAME); final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore); // WHEN display("Modifying LDAP entry"); ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_WILL_MODIFY_FILE); // THEN display("Entry from LDIF", entry); // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result); // Search for the user that should be created now UserType user = searchUserByName (WILL_NAME); // AssertJUnit.assertEquals(WILL_NAME, user.getName()); PrismAsserts.assertEqualsPolyString("Wrong name.", WILL_NAME, user.getName()); PrismAsserts.assertEqualsPolyString("wrong givenName", "asdf", user.getGivenName()); assertAndStoreSyncTokenIncrement(syncCycle, 1); checkAllShadows(); } @Test public void test303LiveSyncLink() throws Exception { final String TEST_NAME = "test303LiveSyncLink"; displayTestTitle(TEST_NAME); // GIVEN assertNoRepoCache(); PrismObject<UserType> user = PrismTestUtil.parseObject(USER_E_LINK_ACTION_FILE); UserType userType = user.asObjectable(); final String userOid = userType.getOid(); // Encrypt e's password protector.encrypt(userType.getCredentials().getPassword().getValue()); // create user in repository OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<String> oidHolder = new Holder<>(); display("Adding user object", userType); addObjectViaModelWS(userType, null, oidHolder, resultHolder); //check results assertNoRepoCache(); displayJaxb("addObject result:", resultHolder.value, SchemaConstants.C_RESULT); TestUtil.assertSuccess("addObject has failed", resultHolder.value); // AssertJUnit.assertEquals(userOid, oidHolder.value); //WHEN displayWhen(TEST_NAME); //create account for e which should be correlated final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore); Entry entry = openDJController.addEntryFromLdifFile(LDIF_E_FILENAME_LINK); display("Entry from LDIF", entry); // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 1, result); // THEN displayThen(TEST_NAME); //check user and account ref userType = searchUserByName("e"); List<ObjectReferenceType> accountRefs = userType.getLinkRef(); assertEquals("Account ref not found, or found too many", 1, accountRefs.size()); //check account defined by account ref String accountOid = accountRefs.get(0).getOid(); ShadowType account = searchAccountByOid(accountOid); assertEqualsPolyString("Name doesn't match", "uid=e,ou=People,dc=example,dc=com", account.getName()); assertAndStoreSyncTokenIncrement(syncCycle, 1); checkAllShadows(); } /** * Create LDAP object. That should be picked up by liveSync and a user * should be created in repo. * Also location (ldap l) should be updated through outbound */ @Test public void test304LiveSyncCreateNoLocation() throws Exception { final String TEST_NAME = "test304LiveSyncCreateNoLocation"; displayTestTitle(TEST_NAME); // Sync task should be running (tested in previous test), so just create // new LDAP object. final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); display("Sync token before", tokenBefore); // WHEN Entry entry = openDJController.addEntryFromLdifFile(LDIF_WILL_WITHOUT_LOCATION_FILENAME); display("Entry from LDIF", entry); // THEN // Wait a bit to give the sync cycle time to detect the change basicWaitForSyncChangeDetection(syncCycle, tokenBefore, 3, result, 60000); // Search for the user that should be created now final String userName = "wturner1"; UserType user = searchUserByName(userName); List<ObjectReferenceType> accountRefs = user.getLinkRef(); assertEquals("Account ref not found, or found too many", 1, accountRefs.size()); //check account defined by account ref String accountOid = accountRefs.get(0).getOid(); ShadowType account = searchAccountByOid(accountOid); assertEqualsPolyString("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName()); // assertEquals("Name doesn't match", "uid=" + userName + ",ou=People,dc=example,dc=com", account.getName()); Collection<String> localities = getAttributeValues(account, new QName(RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS.getNamespaceURI(), "l")); assertNotNull("null value list for attribute 'l'", localities); assertEquals("unexpected number of values of attribute 'l'", 1, localities.size()); assertEquals("Locality doesn't match", "middle of nowhere", localities.iterator().next()); assertAndStoreSyncTokenIncrement(syncCycle, 3); checkAllShadows(); } private void assertAndStoreSyncTokenIncrement(Task syncCycle, int increment) { final Object tokenAfter = findSyncToken(syncCycle); display("Sync token after", tokenAfter.toString()); int tokenAfterInt = (Integer)tokenAfter; int expectedToken = lastSyncToken + increment; lastSyncToken = tokenAfterInt; assertEquals("Unexpected sync toke value", expectedToken, tokenAfterInt); } private int findSyncToken(Task syncCycle) { return (Integer)findSyncTokenObject(syncCycle); } private Object findSyncTokenObject(Task syncCycle) { Object token = null; PrismProperty<?> tokenProperty = syncCycle.getExtensionOrClone().findProperty(SchemaConstants.SYNC_TOKEN); if (tokenProperty != null) { Collection<?> values = tokenProperty.getRealValues(); if (values.size() > 1) { throw new IllegalStateException("Too must values in token "+tokenProperty); } token = values.iterator().next(); } return token; } /** * Not really a test. Just cleans up after live sync. */ @Test public void test399LiveSyncCleanup() throws Exception { final String TEST_NAME = "test399LiveSyncCleanup"; displayTestTitle(TEST_NAME); final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); taskManager.deleteTask(TASK_OPENDJ_SYNC_OID, result); // TODO: check if the task is really stopped } @Test public void test400ImportFromResource() throws Exception { final String TEST_NAME = "test400ImportFromResource"; displayTestTitle(TEST_NAME); // GIVEN checkAllShadows(); assertNoRepoCache(); OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); // Make sure Mr. Gibbs has "l" attribute set to the same value as an outbound expression is setting ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_GIBBS_MODIFY_FILE); display("Entry from LDIF", entry); // Let's add an entry with multiple uids. Entry addEntry = openDJController.addEntryFromLdifFile(LDIF_HERMAN_FILENAME); display("Entry from LDIF", addEntry); // WHEN displayWhen(TEST_NAME); TaskType taskType = modelWeb.importFromResource(RESOURCE_OPENDJ_OID, RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS); // THEN displayThen(TEST_NAME); assertNoRepoCache(); displayJaxb("importFromResource result", taskType.getResult(), SchemaConstants.C_RESULT); AssertJUnit.assertEquals("importFromResource has failed", OperationResultStatusType.IN_PROGRESS, taskType.getResult().getStatus()); // Convert the returned TaskType to a more usable Task Task task = taskManager.createTaskInstance(taskType.asPrismObject(), result); AssertJUnit.assertNotNull(task); assertNotNull(task.getOid()); AssertJUnit.assertTrue(task.isAsynchronous()); AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); // AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus()); display("Import task after launch", task); PrismObject<TaskType> tObject = repositoryService.getObject(TaskType.class, task.getOid(), null, result); TaskType taskAfter = tObject.asObjectable(); display("Import task in repo after launch", taskAfter); result.computeStatus(); TestUtil.assertSuccess("getObject has failed", result); final String taskOid = task.getOid(); waitFor("Waiting for import to complete", new Checker() { @Override public boolean check() throws CommonException { Holder<OperationResultType> resultHolder = new Holder<>(); Holder<ObjectType> objectHolder = new Holder<>(); OperationResult opResult = new OperationResult("import check"); assertNoRepoCache(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); try { modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), taskOid, options, objectHolder, resultHolder); } catch (FaultMessage faultMessage) { throw new SystemException(faultMessage); } assertNoRepoCache(); // display("getObject result (wait loop)",resultHolder.value); TestUtil.assertSuccess("getObject has failed", resultHolder.value); Task task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), opResult); System.out.println(new Date() + ": Import task status: " + task.getExecutionStatus() + ", progress: " + task.getProgress()); if (task.getExecutionStatus() == TaskExecutionStatus.CLOSED) { // Task closed, wait finished return true; } // IntegrationTestTools.display("Task result while waiting: ", task.getResult()); return false; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 180000); // wait a second until the task will be definitely saved Thread.sleep(1000); //### Check task state after the task is finished ### Holder<ObjectType> objectHolder = new Holder<>(); Holder<OperationResultType> resultHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); assertNoRepoCache(); modelWeb.getObject(ObjectTypes.TASK.getTypeQName(), task.getOid(), options, objectHolder, resultHolder); assertNoRepoCache(); TestUtil.assertSuccess("getObject has failed", resultHolder.value); task = taskManager.createTaskInstance((PrismObject<TaskType>) objectHolder.value.asPrismObject(), result); display("Import task after finish (fetched from model)", task); AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus()); assertNotNull("Null lastRunStartTimestamp in "+task, task.getLastRunStartTimestamp()); assertNotNull("Null lastRunFinishTimestamp in "+task, task.getLastRunFinishTimestamp()); long importDuration = task.getLastRunFinishTimestamp() - task.getLastRunStartTimestamp(); double usersPerSec = (task.getProgress() * 1000) / importDuration; display("Imported " + task.getProgress() + " users in " + importDuration + " milliseconds (" + usersPerSec + " users/sec)"); OperationResultStatusType taskResultStatus = task.getResultStatus(); AssertJUnit.assertNotNull("Task has no result status", taskResultStatus); assertEquals("Import task result is not success", OperationResultStatusType.SUCCESS, taskResultStatus); AssertJUnit.assertTrue("No progress", task.getProgress() > 0); //### Check if the import created users and shadows ### // Listing of shadows is not supported by the provisioning. So we need // to look directly into repository List<PrismObject<ShadowType>> sobjects = repositoryService.searchObjects(ShadowType.class, null, null, result); result.computeStatus(); TestUtil.assertSuccess("listObjects has failed", result); AssertJUnit.assertFalse("No shadows created", sobjects.isEmpty()); for (PrismObject<ShadowType> aObject : sobjects) { ShadowType shadow = aObject.asObjectable(); display("Shadow object after import (repo)", shadow); assertNotEmpty("No OID in shadow", shadow.getOid()); // This would be really strange ;-) assertNotEmpty("No name in shadow", shadow.getName()); AssertJUnit.assertNotNull("No objectclass in shadow", shadow.getObjectClass()); AssertJUnit.assertNotNull("Null attributes in shadow", shadow.getAttributes()); String resourceOid = shadow.getResourceRef().getOid(); if (resourceOid.equals(RESOURCE_OPENDJ_OID)) { assertAttributeNotNull("No identifier in shadow", shadow, getOpenDjPrimaryIdentifierQName()); } else { assertAttributeNotNull("No UID in shadow", shadow, SchemaConstants.ICFS_UID); } } Holder<ObjectListType> listHolder = new Holder<>(); assertNoRepoCache(); modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), null, null, listHolder, resultHolder); assertNoRepoCache(); ObjectListType uobjects = listHolder.value; TestUtil.assertSuccess("listObjects has failed", resultHolder.value); AssertJUnit.assertFalse("No users created", uobjects.getObject().isEmpty()); // TODO: use another account, not guybrush display("Users after import "+uobjects.getObject().size()); for (ObjectType oo : uobjects.getObject()) { UserType user = (UserType) oo; if (SystemObjectsType.USER_ADMINISTRATOR.value().equals(user.getOid())) { //skip administrator check continue; } display("User after import (repo)", user); assertNotEmpty("No OID in user", user.getOid()); // This would be // really // strange ;-) assertNotEmpty("No name in user", user.getName()); assertNotNull("No fullName in user", user.getFullName()); assertNotEmpty("No fullName in user", user.getFullName().getOrig()); assertNotEmpty("No familyName in user", user.getFamilyName().getOrig()); // givenName is not mandatory in LDAP, therefore givenName may not // be present on user if (user.getName().getOrig().equals(USER_GUYBRUSH_USERNAME)) { // skip the rest of checks for guybrush, he does not have LDAP account now continue; } assertTrue("User "+user.getName()+" is disabled ("+user.getActivation().getAdministrativeStatus()+")", user.getActivation() == null || user.getActivation().getAdministrativeStatus() == ActivationStatusType.ENABLED); List<ObjectReferenceType> accountRefs = user.getLinkRef(); AssertJUnit.assertEquals("Wrong accountRef for user " + user.getName(), 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); boolean found = false; for (PrismObject<ShadowType> aObject : sobjects) { ShadowType acc = aObject.asObjectable(); if (accountRef.getOid().equals(acc.getOid())) { found = true; break; } } if (!found) { AssertJUnit.fail("accountRef does not point to existing account " + accountRef.getOid()); } PrismObject<ShadowType> aObject = modelService.getObject(ShadowType.class, accountRef.getOid(), null, task, result); ShadowType account = aObject.asObjectable(); display("Account after import ", account); String attributeValueL = ShadowUtil.getMultiStringAttributeValueAsSingle(account, new QName(ResourceTypeUtil.getResourceNamespace(resourceTypeOpenDjrepo), "l")); // assertEquals("Unexcpected value of l", "middle of nowhere", attributeValueL); assertEquals("Unexcpected value of l", getUserLocality(user), attributeValueL); } // This also includes "idm" user imported from LDAP. Later we need to ignore that one. assertEquals("Wrong number of users after import", 10, uobjects.getObject().size()); checkAllShadows(); } private String getUserLocality(UserType user){ return user.getLocality() != null ? user.getLocality().getOrig() :"middle of nowhere"; } @Test public void test420RecomputeUsers() throws Exception { final String TEST_NAME = "test420RecomputeUsers"; displayTestTitle(TEST_NAME); // GIVEN final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); // Assign role to a user, but we do this using a repository instead of model. // The role assignment will not be executed and this created an inconsistent state. ObjectDeltaType changeAddRoleCaptain = unmarshallValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); Collection<? extends ItemDelta> modifications = DeltaConvertor.toModifications(changeAddRoleCaptain.getItemDelta(), getUserDefinition()); repositoryService.modifyObject(UserType.class, changeAddRoleCaptain.getOid(), modifications, result); // TODO: setup more "inconsistent" state // Add reconciliation task. This will trigger reconciliation importObjectFromFile(TASK_USER_RECOMPUTE_FILENAME, result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task waitFor("Waiting for task to finish", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, result); //display("Task while waiting for task manager to pick up the task", task); // wait until the task is finished if (TaskExecutionStatus.CLOSED == task.getExecutionStatus()) { return true; } return false; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 40000); // wait a second until the task will be definitely saved Thread.sleep(1000); // Check task status Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, retrieveTaskResult(), result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); AssertJUnit.assertNotNull(task); display("Task after finish", task); AssertJUnit.assertNotNull(task.getTaskIdentifier()); assertFalse(task.getTaskIdentifier().isEmpty()); PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_USER_RECOMPUTE_OID, null, result); display("Task after pickup in the repository", o.asObjectable()); AssertJUnit.assertEquals(TaskExecutionStatus.CLOSED, task.getExecutionStatus()); // .. and last run should not be zero assertNotNull(task.getLastRunStartTimestamp()); AssertJUnit.assertFalse(task.getLastRunStartTimestamp().longValue() == 0); assertNotNull(task.getLastRunFinishTimestamp()); AssertJUnit.assertFalse(task.getLastRunFinishTimestamp().longValue() == 0); AssertJUnit.assertEquals(10, task.getProgress()); // Test for presence of a result. It should be there and it should // indicate success OperationResult taskResult = task.getResult(); display("Recompute task result", taskResult); AssertJUnit.assertNotNull(taskResult); TestUtil.assertSuccess("Recompute task result", taskResult); // STOP the task. We don't need it any more and we don't want to give it a chance to run more than once taskManager.deleteTask(TASK_USER_RECOMPUTE_OID, result); // CHECK RESULT: account created for user guybrush // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> object = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = object.asObjectable(); repoResult.computeStatus(); displayJaxb("User (repository)", repoUser, new QName("user")); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals("Wrong number of accountRefs after recompute for user "+repoUser.getName(), 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidGuybrushOpendj = accountRef.getOid(); assertFalse(accountShadowOidGuybrushOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow")); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); OpenDJController.assertAttribute(entry, "title", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", guybrushPassword); checkAllShadows(); } @Test public void test440ReconcileResourceOpenDj() throws Exception { final String TEST_NAME = "test440ReconcileResourceOpenDj"; displayTestTitle(TEST_NAME); // GIVEN final OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); // Create LDAP account without an owner. The liveSync is off, so it will not be picked up Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ELAINE_FILENAME); display("Entry from LDIF", ldifEntry); // Guybrush's attributes were set up by a role in the previous test. Let's mess the up a bit. Recon should sort it out. List<RawModification> modifications = new ArrayList<>(); // Expect that a correct title will be added to this one RawModification titleMod = RawModification.create(ModificationType.REPLACE, "title", "Scurvy earthworm"); modifications.add(titleMod); // Expect that the correct location will replace this one RawModification lMod = RawModification.create(ModificationType.REPLACE, "l", "Davie Jones' locker"); modifications.add(lMod); // Expect that this will be untouched RawModification poMod = RawModification.create(ModificationType.REPLACE, "postOfficeBox", "X marks the spot"); modifications.add(poMod); ModifyOperation modifyOperation = openDJController.getInternalConnection().processModify(USER_GUYBRUSH_LDAP_DN, modifications); if (ResultCode.SUCCESS != modifyOperation.getResultCode()) { AssertJUnit.fail("LDAP operation failed: " + modifyOperation.getErrorMessage()); } // TODO: setup more "inconsistent" state // Add reconciliation task. This will trigger reconciliation repoAddObjectFromFile(TASK_OPENDJ_RECON_FILENAME, result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task waitFor("Waiting for task to finish first run", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result); display("Task while waiting for task manager to pick up the task", task); // wait until the task is finished return task.getLastRunFinishTimestamp() != null; } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 180000); // Check task status Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); AssertJUnit.assertNotNull(task); display("Task after pickup", task); PrismObject<TaskType> o = repositoryService.getObject(TaskType.class, TASK_OPENDJ_RECON_OID, null, result); display("Task after pickup in the repository", o.asObjectable()); // .. it should be running AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); // .. and claimed // AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task.getExclusivityStatus()); // .. and last run should not be zero assertNotNull("Null last run start in recon task", task.getLastRunStartTimestamp()); AssertJUnit.assertFalse("Zero last run start in recon task", task.getLastRunStartTimestamp().longValue() == 0); assertNotNull("Null last run finish in recon task", task.getLastRunFinishTimestamp()); AssertJUnit.assertFalse("Zero last run finish in recon task", task.getLastRunFinishTimestamp().longValue() == 0); // The progress should be 0, as there were no changes yet // [pm] commented out, as progress in recon task is now determined not only using # of changes //AssertJUnit.assertEquals(0, task.getProgress()); // Test for presence of a result. It was not fetched - so it should NOT be there OperationResult taskResult = task.getResult(); AssertJUnit.assertNull(taskResult); // However, the task should indicate success AssertJUnit.assertEquals(OperationResultStatusType.SUCCESS, task.getResultStatus()); // STOP the task. We don't need it any more and we don't want to give it a chance to run more than once taskManager.deleteTask(TASK_OPENDJ_RECON_OID, result); // CHECK RESULT: account for user guybrush should be still there and unchanged // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); PrismObject<UserType> uObject = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUser = uObject.asObjectable(); repoResult.computeStatus(); displayJaxb("User (repository)", repoUser, new QName("user")); List<ObjectReferenceType> accountRefs = repoUser.getLinkRef(); assertEquals("Guybrush has wrong number of accounts", 1, accountRefs.size()); ObjectReferenceType accountRef = accountRefs.get(0); accountShadowOidGuybrushOpendj = accountRef.getOid(); assertFalse(accountShadowOidGuybrushOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, repoResult); ShadowType repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow")); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); accountGuybrushOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account was created in LDAP Entry entry = openDJController.searchAndAssertByEntryUuid(accountGuybrushOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", "guybrush"); OpenDJController.assertAttribute(entry, "givenName", "Guybrush"); OpenDJController.assertAttribute(entry, "sn", "Threepwood"); OpenDJController.assertAttribute(entry, "cn", "Guybrush Threepwood"); OpenDJController.assertAttribute(entry, "displayName", "Guybrush Threepwood"); // The "l" attribute is assigned indirectly through schemaHandling and // config object. It is not tolerant, therefore the other value should be gone now OpenDJController.assertAttribute(entry, "l", "Deep in the Caribbean"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "sailor"); // "title" is tolerant, so it will retain the original value as well as the one provided by the role OpenDJController.assertAttribute(entry, "title", "Scurvy earthworm", "Honorable Captain"); OpenDJController.assertAttribute(entry, "carLicense", "C4PT41N"); OpenDJController.assertAttribute(entry, "businessCategory", "cruise"); // No setting for "postOfficeBox", so the value should be unchanged OpenDJController.assertAttribute(entry, "postOfficeBox", "X marks the spot"); String guybrushPassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Pasword was not set on create", guybrushPassword); // QueryType query = QueryUtil.createNameQuery(ELAINE_NAME); // ObjectQuery query = ObjectQuery.createObjectQuery(EqualsFilter.createEqual(UserType.class, prismContext, UserType.F_NAME, ELAINE_NAME)); ObjectQuery query = ObjectQueryUtil.createNameQuery(ELAINE_NAME, prismContext); List<PrismObject<UserType>> users = repositoryService.searchObjects(UserType.class, query, null, repoResult); assertEquals("Wrong number of Elaines", 1, users.size()); repoUser = users.get(0).asObjectable(); repoResult.computeStatus(); displayJaxb("User Elaine (repository)", repoUser, new QName("user")); assertNotNull(repoUser.getOid()); assertEquals(PrismTestUtil.createPolyStringType(ELAINE_NAME), repoUser.getName()); PrismAsserts.assertEqualsPolyString("wrong repo givenName", "Elaine", repoUser.getGivenName()); PrismAsserts.assertEqualsPolyString("wrong repo familyName", "Marley", repoUser.getFamilyName()); PrismAsserts.assertEqualsPolyString("wrong repo fullName", "Elaine Marley", repoUser.getFullName()); accountRefs = repoUser.getLinkRef(); assertEquals("Elaine has wrong number of accounts", 1, accountRefs.size()); accountRef = accountRefs.get(0); String accountShadowOidElaineOpendj = accountRef.getOid(); assertFalse(accountShadowOidElaineOpendj.isEmpty()); // Check if shadow was created in the repo repoResult = new OperationResult("getObject"); repoShadow = repositoryService.getObject(ShadowType.class, accountShadowOidElaineOpendj, null, repoResult); repoShadowType = repoShadow.asObjectable(); repoResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", repoResult); displayJaxb("Shadow (repository)", repoShadowType, new QName("shadow")); assertNotNull(repoShadowType); assertEquals(RESOURCE_OPENDJ_OID, repoShadowType.getResourceRef().getOid()); String accountElainehOpendjEntryUuuid = checkRepoShadow(repoShadow); // check if account is still in LDAP entry = openDJController.searchAndAssertByEntryUuid(accountElainehOpendjEntryUuuid); display("LDAP account", entry); OpenDJController.assertAttribute(entry, "uid", ELAINE_NAME); OpenDJController.assertAttribute(entry, "givenName", "Elaine"); OpenDJController.assertAttribute(entry, "sn", "Marley"); OpenDJController.assertAttribute(entry, "cn", "Elaine Marley"); OpenDJController.assertAttribute(entry, "displayName", "Elaine Marley"); // The "l" attribute is assigned indirectly through schemaHandling and // config object // FIXME //OpenDJController.assertAttribute(entry, "l", "middle of nowhere"); // Set by the role OpenDJController.assertAttribute(entry, "employeeType", "governor"); OpenDJController.assertAttribute(entry, "title", "Governor"); OpenDJController.assertAttribute(entry, "businessCategory", "state"); String elainePassword = OpenDJController.getAttributeValue(entry, "userPassword"); assertNotNull("Password of Elaine has disappeared", elainePassword); checkAllShadows(); } @Test public void test480ListResources() throws Exception { final String TEST_NAME = "test480ListResources"; displayTestTitle(TEST_NAME); // GIVEN OperationResultType result = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(result); Holder<ObjectListType> objectListHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); // WHEN modelWeb.searchObjects(ObjectTypes.RESOURCE.getTypeQName(), null, options, objectListHolder, resultHolder); // THEN display("Resources", objectListHolder.value); assertEquals("Unexpected number of resources", 4, objectListHolder.value.getObject().size()); // TODO for(ObjectType object: objectListHolder.value.getObject()) { // Marshalling may fail even though the Java object is OK so test for it String xml = prismContext.serializeObjectToString(object.asPrismObject(), PrismContext.LANG_XML); } } @Test public void test485ListResourcesWithBrokenResource() throws Exception { TestUtil.displayTestTitle("test485ListResourcesWithBrokenResource"); // GIVEN Task task = taskManager.createTaskInstance(TestSanity.class.getName() + ".test410ListResourcesWithBrokenResource"); final OperationResult result = task.getResult(); // WHEN List<PrismObject<ResourceType>> resources = modelService.searchObjects(ResourceType.class, null, null, task, result); // THEN assertNotNull("listObjects returned null list", resources); for (PrismObject<ResourceType> object : resources) { ResourceType resource = object.asObjectable(); //display("Resource found",resource); display("Found " + ObjectTypeUtil.toShortString(resource) + ", result " + (resource.getFetchResult() == null ? "null" : resource.getFetchResult().getStatus())); assertNotNull(resource.getOid()); assertNotNull(resource.getName()); if (resource.getOid().equals(RESOURCE_BROKEN_OID)) { assertTrue("No error in fetchResult in " + ObjectTypeUtil.toShortString(resource), resource.getFetchResult() != null && (resource.getFetchResult().getStatus() == OperationResultStatusType.PARTIAL_ERROR || resource.getFetchResult().getStatus() == OperationResultStatusType.FATAL_ERROR)); } else { assertTrue("Unexpected error in fetchResult in " + ObjectTypeUtil.toShortString(resource), resource.getFetchResult() == null || resource.getFetchResult().getStatus() == OperationResultStatusType.SUCCESS); } } } @Test public void test500NotifyChangeCreateAccount() throws Exception{ final String TEST_NAME = "test500NotifyChangeCreateAccount"; displayTestTitle(TEST_NAME); Entry ldifEntry = openDJController.addEntryFromLdifFile(LDIF_ANGELIKA_FILENAME); display("Entry from LDIF", ldifEntry); List<Attribute> attributes = ldifEntry.getAttributes(); List<Attribute> attrs = ldifEntry.getAttribute("entryUUID"); AttributeValue val = null; if (attrs == null){ for (Attribute a : attributes){ if (a.getName().equals("entryUUID")){ val = a.iterator().next(); } } } else{ val = attrs.get(0).iterator().next(); } String entryUuid = val.toString(); ShadowType anglicaAccount = parseObjectType(new File(ACCOUNT_ANGELIKA_FILENAME), ShadowType.class); PrismProperty<String> prop = anglicaAccount.asPrismObject().findContainer(ShadowType.F_ATTRIBUTES).getValue().createProperty( prismContext.definitionFactory().createPropertyDefinition(getOpenDjPrimaryIdentifierQName(), DOMUtil.XSD_STRING)); prop.setRealValue(entryUuid); anglicaAccount.setResourceRef(ObjectTypeUtil.createObjectRef(RESOURCE_OPENDJ_OID, ObjectTypes.RESOURCE)); display("Angelica shadow: ", anglicaAccount.asPrismObject().debugDump()); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.ADD); delta.setObjectToAdd(anglicaAccount); delta.setObjectType(ShadowType.COMPLEX_TYPE); changeDescription.setObjectDelta(delta); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); PrismObject<ShadowType> modelShadow = modelService.getObject(ShadowType.class, oid, null, taskManager.createTaskInstance(), result); assertAttributeNotNull(modelShadow, getOpenDjPrimaryIdentifierQName()); assertAttribute(modelShadow, "uid", "angelika"); assertAttribute(modelShadow, "givenName", "Angelika"); assertAttribute(modelShadow, "sn", "Marley"); assertAttribute(modelShadow, "cn", "Angelika Marley"); } @Test public void test501NotifyChangeModifyAccount() throws Exception{ final String TEST_NAME = "test501NotifyChangeModifyAccount"; displayTestTitle(TEST_NAME); OperationResult parentResult = new OperationResult(TEST_NAME); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.MODIFY); delta.setObjectType(ShadowType.COMPLEX_TYPE); ItemDeltaType mod1 = new ItemDeltaType(); mod1.setModificationType(ModificationTypeType.REPLACE); ItemPathType path = new ItemPathType(ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(resourceTypeOpenDjrepo.getNamespace(), "givenName"))); mod1.setPath(path); RawType value = new RawType(prismContext.xnodeFactory().primitive("newAngelika"), prismContext); mod1.getValue().add(value); delta.getItemDelta().add(mod1); delta.setOid(oid); LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(mod1)); LOGGER.info("delta: {}", DebugUtil.dump(mod1)); changeDescription.setObjectDelta(delta); changeDescription.setOldShadowOid(oid); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); UserType userAfterSync = userAngelikaAfterSync.asObjectable(); PrismAsserts.assertEqualsPolyString("wrong given name in user angelika", PrismTestUtil.createPolyStringType("newAngelika"), userAfterSync.getGivenName()); } @Test public void test502NotifyChangeModifyAccountPassword() throws Exception{ final String TEST_NAME = "test502NotifyChangeModifyAccountPassword"; displayTestTitle(TEST_NAME); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); String newPassword = "newPassword"; openDJController.modifyReplace("uid="+ANGELIKA_NAME+","+openDJController.getSuffixPeople(), "userPassword", newPassword); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.MODIFY); delta.setObjectType(ShadowType.COMPLEX_TYPE); ItemDeltaType passwordDelta = new ItemDeltaType(); passwordDelta.setModificationType(ModificationTypeType.REPLACE); passwordDelta.setPath(ModelClientUtil.createItemPathType("credentials/password/value", prismContext)); RawType passwordValue = new RawType(prismContext.xnodeSerializer().root(new QName("dummy")).serializeRealValue(ModelClientUtil.createProtectedString(newPassword)).getSubnode(), prismContext); passwordDelta.getValue().add(passwordValue); delta.getItemDelta().add(passwordDelta); delta.setOid(oid); LOGGER.info("item delta: {}", SchemaDebugUtil.prettyPrint(passwordDelta)); LOGGER.info("delta: {}", DebugUtil.dump(passwordDelta)); changeDescription.setObjectDelta(delta); changeDescription.setOldShadowOid(oid); // changeDescription.setCurrentShadow(angelicaShadowType); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertSuccess(result); PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); assertUserLdapPassword(userAngelikaAfterSync, newPassword); } @Test public void test503NotifyChangeDeleteAccount() throws Exception{ final String TEST_NAME = "test503NotifyChangeDeleteAccount"; displayTestTitle(TEST_NAME); PrismObject<UserType> userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); UserType user = userAngelika.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", user.getLinkRef()); assertEquals("Expected one account ref in user", 1, user.getLinkRef().size()); String oid = user.getLinkRef().get(0).getOid(); ResourceObjectShadowChangeDescriptionType changeDescription = new ResourceObjectShadowChangeDescriptionType(); ObjectDeltaType delta = new ObjectDeltaType(); delta.setChangeType(ChangeTypeType.DELETE); delta.setObjectType(ShadowType.COMPLEX_TYPE); delta.setOid(oid); changeDescription.setObjectDelta(delta); changeDescription.setOldShadowOid(oid); changeDescription.setChannel(SchemaConstants.CHANNEL_WEB_SERVICE_URI); // WHEN TaskType task = modelWeb.notifyChange(changeDescription); // THEN OperationResult result = OperationResult.createOperationResult(task.getResult()); display(result); assertTrue(result.isAcceptable()); PrismObject<UserType> userAngelikaAfterSync = findUserByUsername(ANGELIKA_NAME); display("User after", userAngelikaAfterSync); assertNotNull("User with the name angelika must exist.", userAngelikaAfterSync); UserType userType = userAngelikaAfterSync.asObjectable(); assertNotNull("User with the name angelika must have one link ref.", userType.getLinkRef()); assertEquals("Expected no account ref in user", 0, userType.getLinkRef().size()); } @Test public void test999Shutdown() throws Exception { taskManager.shutdown(); waitFor("waiting for task manager shutdown", new Checker() { @Override public boolean check() { return taskManager.getLocallyRunningTasks(new OperationResult("dummy")).isEmpty(); } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, 10000); AssertJUnit.assertEquals("Some tasks left running after shutdown", new HashSet<Task>(), new HashSet<>(taskManager.getLocallyRunningTasks(new OperationResult("dummy")))); } // TODO: test for missing/corrupt system configuration // TODO: test for missing sample config (bad reference in expression // arguments) private String checkRepoShadow(PrismObject<ShadowType> repoShadow) { ShadowType repoShadowType = repoShadow.asObjectable(); String uid = null; boolean hasOthers = false; List<Object> xmlAttributes = repoShadowType.getAttributes().getAny(); for (Object element : xmlAttributes) { if (SchemaConstants.ICFS_UID.equals(JAXBUtil.getElementQName(element)) || getOpenDjPrimaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) { if (uid != null) { AssertJUnit.fail("Multiple values for ICF UID in shadow attributes"); } else { uid = ((Element) element).getTextContent(); } } else if (SchemaConstants.ICFS_NAME.equals(JAXBUtil.getElementQName(element)) || getOpenDjSecondaryIdentifierQName().equals(JAXBUtil.getElementQName(element))) { // This is OK } else { hasOthers = true; } } assertFalse("Shadow "+repoShadow+" has unexpected elements", hasOthers); assertNotNull(uid); return uid; } private QName getOpenDjPrimaryIdentifierQName() { return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME); } private QName getOpenDjSecondaryIdentifierQName() { return new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME); } private ShadowType searchAccountByOid(final String accountOid) throws Exception { OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<ObjectType> accountHolder = new Holder<>(); SelectorQualifiedGetOptionsType options = new SelectorQualifiedGetOptionsType(); modelWeb.getObject(ObjectTypes.SHADOW.getTypeQName(), accountOid, options, accountHolder, resultHolder); ObjectType object = accountHolder.value; TestUtil.assertSuccess("searchObjects has failed", resultHolder.value); assertNotNull("Account is null", object); if (!(object instanceof ShadowType)) { fail("Object is not account."); } ShadowType account = (ShadowType) object; assertEquals(accountOid, account.getOid()); return account; } private UserType searchUserByName(String name) throws Exception { // Document doc = DOMUtil.getDocument(); // Element nameElement = doc.createElementNS(SchemaConstants.C_NAME.getNamespaceURI(), // SchemaConstants.C_NAME.getLocalPart()); // nameElement.setTextContent(name); // Element filter = QueryUtil.createEqualFilter(doc, null, nameElement); // // QueryType query = new QueryType(); // query.setFilter(filter); ObjectQuery q = ObjectQueryUtil.createNameQuery(UserType.class, prismContext, name); QueryType query = prismContext.getQueryConverter().createQueryType(q); OperationResultType resultType = new OperationResultType(); Holder<OperationResultType> resultHolder = new Holder<>(resultType); Holder<ObjectListType> listHolder = new Holder<>(); assertNoRepoCache(); modelWeb.searchObjects(ObjectTypes.USER.getTypeQName(), query, null, listHolder, resultHolder); assertNoRepoCache(); ObjectListType objects = listHolder.value; TestUtil.assertSuccess("searchObjects has failed", resultHolder.value); AssertJUnit.assertEquals("User not found (or found too many)", 1, objects.getObject().size()); UserType user = (UserType) objects.getObject().get(0); AssertJUnit.assertEquals(user.getName(), PrismTestUtil.createPolyStringType(name)); return user; } private void basicWaitForSyncChangeDetection(Task syncCycle, Object tokenBefore, int increment, final OperationResult result) throws Exception { basicWaitForSyncChangeDetection(syncCycle, (int)((Integer)tokenBefore), increment, result); } private void basicWaitForSyncChangeDetection(Task syncCycle, int tokenBefore, int increment, final OperationResult result) throws Exception { basicWaitForSyncChangeDetection(syncCycle, tokenBefore, increment, result, 40000); } private void basicWaitForSyncChangeDetection(final Task syncCycle, final int tokenBefore, final int increment, final OperationResult result, int timeout) throws Exception { waitFor("Waiting for sync cycle to detect change", new Checker() { @Override public boolean check() throws CommonException { syncCycle.refresh(result); display("SyncCycle while waiting for sync cycle to detect change", syncCycle); if (syncCycle.getExecutionStatus() != TaskExecutionStatus.RUNNABLE) { throw new IllegalStateException("Task not runnable: "+syncCycle.getExecutionStatus()+"; "+syncCycle); } int tokenNow = findSyncToken(syncCycle); display("tokenNow = " + tokenNow); if (tokenNow >= tokenBefore + increment) { return true; } else { return false; } } @Override public void timeout() { // No reaction, the test will fail right after return from this } }, timeout, WAIT_FOR_LOOP_SLEEP_MILIS); } private void setAssignmentEnforcement(AssignmentPolicyEnforcementType enforcementType) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(enforcementType); // AccountSynchronizationSettingsType syncSettings = new AccountSynchronizationSettingsType(); // syncSettings.setAssignmentPolicyEnforcement(enforcementType); // applySyncSettings(SystemConfigurationType.class, syncSettings); } private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType assignmentPolicy) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult("Asserting sync settings"); PrismObject<SystemConfigurationType> systemConfigurationType = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result); result.computeStatus(); TestUtil.assertSuccess("Asserting sync settings failed (result)", result); ProjectionPolicyType globalAccountSynchronizationSettings = systemConfigurationType.asObjectable().getGlobalAccountSynchronizationSettings(); assertNotNull("globalAccountSynchronizationSettings is null", globalAccountSynchronizationSettings); AssignmentPolicyEnforcementType assignmentPolicyEnforcement = globalAccountSynchronizationSettings.getAssignmentPolicyEnforcement(); assertNotNull("assignmentPolicyEnforcement is null", assignmentPolicyEnforcement); assertEquals("Assignment policy mismatch", assignmentPolicy, assignmentPolicyEnforcement); } private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { LOGGER.trace("Checking all shadows"); System.out.println("Checking all shadows"); ObjectChecker<ShadowType> checker = null; IntegrationTestTools.checkAllShadows(resourceTypeOpenDjrepo, repositoryService, checker, prismContext); } public static String getNormalizedAttributeValue(ShadowType repoShadow, RefinedObjectClassDefinition objClassDef, QName name) { String value = getAttributeValue(repoShadow, name); RefinedAttributeDefinition idDef = objClassDef.getPrimaryIdentifiers().iterator().next(); if (idDef.getMatchingRuleQName() != null && idDef.getMatchingRuleQName().equals(PrismConstants.STRING_IGNORE_CASE_MATCHING_RULE_NAME)){ return value.toLowerCase(); } return value; } protected <T> void assertAttribute(ShadowType shadowType, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadowType, attrName, expectedValues); } protected <T> void assertAttribute(PrismObject<ShadowType> shadow, String attrName, T... expectedValues) { assertAttribute(resourceTypeOpenDjrepo, shadow.asObjectable(), attrName, expectedValues); } }
bshp/midPoint
testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java
Java
apache-2.0
199,213
/* * Copyright 2017 Crown Copyright * * 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 stroom.security.identity.authenticate; import stroom.security.identity.authenticate.api.AuthenticationService; import stroom.util.guice.RestResourcesBinder; import com.google.inject.AbstractModule; public final class AuthenticateModule extends AbstractModule { @Override protected void configure() { bind(AuthenticationService.class).to(AuthenticationServiceImpl.class); RestResourcesBinder.create(binder()) .bind(AuthenticationResourceImpl.class); } }
gchq/stroom
stroom-security/stroom-security-identity/src/main/java/stroom/security/identity/authenticate/AuthenticateModule.java
Java
apache-2.0
1,110
package com.example.android.bluetoothlegatt.ble_service; /** * @author Sopheak Tuon * @created on 04-Oct-17 */ import java.util.Locale; public class CountryUtils { public static boolean getMonthAndDayFormate() { Locale locale = Locale.getDefault(); String lang = locale.getLanguage(); String contr = locale.getCountry(); if (lang == null || (!lang.equals("zh") && !lang.equals("ja") && !lang.equals("ko") && (!lang.equals("en") || contr == null || !contr.equals("US")))) { return false; } return true; } public static boolean getLanguageFormate() { String language = Locale.getDefault().getLanguage(); if (language == null || !language.equals("zh")) { return false; } return true; } }
SopheakTuon/Smart-Bracelet
Application/src/main/java/com/example/android/bluetoothlegatt/ble_service/CountryUtils.java
Java
apache-2.0
812
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.workmailmessageflow.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.workmailmessageflow.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * MessageRejectedException JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MessageRejectedExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller { private MessageRejectedExceptionUnmarshaller() { super(com.amazonaws.services.workmailmessageflow.model.MessageRejectedException.class, "MessageRejected"); } @Override public com.amazonaws.services.workmailmessageflow.model.MessageRejectedException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception { com.amazonaws.services.workmailmessageflow.model.MessageRejectedException messageRejectedException = new com.amazonaws.services.workmailmessageflow.model.MessageRejectedException( null); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return messageRejectedException; } private static MessageRejectedExceptionUnmarshaller instance; public static MessageRejectedExceptionUnmarshaller getInstance() { if (instance == null) instance = new MessageRejectedExceptionUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-workmailmessageflow/src/main/java/com/amazonaws/services/workmailmessageflow/model/transform/MessageRejectedExceptionUnmarshaller.java
Java
apache-2.0
2,934
package nl.esciencecenter.e3dchem.modifiedtanimoto; import org.knime.base.util.flowvariable.FlowVariableProvider; import org.knime.core.data.DataTableSpec; import org.knime.core.node.InvalidSettingsException; import org.knime.core.node.util.CheckUtils; import org.knime.distance.category.DistanceCategoryConfig; import org.knime.distance.util.propertyresolver.Configuration; import org.knime.distance.util.propertyresolver.Property; @Configuration public final class ModifiedTanimotoDistanceConfig extends DistanceCategoryConfig<ModifiedTanimotoDistance> { @Property("meanBitDensity") private double meanBitDensity = 0.01; /** * Framework constructor. */ ModifiedTanimotoDistanceConfig() { } public ModifiedTanimotoDistanceConfig(final double meanBitDensity, String column) throws InvalidSettingsException { super(column); this.meanBitDensity = meanBitDensity; CheckUtils.checkSetting(meanBitDensity >= 0, "mean bit density is not positive: %f ", meanBitDensity); } @Override protected DistanceCategoryConfig<?> clone(String... columns) throws InvalidSettingsException { CheckUtils.checkSetting(columns != null && columns.length == 1, "Exactly one column must be selected."); return new ModifiedTanimotoDistanceConfig(meanBitDensity, columns[0]); } @Override public String getFactoryId() { return ModifiedTanimotoDistanceFactory.ID; } /** * {@inheritDoc} */ @Override public ModifiedTanimotoDistance createDistanceMeasure(DataTableSpec spec, FlowVariableProvider flowVariableProvider) throws InvalidSettingsException { return new ModifiedTanimotoDistance(this, spec); } public double getMeanBitDensity() { return meanBitDensity; } public void setMeanBitDensity(final double meanBitDensity) { this.meanBitDensity = meanBitDensity; } }
3D-e-Chem/knime-modified-tanimoto
nl.esciencecenter.e3dchem.modifiedtanimoto/src/nl/esciencecenter/e3dchem/modifiedtanimoto/ModifiedTanimotoDistanceConfig.java
Java
apache-2.0
1,815
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.jmeter.protocol.http.sampler; import java.io.IOException; import java.net.Socket; import javax.net.ssl.SSLSocket; import org.apache.http.HttpHost; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.OperatedClientConnection; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.conn.DefaultClientConnection; import org.apache.http.impl.conn.DefaultClientConnectionOperator; import org.apache.jmeter.util.HostNameSetter; /** * Custom implementation of {@link DefaultClientConnectionOperator} to fix SNI Issue * @see "https://bz.apache.org/bugzilla/show_bug.cgi?id=57935" * @since 3.0 * TODO Remove it when full upgrade to 4.5.X is done and cleanup is made in the Socket Factory of JMeter that handles client certificates and Slow socket */ public class JMeterClientConnectionOperator extends DefaultClientConnectionOperator { /** * @param schemes * the scheme registry */ public JMeterClientConnectionOperator(final SchemeRegistry schemes) { super(schemes); } /** * @param schemes * the scheme registry * @param dnsResolver * the custom DNS lookup mechanism */ public JMeterClientConnectionOperator(final SchemeRegistry schemes, final DnsResolver dnsResolver) { super(schemes, dnsResolver); } @Override public OperatedClientConnection createConnection() { return new JMeterDefaultClientConnection(); } private static class JMeterDefaultClientConnection extends DefaultClientConnection { public JMeterDefaultClientConnection() { super(); } /* (non-Javadoc) * @see org.apache.http.impl.conn.DefaultClientConnection#opening(java.net.Socket, org.apache.http.HttpHost) */ @Override public void opening(Socket sock, HttpHost target) throws IOException { super.opening(sock, target); if(sock instanceof SSLSocket) { HostNameSetter.setServerNameIndication(target.getHostName(), (SSLSocket) sock); } } } }
ra0077/jmeter
src/protocol/http/org/apache/jmeter/protocol/http/sampler/JMeterClientConnectionOperator.java
Java
apache-2.0
3,341
package com.jota.patterns.singleton; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.jota.patterns.singleton.singleton.User; public class MainActivity extends AppCompatActivity { @BindView(R.id.user1) TextView user1Text; @BindView(R.id.user2) TextView user2Text; @BindView(R.id.user3) TextView user3Text; private User user, user1, user2, user3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); user = User.getInstance(); user.setToken("token"); user.setSocialNetwork("Facebook"); user1 = User.getInstance(); user2 = User.getInstance(); user3 = User.getInstance(); } private void showUsers() { user1Text.setText(user1.getSocialNetwork() + " - " + user1.getToken()); user2Text.setText(user2.getSocialNetwork() + " - " + user2.getToken()); user3Text.setText(user3.getSocialNetwork() + " - " + user3.getToken()); } @OnClick(R.id.change_social_button) public void changeSocial() { user.setSocialNetwork("Twitter"); showUsers(); } @OnClick(R.id.change_token_button) public void changeToken() { user.setToken("Token token"); showUsers(); } }
jotaramirez90/Android-DesignPatterns
singleton/src/main/java/com/jota/patterns/singleton/MainActivity.java
Java
apache-2.0
1,406
package com.gotcreations.emojilibrary.controller; import android.animation.Animator; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import androidx.annotation.DrawableRes; import androidx.appcompat.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.gotcreations.emojilibrary.R; import com.gotcreations.emojilibrary.model.layout.EmojiCompatActivity; import com.gotcreations.emojilibrary.model.layout.EmojiEditText; import com.gotcreations.emojilibrary.model.layout.AppPanelEventListener; import com.gotcreations.emojilibrary.model.layout.TelegramPanelView; import com.gotcreations.emojilibrary.util.AbstractAnimatorListener; import static android.view.View.GONE; import static android.view.View.getDefaultSize; /** * Created by edgar on 18/02/2016. */ public class TelegramPanel extends AppPanel{ private static final String TAG = "TelegramPanel"; public static final int EMPTY_MESSAGE = 0; public static final int EMPTY_MESSAGE_EMOJI_KEYBOARD = 1; public static final int EMPTY_MESSAGE_KEYBOARD = 2; public static final int PREPARED_MESSAGE = 3; public static final int PREPARED_MESSAGE_EMOJI_KEYBOARD = 4; public static final int PREPARED_MESSAGE_KEYBOARD = 5; public static final int AUDIO = 6; private Toolbar mBottomPanel; private TextView audioTime; private TelegramPanelView panelView; private int state; // CONSTRUCTOR public TelegramPanel(EmojiCompatActivity activity, AppPanelEventListener listener) { super(activity); this.mActivity = activity; init(); this.mEmojiKeyboard = new EmojiKeyboard(this.mActivity, this.mInput); this.mListener = listener; } public TelegramPanel(EmojiCompatActivity activity) { this(activity, null); } // INITIALIZATION @Override protected void initBottomPanel() { this.audioTime = (TextView) this.mActivity.findViewById(R.id.audio_time); this.mBottomPanel = (Toolbar) this.mActivity.findViewById(R.id.panel); this.panelView = (TelegramPanelView) this.mActivity.findViewById(R.id.panel_container).getParent(); this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); this.mBottomPanel.inflateMenu(R.menu.telegram_menu); this.mBottomPanel.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (state == AUDIO) { fireOnMicOffClicked(); showAudioPanel(false); } else if (TelegramPanel.this.isEmojiKeyboardVisible) { TelegramPanel.this.closeCurtain(); if (TelegramPanel.this.mInput.isSoftKeyboardVisible()) { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); TelegramPanel.this.mInput.hideSoftKeyboard(); } else { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); TelegramPanel.this.mInput.showSoftKeyboard(); } } else { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); TelegramPanel.this.closeCurtain(); TelegramPanel.this.showEmojiKeyboard(0); } } }); this.mBottomPanel.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_attach) { fireOnAttachClicked(); } else if (item.getItemId() == R.id.action_mic) { switch (state) { case AUDIO: fireOnSendClicked(); showAudioPanel(false); break; default: if (TelegramPanel.this.mInput.getText().toString().equals("")) { showAudioPanel(true); } else { fireOnSendClicked(); } } } return Boolean.TRUE; } }); this.mCurtain = (LinearLayout) this.mActivity.findViewById(R.id.curtain); this.state = EMPTY_MESSAGE; } @Override protected void setInputConfig() { this.mInput = (EmojiEditText) this.mBottomPanel.findViewById(R.id.input); mInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); this.mInput.addOnSoftKeyboardListener(new EmojiEditText.OnSoftKeyboardListener() { @Override public void onSoftKeyboardDisplay() { if (!TelegramPanel.this.isEmojiKeyboardVisible) { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.schedule(new Runnable() { @Override public void run() { Handler mainHandler = new Handler(TelegramPanel.this.mActivity.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { TelegramPanel.this.openCurtain(); TelegramPanel.this.showEmojiKeyboard(0); } }; mainHandler.post(myRunnable); } }, 150, TimeUnit.MILLISECONDS); } } @Override public void onSoftKeyboardHidden() { if (TelegramPanel.this.isEmojiKeyboardVisible) { TelegramPanel.this.closeCurtain(); TelegramPanel.this.hideEmojiKeyboard(200); } } }); this.mInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { showSendOptions(true); } @Override public void afterTextChanged(Editable s) { } }); audioTime.setTextColor(panelView.getAudioTextColor()); mInput.setTextColor(panelView.getTextColor()); mInput.setHint(panelView.getHintText()); mInput.setHintTextColor(panelView.getTextColorHint()); setIcon(R.id.action_attach, panelView.getAttachIconColor(), R.drawable.ic_attachment); setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic); } private void setIcon(int itemId, int color, @DrawableRes int drawableId) { Drawable icon = mActivity.getResources().getDrawable(drawableId); icon.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); setIcon(itemId, icon); } private void setIcon(int itemId, Drawable icon) { Menu menu = this.mBottomPanel.getMenu(); MenuItem mi = menu.findItem(itemId); mi.setIcon(icon); } @Override public void showAudioPanel(final boolean show) { if (show) { state = AUDIO; hideEmojiKeyboard(0); this.mInput.hideSoftKeyboard(); this.mInput.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Hide mInput"); mInput.setVisibility(GONE); } }).start(); this.audioTime.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "show audioTime"); audioTime.setVisibility(View.VISIBLE); } }).start(); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } Drawable icCircle = mActivity.getResources().getDrawable(R.drawable.ic_circle); icCircle.setColorFilter(panelView.getAudioIconColor(), PorterDuff.Mode.SRC_ATOP); this.mBottomPanel.setNavigationIcon(icCircle); fireOnMicOnClicked(); } else { this.audioTime.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Hide audioInput"); audioTime.setVisibility(GONE); } }).start(); this.mInput.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Show mInput"); mInput.setVisibility(View.VISIBLE); } }).start(); showSendOptions(true); } } public void showSendOptions(boolean show) { final MenuItem micButton = TelegramPanel.this.mBottomPanel.getMenu().findItem(R.id.action_mic); if (isEmojiKeyboardVisible) { this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); } else { this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); } if (!this.mInput.getText().toString().equals("") && show) { if (state != PREPARED_MESSAGE && state != PREPARED_MESSAGE_EMOJI_KEYBOARD && state != PREPARED_MESSAGE_KEYBOARD) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } } state = PREPARED_MESSAGE; if (mInput.isSoftKeyboardVisible()) { state = PREPARED_MESSAGE_KEYBOARD; } else if (isEmojiKeyboardVisible) { state = PREPARED_MESSAGE_EMOJI_KEYBOARD; } } else { state = EMPTY_MESSAGE; if (mInput.isSoftKeyboardVisible()) { state = EMPTY_MESSAGE_KEYBOARD; } else if (isEmojiKeyboardVisible) { state = EMPTY_MESSAGE_EMOJI_KEYBOARD; } TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(1).scaleY(1).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } } } public int getState() { return state; } public boolean isInState(int state) { return this.state == state; } public boolean isInAudioState() { return isInState(AUDIO); } public boolean isInMessageState() { return !isInAudioState(); } @Override public void hideEmojiKeyboard(int delay) { super.hideEmojiKeyboard(delay); this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); } public void setAudioTime(CharSequence time) { this.audioTime.setText(time); } }
ander7agar/emoji-keyboard
emoji-library/src/main/java/com/gotcreations/emojilibrary/controller/TelegramPanel.java
Java
apache-2.0
13,759
/** * Copyright Pravega 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 io.pravega.controller.server.eventProcessor.requesthandlers; import com.google.common.annotations.VisibleForTesting; import io.pravega.common.Timer; import io.pravega.common.concurrent.Futures; import io.pravega.common.tracing.TagLogger; import io.pravega.controller.eventProcessor.impl.SerializedRequestHandler; import io.pravega.controller.metrics.TransactionMetrics; import io.pravega.controller.server.ControllerService; import io.pravega.controller.store.stream.OperationContext; import io.pravega.controller.store.stream.StreamMetadataStore; import io.pravega.controller.store.stream.records.StreamSegmentRecord; import io.pravega.controller.task.Stream.StreamMetadataTasks; import io.pravega.shared.controller.event.AbortEvent; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import org.slf4j.LoggerFactory; /** * This actor processes commit txn events. * It does the following 2 operations in order. * 1. Send abort txn message to active segments of the stream. * 2. Change txn state from aborting to aborted. */ public class AbortRequestHandler extends SerializedRequestHandler<AbortEvent> { private static final TagLogger log = new TagLogger(LoggerFactory.getLogger(AbortRequestHandler.class)); private final StreamMetadataStore streamMetadataStore; private final StreamMetadataTasks streamMetadataTasks; private final ScheduledExecutorService executor; private final BlockingQueue<AbortEvent> processedEvents; @VisibleForTesting public AbortRequestHandler(final StreamMetadataStore streamMetadataStore, final StreamMetadataTasks streamMetadataTasks, final ScheduledExecutorService executor, final BlockingQueue<AbortEvent> queue) { super(executor); this.streamMetadataStore = streamMetadataStore; this.streamMetadataTasks = streamMetadataTasks; this.executor = executor; this.processedEvents = queue; } public AbortRequestHandler(final StreamMetadataStore streamMetadataStore, final StreamMetadataTasks streamMetadataTasks, final ScheduledExecutorService executor) { super(executor); this.streamMetadataStore = streamMetadataStore; this.streamMetadataTasks = streamMetadataTasks; this.executor = executor; this.processedEvents = null; } @Override public CompletableFuture<Void> processEvent(AbortEvent event) { String scope = event.getScope(); String stream = event.getStream(); int epoch = event.getEpoch(); UUID txId = event.getTxid(); long requestId = event.getRequestId(); if (requestId == 0L) { requestId = ControllerService.nextRequestId(); } Timer timer = new Timer(); OperationContext context = streamMetadataStore.createStreamContext(scope, stream, requestId); log.info(requestId, "Aborting transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); return Futures.toVoid(streamMetadataStore.getSegmentsInEpoch(event.getScope(), event.getStream(), epoch, context, executor) .thenApply(segments -> segments.stream().map(StreamSegmentRecord::segmentId) .collect(Collectors.toList())) .thenCompose(segments -> streamMetadataTasks.notifyTxnAbort(scope, stream, segments, txId, context.getRequestId())) .thenCompose(x -> streamMetadataStore.abortTransaction(scope, stream, txId, context, executor)) .whenComplete((result, error) -> { if (error != null) { log.warn(context.getRequestId(), "Failed aborting transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); TransactionMetrics.getInstance().abortTransactionFailed(scope, stream); } else { log.info(context.getRequestId(), "Successfully aborted transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); if (processedEvents != null) { processedEvents.offer(event); } TransactionMetrics.getInstance().abortTransaction(scope, stream, timer.getElapsed()); } })); } }
pravega/pravega
controller/src/main/java/io/pravega/controller/server/eventProcessor/requesthandlers/AbortRequestHandler.java
Java
apache-2.0
5,395
/** * Copyright 2011-2021 Asakusa Framework Team. * * 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.asakusafw.directio.hive.serde; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.math.BigDecimal; import java.sql.Timestamp; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.serde2.io.HiveCharWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable; import org.apache.hadoop.hive.serde2.io.TimestampWritable; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveCharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector; import org.apache.hadoop.io.Text; import org.junit.Test; import com.asakusafw.runtime.value.Date; import com.asakusafw.runtime.value.DateOption; import com.asakusafw.runtime.value.DateTime; import com.asakusafw.runtime.value.DateTimeOption; import com.asakusafw.runtime.value.DecimalOption; import com.asakusafw.runtime.value.StringOption; /** * Test for {@link ValueSerdeFactory}. */ public class ValueSerdeFactoryTest { /** * constants. */ @Test public void constants() { for (ValueSerdeFactory serde : ValueSerdeFactory.values()) { serde.getDriver(serde.getInspector()); } } /** * char. */ @Test public void getChar() { ValueSerde serde = ValueSerdeFactory.getChar(10); HiveCharObjectInspector inspector = (HiveCharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveChar value = new HiveChar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveCharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * varchar. */ @Test public void getVarchar() { ValueSerde serde = ValueSerdeFactory.getVarchar(10); HiveVarcharObjectInspector inspector = (HiveVarcharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveVarchar value = new HiveVarchar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); // HiveVarchar cannot compare by equals assertThat(inspector.getPrimitiveJavaObject(option).compareTo(value), is(0)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveVarcharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * qualified decimal. */ @Test public void getDecimal() { ValueSerde serde = ValueSerdeFactory.getDecimal(10, 2); HiveDecimalObjectInspector inspector = (HiveDecimalObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45")); HiveDecimal value = HiveDecimal.create(new BigDecimal("123.45")); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveDecimalWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * decimal by string. */ @Test public void decimal_by_string() { ValueSerde serde = StringValueSerdeFactory.DECIMAL; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45")); String value = "123.45"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by string. */ @Test public void date_by_string() { ValueSerde serde = StringValueSerdeFactory.DATE; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); String value = "2014-07-01"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(2014, 7, 1, 12, 5, 59)); String value = "2014-07-01 12:05:59"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string_w_zeros() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(1, 1, 1, 0, 0, 0)); String value = "0001-01-01 00:00:00"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by timestamp. */ @SuppressWarnings("deprecation") @Test public void date_by_timestamp() { ValueSerde serde = TimestampValueSerdeFactory.DATE; TimestampObjectInspector inspector = (TimestampObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); Timestamp value = new Timestamp(2014 - 1900, 7 - 1, 1, 0, 0, 0, 0); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new TimestampWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } }
asakusafw/asakusafw
hive-project/core-v2/src/test/java/com/asakusafw/directio/hive/serde/ValueSerdeFactoryTest.java
Java
apache-2.0
11,792
import arez.Arez; import arez.ArezContext; import arez.Component; import arez.Disposable; import arez.ObservableValue; import arez.SafeProcedure; import arez.component.DisposeNotifier; import arez.component.Identifiable; import arez.component.internal.ComponentKernel; import java.text.ParseException; import javax.annotation.Generated; import javax.annotation.Nonnull; import org.realityforge.braincheck.Guards; @Generated("arez.processor.ArezProcessor") final class Arez_ObservableWithSpecificExceptionModel extends ObservableWithSpecificExceptionModel implements Disposable, Identifiable<Integer>, DisposeNotifier { private static volatile int $$arezi$$_nextId; private final ComponentKernel $$arezi$$_kernel; @Nonnull private final ObservableValue<Long> $$arez$$_time; Arez_ObservableWithSpecificExceptionModel() { super(); final ArezContext $$arezv$$_context = Arez.context(); final int $$arezv$$_id = ++$$arezi$$_nextId; final String $$arezv$$_name = Arez.areNamesEnabled() ? "ObservableWithSpecificExceptionModel." + $$arezv$$_id : null; final Component $$arezv$$_component = Arez.areNativeComponentsEnabled() ? $$arezv$$_context.component( "ObservableWithSpecificExceptionModel", $$arezv$$_id, $$arezv$$_name, this::$$arezi$$_nativeComponentPreDispose ) : null; this.$$arezi$$_kernel = new ComponentKernel( Arez.areZonesEnabled() ? $$arezv$$_context : null, Arez.areNamesEnabled() ? $$arezv$$_name : null, $$arezv$$_id, Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, null, Arez.areNativeComponentsEnabled() ? null : this::$$arezi$$_dispose, null, true, false, false ); this.$$arez$$_time = $$arezv$$_context.observable( Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, Arez.areNamesEnabled() ? $$arezv$$_name + ".time" : null, Arez.arePropertyIntrospectorsEnabled() ? () -> super.getTime() : null, Arez.arePropertyIntrospectorsEnabled() ? v -> super.setTime( v ) : null ); this.$$arezi$$_kernel.componentConstructed(); this.$$arezi$$_kernel.componentReady(); } private int $$arezi$$_id() { return this.$$arezi$$_kernel.getId(); } @Override @Nonnull public Integer getArezId() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'getArezId' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'getArezId' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return $$arezi$$_id(); } private void $$arezi$$_nativeComponentPreDispose() { this.$$arezi$$_kernel.notifyOnDisposeListeners(); } @Override public void addOnDisposeListener(@Nonnull final Object key, @Nonnull final SafeProcedure action) { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'addOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } this.$$arezi$$_kernel.addOnDisposeListener( key, action ); } @Override public void removeOnDisposeListener(@Nonnull final Object key) { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'removeOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'removeOnDisposeListener' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } this.$$arezi$$_kernel.removeOnDisposeListener( key ); } @Override public boolean isDisposed() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'isDisposed' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'isDisposed' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return this.$$arezi$$_kernel.isDisposed(); } @Override public void dispose() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'dispose' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'dispose' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } this.$$arezi$$_kernel.dispose(); } private void $$arezi$$_dispose() { this.$$arez$$_time.dispose(); } @Override public long getTime() throws ParseException { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'getTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" ); } this.$$arez$$_time.reportObserved(); return super.getTime(); } @Override public void setTime(final long time) throws ParseException { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'setTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" ); } this.$$arez$$_time.preReportChanged(); final long $$arezv$$_currentValue = super.getTime(); if ( time != $$arezv$$_currentValue ) { super.setTime( time ); this.$$arez$$_time.reportChanged(); } } @Override public String toString() { if ( Arez.areNamesEnabled() ) { return "ArezComponent[" + this.$$arezi$$_kernel.getName() + "]"; } else { return super.toString(); } } }
realityforge/arez
processor/src/test/fixtures/expected/Arez_ObservableWithSpecificExceptionModel.java
Java
apache-2.0
6,870
/** * Licensing arrangement (from website FAQ): * * The software is completely free for any purpose, unless notes at the * head of the program text indicates otherwise (which is rare). In any * case, the notes about licensing are never more restrictive than the * BSD License. * */ package com.novartis.pcs.ontology.service.mapper; /* Porter stemmer in Java. The original paper is in Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, no. 3, pp 130-137, See also http://www.tartarus.org/~martin/PorterStemmer/index.html Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below. Tthe words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1] is then out outside the bounds of b. Similarly, Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below. 'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and b[j] is then outside the bounds of b. Release 3. [ This version is derived from Release 3, modified by Brian Goetz to optimize for fewer object creations. ] */ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * * Stemmer, implementing the Porter Stemming Algorithm * * The Stemmer class transforms a word into its root form. The input * word can be provided a character at time (by calling add()), or at once * by calling one of the various stem(something) methods. */ class PorterStemmer { private char[] b; private int i, /* offset into b */ j, k, k0; private boolean dirty = false; private static final int INC = 50; /* unit of size whereby b is increased */ private static final int EXTRA = 1; public PorterStemmer() { b = new char[INC]; i = 0; } /** * reset() resets the stemmer so it can stem another word. If you invoke * the stemmer by calling add(char) and then stem(), you must call reset() * before starting another word. */ public void reset() { i = 0; dirty = false; } /** * Add a character to the word being stemmed. When you are finished * adding characters, you can call stem(void) to process the word. */ public void add(char ch) { if (b.length <= i + EXTRA) { char[] new_b = new char[b.length+INC]; System.arraycopy(b, 0, new_b, 0, b.length); b = new_b; } b[i++] = ch; } /** * After a word has been stemmed, it can be retrieved by toString(), * or a reference to the internal buffer can be retrieved by getResultBuffer * and getResultLength (which is generally more efficient.) */ @Override public String toString() { return new String(b,0,i); } /** * Returns the length of the word resulting from the stemming process. */ public int getResultLength() { return i; } /** * Returns a reference to a character buffer containing the results of * the stemming process. You also need to consult getResultLength() * to determine the length of the result. */ public char[] getResultBuffer() { return b; } /* cons(i) is true <=> b[i] is a consonant. */ private final boolean cons(int i) { switch (b[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': return false; case 'y': return (i==k0) ? true : !cons(i-1); default: return true; } } /* m() measures the number of consonant sequences between k0 and j. if c is a consonant sequence and v a vowel sequence, and <..> indicates arbitrary presence, <c><v> gives 0 <c>vc<v> gives 1 <c>vcvc<v> gives 2 <c>vcvcvc<v> gives 3 .... */ private final int m() { int n = 0; int i = k0; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; while(true) { while(true) { if (i > j) return n; if (cons(i)) break; i++; } i++; n++; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; } } /* vowelinstem() is true <=> k0,...j contains a vowel */ private final boolean vowelinstem() { int i; for (i = k0; i <= j; i++) if (! cons(i)) return true; return false; } /* doublec(j) is true <=> j,(j-1) contain a double consonant. */ private final boolean doublec(int j) { if (j < k0+1) return false; if (b[j] != b[j-1]) return false; return cons(j); } /* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant and also if the second c is not w,x or y. this is used when trying to restore an e at the end of a short word. e.g. cav(e), lov(e), hop(e), crim(e), but snow, box, tray. */ private final boolean cvc(int i) { if (i < k0+2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; else { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; } private final boolean ends(String s) { int l = s.length(); int o = k-l+1; if (o < k0) return false; for (int i = 0; i < l; i++) if (b[o+i] != s.charAt(i)) return false; j = k-l; return true; } /* setto(s) sets (j+1),...k to the characters in the string s, readjusting k. */ void setto(String s) { int l = s.length(); int o = j+1; for (int i = 0; i < l; i++) b[o+i] = s.charAt(i); k = j+l; dirty = true; } /* r(s) is used further down. */ void r(String s) { if (m() > 0) setto(s); } /* step1() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree disabled -> disable matting -> mat mating -> mate meeting -> meet milling -> mill messing -> mess meetings -> meet */ private final void step1() { if (b[k] == 's') { if (ends("sses")) k -= 2; else if (ends("ies")) setto("i"); else if (b[k-1] != 's') k--; } if (ends("eed")) { if (m() > 0) k--; } else if ((ends("ed") || ends("ing")) && vowelinstem()) { k = j; if (ends("at")) setto("ate"); else if (ends("bl")) setto("ble"); else if (ends("iz")) setto("ize"); else if (doublec(k)) { int ch = b[k--]; if (ch == 'l' || ch == 's' || ch == 'z') k++; } else if (m() == 1 && cvc(k)) setto("e"); } } /* step2() turns terminal y to i when there is another vowel in the stem. */ private final void step2() { if (ends("y") && vowelinstem()) { b[k] = 'i'; dirty = true; } } /* step3() maps double suffices to single ones. so -ization ( = -ize plus -ation) maps to -ize etc. note that the string before the suffix must give m() > 0. */ private final void step3() { if (k == k0) return; /* For Bug 1 */ switch (b[k-1]) { case 'a': if (ends("ational")) { r("ate"); break; } if (ends("tional")) { r("tion"); break; } break; case 'c': if (ends("enci")) { r("ence"); break; } if (ends("anci")) { r("ance"); break; } break; case 'e': if (ends("izer")) { r("ize"); break; } break; case 'l': if (ends("bli")) { r("ble"); break; } if (ends("alli")) { r("al"); break; } if (ends("entli")) { r("ent"); break; } if (ends("eli")) { r("e"); break; } if (ends("ousli")) { r("ous"); break; } break; case 'o': if (ends("ization")) { r("ize"); break; } if (ends("ation")) { r("ate"); break; } if (ends("ator")) { r("ate"); break; } break; case 's': if (ends("alism")) { r("al"); break; } if (ends("iveness")) { r("ive"); break; } if (ends("fulness")) { r("ful"); break; } if (ends("ousness")) { r("ous"); break; } break; case 't': if (ends("aliti")) { r("al"); break; } if (ends("iviti")) { r("ive"); break; } if (ends("biliti")) { r("ble"); break; } break; case 'g': if (ends("logi")) { r("log"); break; } } } /* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */ private final void step4() { switch (b[k]) { case 'e': if (ends("icate")) { r("ic"); break; } if (ends("ative")) { r(""); break; } if (ends("alize")) { r("al"); break; } break; case 'i': if (ends("iciti")) { r("ic"); break; } break; case 'l': if (ends("ical")) { r("ic"); break; } if (ends("ful")) { r(""); break; } break; case 's': if (ends("ness")) { r(""); break; } break; } } /* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */ private final void step5() { if (k == k0) return; /* for Bug 1 */ switch (b[k-1]) { case 'a': if (ends("al")) break; return; case 'c': if (ends("ance")) break; if (ends("ence")) break; return; case 'e': if (ends("er")) break; return; case 'i': if (ends("ic")) break; return; case 'l': if (ends("able")) break; if (ends("ible")) break; return; case 'n': if (ends("ant")) break; if (ends("ement")) break; if (ends("ment")) break; /* element etc. not stripped before the m */ if (ends("ent")) break; return; case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break; /* j >= 0 fixes Bug 2 */ if (ends("ou")) break; return; /* takes care of -ous */ case 's': if (ends("ism")) break; return; case 't': if (ends("ate")) break; if (ends("iti")) break; return; case 'u': if (ends("ous")) break; return; case 'v': if (ends("ive")) break; return; case 'z': if (ends("ize")) break; return; default: return; } if (m() > 1) k = j; } /* step6() removes a final -e if m() > 1. */ private final void step6() { j = k; if (b[k] == 'e') { int a = m(); if (a > 1 || a == 1 && !cvc(k-1)) k--; } if (b[k] == 'l' && doublec(k) && m() > 1) k--; } /** * Stem a word provided as a String. Returns the result as a String. */ public String stem(String s) { if (stem(s.toCharArray(), s.length())) return toString(); else return s; } /** Stem a word contained in a char[]. Returns true if the stemming process * resulted in a word different from the input. You can retrieve the * result with getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] word) { return stem(word, word.length); } /** Stem a word contained in a portion of a char[] array. Returns * true if the stemming process resulted in a word different from * the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] wordBuffer, int offset, int wordLen) { reset(); if (b.length < wordLen) { char[] new_b = new char[wordLen + EXTRA]; b = new_b; } System.arraycopy(wordBuffer, offset, b, 0, wordLen); i = wordLen; return stem(0); } /** Stem a word contained in a leading portion of a char[] array. * Returns true if the stemming process resulted in a word different * from the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] word, int wordLen) { return stem(word, 0, wordLen); } /** Stem the word placed into the Stemmer buffer through calls to add(). * Returns true if the stemming process resulted in a word different * from the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem() { return stem(0); } public boolean stem(int i0) { k = i - 1; k0 = i0; if (k > k0+1) { step1(); step2(); step3(); step4(); step5(); step6(); } // Also, a word is considered dirty if we lopped off letters // Thanks to Ifigenia Vairelles for pointing this out. if (i != k+1) dirty = true; i = k+1; return dirty; } /** Test program for demonstrating the Stemmer. It reads a file and * stems each word, writing the result to standard out. * Usage: Stemmer file-name */ public static void main(String[] args) { PorterStemmer s = new PorterStemmer(); for (int i = 0; i < args.length; i++) { try { InputStream in = new FileInputStream(args[i]); byte[] buffer = new byte[1024]; int bufferLen, offset, ch; bufferLen = in.read(buffer); offset = 0; s.reset(); while(true) { if (offset < bufferLen) ch = buffer[offset++]; else { bufferLen = in.read(buffer); offset = 0; if (bufferLen < 0) ch = -1; else ch = buffer[offset++]; } if (Character.isLetter((char) ch)) { s.add(Character.toLowerCase((char) ch)); } else { s.stem(); System.out.print(s.toString()); s.reset(); if (ch < 0) break; else { System.out.print((char) ch); } } } in.close(); } catch (IOException e) { System.out.println("error reading " + args[i]); } } } }
Novartis/ontobrowser
src/main/java/com/novartis/pcs/ontology/service/mapper/PorterStemmer.java
Java
apache-2.0
13,830
/* * Copyright 2014-2021 Sayi * * 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.deepoove.poi.xwpf; import java.util.List; import org.apache.poi.xwpf.usermodel.IRunBody; import org.apache.poi.xwpf.usermodel.XWPFFieldRun; import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.xmlbeans.XmlObject; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField; public class ParagraphContext implements RunBodyContext { private XWPFParagraphWrapper paragraphWrapper; public ParagraphContext(XWPFParagraphWrapper paragraphWrapper) { this.paragraphWrapper = paragraphWrapper; } @Override public IRunBody getTarget() { return paragraphWrapper.getParagraph(); } @Override public List<XWPFRun> getRuns() { return paragraphWrapper.getParagraph().getRuns(); } @Override public void setAndUpdateRun(XWPFRun xwpfRun, XWPFRun sourceRun, int insertPostionCursor) { paragraphWrapper.setAndUpdateRun(xwpfRun, sourceRun, insertPostionCursor); } @Override public XWPFRun insertNewRun(XWPFRun xwpfRun, int insertPostionCursor) { if (xwpfRun instanceof XWPFHyperlinkRun) { return paragraphWrapper.insertNewHyperLinkRun(insertPostionCursor, ""); } else if (xwpfRun instanceof XWPFFieldRun) { return paragraphWrapper.insertNewField(insertPostionCursor); } else { return paragraphWrapper.insertNewRun(insertPostionCursor); } } @Override public XWPFRun createRun(XWPFRun xwpfRun, IRunBody p) { if (xwpfRun instanceof XWPFHyperlinkRun) { return new XWPFHyperlinkRun((CTHyperlink) ((XWPFHyperlinkRun) xwpfRun).getCTHyperlink().copy(), (CTR) ((XWPFHyperlinkRun) xwpfRun).getCTR().copy(), p); } else if (xwpfRun instanceof XWPFFieldRun) { return new XWPFFieldRun((CTSimpleField) ((XWPFFieldRun) xwpfRun).getCTField().copy(), (CTR) ((XWPFFieldRun) xwpfRun).getCTR().copy(), p); } else { return new XWPFRun((CTR) xwpfRun.getCTR().copy(), p); } } @Override public XWPFRun createRun(XmlObject object, IRunBody p) { if (object instanceof CTHyperlink) { return new XWPFHyperlinkRun((CTHyperlink) object, ((CTHyperlink) object).getRArray(0), p); } else if (object instanceof CTSimpleField) { return new XWPFFieldRun((CTSimpleField) object, ((CTSimpleField) object).getRArray(0), p); } else { return new XWPFRun((CTR) object, p); } } @Override public void removeRun(int pos) { paragraphWrapper.removeRun(pos); } }
Sayi/poi-tl
poi-tl/src/main/java/com/deepoove/poi/xwpf/ParagraphContext.java
Java
apache-2.0
3,416
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.portable; import org.apache.ignite.internal.portable.streams.*; import org.apache.ignite.internal.util.*; import org.apache.ignite.internal.util.typedef.internal.*; import sun.misc.*; import static org.apache.ignite.IgniteSystemProperties.*; /** * Thread-local memory allocator. */ public class PortableThreadLocalMemoryAllocator implements PortableMemoryAllocator { /** Memory allocator instance. */ public static final PortableThreadLocalMemoryAllocator THREAD_LOCAL_ALLOC = new PortableThreadLocalMemoryAllocator(); /** Holders. */ private static final ThreadLocal<ByteArrayHolder> holders = new ThreadLocal<>(); /** Unsafe instance. */ protected static final Unsafe UNSAFE = GridUnsafe.unsafe(); /** Array offset: byte. */ protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class); /** * Ensures singleton. */ private PortableThreadLocalMemoryAllocator() { // No-op. } /** {@inheritDoc} */ @Override public byte[] allocate(int size) { ByteArrayHolder holder = holders.get(); if (holder == null) holders.set(holder = new ByteArrayHolder()); if (holder.acquired) return new byte[size]; holder.acquired = true; if (holder.data == null || size > holder.data.length) holder.data = new byte[size]; return holder.data; } /** {@inheritDoc} */ @Override public byte[] reallocate(byte[] data, int size) { ByteArrayHolder holder = holders.get(); assert holder != null; byte[] newData = new byte[size]; if (holder.data == data) holder.data = newData; UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length); return newData; } /** {@inheritDoc} */ @Override public void release(byte[] data, int maxMsgSize) { ByteArrayHolder holder = holders.get(); assert holder != null; if (holder.data != data) return; holder.maxMsgSize = maxMsgSize; holder.acquired = false; holder.shrink(); } /** {@inheritDoc} */ @Override public long allocateDirect(int size) { return 0; } /** {@inheritDoc} */ @Override public long reallocateDirect(long addr, int size) { return 0; } /** {@inheritDoc} */ @Override public void releaseDirect(long addr) { // No-op } /** * Checks whether a thread-local array is acquired or not. * The function is used by Unit tests. * * @return {@code true} if acquired {@code false} otherwise. */ public boolean isThreadLocalArrayAcquired() { ByteArrayHolder holder = holders.get(); return holder != null && holder.acquired; } /** * Thread-local byte array holder. */ private static class ByteArrayHolder { /** */ private static final Long CHECK_FREQ = Long.getLong(IGNITE_MARSHAL_BUFFERS_RECHECK, 10000); /** Data array */ private byte[] data; /** Max message size detected between checks. */ private int maxMsgSize; /** Last time array size is checked. */ private long lastCheck = U.currentTimeMillis(); /** Whether the holder is acquired or not. */ private boolean acquired; /** * Shrinks array size if needed. */ private void shrink() { long now = U.currentTimeMillis(); if (now - lastCheck >= CHECK_FREQ) { int halfSize = data.length >> 1; if (maxMsgSize < halfSize) data = new byte[halfSize]; lastCheck = now; } } } }
avinogradovgg/ignite
modules/core/src/main/java/org/apache/ignite/internal/portable/PortableThreadLocalMemoryAllocator.java
Java
apache-2.0
4,612
package BinaryTreeLevelOrderTraversal; import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class BinaryTreeLevelOrderTraversalSolutionTest { private BinaryTreeLevelOrderTraversalSolution solution = new BinaryTreeLevelOrderTraversalSolution(); @Test public void nullInput() { List<List<Integer>> result = solution.levelOrder(null); assertThat(result).isEmpty(); } @Test public void singleNodeInput() { TreeNode root = new TreeNode(1); List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(1); assertThat(result.get(0)).containsExactly(1); } @Test public void twoNodesInput() { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(2); assertThat(result.get(0)).containsExactly(1); assertThat(result.get(1)).containsExactly(2); } @Test public void threeNodesInput() { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(2); assertThat(result.get(0)).containsExactly(1); assertThat(result.get(1)).containsExactly(2, 3); } @Test public void fiveNodesInput() { TreeNode root = new TreeNode(3); root.left = new TreeNode(9); TreeNode rightTree = new TreeNode(20); rightTree.left = new TreeNode(15); rightTree.right = new TreeNode(7); root.right = rightTree; List<List<Integer>> result = solution.levelOrder(root); assertThat(result).hasSize(3); assertThat(result.get(0)).containsExactly(3); assertThat(result.get(1)).containsExactly(9, 20); assertThat(result.get(2)).containsExactly(15, 7); } }
mengdd/LeetCode
algorithms/src/test/java/BinaryTreeLevelOrderTraversal/BinaryTreeLevelOrderTraversalSolutionTest.java
Java
apache-2.0
2,013
package cn.aezo.spring.base.annotation.combineannotation; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by smalle on 2017/6/11. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration @ComponentScan public @interface WiselyConfiguration { String[] value() default {}; }
oldinaction/smjava
javaee/spring/src/main/java/cn/aezo/spring/base/annotation/combineannotation/WiselyConfiguration.java
Java
apache-2.0
607
/* * Copyright 2006-2011 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kew.xml.export; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.kew.export.KewExportDataSet; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.group.GroupService; import org.kuali.rice.kim.api.identity.IdentityService; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.test.BaselineTestCase; import java.util.List; import static org.junit.Assert.assertTrue; /** * This is a description of what this class does - jjhanso don't forget to fill this in. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ @BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE) public class GroupXmlExporterTest extends XmlExporterTestCase { /** * This overridden method ... * * @see org.kuali.rice.kew.xml.export.XmlExporterTestCase#assertExport() */ @Override protected void assertExport() throws Exception { IdentityService identityService = KimApiServiceLocator.getIdentityService(); GroupService groupService = KimApiServiceLocator.getGroupService(); List<? extends Group> oldGroups = groupService.getGroupsByPrincipalId( identityService.getPrincipalByPrincipalName("ewestfal").getPrincipalId()); KewExportDataSet dataSet = new KewExportDataSet(); dataSet.getGroups().addAll(oldGroups); byte[] xmlBytes = CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet()); assertTrue("XML should be non empty.", xmlBytes != null && xmlBytes.length > 0); StringBuffer output = new StringBuffer(); for (int i=0; i < xmlBytes.length; i++){ output.append((char)xmlBytes[i]); } System.out.print(output.toString()); // now clear the tables //ClearDatabaseLifecycle clearLifeCycle = new ClearDatabaseLifecycle(); //clearLifeCycle.getTablesToClear().add("EN_RULE_BASE_VAL_T"); //clearLifeCycle.getTablesToClear().add("EN_RULE_ATTRIB_T"); //clearLifeCycle.getTablesToClear().add("EN_RULE_TMPL_T"); //clearLifeCycle.getTablesToClear().add("EN_DOC_TYP_T"); //clearLifeCycle.start(); //new ClearCacheLifecycle().stop(); //KimImplServiceLocator.getGroupService(). // import the exported xml //loadXmlStream(new BufferedInputStream(new ByteArrayInputStream(xmlBytes))); /* List newRules = KEWServiceLocator.getRuleService().fetchAllRules(true); assertEquals("Should have same number of old and new Rules.", oldRules.size(), newRules.size()); for (Iterator iterator = oldRules.iterator(); iterator.hasNext();) { RuleBaseValues oldRule = (RuleBaseValues) iterator.next(); boolean foundRule = false; for (Iterator iterator2 = newRules.iterator(); iterator2.hasNext();) { RuleBaseValues newRule = (RuleBaseValues) iterator2.next(); if (oldRule.getDescription().equals(newRule.getDescription())) { assertRuleExport(oldRule, newRule); foundRule = true; } } assertTrue("Could not locate the new rule for description " + oldRule.getDescription(), foundRule); } */ } }
sbower/kuali-rice-1
it/kew/src/test/java/org/kuali/rice/kew/xml/export/GroupXmlExporterTest.java
Java
apache-2.0
4,009
/** * Copyright 2015 Smart Society Services B.V. * * 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 */ package com.alliander.osgp.core.infra.jms.protocol.in; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jms.ConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; import org.springframework.beans.factory.InitializingBean; import org.springframework.jms.core.JmsTemplate; import com.alliander.osgp.core.infra.jms.JmsTemplateSettings; import com.alliander.osgp.domain.core.entities.ProtocolInfo; public class ProtocolResponseMessageJmsTemplateFactory implements InitializingBean { private final ConnectionFactory connectionFactory; private final JmsTemplateSettings jmsTemplateSettings; private Map<String, JmsTemplate> jmsTemplateMap = new HashMap<>(); public ProtocolResponseMessageJmsTemplateFactory(final ConnectionFactory connectionFactory, final JmsTemplateSettings jmsTemplateSettings, final List<ProtocolInfo> protocolInfos) { this.connectionFactory = connectionFactory; this.jmsTemplateSettings = jmsTemplateSettings; for (final ProtocolInfo protocolInfo : protocolInfos) { this.jmsTemplateMap.put(protocolInfo.getKey(), this.createJmsTemplate(protocolInfo)); } } public JmsTemplate getJmsTemplate(final String key) { return this.jmsTemplateMap.get(key); } @Override public void afterPropertiesSet() { for (final JmsTemplate jmsTemplate : this.jmsTemplateMap.values()) { jmsTemplate.afterPropertiesSet(); } } private JmsTemplate createJmsTemplate(final ProtocolInfo protocolInfo) { final JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setDefaultDestination(new ActiveMQQueue(protocolInfo.getOutgoingProtocolResponsesQueue())); // Enable the use of deliveryMode, priority, and timeToLive jmsTemplate.setExplicitQosEnabled(this.jmsTemplateSettings.isExplicitQosEnabled()); jmsTemplate.setTimeToLive(this.jmsTemplateSettings.getTimeToLive()); jmsTemplate.setDeliveryPersistent(this.jmsTemplateSettings.isDeliveryPersistent()); jmsTemplate.setConnectionFactory(this.connectionFactory); return jmsTemplate; } }
wernerb/Platform
osgp-core/src/main/java/com/alliander/osgp/core/infra/jms/protocol/in/ProtocolResponseMessageJmsTemplateFactory.java
Java
apache-2.0
2,471
package com.codedpoetry.maven.dockerplugin.templates; import java.io.StringWriter; import java.util.Map; public interface TemplateRenderer { StringWriter renderTemplate(String templateUrl, Map context); }
fllaca/docker-maven-plugin
src/main/java/com/codedpoetry/maven/dockerplugin/templates/TemplateRenderer.java
Java
apache-2.0
209
package st.domain.quitanda.client.model.contract; /** * Created by Daniel Costa at 8/27/16. * Using user computer xdata */ public interface TypePayment { public int getDataBaseId(); }
danie555costa/Quitanda
app/src/main/java/st/domain/quitanda/client/model/contract/TypePayment.java
Java
apache-2.0
192
package example.repo; import example.model.Customer1794; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1794Repository extends CrudRepository<Customer1794, Long> { List<Customer1794> findByLastName(String lastName); }
spring-projects/spring-data-examples
jpa/deferred/src/main/java/example/repo/Customer1794Repository.java
Java
apache-2.0
284
package io.github.dantesun.petclinic.data.velocity; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.parsing.XNode; import org.apache.ibatis.scripting.LanguageDriver; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.Alias; import org.mybatis.scripting.velocity.Driver; /** * Created by dsun on 15/2/22. */ @Alias("velocity") public class VelocityDriver implements LanguageDriver { private Driver driverImpl = new Driver(); @Override public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { return driverImpl.createParameterHandler(mappedStatement, parameterObject, boundSql); } @Override public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) { return createSqlSource(configuration, script.getNode().getTextContent(), parameterType); } @Override public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) { if (parameterType == null) { parameterType = Object.class; } return new VelocitySqlSource(configuration, script, parameterType); } }
dantesun/webapp-boilerplate
core-models/src/main/java/io/github/dantesun/petclinic/data/velocity/VelocityDriver.java
Java
apache-2.0
1,398
package core.utils; import java.util.ArrayList; import java.util.List; public class Page<T> { public static final int PAGE_SIZE = 10; protected List<T> listObjects = new ArrayList<>(); protected int currentPage; protected int pageSize = PAGE_SIZE; /** * Constructor. * @param list contains the ArrayList to copy * @param page correspond to the currentPage */ public Page(List<T> list, int page) { for (int i = 0; i < list.size(); i++) { this.listObjects.add(list.get(i)); } this.currentPage = page; } /** * Constructor. * @param list contains the ArrayList to copy * @param page correspond to the currentPage * @param pageSize the page size */ public Page(List<T> list, int page, int pageSize) { for (int i = 0; i < list.size(); i++) { this.listObjects.add(list.get(i)); } this.currentPage = page; this.pageSize = pageSize; } /** * Get the ArrayList containing a T page. * @return the ArrayList containing a T page */ public List<T> getListPage() { return listObjects; } /** * Get the next page. * @return next page */ public int getNextPage() { return currentPage + 1; } /** * Get previous page. * @return previous page if currentPage > 0 else 0 */ public int getPreviousPage() { if (currentPage > 0) { return currentPage - 1; } else { return 0; } } /** * Get the current page. * @return the current page */ public int getCurrentPage() { return currentPage; } /** * Get the page size. * @return the page size */ public int getPageSize() { return pageSize; } /** * Test if the ArrayList<T> is empty. * @return True if Empty, else false */ public boolean isEmpty() { return listObjects.isEmpty(); } /** * Returns a string representation of the object. * @return a string representation of the object. */ @Override public String toString() { return this.getClass() + " [listObjects = " + listObjects + "]"; } /** * Equals Methode. * @param o other object * @return true if equals, else false */ @Override public boolean equals(Object o) { Page<T> page = (Page<T>) o; if (page.getPageSize() != this.pageSize || page.getCurrentPage() != this.currentPage) { return false; } boolean equals = true; int i = 0; while (i < this.pageSize && equals) { equals = page.getListPage().get(i).equals(this.listObjects.get(i)); i++; } return equals; } /** * Hash Code. * @return hash code */ @Override public int hashCode() { int result = listObjects != null ? listObjects.hashCode() : 0; result = 31 * result + currentPage; result = 31 * result + pageSize; return result; } /** * Add a Object in the ArrayList. * @param t the object */ public void add(T t) { listObjects.add(t); } }
gdanguy/training-java-gdanguy
core/src/main/java/core/utils/Page.java
Java
apache-2.0
3,276