repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
jminusminus/core | stream/Readable.java | 2510 | //
// Copyright 2016, Yahoo Inc.
// Copyrights licensed under the New BSD License.
// See the accompanying LICENSE file for terms.
//
package github.com.jminusminus.core.stream;
public class Readable {
// Jmm Readable wraps https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html
protected java.io.InputStream stream;
Readable(String str) {
try {
this.stream = new InputStream(str.getBytes("utf8"));
} catch (Exception e) {
System.out.println(e);
}
}
Readable(String str, String encoding) {
try {
this.stream = new InputStream(str.getBytes(encoding));
} catch (Exception e) {
System.out.println(e);
}
}
Readable(byte[] b) {
this.stream = new InputStream(b);
}
Readable(java.io.InputStream stream) {
this.stream = stream;
}
// Returns an estimate of the number of bytes that can be read (or skipped over) from this
// input stream without blocking by the next invocation of a method for this input stream.
public int available() {
try {
return this.stream.available();
} catch (Exception e) {
System.out.println(e);
}
return -1;
}
// Closes this input stream and releases any system resources associated with the stream.
public boolean close() {
try {
this.stream.close();
return true;
} catch (Exception e) {
System.out.println(e);
}
return false;
}
// Marks the current position in this input stream.
public void mark(int readlimit){
this.stream.mark(readlimit);
}
// Repositions this stream to the position at the time the mark method was last called on this input stream.
public boolean reset() {
try {
this.stream.reset();
return true;
} catch (Exception e) {
System.out.println(e);
}
return false;
}
//
public String read(int size, String encoding) {
return "";
}
//
public byte[] read(int size) {
return new byte[size];
}
//
public String readTo(String str, String encoding) {
return "";
}
//
public byte[] readTo(int code) {
return new byte[0];
}
//
public byte[] readTo(byte code) {
return new byte[0];
}
//
public void pipe(Writable destination) {
}
}
| bsd-3-clause |
fwix/java-gearman | src/org/gearman/WorkerJob.java | 3036 | package org.gearman;
import org.gearman.JobServerPoolAbstract.ConnectionController;
import org.gearman.core.GearmanConnection;
import org.gearman.core.GearmanPacket;
import org.gearman.core.GearmanPacket.Magic;
import org.gearman.util.ByteArray;
/**
* The {@link GearmanJob} implementation for the {@link GearmanFunction} object. It provides
* the underlying implementation in sending data back to the client.
*
* @author isaiah.v
*/
class WorkerJob extends GearmanJob {
private final static byte[] DEFAULT_UID = new byte[]{0};
protected WorkerJob(final String function,final byte[] jobData,final ConnectionController<?,?> conn,final ByteArray jobHandle) {
super(function, jobData, DEFAULT_UID);
super.setConnection(conn, jobHandle);
}
@Override
public synchronized final void callbackData(final byte[] data) {
if(this.isComplete()) throw new IllegalStateException("Job has completed");
final GearmanConnection<?> conn = super.getConnection();
final ByteArray jobHandle = super.getJobHandle();
assert conn!=null;
assert jobHandle!=null;
conn.sendPacket(GearmanPacket.createWORK_DATA(Magic.REQ, jobHandle.getBytes(), data), null /*TODO*/);
}
@Override
public synchronized final void callbackWarning(final byte[] warning) {
if(this.isComplete()) throw new IllegalStateException("Job has completed");
final GearmanConnection<?> conn = super.getConnection();
final ByteArray jobHandle = super.getJobHandle();
assert conn!=null;
assert jobHandle!=null;
conn.sendPacket(GearmanPacket.createWORK_WARNING(Magic.REQ, jobHandle.getBytes(), warning), null /*TODO*/);
}
/*
@Override
public synchronized final void callbackException(final byte[] exception) {
if(this.isComplete()) throw new IllegalStateException("Job has completed");
final GearmanConnection<?> conn = super.getConnection();
final byte[] jobHandle = super.getJobHandle();
assert conn!=null;
assert jobHandle!=null;
conn.sendPacket(GearmanPacket.createWORK_EXCEPTION(Magic.REQ, jobHandle, exception),null ,null); //TODO
}
*/
@Override
public void callbackStatus(long numerator, long denominator) {
if(this.isComplete()) throw new IllegalStateException("Job has completed");
final GearmanConnection<?> conn = super.getConnection();
final ByteArray jobHandle = super.getJobHandle();
assert conn!=null;
assert jobHandle!=null;
conn.sendPacket(GearmanPacket.createWORK_STATUS(Magic.REQ, jobHandle.getBytes(), numerator, denominator), null /*TODO*/);
}
@Override
protected synchronized void onComplete(GearmanJobResult result) {
final GearmanConnection<?> conn = super.getConnection();
final ByteArray jobHandle = super.getJobHandle();
assert conn!=null;
assert jobHandle!=null;
if(result.isSuccessful()) {
conn.sendPacket(GearmanPacket.createWORK_COMPLETE(Magic.REQ, jobHandle.getBytes(), result.getData()),null /*TODO*/);
} else {
conn.sendPacket(GearmanPacket.createWORK_FAIL(Magic.REQ, jobHandle.getBytes()),null /*TODO*/);
}
}
}
| bsd-3-clause |
broadinstitute/picard | src/test/java/picard/fingerprint/CalculateFingerprintMetricsTest.java | 3721 | package picard.fingerprint;
import htsjdk.samtools.metrics.MetricsFile;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import picard.cmdline.CommandLineProgramTest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.testng.Assert.assertEquals;
public class CalculateFingerprintMetricsTest extends CommandLineProgramTest {
@Override
public String getCommandLineProgramName() {
return CalculateFingerprintMetrics.class.getSimpleName();
}
private static final File TEST_DATA_DIR = new File("testdata/picard/fingerprint/");
private static final File TEST_GENOTYPES_VCF1 = new File(TEST_DATA_DIR, "NA12892.g.vcf");
private static final File NA12891_r1_sam = new File(TEST_DATA_DIR, "NA12891.over.fingerprints.r1.sam");
private static final File NA12892_r1_sam = new File(TEST_DATA_DIR, "NA12892.over.fingerprints.r1.sam");
private static final File na12891_fp = new File(TEST_DATA_DIR, "NA12891.fp.vcf");
private static final File na12892_fp = new File(TEST_DATA_DIR, "NA12892.fp.vcf");
private static final File HAPLOTYPE_MAP = new File(TEST_DATA_DIR, "Homo_sapiens_assembly19.haplotype_database.subset.txt");
@DataProvider
public static Object[][] testFingerprintMetricData() {
return new Object[][]{
{TEST_GENOTYPES_VCF1},
{NA12891_r1_sam},
{NA12892_r1_sam},
{na12891_fp},
{na12892_fp}
};
}
@Test(dataProvider = "testFingerprintMetricData")
public void testFingerprintMetric(final File fingerprintFile) throws IOException {
final File outputFile = File.createTempFile("testFingerprintMetric", "fingerprint_metric");
outputFile.deleteOnExit();
runIt(fingerprintFile, outputFile);
}
private void runIt(final File inputFile, final File outputFile) {
final List<String> args = new ArrayList<>(Arrays.asList(
"INPUT=" + inputFile.getAbsolutePath(),
"OUTPUT=" + outputFile.getAbsolutePath(),
"H=" + HAPLOTYPE_MAP.getAbsolutePath()));
assertEquals(runPicardCommandLine(args),0);
final List<FingerprintMetrics> metrics = MetricsFile.readBeans(outputFile);
for (FingerprintMetrics metric : metrics) {
Assert.assertTrue(metric.CHI_SQUARED_PVALUE > 0.05);
Assert.assertTrue(metric.LOG10_CHI_SQUARED_PVALUE > -2);
Assert.assertTrue(metric.LOD_SELF_CHECK > 0);
Assert.assertTrue(metric.CROSS_ENTROPY_LOD < 1);
Assert.assertTrue(metric.DEFINITE_GENOTYPES >= 0);
Assert.assertTrue(metric.HAPLOTYPES > 4);
Assert.assertTrue(metric.HAPLOTYPES_WITH_EVIDENCE > 0);
Assert.assertTrue(metric.HET_CHI_SQUARED_PVALUE > 0.05);
Assert.assertTrue(metric.LOG10_HET_CHI_SQUARED_PVALUE > -2);
Assert.assertTrue(metric.HET_CROSS_ENTROPY_LOD < 1);
Assert.assertTrue(metric.HOM_CHI_SQUARED_PVALUE > 0.05);
Assert.assertTrue(metric.LOG10_HOM_CHI_SQUARED_PVALUE > -2);
Assert.assertTrue(metric.HOM_CROSS_ENTROPY_LOD < 1);
Assert.assertTrue(metric.NUM_HET >= 0);
Assert.assertTrue(metric.NUM_HOM_ALLELE1 >= 0);
Assert.assertTrue(metric.NUM_HOM_ALLELE2 >= 0);
Assert.assertTrue(metric.EXPECTED_HET >= 0);
Assert.assertTrue(metric.EXPECTED_HOM_ALLELE1>= 0);
Assert.assertTrue(metric.EXPECTED_HOM_ALLELE2 >= 0);
Assert.assertTrue(metric.DISCRIMINATORY_POWER > 0);
}
}
} | mit |
TlatoaniHJ/MundoSK | src/com/pie/tlatoani/WebSocket/ExprWebSocketID.java | 522 | package com.pie.tlatoani.WebSocket;
import com.pie.tlatoani.Core.Skript.MundoPropertyExpression;
import com.pie.tlatoani.Core.Static.OptionalUtil;
import mundosk_libraries.java_websocket.WebSocket;
/**
* Created by Tlatoani on 9/3/17.
*/
public class ExprWebSocketID extends MundoPropertyExpression<WebSocket, String> {
@Override
public String convert(WebSocket webSocket) {
return OptionalUtil.cast(webSocket, SkriptWebSocketClient.class).map(client -> client.functionality.id).orElse(null);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/kusto/mgmt-v2019_05_15/src/main/java/com/microsoft/azure/management/kusto/v2019_05_15/implementation/DatabasePrincipalListResultInner.java | 1165 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.kusto.v2019_05_15.implementation;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The list Kusto database principals operation response.
*/
public class DatabasePrincipalListResultInner {
/**
* The list of Kusto database principals.
*/
@JsonProperty(value = "value")
private List<DatabasePrincipalInner> value;
/**
* Get the list of Kusto database principals.
*
* @return the value value
*/
public List<DatabasePrincipalInner> value() {
return this.value;
}
/**
* Set the list of Kusto database principals.
*
* @param value the value value to set
* @return the DatabasePrincipalListResultInner object itself.
*/
public DatabasePrincipalListResultInner withValue(List<DatabasePrincipalInner> value) {
this.value = value;
return this;
}
}
| mit |
ldebello/javacuriosities | JavaEE/JavaWebServices/JAX-WS/WSGenBasics/src/main/java/ar/com/javacuriosities/ws/gen/service/jaxws/GetIpAddressResponse.java | 962 |
package ar.com.javacuriosities.ws.gen.service.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "getIpAddressResponse", namespace = "http://service.gen.ws.javacuriosities.com.ar/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getIpAddressResponse", namespace = "http://service.gen.ws.javacuriosities.com.ar/")
public class GetIpAddressResponse {
@XmlElement(name = "return", namespace = "")
private String _return;
/**
*
* @return
* returns String
*/
public String getReturn() {
return this._return;
}
/**
*
* @param _return
* the value for the _return property
*/
public void setReturn(String _return) {
this._return = _return;
}
}
| mit |
CyanogenMod/android_external_mockito | test/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java | 3568 | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockitousage.annotation;
import org.fest.assertions.Assertions;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.util.MockUtil;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockitousage.examples.use.ArticleCalculator;
import org.mockitousage.examples.use.ArticleDatabase;
import org.mockitousage.examples.use.ArticleManager;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MockInjectionUsingConstructorTest {
private MockUtil mockUtil = new MockUtil();
@Mock private ArticleCalculator calculator;
@Mock private ArticleDatabase database;
@InjectMocks private ArticleManager articleManager;
@Spy @InjectMocks private ArticleManager spiedArticleManager;
@InjectMocks private ArticleVisitor should_be_initialized_several_times;
@Test
public void shouldNotFailWhenNotInitialized() {
assertNotNull(articleManager);
}
@Test(expected = IllegalArgumentException.class)
public void innerMockShouldRaiseAnExceptionThatChangesOuterMockBehavior() {
when(calculator.countArticles("new")).thenThrow(new IllegalArgumentException());
articleManager.updateArticleCounters("new");
}
@Test
public void mockJustWorks() {
articleManager.updateArticleCounters("new");
}
@Test
public void constructor_is_called_for_each_test() throws Exception {
int minimum_number_of_test_before = 3;
Assertions.assertThat(articleVisitorInstantiationCount).isGreaterThan(minimum_number_of_test_before);
Assertions.assertThat(articleVisitorMockInjectedInstances.size()).isGreaterThan(minimum_number_of_test_before);
}
@Test
public void objects_created_with_constructor_initialization_can_be_spied() throws Exception {
assertFalse(mockUtil.isMock(articleManager));
assertTrue(mockUtil.isMock(spiedArticleManager));
}
@Test
public void should_report_failure_only_when_object_initialization_throws_exception() throws Exception {
try {
MockitoAnnotations.initMocks(new ATest());
fail();
} catch (MockitoException e) {
Assertions.assertThat(e.getMessage()).contains("failingConstructor").contains("constructor").contains("threw an exception");
Assertions.assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
}
}
private static int articleVisitorInstantiationCount = 0;
private static Set<Object> articleVisitorMockInjectedInstances = new HashSet<Object>();
private static class ArticleVisitor {
public ArticleVisitor(ArticleCalculator calculator) {
articleVisitorInstantiationCount++;
articleVisitorMockInjectedInstances.add(calculator);
}
}
private static class FailingConstructor {
FailingConstructor(Set set) {
throw new IllegalStateException("always fail");
}
}
@Ignore("don't run this code in the test runner")
private static class ATest {
@Mock Set set;
@InjectMocks FailingConstructor failingConstructor;
}
}
| mit |
navalev/azure-sdk-for-java | sdk/network/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/network/v2019_08_01/Probe.java | 1770 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_08_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.network.v2019_08_01.implementation.ProbeInner;
import com.microsoft.azure.arm.model.Indexable;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2019_08_01.implementation.NetworkManager;
import java.util.List;
import com.microsoft.azure.SubResource;
/**
* Type representing Probe.
*/
public interface Probe extends HasInner<ProbeInner>, Indexable, Refreshable<Probe>, HasManager<NetworkManager> {
/**
* @return the etag value.
*/
String etag();
/**
* @return the id value.
*/
String id();
/**
* @return the intervalInSeconds value.
*/
Integer intervalInSeconds();
/**
* @return the loadBalancingRules value.
*/
List<SubResource> loadBalancingRules();
/**
* @return the name value.
*/
String name();
/**
* @return the numberOfProbes value.
*/
Integer numberOfProbes();
/**
* @return the port value.
*/
int port();
/**
* @return the protocol value.
*/
ProbeProtocol protocol();
/**
* @return the provisioningState value.
*/
ProvisioningState provisioningState();
/**
* @return the requestPath value.
*/
String requestPath();
/**
* @return the type value.
*/
String type();
}
| mit |
Aurasphere/facebot | src/main/java/co/aurasphere/botmill/fb/FbBotMillServlet.java | 8084 | /*
* MIT License
*
* Copyright (c) 2016 BotMill.io
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package co.aurasphere.botmill.fb;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import co.aurasphere.botmill.core.BotDefinition;
import co.aurasphere.botmill.core.base.BotMillServlet;
import co.aurasphere.botmill.fb.internal.util.json.FbBotMillJsonUtils;
import co.aurasphere.botmill.fb.internal.util.network.FbBotMillNetworkConstants;
import co.aurasphere.botmill.fb.model.incoming.MessageEnvelope;
import co.aurasphere.botmill.fb.model.incoming.MessengerCallback;
import co.aurasphere.botmill.fb.model.incoming.MessengerCallbackEntry;
import co.aurasphere.botmill.fb.model.incoming.handler.IncomingToOutgoingMessageHandler;
/**
* Main Servlet for FbBotMill framework. This servlet requires an init-param
* containing the fully qualified name of a class implementing
* {@link BotDefinition} in which the initial configuration is done. If not such
* class is found or can't be loaded, a ServletException is thrown during
* initialization.
*
* The FbBotMillServlet supports GET requests only for the Subscribing phase and
* POST requests for all the Facebook callbacks. For more information about how
* the communication is handled, check the documentation for {@link #doGet},
* {@link #doPost(HttpServletRequest, HttpServletResponse)} and Facebook's
* documentation with the link below.
*
* @author Donato Rimenti
* @author Alvin Reyes
*
* @see <a href=
* "https://developers.facebook.com/docs/messenger-platform/quickstart">
* Facebook Subscription info</a>
*
*/
public class FbBotMillServlet extends BotMillServlet {
/**
* The logger.
*/
private static final Logger logger = LoggerFactory
.getLogger(FbBotMillServlet.class);
/**
* The serial version UID.
*/
private static final long serialVersionUID = 1L;
/**
* Specifies how to handle a GET request. GET requests are used by Facebook
* only during the WebHook registration. During this phase, the
* FbBotMillServlet checks that the
* {@link FbBotMillNetworkConstants#HUB_MODE_PARAMETER} value received
* equals to {@link FbBotMillNetworkConstants#HUB_MODE_SUBSCRIBE} and that
* the {@link FbBotMillNetworkConstants#HUB_VERIFY_TOKEN_PARAMETER} value
* received equals to the {@link FbBotMillContext#getValidationToken()}. If
* that's true, then the FbBotMillServlet will reply sending back the value
* of the {@link FbBotMillNetworkConstants#HUB_CHALLENGE_PARAMETER}
* received, in order to confirm the registration, otherwise it will return
* an error 403.
*
* @param req
* the req
* @param resp
* the resp
* @throws ServletException
* the servlet exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Override
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Retrieves GET parameters.
String validationToken = FbBotMillContext.getInstance()
.getValidationToken();
Map<String, String[]> parameters = req.getParameterMap();
String hubMode = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_MODE_PARAMETER));
String hubToken = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_VERIFY_TOKEN_PARAMETER));
String hubChallenge = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_CHALLENGE_PARAMETER));
// Checks parameters and responds according to that.
if (hubMode.equals(FbBotMillNetworkConstants.HUB_MODE_SUBSCRIBE)
&& hubToken.equals(validationToken)) {
logger.info("Subscription OK.");
resp.setStatus(200);
resp.setContentType("text/plain");
resp.getWriter().write(hubChallenge);
} else {
logger.warn("GET received is not a subscription or wrong validation token. Ensure you have set the correct validation token using FbBotMillContext.getInstance().setup(String, String).");
resp.sendError(403);
}
}
/**
* Specifies how to handle a POST request. It parses the request as a
* {@link MessengerCallback} object. If the request is not a
* MessengerCallback, then the FbBotMillServlet logs an error and does
* nothing, otherwise it will forward the request to all registered bots in
* order to let them process the callbacks.
*
* @param req
* the req
* @param resp
* the resp
* @throws ServletException
* the servlet exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.trace("POST received!");
MessengerCallback callback = new MessengerCallback();
// Extrapolates and logs the JSON for debugging.
String json = readerToString(req.getReader());
logger.debug("JSON input: " + json);
// Parses the request as a MessengerCallback.
try {
callback = FbBotMillJsonUtils.fromJson(json, MessengerCallback.class);
} catch (Exception e) {
logger.error("Error during MessengerCallback parsing: ", e);
return;
}
// If the received POST is a MessengerCallback, it forwards the last
// envelope of all the callbacks received to the registered bots.
if (callback != null) {
List<MessengerCallbackEntry> callbackEntries = callback.getEntry();
if (callbackEntries != null) {
for (MessengerCallbackEntry entry : callbackEntries) {
List<MessageEnvelope> envelopes = entry.getMessaging();
if (envelopes != null) {
MessageEnvelope lastEnvelope = envelopes.get(envelopes.size() - 1);
IncomingToOutgoingMessageHandler.getInstance().process(lastEnvelope);
}
}
}
}
// Always set to ok.
resp.setStatus(HttpServletResponse.SC_OK);
}
/**
* Method which returns the first String in a String array if present or the
* empty String otherwise. Used to unwrap the GET arguments from an
* {@link HttpServletRequest#getParameterMap()} which returns a String array
* for each GET parameter.
*
* @param parameter
* the String array to unwrap.
* @return the first String of the array if found or the empty String
* otherwise.
*/
private static String safeUnwrapGetParameters(String[] parameter) {
if (parameter == null || parameter[0] == null) {
return "";
}
return parameter[0];
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "FbBotMillServlet []";
}
} | mit |
mhcrnl/java-swing-tips | DnDReorderTable/src/java/example/MainPanel.java | 7343 | package example;
//-*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import javax.activation.*;
import javax.swing.*;
import javax.swing.table.*;
public final class MainPanel extends JPanel {
private final TransferHandler handler = new TableRowTransferHandler();
private final String[] columnNames = {"String", "Integer", "Boolean"};
private final Object[][] data = {
{"AAA", 12, true}, {"aaa", 1, false},
{"BBB", 13, true}, {"bbb", 2, false},
{"CCC", 15, true}, {"ccc", 3, false},
{"DDD", 17, true}, {"ddd", 4, false},
{"EEE", 18, true}, {"eee", 5, false},
{"FFF", 19, true}, {"fff", 6, false},
{"GGG", 92, true}, {"ggg", 0, false}
};
private final DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override public Class<?> getColumnClass(int column) {
// ArrayIndexOutOfBoundsException: 0 >= 0
// Bug ID: JDK-6967479 JTable sorter fires even if the model is empty
// http://bugs.java.com/view_bug.do?bug_id=6967479
//return getValueAt(0, column).getClass();
switch (column) {
case 0:
return String.class;
case 1:
return Number.class;
case 2:
return Boolean.class;
default:
return super.getColumnClass(column);
}
}
};
private final JTable table = new JTable(model);
public MainPanel() {
super(new BorderLayout());
table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setTransferHandler(handler);
table.setDropMode(DropMode.INSERT_ROWS);
table.setDragEnabled(true);
table.setFillsViewportHeight(true);
//table.setAutoCreateRowSorter(true); //XXX
//Disable row Cut, Copy, Paste
ActionMap map = table.getActionMap();
AbstractAction dummy = new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) { /* Dummy action */ }
};
map.put(TransferHandler.getCutAction().getValue(Action.NAME), dummy);
map.put(TransferHandler.getCopyAction().getValue(Action.NAME), dummy);
map.put(TransferHandler.getPasteAction().getValue(Action.NAME), dummy);
JPanel p = new JPanel(new BorderLayout());
p.add(new JScrollPane(table));
p.setBorder(BorderFactory.createTitledBorder("Drag & Drop JTable"));
add(p);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
//Demo - BasicDnD (Drag and Drop and Data Transfer)>http://docs.oracle.com/javase/tutorial/uiswing/dnd/basicdemo.html
class TableRowTransferHandler extends TransferHandler {
private final DataFlavor localObjectFlavor;
private int[] indices;
private int addIndex = -1; //Location where items were added
private int addCount; //Number of items added.
public TableRowTransferHandler() {
super();
localObjectFlavor = new ActivationDataFlavor(Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
}
@Override protected Transferable createTransferable(JComponent c) {
JTable table = (JTable) c;
DefaultTableModel model = (DefaultTableModel) table.getModel();
List<Object> list = new ArrayList<>();
indices = table.getSelectedRows();
for (int i: indices) {
list.add(model.getDataVector().get(i));
}
Object[] transferedObjects = list.toArray();
return new DataHandler(transferedObjects, localObjectFlavor.getMimeType());
}
@Override public boolean canImport(TransferSupport info) {
JTable table = (JTable) info.getComponent();
boolean isDropable = info.isDrop() && info.isDataFlavorSupported(localObjectFlavor);
//XXX bug?
table.setCursor(isDropable ? DragSource.DefaultMoveDrop : DragSource.DefaultMoveNoDrop);
return isDropable;
}
@Override public int getSourceActions(JComponent c) {
return MOVE; //TransferHandler.COPY_OR_MOVE;
}
@Override public boolean importData(TransferSupport info) {
if (!canImport(info)) {
return false;
}
TransferHandler.DropLocation tdl = info.getDropLocation();
if (!(tdl instanceof JTable.DropLocation)) {
return false;
}
JTable.DropLocation dl = (JTable.DropLocation) tdl;
JTable target = (JTable) info.getComponent();
DefaultTableModel model = (DefaultTableModel) target.getModel();
int index = dl.getRow();
//boolean insert = dl.isInsert();
int max = model.getRowCount();
if (index < 0 || index > max) {
index = max;
}
addIndex = index;
target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
try {
Object[] values = (Object[]) info.getTransferable().getTransferData(localObjectFlavor);
addCount = values.length;
for (int i = 0; i < values.length; i++) {
int idx = index++;
model.insertRow(idx, (Vector) values[i]);
target.getSelectionModel().addSelectionInterval(idx, idx);
}
return true;
} catch (UnsupportedFlavorException | IOException ex) {
ex.printStackTrace();
}
return false;
}
@Override protected void exportDone(JComponent c, Transferable data, int action) {
cleanup(c, action == MOVE);
}
private void cleanup(JComponent c, boolean remove) {
if (remove && indices != null) {
c.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
DefaultTableModel model = (DefaultTableModel) ((JTable) c).getModel();
if (addCount > 0) {
for (int i = 0; i < indices.length; i++) {
if (indices[i] >= addIndex) {
indices[i] += addCount;
}
}
}
for (int i = indices.length - 1; i >= 0; i--) {
model.removeRow(indices[i]);
}
}
indices = null;
addCount = 0;
addIndex = -1;
}
}
| mit |
bjrke/just-java-toolbox | just-java-test-toolbox/src/main/java/de/justsoftware/toolbox/testng/DataProviders.java | 3248 | package de.justsoftware.toolbox.testng;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
/**
* Utility for {@link org.testng.annotations.DataProvider}s.
*
* @author Jan Burkhardt (initial creation)
*/
public final class DataProviders {
private DataProviders() {
super();
}
private abstract static class DataProviderIterator<T> implements Iterator<Object[]> {
private final Iterator<? extends T> _iterator;
private DataProviderIterator(@Nonnull final Iterator<? extends T> iterator) {
_iterator = iterator;
}
@Override
public final boolean hasNext() {
return _iterator.hasNext();
}
@Override
public final Object[] next() {
return next(_iterator.next());
}
@Nonnull
protected abstract Object[] next(@Nullable T next);
@Override
public final void remove() {
throw new UnsupportedOperationException();
}
}
@Nonnull
public static Iterator<Object[]> provideIterator(@Nonnull final Iterator<?> iterator) {
return new DataProviderIterator<Object>(iterator) {
@Override
protected Object[] next(final Object next) {
return new Object[] { next };
}
};
}
@Nonnull
public static Iterator<Object[]> provideIterable(@Nonnull final Iterable<?> iterable) {
return provideIterator(iterable.iterator());
}
@Nonnull
public static <T> Iterator<Object[]> provideArray(@Nonnull final T[] objects) {
return provideIterator(Iterators.forArray(objects));
}
@Nonnull
public static Iterator<Object[]> provideVarargs(@Nonnull final Object... objects) {
return provideArray(objects);
}
@Nonnull
public static <T extends Entry<?, ?>> Iterator<Object[]> provideEntryIterator(@Nonnull final Iterator<T> iterator) {
return new DataProviderIterator<T>(iterator) {
@Override
protected Object[] next(final T next) {
if (next == null) {
return new Object[] { null, null };
}
return new Object[] { next.getKey(), next.getValue() };
}
};
}
@Nonnull
public static Iterator<Object[]> provideEntrySet(@Nonnull final Iterable<? extends Entry<?, ?>> iterable) {
return provideEntryIterator(iterable.iterator());
}
@Nonnull
public static Iterator<Object[]> provideMap(@Nonnull final Map<?, ?> map) {
return provideEntrySet(map.entrySet());
}
/**
* produces a cartesian product of the provided sets, see {@link Sets#cartesianProduct#cartesianProduct} for
* more info
*/
@Nonnull
public static Iterator<Object[]> cartesianProduct(@Nonnull final Set<?>... sets) {
return FluentIterable.from(Sets.cartesianProduct(sets)).transform(List::toArray).iterator();
}
}
| mit |
lintyleo/seleniumpro | SealSelenium/src/main/java/CsvUtility.java | 1057 | import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
/**
* Created by Linty on 2/12/2017.
* 用 apache的 commons-csv 的公共类,编写一个适用于用例中读取Csv的方法
*/
public class CsvUtility {
public Iterable<CSVRecord> readCsvFile(String csvPath) {
// 读取 csv 文件到FilerReader中
// 用捕获异常的方式 进行文件读取,防止出现“文件不存在”的异常
Reader reader = null;
try {
reader = new FileReader(csvPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 读取 csv 到 records中
Iterable<CSVRecord> records = null;
try {
if (reader != null) {
records = CSVFormat.EXCEL.parse(reader);
}
} catch (IOException e) {
e.printStackTrace();
}
return records;
}
}
| mit |
uwol/cobol85parser | src/main/java/io/proleap/cobol/asg/metamodel/identification/ProgramIdParagraph.java | 685 | /*
* Copyright (C) 2017, Ulrich Wolffgang <ulrich.wolffgang@proleap.io>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package io.proleap.cobol.asg.metamodel.identification;
import io.proleap.cobol.asg.metamodel.CobolDivisionElement;
import io.proleap.cobol.asg.metamodel.NamedElement;
/**
* Specifies program name and assigns attributes to it.
*/
public interface ProgramIdParagraph extends CobolDivisionElement, NamedElement {
enum Attribute {
COMMON, DEFINITION, INITIAL, LIBRARY, RECURSIVE
}
Attribute getAttribute();
void setAttribute(Attribute attribute);
}
| mit |
manuel-zulian/Match-Point | trunk/src/java/it/gemmed/database/CreateIscrizioneDatabase.java | 1902 | package it.gemmed.database;
import it.gemmed.resource.Iscrizione;
import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Crea una nuova iscrizione all'interno del database. Sono richiesti solo i campi
* not NULL, per settare gli altri campi utilizzare la classe UpdateIscrizioneDatabase
*
* @author GEMMED
* @version 0.1
*/
public class CreateIscrizioneDatabase {
/**
* Statement SQL per l'inserimento
*/
private static final String STATEMENT = "INSERT INTO iscrizione (giocatore,torneo, disponibilita) VALUES (?, ?, ?)";
/**
* Connessione al database
*/
private final Connection con;
/**
* Elemento di tipo iscrizione che dese essere aggiunto al database
*/
private final Iscrizione iscrizione;
/**
* Creazione di un nuovo oggetto per poter inserire elementi di tipo iscrizione nel database
*
* @param con
* connessione al database
* @param i
* iscrizione da salvare nel database
*/
public CreateIscrizioneDatabase(final Connection con, final Iscrizione i) {
this.con = con;
this.iscrizione = i;
}
/**
* Savataggio di elementi di tipo iscrizione nel database
*
* @throws SQLException
* se si verificano errori nello storing dell'elemento
*/
public void createIscrizione() throws SQLException {
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement(STATEMENT);
pstmt.setString(1, iscrizione.getGiocatore());
pstmt.setInt(2, iscrizione.getTorneo());
// iscrizione.getDisponibilita().toByteArray();
Array sql = con.createArrayOf("boolean", iscrizione.getDisponibilita());
pstmt.setArray(3, sql);
pstmt.execute();
} finally {
if (pstmt != null) {
pstmt.close();
}
con.close();
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/storage/azure-storage-blob-changefeed/src/main/java/com/azure/storage/blob/changefeed/models/BlobChangefeedEventType.java | 1274 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.blob.changefeed.models;
import com.azure.core.util.ExpandableStringEnum;
import java.util.Collection;
/**
* This class represents the different BlobChangefeedEventTypes.
*/
public final class BlobChangefeedEventType extends ExpandableStringEnum<BlobChangefeedEventType> {
/**
* Static value BlobCreated for BlobChangefeedEventType.
*/
public static final BlobChangefeedEventType BLOB_CREATED = fromString("BlobCreated");
/**
* Static value BlobDeleted for BlobChangefeedEventType.
*/
public static final BlobChangefeedEventType BLOB_DELETED = fromString("BlobDeleted");
/**
* Creates or finds a BlobChangefeedEventType from its string representation.
*
* @param name a name to look for.
* @return the corresponding BlobChangefeedEventType.
*/
public static BlobChangefeedEventType fromString(String name) {
return fromString(name, BlobChangefeedEventType.class);
}
/**
* @return known BlobChangefeedEventType values.
*/
public static Collection<BlobChangefeedEventType> values() {
return values(BlobChangefeedEventType.class);
}
}
| mit |
klinker41/Android-TextView-LinkBuilder | library/src/main/java/com/klinker/android/link_builder/TouchableSpan.java | 3202 | /*
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.klinker.android.link_builder;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
public class TouchableSpan extends ClickableSpan {
private final Link link;
public boolean touched = false;
/**
* Construct new TouchableSpan using the link
* @param link
*/
public TouchableSpan(Link link) {
this.link = link;
}
/**
* This TouchableSpan has been clicked.
* @param widget TextView containing the touchable span
*/
public void onClick(View widget) {
// handle the click
if (link.getClickListener() != null) {
link.getClickListener().onClick(link.getText());
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
TouchableMovementMethod.touched = false;
}
}, 500);
}
/**
* This TouchableSpan has been long clicked.
* @param widget TextView containing the touchable span
*/
public void onLongClick(View widget) {
// handle the long click
if (link.getLongClickListener() != null) {
link.getLongClickListener().onLongClick(link.getText());
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
TouchableMovementMethod.touched = false;
}
}, 500);
}
/**
* Set the alpha for the color based on the alpha factor
* @param color original color
* @param factor how much we want to scale the alpha to
* @return new color with scaled alpha
*/
public int adjustAlpha(int color, float factor) {
int alpha = Math.round(Color.alpha(color) * factor);
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
return Color.argb(alpha, red, green, blue);
}
/**
* Draw the links background and set whether or not we want it to be underlined
* @param ds the link
*/
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(link.isUnderlined());
ds.setColor(link.getTextColor());
ds.bgColor = touched ? adjustAlpha(link.getTextColor(), link.getHighlightAlpha()) : Color.TRANSPARENT;
}
/**
* Specifiy whether or not the link is currently touched
* @param touched
*/
public void setTouched(boolean touched) {
this.touched = touched;
}
} | mit |
navalev/azure-sdk-for-java | sdk/policy/mgmt-v2018_05_01/src/main/java/com/microsoft/azure/management/policy/v2018_05_01/PolicyType.java | 1356 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.policy.v2018_05_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for PolicyType.
*/
public final class PolicyType extends ExpandableStringEnum<PolicyType> {
/** Static value NotSpecified for PolicyType. */
public static final PolicyType NOT_SPECIFIED = fromString("NotSpecified");
/** Static value BuiltIn for PolicyType. */
public static final PolicyType BUILT_IN = fromString("BuiltIn");
/** Static value Custom for PolicyType. */
public static final PolicyType CUSTOM = fromString("Custom");
/**
* Creates or finds a PolicyType from its string representation.
* @param name a name to look for
* @return the corresponding PolicyType
*/
@JsonCreator
public static PolicyType fromString(String name) {
return fromString(name, PolicyType.class);
}
/**
* @return known PolicyType values
*/
public static Collection<PolicyType> values() {
return values(PolicyType.class);
}
}
| mit |
joshsh/extendo | brain/src/test/java/net/fortytwo/smsn/brain/model/GetAtomsByAcronymTest.java | 2472 | package net.fortytwo.smsn.brain.model;
import net.fortytwo.smsn.SemanticSynchrony;
import net.fortytwo.smsn.brain.BrainTestBase;
import net.fortytwo.smsn.brain.model.entities.Atom;
import net.fortytwo.smsn.brain.model.pg.PGAtom;
import org.junit.Test;
import java.io.IOException;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
public class GetAtomsByAcronymTest extends BrainTestBase {
@Override
protected TopicGraph createAtomGraph() throws IOException {
return createNeo4jAtomGraph();
}
@Test
public void testAcronymSearch() throws Exception {
Atom a = topicGraph.createAtomWithProperties(filter, null);
a.setTitle("Arthur\tP. Dent ");
Atom t = topicGraph.createAtomWithProperties(filter, null);
t.setTitle("Arthur's moth-eaten towel");
Atom l = topicGraph.createAtomWithProperties(filter, null);
l.setTitle("ooooooooo0ooooooooo1ooooooooo2ooooooooo3ooooooooo4ooooooooo5ooooooooo6ooooooooo7" +
"ooooooooo8ooooooooo9oooooooooAoooooooooBoooooooooCoooooooooDoooooooooEoooooooooF");
Collection<Atom> result;
// oops. This is not a full-text query.
result = topicGraph.getAtomsByAcronym("Arthur*", filter);
assertEquals(0, result.size());
// l has not been indexed because its value is too long
result = topicGraph.getAtomsByAcronym("o", filter);
assertEquals(0, result.size());
for (Atom atom : topicGraph.getAllAtoms()) {
System.out.println(atom.getId() + ": "
+ ((PGAtom) atom).asVertex().property(SemanticSynchrony.PropertyKeys.ACRONYM));
}
// exact acronym match
// capitalization, punctuation, and idiosyncrasies of white space are ignored
result = topicGraph.getAtomsByAcronym("apd", filter);
assertEquals(1, result.size());
assertEquals(a.getId(), result.iterator().next().getId());
// hyphens and underscores are treated as white space, while apostrophes and other punctuation are ignored
result = topicGraph.getAtomsByAcronym("amet", filter);
assertEquals(1, result.size());
assertEquals(t.getId(), result.iterator().next().getId());
// acronym search is case insensitive
result = topicGraph.getAtomsByAcronym("APD", filter);
assertEquals(1, result.size());
assertEquals(a.getId(), result.iterator().next().getId());
}
}
| mit |
devopsmwas/javapractice | NetBeansProjects/practice/src/threads/Bounce.java | 4470 | /*
* 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 threads;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author mars
*/
public class Bounce {
public static void main(String[] args) {
JFrame frame = new BounceFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
* A Ball that moves and bounces off the edges of a rectangle
*
*/
class Ball {
private static final int XSIZE = 15;
private static final int YSIZE = 15;
private double x = 0;
private double y = 0;
private double dx = 1;
private double dy = 1;
/**
* Moves the ball to the next position,reversing direction if it hits one of
* the edges
*/
public void move(Rectangle2D bounds) {
x += dx;
y += dy;
if (x < bounds.getMinX()) {
x = bounds.getMinX();
dx = -dx;
}
if (x + XSIZE >= bounds.getMaxX()) {
x = bounds.getMaxX() - XSIZE;
dx = -dx;
}
if (y < bounds.getMinY()) {
y = bounds.getMinY();
dy = -dy;
}
if (y + YSIZE >= bounds.getMaxY()) {
y = bounds.getMaxY() - YSIZE;
dy = -dy;
}
}
/**
* Gets the shape of the ball at its current position
*/
public Ellipse2D getShape() {
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
}
/**
* The panel that draws the balls.
*/
class BallPanel extends JPanel {
private ArrayList<Ball> balls = new ArrayList<>();
/**
* Add a ball to the panel
*
* @param b the ball to add
*/
public void add(Ball b) {
balls.add(b);
}
@Override
public void paintComponents(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Ball b : balls) {
g2.fill(b.getShape());
}
}
}
/**
* The frame with the panel and buttons
*
*/
class BounceFrame extends JFrame {
private BallPanel panel;
private static final int DEFAULT_WIDTH = 450;
private static final int DEFAULT_HEIGHT = 350;
private final int STEPS = 1000;
private final int DELAY = 3;
/**
* Constructs the frame with the panel for showing the bouncing ball and
* start and close buttons
*/
public BounceFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setTitle("Bounce");
panel = new BallPanel();
add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
addButton(buttonPanel, "Start", new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//To change body of generated methods, choose Tools | Templates.
addBall();
}
});
addButton(buttonPanel, "Close", new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//To change body of generated methods, choose Tools | Templates.
System.exit(0);
}
});
add(buttonPanel, BorderLayout.SOUTH);
}
/**
* Adds a button to a container
*
* @param c the container
* @param title the button title
* @param listener the action listener for the button
*/
public void addButton(Container c, String title, ActionListener listener) {
JButton button = new JButton(title);
c.add(button);
button.addActionListener(listener);
}
/**
* Adds a bouncing ball to the panel and makes it bounce 1,000 times
*/
public void addBall() {
try {
Ball ball = new Ball();
panel.add(ball);
for (int i = 1; i <= STEPS; i++) {
ball.move(panel.getBounds());
panel.paint(panel.getGraphics());
Thread.sleep(DELAY);
}
} catch (InterruptedException e) {
}
}
}
| mit |
martinsawicki/azure-sdk-for-java | azure-mgmt-containerregistry/src/main/java/com/microsoft/azure/management/containerregistry/implementation/WebhookEventInfoImpl.java | 1154 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.containerregistry.implementation;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.containerregistry.EventRequestMessage;
import com.microsoft.azure.management.containerregistry.EventResponseMessage;
import com.microsoft.azure.management.containerregistry.WebhookEventInfo;
import com.microsoft.azure.management.resources.fluentcore.model.implementation.WrapperImpl;
/**
* Response containing the webhook event info.
*/
@LangDefinition
public class WebhookEventInfoImpl extends WrapperImpl<EventInner> implements WebhookEventInfo {
protected WebhookEventInfoImpl(EventInner innerObject) {
super(innerObject);
}
@Override
public EventRequestMessage eventRequestMessage() {
return this.inner().eventRequestMessage();
}
@Override
public EventResponseMessage eventResponseMessage() {
return this.inner().eventResponseMessage();
}
}
| mit |
Daeliin/rest-framework | components-core/src/main/java/com/blebail/components/core/security/cryptography/Md5.java | 366 | package com.blebail.components.core.security.cryptography;
import org.apache.commons.codec.digest.DigestUtils;
public class Md5 implements DigestAlgorithm {
@Override
public String digest(final String data) {
return DigestUtils.md5Hex(data);
}
@Override
public String toString() {
return "Digest Algorithm (Md5)";
}
}
| mit |
Stonebound/Prism | src/main/java/com/helion3/prism/util/BlockUtil.java | 6277 | /*
* This file is part of Prism, licensed under the MIT License (MIT).
*
* Copyright (c) 2015 Helion3 http://helion3.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.helion3.prism.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.data.property.block.MatterProperty;
import org.spongepowered.api.data.property.block.MatterProperty.Matter;
public class BlockUtil {
private BlockUtil() {}
/**
* Get a list of all LIQUID block types.
*
* @return List<BlockType>
*/
public static List<BlockType> getLiquidBlockTypes() {
List<BlockType> liquids = new ArrayList<>();
Collection<BlockType> types = Sponge.getRegistry().getAllOf(BlockType.class);
for (BlockType type : types) {
Optional<MatterProperty> property = type.getProperty(MatterProperty.class);
if (property.isPresent() && Objects.equals(property.get().getValue(), Matter.LIQUID)) {
liquids.add(type);
}
}
// @todo Sponge has not yet implemented the MatterProperties...
liquids.add(BlockTypes.LAVA);
liquids.add(BlockTypes.FLOWING_LAVA);
liquids.add(BlockTypes.WATER);
liquids.add(BlockTypes.FLOWING_WATER);
return liquids;
}
/**
* Reject specific blocks from an applier because they're 99% going to do more harm.
*
* @param type BlockType
* @return
*/
public static boolean rejectIllegalApplierBlock(BlockType type) {
return (type.equals(BlockTypes.FIRE) ||
type.equals(BlockTypes.TNT) ||
type.equals(BlockTypes.LAVA) ||
type.equals(BlockTypes.FLOWING_LAVA));
}
/**
* Sponge's ChangeBlockEvent.Place covers a lot, but it also includes a lot
* we don't want. So here we can setup checks to filter out block combinations.
*
* @param a BlockType original
* @param b BlockType final
* @return boolean True if combo should be rejected
*/
public static boolean rejectPlaceCombination(BlockType a, BlockType b) {
return (
// Just basic state changes
a.equals(BlockTypes.LIT_FURNACE) || b.equals(BlockTypes.LIT_FURNACE) ||
a.equals(BlockTypes.LIT_REDSTONE_LAMP) || b.equals(BlockTypes.LIT_REDSTONE_LAMP) ||
a.equals(BlockTypes.LIT_REDSTONE_ORE) || b.equals(BlockTypes.LIT_REDSTONE_ORE) ||
a.equals(BlockTypes.UNLIT_REDSTONE_TORCH) || b.equals(BlockTypes.UNLIT_REDSTONE_TORCH) ||
(a.equals(BlockTypes.POWERED_REPEATER) && b.equals(BlockTypes.UNPOWERED_REPEATER)) ||
(a.equals(BlockTypes.UNPOWERED_REPEATER) && b.equals(BlockTypes.POWERED_REPEATER)) ||
(a.equals(BlockTypes.POWERED_COMPARATOR) && b.equals(BlockTypes.UNPOWERED_COMPARATOR)) ||
(a.equals(BlockTypes.UNPOWERED_COMPARATOR) && b.equals(BlockTypes.POWERED_COMPARATOR)) ||
// It's all water...
(a.equals(BlockTypes.WATER) && b.equals(BlockTypes.FLOWING_WATER)) ||
(a.equals(BlockTypes.FLOWING_WATER) && b.equals(BlockTypes.WATER)) ||
// It's all lava....
(a.equals(BlockTypes.LAVA) && b.equals(BlockTypes.FLOWING_LAVA)) ||
(a.equals(BlockTypes.FLOWING_LAVA) && b.equals(BlockTypes.LAVA)) ||
// Crap that fell into lava
(a.equals(BlockTypes.LAVA) && b.equals(BlockTypes.GRAVEL)) ||
(a.equals(BlockTypes.FLOWING_LAVA) && b.equals(BlockTypes.GRAVEL)) ||
(a.equals(BlockTypes.LAVA) && b.equals(BlockTypes.SAND)) ||
(a.equals(BlockTypes.FLOWING_LAVA) && b.equals(BlockTypes.SAND)) ||
// It's fire (which didn't burn anything)
(a.equals(BlockTypes.FIRE) && b.equals(BlockTypes.AIR)) ||
// Piston
a.equals(BlockTypes.PISTON_EXTENSION) || b.equals(BlockTypes.PISTON_EXTENSION) ||
a.equals(BlockTypes.PISTON_HEAD) || b.equals(BlockTypes.PISTON_HEAD) ||
// You can't place air
b.equals(BlockTypes.AIR)
);
}
/**
* Sponge's ChangeBlockEvent.Break covers a lot, but it also includes a lot
* we don't want. So here we can setup checks to filter out block combinations.
*
* @param a BlockType original
* @param b BlockType final
* @return boolean True if combo should be rejected
*/
public static boolean rejectBreakCombination(BlockType a, BlockType b) {
return (
// You can't break these...
a.equals(BlockTypes.FIRE) ||
a.equals(BlockTypes.AIR) ||
// Note, see "natural flow" comment above.
((a.equals(BlockTypes.FLOWING_WATER) || a.equals(BlockTypes.FLOWING_LAVA)) && b.equals(BlockTypes.AIR)) ||
// Piston
a.equals(BlockTypes.PISTON_EXTENSION) || b.equals(BlockTypes.PISTON_EXTENSION) ||
a.equals(BlockTypes.PISTON_HEAD) || b.equals(BlockTypes.PISTON_HEAD)
);
}
}
| mit |
AlexShilon/RohosLogonMobile | Android/RohosLogonKey/src/main/java/com/rohos/logon1/HelpActivity.java | 1571 | package com.rohos.logon1;
/*
* Copyright 2014 Tesline-Service SRL. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
/**
* Created by Alex on 03.01.14.
* Rohos Loogn Key How it works help
*
* @author AlexShilon
*/
public class HelpActivity extends Activity {
private final String TAG = "HelpActiviy";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
Button learnMore = findViewById(R.id.learn_more);
learnMore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openWebPage();
}
});
//setPageContentView(R.layout.activity_help);
//setTextViewHtmlFromResource(R.id.details, R.string.howitworks_page_enter_code_details);
}
private void openWebPage() {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.rohos.com/2013/12/login-unlock-computer-by-using-smartphone/"));
startActivity(intent);
} catch (Exception e) {
// Log.e(TAG, e.toString());
}
}
/*@Override
protected void onRightButtonPressed() {
//startPageActivity(IntroVerifyDeviceActivity.class);
}*/
}
| mit |
open-keychain/spongycastle | pkix/src/main/java/org/spongycastle/openssl/jcajce/JceOpenSSLPKCS8EncryptorBuilder.java | 6994 | package org.spongycastle.openssl.jcajce;
import java.io.IOException;
import java.io.OutputStream;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import org.spongycastle.asn1.ASN1EncodableVector;
import org.spongycastle.asn1.ASN1Integer;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.ASN1Primitive;
import org.spongycastle.asn1.DEROctetString;
import org.spongycastle.asn1.DERSequence;
import org.spongycastle.asn1.nist.NISTObjectIdentifiers;
import org.spongycastle.asn1.pkcs.KeyDerivationFunc;
import org.spongycastle.asn1.pkcs.PBES2Parameters;
import org.spongycastle.asn1.pkcs.PBKDF2Params;
import org.spongycastle.asn1.pkcs.PKCS12PBEParams;
import org.spongycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.spongycastle.asn1.x509.AlgorithmIdentifier;
import org.spongycastle.jcajce.PKCS12KeyWithParameters;
import org.spongycastle.jcajce.util.DefaultJcaJceHelper;
import org.spongycastle.jcajce.util.JcaJceHelper;
import org.spongycastle.jcajce.util.NamedJcaJceHelper;
import org.spongycastle.jcajce.util.ProviderJcaJceHelper;
import org.spongycastle.operator.GenericKey;
import org.spongycastle.operator.OperatorCreationException;
import org.spongycastle.operator.OutputEncryptor;
import org.spongycastle.operator.jcajce.JceGenericKey;
public class JceOpenSSLPKCS8EncryptorBuilder
{
public static final String AES_128_CBC = NISTObjectIdentifiers.id_aes128_CBC.getId();
public static final String AES_192_CBC = NISTObjectIdentifiers.id_aes192_CBC.getId();
public static final String AES_256_CBC = NISTObjectIdentifiers.id_aes256_CBC.getId();
public static final String DES3_CBC = PKCSObjectIdentifiers.des_EDE3_CBC.getId();
public static final String PBE_SHA1_RC4_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC4.getId();
public static final String PBE_SHA1_RC4_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC4.getId();
public static final String PBE_SHA1_3DES = PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC.getId();
public static final String PBE_SHA1_2DES = PKCSObjectIdentifiers.pbeWithSHAAnd2_KeyTripleDES_CBC.getId();
public static final String PBE_SHA1_RC2_128 = PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC.getId();
public static final String PBE_SHA1_RC2_40 = PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC.getId();
private JcaJceHelper helper = new DefaultJcaJceHelper();
private AlgorithmParameters params;
private ASN1ObjectIdentifier algOID;
byte[] salt;
int iterationCount;
private Cipher cipher;
private SecureRandom random;
private AlgorithmParameterGenerator paramGen;
private char[] password;
private SecretKey key;
public JceOpenSSLPKCS8EncryptorBuilder(ASN1ObjectIdentifier algorithm)
{
algOID = algorithm;
this.iterationCount = 2048;
}
public JceOpenSSLPKCS8EncryptorBuilder setRandom(SecureRandom random)
{
this.random = random;
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setPasssword(char[] password)
{
this.password = password;
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setIterationCount(int iterationCount)
{
this.iterationCount = iterationCount;
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setProvider(String providerName)
{
helper = new NamedJcaJceHelper(providerName);
return this;
}
public JceOpenSSLPKCS8EncryptorBuilder setProvider(Provider provider)
{
helper = new ProviderJcaJceHelper(provider);
return this;
}
public OutputEncryptor build()
throws OperatorCreationException
{
final AlgorithmIdentifier algID;
salt = new byte[20];
if (random == null)
{
random = new SecureRandom();
}
random.nextBytes(salt);
try
{
this.cipher = helper.createCipher(algOID.getId());
if (PEMUtilities.isPKCS5Scheme2(algOID))
{
this.paramGen = helper.createAlgorithmParameterGenerator(algOID.getId());
}
}
catch (GeneralSecurityException e)
{
throw new OperatorCreationException(algOID + " not available: " + e.getMessage(), e);
}
if (PEMUtilities.isPKCS5Scheme2(algOID))
{
params = paramGen.generateParameters();
try
{
KeyDerivationFunc scheme = new KeyDerivationFunc(algOID, ASN1Primitive.fromByteArray(params.getEncoded()));
KeyDerivationFunc func = new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(func);
v.add(scheme);
algID = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, PBES2Parameters.getInstance(new DERSequence(v)));
}
catch (IOException e)
{
throw new OperatorCreationException(e.getMessage(), e);
}
try
{
key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(helper, algOID.getId(), password, salt, iterationCount);
cipher.init(Cipher.ENCRYPT_MODE, key, params);
}
catch (GeneralSecurityException e)
{
throw new OperatorCreationException(e.getMessage(), e);
}
}
else if (PEMUtilities.isPKCS12(algOID))
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DEROctetString(salt));
v.add(new ASN1Integer(iterationCount));
algID = new AlgorithmIdentifier(algOID, PKCS12PBEParams.getInstance(new DERSequence(v)));
try
{
cipher.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters(password, salt, iterationCount));
}
catch (GeneralSecurityException e)
{
throw new OperatorCreationException(e.getMessage(), e);
}
}
else
{
throw new OperatorCreationException("unknown algorithm: " + algOID, null);
}
return new OutputEncryptor()
{
public AlgorithmIdentifier getAlgorithmIdentifier()
{
return algID;
}
public OutputStream getOutputStream(OutputStream encOut)
{
return new CipherOutputStream(encOut, cipher);
}
public GenericKey getKey()
{
return new JceGenericKey(algID, key);
}
};
}
}
| mit |
uwol/vb6parser | src/test/java/io/proleap/vb6/ast/statements/DoLoopTest.java | 461 | package io.proleap.vb6.ast.statements;
import java.io.File;
import org.junit.Test;
import io.proleap.vb6.runner.VbParseTestRunner;
import io.proleap.vb6.runner.impl.VbParseTestRunnerImpl;
public class DoLoopTest {
@Test
public void test() throws Exception {
final File inputFile = new File("src/test/resources/io/proleap/vb6/ast/statements/DoLoop.cls");
final VbParseTestRunner runner = new VbParseTestRunnerImpl();
runner.parseFile(inputFile);
}
} | mit |
howenkakao/style-web | app/domain/Msg.java | 2436 | package domain;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* 全体系统消息
* Created by sibyl.sun on 16/2/22.
*/
public class Msg implements Serializable {
private static final long serialVersionUID = 1L;
private long msgId;//消息id
private String msgTitle; //消息标题
private String msgContent;//消息内容
private String msgImg; //消息商品图片
private String msgUrl; //消息跳转的URL
private String msgType; //消息类型
private Timestamp createAt; //创建时间
private Timestamp endAt;//失效时间
private String targetType; //T:主题,D:详细页面,P:拼购商品页,A:拼购活动页面,U:一个促销活动的链接
public long getMsgId() {
return msgId;
}
public void setMsgId(long msgId) {
this.msgId = msgId;
}
public String getMsgTitle() {
return msgTitle;
}
public void setMsgTitle(String msgTitle) {
this.msgTitle = msgTitle;
}
public String getMsgContent() {
return msgContent;
}
public void setMsgContent(String msgContent) {
this.msgContent = msgContent;
}
public String getMsgImg() {
return msgImg;
}
public void setMsgImg(String msgImg) {
this.msgImg = msgImg;
}
public String getMsgUrl() {
return msgUrl;
}
public void setMsgUrl(String msgUrl) {
this.msgUrl = msgUrl;
}
public Timestamp getCreateAt() {
return createAt;
}
public void setCreateAt(Timestamp createAt) {
this.createAt = createAt;
}
public Timestamp getEndAt() {
return endAt;
}
public void setEndAt(Timestamp endAt) {
this.endAt = endAt;
}
public String getTargetType() {
return targetType;
}
public void setTargetType(String targetType) {
this.targetType = targetType;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
@Override
public String toString(){
return "Msg [msgTitle="+msgTitle+
",msgContent="+msgContent+
",msgImg="+msgImg+
",msgUrl="+msgUrl+
",msgType="+msgType+
",createAt="+createAt+
",endAt="+endAt+
",targetType="+targetType;
}
}
| mit |
AjitPS/KnetMiner | server-base/src/main/java/rres/knetminer/datasource/server/KnetminerServer.java | 15807 | package rres.knetminer.datasource.server;
import static uk.ac.ebi.utils.exceptions.ExceptionUtils.getSignificantMessage;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ObjectMessage;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import com.brsanthu.googleanalytics.GoogleAnalytics;
import com.brsanthu.googleanalytics.GoogleAnalyticsBuilder;
import rres.knetminer.datasource.api.KnetminerDataSource;
import rres.knetminer.datasource.api.KnetminerRequest;
import rres.knetminer.datasource.api.KnetminerResponse;
import uk.ac.ebi.utils.exceptions.ExceptionUtils;
import uk.ac.ebi.utils.opt.springweb.exceptions.ResponseStatusException2;
/**
* KnetminerServer is a fully working server, except that it lacks any data
* sources. To make a server with data sources, just add one or more JARs to the
* classpath which include classes that implement KnetminerDataSourceProvider
* (and are in package rres.knetminer.datasource). They are detected and loaded
* via autowiring. See the sister server-example project for how this is done.
*
* @author holland
* @author Marco Brandizi (2021, removed custom exception management and linked it to {@link KnetminerExceptionHandler})
*/
@Controller
@RequestMapping("/")
public class KnetminerServer {
protected final Logger log = LogManager.getLogger(getClass());
@Autowired
private List<KnetminerDataSource> dataSources;
private Map<String, KnetminerDataSource> dataSourceCache;
private String gaTrackingId;
// Special logging to achieve web analytics info.
private static final Logger logAnalytics = LogManager.getLogger("analytics-log");
/**
* Autowiring will populate the basic dataSources list with all instances of
* KnetminerDataSourceProvider. This method is used, upon first access, to take
* that list and turn it into a map of URL paths to data sources, using the
* getName() function of each data source to build an equivalent URL. For
* instance a data source with getName()='hello' will receive all requests
* matching '/hello/**'.
*/
@PostConstruct
public void _buildDataSourceCache() {
this.dataSourceCache = new HashMap<String, KnetminerDataSource>();
for (KnetminerDataSource dataSource : this.dataSources) {
for (String ds : dataSource.getDataSourceNames()) {
this.dataSourceCache.put(ds, dataSource);
log.info("Mapped /" + ds + " to " + dataSource.getClass().getName());
}
}
}
/**
* Loads Google Analytics properties from src/main/resources/ga.properties . It expects
* to find GOOGLE_ANALYTICS_ENABLED = True or False. If True, it also expects to find
* GOOGLE_ANALYTICS_TRACKING_ID with a valid Google Analytics tracking ID.
*/
@PostConstruct
public void _loadGATrackingId() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("ga.properties");
Properties props = new Properties();
try {
props.load(input);
log.info("GA enabled= "+ props.getProperty("GOOGLE_ANALYTICS_ENABLED")); // test passing val
log.info("ga_id to use= "+ props.getProperty("GOOGLE_ANALYTICS_TRACKING_ID")); // test passed val
} catch (IOException ex) {
log.warn("Failed to load Google Analytics properties file", ex);
return;
}
if (Boolean.parseBoolean(props.getProperty("GOOGLE_ANALYTICS_ENABLED", "false"))) {
this.gaTrackingId = props.getProperty("GOOGLE_ANALYTICS_TRACKING_ID", null);
if (this.gaTrackingId == null)
log.warn("Google Analytics properties file enabled analytics but did not provide tracking ID");
else
log.info("Google Analytics enabled");
} else
log.info("Google Analytics disabled");
}
private void _googlePageView(String ds, String mode, HttpServletRequest rawRequest)
{
String ipAddress = rawRequest.getHeader("X-FORWARDED-FOR");
log.debug("IP TRACING 1, IP for X-FORWARDED-FOR: {}", ipAddress);
if (ipAddress == null) {
ipAddress = rawRequest.getRemoteAddr();
log.debug("IP TRACING 2, getRemoteAddr(): {}", ipAddress);
}else{
log.debug("IP TRACING 3, IP to be split: {}", ipAddress);
if(ipAddress.indexOf(',')!= -1){
ipAddress = ipAddress.split(",")[0];
}
log.debug("IP TRACING 4, splitted IP: {}", ipAddress);
}
log.debug("IP TRACING 5 post-processed IP: {}", ipAddress);
String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
for (String header : IP_HEADER_CANDIDATES) {
String ip = rawRequest.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
log.debug("IP TRACING, req headers, {}:{}", header, ip);
}
}
if (this.gaTrackingId!=null) {
String pageName = ds+"/"+mode;
GoogleAnalytics ga = new GoogleAnalyticsBuilder().withTrackingId(this.gaTrackingId).build();
ga.pageView().documentTitle(pageName).documentPath("/" + pageName)
.userIp(ipAddress).send();
}
}
/**
* A /genepage shortcut which generates a redirect to a prepopulated KnetMaps
* template with the /network query built for the user already. See WEB-INF/views
* to find the HTML template that this query will return.
* @param ds
* @param keyword
* @param list
* @param rawRequest
* @param model
* @return
*/
@CrossOrigin
@GetMapping("/{ds}/genepage")
public String genepage(@PathVariable String ds, @RequestParam(required = false) String keyword,
@RequestParam(required = true) List<String> list, HttpServletRequest rawRequest, Model model) {
KnetminerDataSource dataSource = this.getConfiguredDatasource(ds, rawRequest);
if (dataSource == null) {
throw new HttpClientErrorException ( HttpStatus.BAD_REQUEST, "Data source '" + ds + "' doesn't exist" );
}
this._googlePageView(ds, "genepage", rawRequest);
model.addAttribute("list", new JSONArray(list).toString());
if (keyword != null && !"".equals(keyword)) {
model.addAttribute("keyword", keyword);
}
return "genepage";
}
/**
* A /evidencepage shortcut which generates a redirect to a prepopulated KnetMaps
* template with the /evidencePath query built for the user already. See WEB-INF/views
* to find the HTML template that this query will return.
* @param ds
* @param keyword
* @param list
* @param rawRequest
* @param model
* @return
*/
@CrossOrigin
@GetMapping("/{ds}/evidencepage")
public String evidencepage(@PathVariable String ds, @RequestParam(required = true) String keyword,
@RequestParam(required = false) List<String> list, HttpServletRequest rawRequest, Model model) {
KnetminerDataSource dataSource = this.getConfiguredDatasource(ds, rawRequest);
if (dataSource == null) {
throw new HttpClientErrorException ( HttpStatus.BAD_REQUEST, "Data source '" + ds + "' doesn't exist" );
}
this._googlePageView(ds, "evidencepage", rawRequest);
if (!list.isEmpty()) {
model.addAttribute("list", new JSONArray(list).toString());
}
model.addAttribute("keyword", keyword);
return "evidencepage";
}
/**
* Pick up all GET requests sent to any URL matching /X/Y. X is taken to be the
* name of the data source to look up by its getName() function (see above for
* the mapping function buildDataSourceCache(). Y is the 'mode' of the request.
* Spring magic automatically converts the response into JSON. We convert the
* GET parameters into a KnetminerRequest object for handling by the _handle()
* method.
*
* @param ds
* @param mode
* @param qtl
* @param keyword
* @param list TODO: what is this?!
* @param listMode
* @param rawRequest
* @return
*/
@CrossOrigin
@GetMapping("/{ds}/{mode}")
public @ResponseBody ResponseEntity<KnetminerResponse> handle(@PathVariable String ds, @PathVariable String mode,
@RequestParam(required = false) List<String> qtl,
@RequestParam(required = false, defaultValue = "") String keyword,
@RequestParam(required = false) List<String> list,
@RequestParam(required = false, defaultValue = "") String listMode, HttpServletRequest rawRequest) {
if (qtl == null) {
qtl = Collections.emptyList();
}
if (list == null) {
list = Collections.emptyList();
}
// TODO: We need VERY MUCH to stop polluting code this way!
// This MUST go to some utilty and there there MUST BE only some invocation that clearly recalls the semantics
// of these operations, eg, KnetminerServerUtils.logAnalytics ( logger, rawRequest, mode, list )
// This is filed under #462
//
Map<String, String> map = new TreeMap<>();
map.put("host",rawRequest.getServerName());
map.put("port",Integer.toString(rawRequest.getServerPort()));
map.put("mode", mode);
if(keyword != null) {
map.put("keywords", keyword);
}
if(!list.isEmpty()) {
map.put("list", new JSONArray(list).toString());
}
map.put("qtl", new JSONArray(qtl).toString());
map.put("datasource", ds);
if (mode.equals("genome") || mode.equals("genepage") || mode.equals("network")) {
ObjectMessage msg = new ObjectMessage(map);
logAnalytics.log(Level.getLevel("ANALYTICS"),msg);
}
KnetminerRequest request = new KnetminerRequest();
request.setKeyword(keyword);
request.setListMode(listMode);
request.setList(list);
request.setQtl(qtl);
return this._handle(ds, mode, request, rawRequest);
}
/**
* Pick up all POST requests sent to any URL matching /X/Y. X is taken to be the
* name of the data source to look up by its getName() function (see above for
* the mapping function buildDataSourceCache(). Y is the 'mode' of the request.
* Spring magic automatically converts the response into JSON. Spring magic also
* automatically converts the inbound POST JSON body into a KnetminerRequest
* object for handling by the _handle() method.
*
* @param ds
* @param mode
* @param request
* @param rawRequest
* @return
*/
@CrossOrigin
@PostMapping("/{ds}/{mode}")
public @ResponseBody ResponseEntity<KnetminerResponse> handle(@PathVariable String ds, @PathVariable String mode,
@RequestBody KnetminerRequest request, HttpServletRequest rawRequest) {
// TODO WRONG! Duplicating code like this is way too poor and
// it needs to be factorised in a separated utility anyway!
//
Map<String, String> map = new TreeMap<>();
map.put("host",rawRequest.getServerName());
map.put("port",Integer.toString(rawRequest.getServerPort()));
map.put("mode", mode);
String keyword = request.getKeyword();
List<String> list = request.getList();
List<String> qtl = request.getQtl();
if(keyword != null) {
map.put("keywords", keyword);
}
if(!list.isEmpty()) {
map.put("list", new JSONArray(list).toString());
}
map.put("qtl", new JSONArray(qtl).toString());
map.put("datasource", ds);
if (mode.equals("genome") || mode.equals("genepage") || mode.equals("network")) {
ObjectMessage msg = new ObjectMessage(map);
logAnalytics.log(Level.getLevel("ANALYTICS"),msg);
}
return this._handle(ds, mode, request, rawRequest);
}
private KnetminerDataSource getConfiguredDatasource(String ds, HttpServletRequest rawRequest) {
KnetminerDataSource dataSource = this.dataSourceCache.get(ds);
if (dataSource == null) {
log.info("Invalid data source requested: /" + ds);
return null;
}
String incomingUrlPath = rawRequest.getRequestURL().toString().split("\\?")[0];
dataSource.setApiUrl(incomingUrlPath.substring(0, incomingUrlPath.lastIndexOf('/')));
return dataSource;
}
/**
* We use reflection to take the 'mode' (the Y part of the /X/Y request path)
* and look up an equivalent method on the requested data source, then we call
* it with the request parameters passed in.
*
* @param ds
* @param mode
* @param request
* @param rawRequest
* @return
*/
private ResponseEntity<KnetminerResponse> _handle(
String ds, String mode, KnetminerRequest request, HttpServletRequest rawRequest)
{
if ( mode == null || mode.isEmpty () || mode.isBlank () )
throw new IllegalArgumentException ( "Knetminer API invoked with null/empty method name" );
KnetminerDataSource dataSource = this.getConfiguredDatasource(ds, rawRequest);
if (dataSource == null) {
throw new HttpServerErrorException (
HttpStatus.BAD_REQUEST,
"data source name isn't set, probably a Knetminer configuration error"
);
}
if (log.isDebugEnabled()) {
String paramsStr = "Keyword:" + request.getKeyword() + " , List:"
+ Arrays.toString ( request.getList().toArray() ) + " , ListMode:" + request.getListMode()
+ " , QTL:" + Arrays.toString(request.getQtl().toArray());
log.debug ( "Calling " + mode + " with " + paramsStr );
}
this._googlePageView(ds, mode, rawRequest);
try
{
Method method = dataSource.getClass().getMethod(mode, String.class, KnetminerRequest.class);
try {
KnetminerResponse response = (KnetminerResponse) method.invoke(dataSource, ds, request);
return new ResponseEntity<>(response, HttpStatus.OK);
}
catch ( InvocationTargetException ex ) {
// This was caused by a underlying more significant exception, best is to try to catch and re-throw it.
throw ( (Exception) ExceptionUtils.getSignificantException ( ex ) );
}
}
catch (NoSuchMethodException|IllegalAccessException|SecurityException ex) {
throw new ResponseStatusException2 (
HttpStatus.BAD_REQUEST, "Bad API call '" + mode + "': " + getSignificantMessage ( ex ), ex
);
}
catch (IllegalArgumentException ex) {
throw new ResponseStatusException2 (
HttpStatus.BAD_REQUEST,
"Bad parameters passed to the API call '" + mode + "': " + getSignificantMessage ( ex ),
ex
);
}
catch ( RuntimeException ex )
{
// Let's re-throw the same exception, with a wrapping message
throw ExceptionUtils.buildEx (
ex.getClass(), ex, "Application error while running the API call '%s': %s", mode, getSignificantMessage ( ex )
);
}
catch (Exception ex) {
throw new RuntimeException (
"Application error while running the API call '" + mode + "': " + getSignificantMessage ( ex ),
ex
);
}
catch (Error ex) {
// TODO: should we really catch this?!
throw new Error (
"System error while running the API call '" + mode + "': " + getSignificantMessage ( ex ),
ex
);
}
}
}
| mit |
QuantumRand/admob-google-cordova | src/android/AdMobAdsAdListener.java | 4742 | /*
AdMobAdsListener.java
Copyright 2015 AppFeel. All rights reserved.
http://www.appfeel.com
AdMobAds Cordova Plugin (com.admob.google)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.appfeel.cordova.admob;
import android.annotation.SuppressLint;
import android.util.Log;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
@SuppressLint("DefaultLocale")
public class AdMobAdsAdListener extends AdListener {
private String adType = "";
private AdMobAds admobAds;
private boolean isBackFill = false;
public AdMobAdsAdListener(String adType, AdMobAds admobAds, boolean isBackFill) {
this.adType = adType;
this.admobAds = admobAds;
this.isBackFill = isBackFill;
}
@Override
public void onAdLoaded() {
admobAds.onAdLoaded(adType);
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad loaded");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdLoaded, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
@Override
public void onAdFailedToLoad(int errorCode) {
if (this.isBackFill) {
final int code = errorCode;
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String reason = getErrorReason(code);
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": fail to load ad (" + reason + ")");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdFailedToLoad, { 'adType': '%s', 'error': %d, 'reason': '%s' });", adType, code, reason);
admobAds.webView.loadUrl(event);
}
});
} else {
admobAds.tryBackfill(adType);
}
}
/** Gets a string error reason from an error code. */
public String getErrorReason(int errorCode) {
String errorReason = "Unknown";
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
@Override
public void onAdOpened() {
admobAds.onAdOpened(adType);
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad opened");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdOpened, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
@Override
public void onAdLeftApplication() {
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": left application");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdLeftApplication, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
@Override
public void onAdClosed() {
admobAds.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(AdMobAds.ADMOBADS_LOGTAG, adType + ": ad closed after clicking on it");
String event = String.format("javascript:cordova.fireDocumentEvent(admob.events.onAdClosed, { 'adType': '%s' });", adType);
admobAds.webView.loadUrl(event);
}
});
}
}
| mit |
TeamSPoon/logicmoo_base | prolog/logicmoo/pdt_server/pdt.graphicalviews/src/org/cs3/pdt/graphicalviews/internal/ui/PredicatesListDialog.java | 2350 | /*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* Author: Andreas Becker, Ilshat Aliev
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail: pdt@lists.iai.uni-bonn.de
* Copyright (C): 2013, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
package org.cs3.pdt.graphicalviews.internal.ui;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
public class PredicatesListDialog extends Dialog {
String predicates;
private org.eclipse.swt.widgets.List list;
public PredicatesListDialog(Shell parentShell, String predicates) {
super(parentShell);
setShellStyle(getShellStyle() | SWT.RESIZE);
this.predicates = predicates;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
String[] predicateList = predicates.split("[\\[,\\]]");
list = new org.eclipse.swt.widgets.List(composite, SWT.V_SCROLL | SWT.BORDER);
for (String p : predicateList) {
if (p.length() > 0)
list.add(p);
}
list.setSelection(0);
GridData gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
gridData.verticalAlignment = GridData.FILL;
list.setLayoutData(gridData);
return composite;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Predicates");
}
@Override
protected Point getInitialSize() {
return new Point(400, 300);
}
}
| mit |
bacta/pre-cu | src/main/java/com/ocdsoft/bacta/swg/shared/collision/DoorInfo.java | 672 | package com.ocdsoft.bacta.swg.shared.collision;
/**
* Created by crush on 8/13/2014.
*/
public class DoorInfo {
public String frameAppearance;
public String doorAppearance;
public String doorAppearance2;
public boolean doorFlip2;
//public Vector delta;
public float openTime;
public float closeTime;
public float sprint;
public float smoothness;
public float triggerRadius;
public boolean forceField;
public String openBeginEffect;
public String openEndEffect;
public String closeBeginEffect;
public String closeEndEffect;
//public IndexedTriangleList portalGeometry;
public boolean alwaysOpen;
}
| mit |
xbony2/Bitm | src/main/java/net/bitm/items/nythoe.java | 613 | package net.bitm.items;
import net.bitm.creativeTab;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemHoe;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class nythoe extends ItemHoe{
public nythoe(ToolMaterial par2ToolMaterial) {
super(par2ToolMaterial);
this.maxStackSize = 1;
this.setCreativeTab(creativeTab.bonetabTools);
this.setUnlocalizedName("nythoe");
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister register){
itemIcon = register.registerIcon("bitm" + ":" + "nythoe");
}
}
| mit |
lkmcl37/Simple-WordSeg-Greedy-Algorithm | Preprocess.java | 595 | package wordsegm;
import java.util.ArrayList;
public class Preprocess {
public ArrayList<String> pretreat(String str, int maxSize) {
ArrayList<String> prepare = new ArrayList<String>();
str = str.replaceAll("[\\pP¡®¡¯¡°¡±]", "");
char[] strChars = str.toCharArray();
for(int index = 0; index < strChars.length; index++) {
String temp = "" + strChars[index];
prepare.add(temp);
for(int count = 1; count < maxSize; count++) {
if(index + count < strChars.length) {
temp = temp + strChars[index + count];
prepare.add(temp);
}
}
}
return prepare;
}
}
| mit |
YagneshShah/SeleniumLearnExploreContribute | orangeHRM/src/utils/ReportParseGoogleUpdate.java | 9210 | /*
* Date: September 1st 2014
* Author: Adil Imroz
* Twitter handle: @adilimroz
* Organization: Moolya Software Testing Pvt Ltd
* License Type: MIT
*/
package utils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.testng.annotations.Test;
import com.google.gdata.client.spreadsheet.CellQuery;
import com.google.gdata.client.spreadsheet.FeedURLFactory;
import com.google.gdata.client.spreadsheet.SpreadsheetQuery;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
public class ReportParseGoogleUpdate {
private static SpreadsheetService service;
private static FeedURLFactory factory;
private static URL url;
public static ReportParseGoogleUpdate spreadSheetDemo;
public static SpreadsheetEntry spreadsheet;
public static WorksheetEntry worksheetEntry;
public static SpreadsheetQuery query;
static int rowFromSearch;
static int colFromSearch;
static List<String> searchArr=new ArrayList<String>();
static List<Object> objects = new ArrayList<Object>();
@Test
public static void ReportParsingGoogleDocUpdate() throws IOException, ServiceException {
System.out.println("Script to parse test report and update google doc with results");
FileReader reader = new FileReader("../orangeHRM/config.properties"); //Reading configuration file
Properties prop = new Properties();
prop.load(reader);
String googleReportParserExecutionFlag = prop.getProperty("googleReportParserExecutionFlag");
String parserGoogleEmail = prop.getProperty("parserGoogleEmail");
String parserGooglePassword = prop.getProperty("parserGooglePassword");
int parserIndexSpreadsheet = Integer.parseInt(prop.getProperty("parserIndexSpreadsheet"));
int parserIndexWorksheet = Integer.parseInt(prop.getProperty("parserIndexWorksheet"));
String parserInputFilePath = prop.getProperty("parserInputFilePath");
if(googleReportParserExecutionFlag.contentEquals("true"))
{
//Auth to access google doc
spreadSheetDemo = new ReportParseGoogleUpdate(parserGoogleEmail, parserGooglePassword); //gmail account via which doc will be accessed for updating test results
spreadsheet = spreadSheetDemo.getSpreadSheet(parserIndexSpreadsheet);//give index to select the spreadsheet from the folder
worksheetEntry = spreadsheet.getWorksheets().get(parserIndexWorksheet); //providing index to access the desired worksheet
url = worksheetEntry.getCellFeedUrl();
query = new SpreadsheetQuery(url);
System.out.println("Title of spreadsheet being updated :: "+spreadsheet.getTitle().getPlainText());
System.out.println("Title of worksheet being updated :: "+worksheetEntry.getTitle().getPlainText());
//
CellFeed feed = service.query(query, CellFeed.class);
//Parsing the Test report from desired folder
File input = new File(parserInputFilePath);
System.out.println("Starting ....");
Document doc = Jsoup.parse(input,null);
System.out.println("midway ....");
Elements testNames = doc.select("html>body>table>tbody>tr>td>a[href~=#t]");//gets the name of the test names from the report
Elements testNameSiblings = doc.select("html>body>table>tbody>tr>td[class~=num]");//gets the siblings of all the test names...they are the test results numbers
System.out.println("testNames size ::"+testNames.size());
System.out.println("testNameSiblings size :: "+testNameSiblings.size());
/////
for (CellEntry entry : feed.getEntries()) {
searchArr.add(entry.getCell().getInputValue());
objects.add(entry.getCell());
}
System.out.println(searchArr);
System.out.println(objects);
int j =0;
for (int i = 0; i < testNames.size(); i++) {
System.out.println("test>"+testNames.get(i).text());
int passed = Integer.parseInt(testNameSiblings.get(j).text());
j=j+1;
int skipped = Integer.parseInt(testNameSiblings.get(j).text());
j=j+1;
int failed = Integer.parseInt(testNameSiblings.get(j).text());
j=j+1;
String testTime = testNameSiblings.get(j).text();
j=j+1;
System.out.println("******************************");
if (passed!=0) {
search(testNames.get(i).text());
CellContentUpdate(worksheetEntry, rowFromSearch, colFromSearch+2, "PASSED");
}
else if (skipped!=0) {
search(testNames.get(i).text());
CellContentUpdate(worksheetEntry, rowFromSearch, colFromSearch+2, "SKIPPED");
}
else if (failed!=0) {
search(testNames.get(i).text());
CellContentUpdate(worksheetEntry, rowFromSearch, colFromSearch+2, "FAILED");
}
}
}
else
{
System.out.println();
System.out.println("googleReportParserExecution feature is turned off via googleReportParserExecutionFlag in config.properties file...");
}
}
/*
* Method Definitions
*/
//Method for authentication to access google doc
public ReportParseGoogleUpdate(String username, String password) throws AuthenticationException {
service = new SpreadsheetService("SpreadSheet-Demo");
factory = FeedURLFactory.getDefault();
System.out.println("Authenticating...");
service.setUserCredentials(username, password);
System.out.println("Successfully authenticated");
}
//Method to get all the spreadsheets associated to the given account
public void GetAllSpreadsheets() throws IOException, ServiceException{
SpreadsheetFeed feed = service.getFeed(factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
System.out.println("Total number of SpreadSheets found : " + spreadsheets.size());
for (int i = 0; i < spreadsheets.size(); ++i) {
System.out.println("("+i+") : "+spreadsheets.get(i).getTitle().getPlainText());
}
}
// Returns spreadsheet
public SpreadsheetEntry getSpreadSheet(int spreadsheetIndex) throws IOException, ServiceException {
SpreadsheetFeed feed = service.getFeed(factory.getSpreadsheetsFeedUrl(), SpreadsheetFeed.class);
SpreadsheetEntry spreadsheet = feed.getEntries().get(spreadsheetIndex);
return spreadsheet;
}
//Method to get Spread sheet details
public void GetSpreadsheetDetails(SpreadsheetEntry spreadsheet) throws IOException, ServiceException{
System.out.println("SpreadSheet Title : "+spreadsheet.getTitle().getPlainText());
List<WorksheetEntry> worksheets = spreadsheet.getWorksheets();
for (int i = 0; i < worksheets.size(); ++i) {
WorksheetEntry worksheetEntry = worksheets.get(i);
System.out.println("("+i+") Worksheet Title : "+worksheetEntry.getTitle().getPlainText()+", num of Rows : "+worksheetEntry.getRowCount()+", num of Columns : "+worksheetEntry.getColCount());
}
}
public static void CellContentUpdate(WorksheetEntry worksheetEntry,int row, int col, String formulaOrValue) throws IOException, ServiceException{
URL cellFeedUrl = worksheetEntry.getCellFeedUrl();
CellEntry newEntry = new CellEntry(row, col, formulaOrValue);
service.insert(cellFeedUrl, newEntry);
System.out.println("Cell Updated!");
}
// public static void searchTestNameGDoc(String testNameToSearch) throws IOException, ServiceException{
//
// CellFeed feed = service.query(query, CellFeed.class);
//
// for (CellEntry entry : feed.getEntries()) {
// searchArr.add(entry.getCell().getInputValue());
// objects.add(entry.getCell());
// }
//
// for (int i = 0; i < objects.size(); i++) {
// if (searchArr.get(i)=="BalanaceEnquiry_MandatoryField" ){
// rowFromSearch = feed.getEntries().get(i).getCell().getRow();
// colFromSearch = feed.getEntries().get(i).getCell().getCol();
// break;
// }
//
// }
//
// }
// public static void printCell(CellEntry cell) {
// System.out.println(cell.getCell().getValue());
// }
public static void printCell(CellEntry cell) {
String shortId = cell.getId().substring(cell.getId().lastIndexOf('/') + 1);
System.out.println(" -- Cell(" + shortId + "/" + cell.getTitle().getPlainText()+ ") formula(" + cell.getCell().getInputValue() + ") numeric("+ cell.getCell().getNumericValue() + ") value("+ cell.getCell().getValue() + ")");
rowFromSearch = cell.getCell().getRow();
colFromSearch = cell.getCell().getCol();
System.out.println("row :: "+rowFromSearch);
System.out.println("col :: "+colFromSearch);
}
public static void search(String fullTextSearchString) throws IOException,ServiceException {
CellQuery query = new CellQuery(url);
query.setFullTextQuery(fullTextSearchString);
CellFeed feed = service.query(query, CellFeed.class);
System.out.println("Results for [" + fullTextSearchString + "]");
for (CellEntry entry : feed.getEntries()) {
printCell(entry);
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-containerservice/src/main/java/com/azure/resourcemanager/containerservice/models/Code.java | 1061 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.containerservice.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for Code. */
public final class Code extends ExpandableStringEnum<Code> {
/** Static value Running for Code. */
public static final Code RUNNING = fromString("Running");
/** Static value Stopped for Code. */
public static final Code STOPPED = fromString("Stopped");
/**
* Creates or finds a Code from its string representation.
*
* @param name a name to look for.
* @return the corresponding Code.
*/
@JsonCreator
public static Code fromString(String name) {
return fromString(name, Code.class);
}
/** @return known Code values. */
public static Collection<Code> values() {
return values(Code.class);
}
}
| mit |
lukaspili/Auto-Mortar | sample/src/main/java/automortar/sample/rest/RestClient.java | 909 | package automortar.sample.rest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javax.inject.Inject;
import autodagger.AutoExpose;
import automortar.sample.app.App;
import automortar.sample.app.DaggerScope;
import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
/**
* Created by lukasz on 19/02/15.
*/
@DaggerScope(App.class)
public class RestClient {
private Service service;
@Inject
public RestClient() {
Gson gson = new GsonBuilder().create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.BASIC)
.setEndpoint("http://jsonplaceholder.typicode.com/")
.setConverter(new GsonConverter(gson))
.build();
service = restAdapter.create(Service.class);
}
public Service getService() {
return service;
}
} | mit |
TheOpenCloudEngine/metaworks | metaworks-dwr/core/impl/main/java/org/directwebremoting/export/Data.java | 5172 | /*
* Copyright 2005 Joe Walker
*
* 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.directwebremoting.export;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.Browser;
import org.directwebremoting.datasync.Directory;
import org.directwebremoting.datasync.StoreProvider;
import org.directwebremoting.io.DwrConvertedException;
import org.directwebremoting.io.Item;
import org.directwebremoting.io.ItemUpdate;
import org.directwebremoting.io.MatchedItems;
import org.directwebremoting.io.StoreChangeListener;
import org.directwebremoting.io.StoreRegion;
/**
* External interface to the set of {@link StoreProvider}s that have been
* registered.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Data
{
/**
* Provide access to a single item of data given its ID.
* @param storeId The ID of the store into which we look for the item
* @param itemId The ID of the item to retrieve from the store
* @param listener The client side interface to pass async updates to.
* Will be <code>null</code> if no async updates are required
* @return The found item, or null if one was not found.
*/
public Item viewItem(String storeId, String itemId, StoreChangeListener<Object> listener)
{
StoreProvider<Object> provider = Directory.getRegistration(storeId, Object.class);
if (provider == null)
{
throw new DwrConvertedException("clientId not found");
}
if (listener != null)
{
return provider.viewItem(itemId, listener);
}
else
{
return provider.viewItem(itemId);
}
}
/**
* Notes that there is a region of a page that wishes to subscribe to server
* side data, and registers a callback function to receive the data.
* @param storeId The ID of a store as registered on the server using
* {@link Directory#register}. If no store has been registered
* on the server using this passed <code>storeId</code>, then this call will
* act as if there was a store registered, but that it was empty. This may
* make it harder to scan the server for exposed stores. Internally however
* the call will be ignored. This behavior may change in the future and
* should <strong>not</strong> be relied upon.
* @param region For field documentation see {@link StoreRegion}.
* @param listener The client side interface to pass async updates to.
* Will be <code>null</code> if no async updates are required
*/
public MatchedItems viewRegion(String storeId, StoreRegion region, StoreChangeListener<Object> listener)
{
StoreProvider<Object> provider = Directory.getRegistration(storeId, Object.class);
if (provider == null)
{
throw new DwrConvertedException("clientId not found");
}
if (region == null)
{
region = new StoreRegion();
}
if (listener != null)
{
provider.unsubscribe(listener);
return provider.viewRegion(region, listener);
}
else
{
return provider.viewRegion(region);
}
}
/**
* Remove a subscription from the list of people that we are remembering
* to keep updated
* @param receiver The client side interface to pass async updates to.
* Will be <code>null</code> if no async updates are required
*/
public void unsubscribe(String storeId, StoreChangeListener<Object> receiver)
{
StoreProvider<Object> provider = Directory.getRegistration(storeId, Object.class);
provider.unsubscribe(receiver);
Browser.close(receiver);
}
/**
* Update server side data.
* @param storeId The store into which data is to be altered/inserted. If
* a store by the given name has not been registered then this method is
* a no-op, however a message will be written to the log detailing the error
* @param changes A list of changes to make to the objects in the store
*/
public <T> void update(String storeId, List<ItemUpdate> changes)
{
StoreProvider<Object> store = Directory.getRegistration(storeId, Object.class);
if (store == null)
{
log.error("update() can't find any stores with storeId=" + storeId);
throw new NullPointerException("Invalid store");
}
store.update(changes);
}
/**
* The log stream
*/
private static final Log log = LogFactory.getLog(Data.class);
}
| mit |
castaway2000/Pawpads | app/src/main/java/saberapplications/pawpads/service/FileDownloadService.java | 4649 | package saberapplications.pawpads.service;
import android.app.IntentService;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import com.quickblox.chat.model.QBAttachment;
import com.quickblox.content.QBContent;
import com.quickblox.content.model.QBFile;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import saberapplications.pawpads.R;
public class FileDownloadService extends IntentService {
private static Handler handler;
public FileDownloadService() {
super("FileDownloadService");
}
public static final String ATTACHMENT_NAME="attachement_name";
public static final String ATTACHMENT_ID="attachement_id";
public static void startService(Context context, QBAttachment attachment) {
Intent intent = new Intent(context, FileDownloadService.class);
intent.putExtra(ATTACHMENT_ID,attachment.getId());
//attachment.getName() + attachment.getType()
intent.putExtra(ATTACHMENT_NAME,attachment.getName());
context.startService(intent);
handler=new Handler();
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
try {
String fileId=intent.getStringExtra(ATTACHMENT_ID);
final String fileName=intent.getStringExtra(ATTACHMENT_NAME);
if (fileId==null) return;
File targetFile = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName);
if (!targetFile.exists()) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(FileDownloadService.this, R.string.download_started,Toast.LENGTH_LONG).show();
}
});
QBFile file = QBContent.getFile(Integer.parseInt(fileId));
URL u = new URL(file.getPrivateUrl());
InputStream inputStream = u.openStream();
OutputStream outStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[1024 * 100];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
}
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(fileExt(fileName));
newIntent.setDataAndType(Uri.fromFile(targetFile),mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(newIntent);
} catch (ActivityNotFoundException e) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(FileDownloadService.this, R.string.file_downloaded, Toast.LENGTH_LONG).show();
}
});
}
} catch (final IOException e) {
e.printStackTrace();
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(FileDownloadService.this,e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
}
private String fileExt(String url) {
if (url.indexOf("?") > -1) {
url = url.substring(0, url.indexOf("?"));
}
if (url.lastIndexOf(".") == -1) {
return null;
} else {
String ext = url.substring(url.lastIndexOf(".") + 1);
if (ext.indexOf("%") > -1) {
ext = ext.substring(0, ext.indexOf("%"));
}
if (ext.indexOf("/") > -1) {
ext = ext.substring(0, ext.indexOf("/"));
}
return ext.toLowerCase();
}
}
}
| mit |
binghuo365/csustRepo | trunk/src/com/yunstudio/struts/listener/SessionListener.java | 1268 | package com.yunstudio.struts.listener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.yunstudio.service.AdminService;
public class SessionListener implements HttpSessionAttributeListener,HttpSessionListener{
private AdminService adminService;
public void attributeAdded(HttpSessionBindingEvent se) {
// TODO Auto-generated method stub
}
public void attributeRemoved(HttpSessionBindingEvent se) {
// TODO Auto-generated method stub
// WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(se.getSession().getServletContext());
// adminService=(AdminService) wac.getBean("adminService");
}
public void attributeReplaced(HttpSessionBindingEvent se) {
// TODO Auto-generated method stub
}
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
public void sessionDestroyed(HttpSessionEvent se) {
// WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(se.getSession().getServletContext());
// adminService=(AdminService) wac.getBean("adminService");
}
}
| mit |
Ernestyj/JStudy | src/main/java/leetcode221_230/SummaryRanges.java | 1582 | package leetcode221_230;
import java.util.ArrayList;
import java.util.List;
/**Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
* Created by eugene on 16/4/23.
*/
public class SummaryRanges {
public List<String> summaryRanges(int[] nums) {
List<String> list = new ArrayList();
for(int i=0; i<nums.length; i++){
int n = nums[i];
while(i+1<nums.length && nums[i+1]-nums[i]==1) i++;
if(n!=nums[i]){
list.add(n+"->"+nums[i]);
}else{
list.add(n+"");
}
}
return list;
}
public List<String> summaryRanges1(int[] nums) {
List<String> result = new ArrayList<>();
if (nums.length==0) return result;
int start = nums[0];
int count = 1;
StringBuilder builder = new StringBuilder();
builder.append(start);
for (int i=1; i<nums.length; i++){
if (nums[i]-nums[i-1]==1){
count++;
} else {
if (count==1) {
result.add(builder.toString());
} else {
result.add(builder.append("->"+nums[i-1]).toString());
}
builder = new StringBuilder(""+nums[i]);
count = 1;
}
}
if (count!=1) result.add(builder.append("->"+nums[nums.length-1]).toString());
else result.add(builder.toString());
return result;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/sql/mgmt-v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/DatabaseStatus.java | 3401 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.sql.v2017_03_01_preview;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for DatabaseStatus.
*/
public final class DatabaseStatus extends ExpandableStringEnum<DatabaseStatus> {
/** Static value Online for DatabaseStatus. */
public static final DatabaseStatus ONLINE = fromString("Online");
/** Static value Restoring for DatabaseStatus. */
public static final DatabaseStatus RESTORING = fromString("Restoring");
/** Static value RecoveryPending for DatabaseStatus. */
public static final DatabaseStatus RECOVERY_PENDING = fromString("RecoveryPending");
/** Static value Recovering for DatabaseStatus. */
public static final DatabaseStatus RECOVERING = fromString("Recovering");
/** Static value Suspect for DatabaseStatus. */
public static final DatabaseStatus SUSPECT = fromString("Suspect");
/** Static value Offline for DatabaseStatus. */
public static final DatabaseStatus OFFLINE = fromString("Offline");
/** Static value Standby for DatabaseStatus. */
public static final DatabaseStatus STANDBY = fromString("Standby");
/** Static value Shutdown for DatabaseStatus. */
public static final DatabaseStatus SHUTDOWN = fromString("Shutdown");
/** Static value EmergencyMode for DatabaseStatus. */
public static final DatabaseStatus EMERGENCY_MODE = fromString("EmergencyMode");
/** Static value AutoClosed for DatabaseStatus. */
public static final DatabaseStatus AUTO_CLOSED = fromString("AutoClosed");
/** Static value Copying for DatabaseStatus. */
public static final DatabaseStatus COPYING = fromString("Copying");
/** Static value Creating for DatabaseStatus. */
public static final DatabaseStatus CREATING = fromString("Creating");
/** Static value Inaccessible for DatabaseStatus. */
public static final DatabaseStatus INACCESSIBLE = fromString("Inaccessible");
/** Static value OfflineSecondary for DatabaseStatus. */
public static final DatabaseStatus OFFLINE_SECONDARY = fromString("OfflineSecondary");
/** Static value Pausing for DatabaseStatus. */
public static final DatabaseStatus PAUSING = fromString("Pausing");
/** Static value Paused for DatabaseStatus. */
public static final DatabaseStatus PAUSED = fromString("Paused");
/** Static value Resuming for DatabaseStatus. */
public static final DatabaseStatus RESUMING = fromString("Resuming");
/** Static value Scaling for DatabaseStatus. */
public static final DatabaseStatus SCALING = fromString("Scaling");
/**
* Creates or finds a DatabaseStatus from its string representation.
* @param name a name to look for
* @return the corresponding DatabaseStatus
*/
@JsonCreator
public static DatabaseStatus fromString(String name) {
return fromString(name, DatabaseStatus.class);
}
/**
* @return known DatabaseStatus values
*/
public static Collection<DatabaseStatus> values() {
return values(DatabaseStatus.class);
}
}
| mit |
plattformbrandenburg/ldadmin | src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/tables/records/BattleParticipantRecord.java | 3599 | /**
* This class is generated by jOOQ
*/
package de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.records;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class BattleParticipantRecord extends org.jooq.impl.TableRecordImpl<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.records.BattleParticipantRecord> implements org.jooq.Record2<java.lang.Integer, java.lang.Integer>, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.interfaces.IBattleParticipant {
private static final long serialVersionUID = -1733415471;
/**
* Setter for <code>battle_participant.id</code>.
*/
public void setId(java.lang.Integer value) {
setValue(0, value);
}
/**
* Getter for <code>battle_participant.id</code>.
*/
@Override
public java.lang.Integer getId() {
return (java.lang.Integer) getValue(0);
}
/**
* Setter for <code>battle_participant.issue_id</code>.
*/
public void setIssueId(java.lang.Integer value) {
setValue(1, value);
}
/**
* Getter for <code>battle_participant.issue_id</code>.
*/
@Override
public java.lang.Integer getIssueId() {
return (java.lang.Integer) getValue(1);
}
// -------------------------------------------------------------------------
// Record2 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row2<java.lang.Integer, java.lang.Integer> fieldsRow() {
return (org.jooq.Row2) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row2<java.lang.Integer, java.lang.Integer> valuesRow() {
return (org.jooq.Row2) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Integer> field1() {
return de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT.ID;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Integer> field2() {
return de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT.ISSUE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.Integer value2() {
return getIssueId();
}
/**
* {@inheritDoc}
*/
@Override
public BattleParticipantRecord value1(java.lang.Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public BattleParticipantRecord value2(java.lang.Integer value) {
setIssueId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public BattleParticipantRecord values(java.lang.Integer value1, java.lang.Integer value2) {
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached BattleParticipantRecord
*/
public BattleParticipantRecord() {
super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT);
}
/**
* Create a detached, initialised BattleParticipantRecord
*/
public BattleParticipantRecord(java.lang.Integer id, java.lang.Integer issueId) {
super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.BattleParticipant.BATTLE_PARTICIPANT);
setValue(0, id);
setValue(1, issueId);
}
}
| mit |
chihane/JDAddressSelector | library/src/main/java/chihane/jdaddressselector/AddressProvider.java | 680 | package chihane.jdaddressselector;
import java.util.List;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;
public interface AddressProvider {
void provideProvinces(AddressReceiver<Province> addressReceiver);
void provideCitiesWith(int provinceId, AddressReceiver<City> addressReceiver);
void provideCountiesWith(int cityId, AddressReceiver<County> addressReceiver);
void provideStreetsWith(int countyId, AddressReceiver<Street> addressReceiver);
interface AddressReceiver<T> {
void send(List<T> data);
}
} | mit |
lalongooo/POSSpring | src/main/java/com/puntodeventa/global/Entity/CredAmortPK.java | 2149 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.puntodeventa.global.Entity;
import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
*
* @author jehernandez
*/
@Embeddable
public class CredAmortPK implements Serializable {
@Basic(optional = false)
@Column(name = "CVE_CLIENTE")
private BigInteger cveCliente;
@Basic(optional = false)
@Column(name = "ID_FOLIO")
private BigInteger idFolio;
public CredAmortPK() {
}
public CredAmortPK(BigInteger cveCliente, BigInteger idFolio) {
this.cveCliente = cveCliente;
this.idFolio = idFolio;
}
public BigInteger getCveCliente() {
return cveCliente;
}
public void setCveCliente(BigInteger cveCliente) {
this.cveCliente = cveCliente;
}
public BigInteger getIdFolio() {
return idFolio;
}
public void setIdFolio(BigInteger idFolio) {
this.idFolio = idFolio;
}
@Override
public int hashCode() {
int hash = 0;
hash += (cveCliente != null ? cveCliente.hashCode() : 0);
hash += (idFolio != null ? idFolio.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 CredAmortPK)) {
return false;
}
CredAmortPK other = (CredAmortPK) object;
if ((this.cveCliente == null && other.cveCliente != null) || (this.cveCliente != null && !this.cveCliente.equals(other.cveCliente))) {
return false;
}
if ((this.idFolio == null && other.idFolio != null) || (this.idFolio != null && !this.idFolio.equals(other.idFolio))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.puntodeventa.persistence.Entity.CredAmortPK[ cveCliente=" + cveCliente + ", idFolio=" + idFolio + " ]";
}
}
| mit |
TakayukiHoshi1984/DeviceConnect-Android | dConnectManager/dConnectManager/dconnect-manager-app/src/main/java/org/deviceconnect/android/manager/setting/ConnectionErrorView.java | 3763 | /*
ConnectionErrorView.java
Copyright (c) 2017 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.manager.setting;
import android.content.Context;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.deviceconnect.android.manager.R;
import org.deviceconnect.android.manager.core.plugin.CommunicationHistory;
import org.deviceconnect.android.manager.core.plugin.ConnectionError;
import org.deviceconnect.android.manager.core.plugin.DevicePlugin;
import java.util.List;
/**
* プラグインとの接続に関するエラーの表示.
*
* @author NTT DOCOMO, INC.
*/
public class ConnectionErrorView extends LinearLayout {
private static final int DEFAULT_VISIBILITY = View.GONE;
private final TextView mErrorView;
public ConnectionErrorView(final Context context,
final @Nullable AttributeSet attrs) {
super(context, attrs);
setVisibility(DEFAULT_VISIBILITY);
View layout = LayoutInflater.from(context).inflate(R.layout.layout_plugin_connection_error, this);
mErrorView = (TextView) layout.findViewById(R.id.plugin_connection_error_message);
}
public void showErrorMessage(final DevicePlugin plugin) {
ConnectionError error = plugin.getCurrentConnectionError();
if (error != null) {
showErrorMessage(error);
return;
}
CommunicationHistory history = plugin.getHistory();
List<CommunicationHistory.Info> timeouts = history.getNotRespondedCommunications();
List<CommunicationHistory.Info> responses = history.getRespondedCommunications();
if (timeouts.size() > 0) {
CommunicationHistory.Info timeout = timeouts.get(timeouts.size() - 1);
boolean showsWarning;
if (responses.size() > 0) {
CommunicationHistory.Info response = responses.get(responses.size() - 1);
showsWarning = response.getStartTime() < timeout.getStartTime();
} else {
showsWarning = true;
}
// NOTE: 最も直近のリクエストについて応答タイムアウトが発生した場合のみ下記のエラーを表示.
if (showsWarning) {
showErrorMessage(R.string.dconnect_error_response_timeout);
}
return;
}
setVisibility(DEFAULT_VISIBILITY);
mErrorView.setText(null);
}
public void showErrorMessage(final ConnectionError error) {
if (error != null) {
int messageId = -1;
switch (error) {
case NOT_PERMITTED:
messageId = R.string.dconnect_error_connection_not_permitted;
break;
case NOT_RESPONDED:
messageId = R.string.dconnect_error_connection_timeout;
break;
case TERMINATED:
messageId = R.string.dconnect_error_connection_terminated;
break;
case INTERNAL_ERROR:
messageId = R.string.dconnect_error_connection_internal_error;
break;
default:
break;
}
showErrorMessage(messageId);
}
}
private void showErrorMessage(final int messageId) {
if (messageId != -1) {
String message = getContext().getString(messageId);
mErrorView.setText(message);
setVisibility(View.VISIBLE);
}
}
}
| mit |
rokn/Count_Words_2015 | testing/droolsjbpm-integration-master/kie-server-parent/kie-server-api/src/main/java/org/kie/server/api/model/instance/TaskAttachmentList.java | 1582 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.kie.server.api.model.instance;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "task-attachment-list")
public class TaskAttachmentList {
@XmlElement(name="task-attachment")
private TaskAttachment[] taskAttachments;
public TaskAttachmentList() {
}
public TaskAttachmentList(TaskAttachment[] taskAttachments) {
this.taskAttachments = taskAttachments;
}
public TaskAttachmentList(List<TaskAttachment> taskAttachments) {
this.taskAttachments = taskAttachments.toArray(new TaskAttachment[taskAttachments.size()]);
}
public TaskAttachment[] getTasks() {
return taskAttachments;
}
public void setTasks(TaskAttachment[] taskAttachments) {
this.taskAttachments = taskAttachments;
}
}
| mit |
codeborne/selenide | src/test/java/integration/ReplacingElementTest.java | 1651 | package integration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static com.codeborne.selenide.CollectionCondition.empty;
import static com.codeborne.selenide.Condition.cssClass;
import static com.codeborne.selenide.Condition.value;
import static org.assertj.core.api.Assertions.assertThat;
final class ReplacingElementTest extends ITest {
@BeforeEach
void openTestPage() {
openFile("page_with_replacing_elements.html");
}
@Test
void shouldWaitsUntilElementIsReplaced() {
withLongTimeout(() -> {
$("#dynamic-element").shouldHave(value("I will be replaced soon"));
driver().executeJavaScript("replaceElement()");
$("#dynamic-element").shouldHave(value("Hello, I am back"), cssClass("reloaded"));
$("#dynamic-element").setValue("New value");
});
}
@Test
void getInnerText() {
assertThat($("#dynamic-element").innerText())
.isEmpty();
}
@Test
void getInnerHtml() {
assertThat($("#dynamic-element").innerHtml())
.isEmpty();
}
@Test
void findAll() {
$("#dynamic-element").findAll(".child").shouldBe(empty);
}
@Test
void testToString() {
assertThat($("#dynamic-element"))
.hasToString("<input id=\"dynamic-element\" type=\"text\" value=\"I will be replaced soon\"></input>");
}
@Test
@Disabled
void tryToCatchStaleElementException() {
driver().executeJavaScript("startRegularReplacement()");
for (int i = 0; i < 10; i++) {
$("#dynamic-element").shouldHave(value("I am back"), cssClass("reloaded")).setValue("New value from test");
}
}
}
| mit |
loremipsumdolor/CastFast | src/com/amazonaws/internal/config/SignerConfig.java | 1109 | /*
* Copyright 2010-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.internal.config;
import com.amazonaws.annotation.Immutable;
/**
* Signer configuration.
*/
@Immutable
public class SignerConfig {
private final String signerType;
SignerConfig(String signerType) {
this.signerType = signerType;
}
SignerConfig(SignerConfig from) {
this.signerType = from.getSignerType();
}
public String getSignerType() {
return signerType;
}
@Override
public String toString() {
return signerType;
}
}
| mit |
ladygagapowerbot/bachelor-thesis-implementation | lib/Encog/src/main/java/org/encog/engine/network/activation/ActivationClippedLinear.java | 2484 | /*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.engine.network.activation;
/**
* Linear activation function that bounds the output to [-1,+1]. This
* activation is typically part of a CPPN neural network, such as
* HyperNEAT.
* <p/>
* The idea for this activation function was developed by Ken Stanley, of
* the University of Texas at Austin.
* http://www.cs.ucf.edu/~kstanley/
*/
public class ActivationClippedLinear implements ActivationFunction {
@Override
public void activationFunction(double[] d, int start, int size) {
for (int i = start; i < start + size; i++) {
if (d[i] < -1.0) {
d[i] = -1.0;
}
if (d[i] > 1.0) {
d[i] = 1.0;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public double derivativeFunction(double b, double a) {
return 1;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasDerivative() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public double[] getParams() {
return ActivationLinear.P;
}
/**
* {@inheritDoc}
*/
@Override
public void setParam(int index, double value) {
}
/**
* {@inheritDoc}
*/
@Override
public String[] getParamNames() {
return ActivationLinear.N;
}
/**
* {@inheritDoc}
*/
@Override
public final ActivationFunction clone() {
return new ActivationClippedLinear();
}
/**
* {@inheritDoc}
*/
@Override
public String getFactoryCode() {
return null;
}
}
| mit |
darshanhs90/Java-InterviewPrep | src/May2021Leetcode/_0621TaskScheduler2.java | 711 | package May2021Leetcode;
import java.util.HashMap;
public class _0621TaskScheduler2 {
// https://leetcode.com/discuss/interview-question/432086/Facebook-or-Phone-Screen-or-Task-Scheduler/394783
public static void main(String[] args) {
System.out.println(leastInterval(new int[] { 1, 1, 2, 1 }, 2));
}
public static int leastInterval(int[] tasks, int n) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int count = 0;
for (int i = 0; i < tasks.length; i++) {
if (!map.containsKey(tasks[i])) {
map.put(tasks[i], count);
count++;
} else {
count = Math.max(count, map.get(tasks[i]) + n + 1);
map.put(tasks[i], count);
count++;
}
}
return count;
}
}
| mit |
ladygagapowerbot/bachelor-thesis-implementation | lib/Encog/src/main/java/org/encog/ml/tree/traverse/tasks/TaskGetNodeIndex.java | 1915 | /*
* Encog(tm) Core v3.2 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2013 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ml.tree.traverse.tasks;
import org.encog.ml.tree.TreeNode;
import org.encog.ml.tree.traverse.DepthFirstTraversal;
import org.encog.ml.tree.traverse.TreeTraversalTask;
public class TaskGetNodeIndex implements TreeTraversalTask {
private int nodeCount;
private int targetIndex;
private TreeNode result;
public TaskGetNodeIndex(int theIndex) {
this.targetIndex = theIndex;
this.nodeCount = 0;
}
@Override
public boolean task(TreeNode node) {
if (this.nodeCount >= targetIndex) {
if (result == null) {
result = node;
}
return false;
}
this.nodeCount++;
return true;
}
public TreeNode getResult() {
return result;
}
public static TreeNode process(int index, TreeNode node) {
TaskGetNodeIndex task = new TaskGetNodeIndex(index);
DepthFirstTraversal trav = new DepthFirstTraversal();
trav.traverse(node, task);
return task.getResult();
}
}
| mit |
zaoying/EChartsAnnotation | src/cn/edu/gdut/zaoying/Option/series/treemap/itemStyle/emphasis/ColorSaturationNumber.java | 368 | package cn.edu.gdut.zaoying.Option.series.treemap.itemStyle.emphasis;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ColorSaturationNumber {
double value() default 0;
} | mit |
martinsawicki/azure-sdk-for-java | azure-samples/src/main/java/com/microsoft/azure/management/graphrbac/samples/ManageServicePrincipalCredentials.java | 10249 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.graphrbac.samples;
import com.google.common.io.ByteStreams;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.credentials.ApplicationTokenCredentials;
import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.graphrbac.BuiltInRole;
import com.microsoft.azure.management.graphrbac.RoleAssignment;
import com.microsoft.azure.management.graphrbac.ServicePrincipal;
import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
import com.microsoft.azure.management.samples.Utils;
import com.microsoft.rest.LogLevel;
import org.joda.time.Duration;
import java.io.File;
/**
* Azure service principal sample for managing its credentials.
* - Create an application with 2 passwords and 1 certificate credentials
* - Create an associated service principal with contributor role
* - Verify all password credentials and certificate credentials are valid
* - Revoke access of a password credential
* - Verify the password credential is no longer valid
* - Revoke the role assignment
* - Verify the remaining password credential is invalid
*/
public final class ManageServicePrincipalCredentials {
/**
* Main function which runs the actual sample.
*
* @param authenticated instance of Authenticated
* @param defaultSubscription default subscription id
* @param environment the environment the sample is running in
* @return true if sample runs successfully
*/
public static boolean runSample(Azure.Authenticated authenticated, String defaultSubscription, AzureEnvironment environment) {
final String spName = Utils.createRandomName("sp");
final String appName = SdkContext.randomResourceName("app", 20);
final String appUrl = "https://" + appName;
final String passwordName1 = SdkContext.randomResourceName("password", 20);
final String password1 = "P@ssw0rd";
final String passwordName2 = SdkContext.randomResourceName("password", 20);
final String password2 = "StrongP@ss!12";
final String certName1 = SdkContext.randomResourceName("cert", 20);
final String raName = SdkContext.randomUuid();
String servicePrincipalId = "";
try {
// ============================================================
// Create service principal
System.out.println("Creating an Active Directory service principal " + spName + "...");
ServicePrincipal servicePrincipal = authenticated.servicePrincipals()
.define(spName)
.withNewApplication(appUrl)
.definePasswordCredential(passwordName1)
.withPasswordValue(password1)
.attach()
.definePasswordCredential(passwordName2)
.withPasswordValue(password2)
.attach()
.defineCertificateCredential(certName1)
.withAsymmetricX509Certificate()
.withPublicKey(ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.cer")))
.withDuration(Duration.standardDays(1))
.attach()
.create();
System.out.println("Created service principal " + spName + ".");
Utils.print(servicePrincipal);
servicePrincipalId = servicePrincipal.id();
// ============================================================
// Create role assignment
System.out.println("Creating a Contributor role assignment " + raName + " for the service principal...");
Thread.sleep(15000);
RoleAssignment roleAssignment = authenticated.roleAssignments()
.define(raName)
.forServicePrincipal(servicePrincipal)
.withBuiltInRole(BuiltInRole.CONTRIBUTOR)
.withSubscriptionScope(defaultSubscription)
.create();
System.out.println("Created role assignment " + raName + ".");
Utils.print(roleAssignment);
// ============================================================
// Verify the credentials are valid
System.out.println("Verifying password credential " + passwordName1 + " is valid...");
ApplicationTokenCredentials testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password1, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Verified " + passwordName1 + " is valid.");
} catch (Exception e) {
System.out.println("Failed to verify " + passwordName1 + " is valid.");
}
System.out.println("Verifying password credential " + passwordName2 + " is valid...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password2, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Verified " + passwordName2 + " is valid.");
} catch (Exception e) {
System.out.println("Failed to verify " + passwordName2 + " is valid.");
}
System.out.println("Verifying certificate credential " + certName1 + " is valid...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(),
authenticated.tenantId(),
ByteStreams.toByteArray(ManageServicePrincipalCredentials.class.getResourceAsStream("/myTest.pfx")),
"Abc123",
environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Verified " + certName1 + " is valid.");
} catch (Exception e) {
System.out.println("Failed to verify " + certName1 + " is valid.");
}
// ============================================================
// Revoke access of the 1st password credential
System.out.println("Revoking access for password credential " + passwordName1 + "...");
servicePrincipal.update()
.withoutCredential(passwordName1)
.apply();
SdkContext.sleep(15000);
System.out.println("Credential revoked.");
// ============================================================
// Verify the revoked password credential is no longer valid
System.out.println("Verifying password credential " + passwordName1 + " is revoked...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password1, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription();
System.out.println("Failed to verify " + passwordName1 + " is revoked.");
} catch (Exception e) {
System.out.println("Verified " + passwordName1 + " is revoked.");
}
// ============================================================
// Revoke the role assignment
System.out.println("Revoking role assignment " + raName + "...");
authenticated.roleAssignments().deleteById(roleAssignment.id());
SdkContext.sleep(5000);
// ============================================================
// Verify the revoked password credential is no longer valid
System.out.println("Verifying password credential " + passwordName2 + " has no access to subscription...");
testCredential = new ApplicationTokenCredentials(
servicePrincipal.applicationId(), authenticated.tenantId(), password2, environment);
try {
Azure.authenticate(testCredential).withDefaultSubscription()
.resourceGroups().list();
System.out.println("Failed to verify " + passwordName2 + " has no access to subscription.");
} catch (Exception e) {
System.out.println("Verified " + passwordName2 + " has no access to subscription.");
}
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting application: " + appName);
authenticated.servicePrincipals().deleteById(servicePrincipalId);
System.out.println("Deleted application: " + appName);
}
catch (Exception e) {
System.out.println("Did not create applications in Azure. No clean up is necessary");
}
}
return false;
}
/**
* Main entry point.
*
* @param args the parameters
*/
public static void main(String[] args) {
try {
final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));
ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
Azure.Authenticated authenticated = Azure.configure()
.withLogLevel(LogLevel.BASIC)
.authenticate(credentials);
runSample(authenticated, credentials.defaultSubscriptionId(), credentials.environment());
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private ManageServicePrincipalCredentials() {
}
}
| mit |
herveyw/azure-sdk-for-java | azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/models/GroupableResource.java | 3293 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.resources.fluentcore.arm.models;
import com.microsoft.azure.management.apigeneration.Fluent;
import com.microsoft.azure.management.resources.ResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
/**
* Base interface for resources in resource groups.
*/
@Fluent()
public interface GroupableResource extends Resource {
/**
* @return the name of the resource group
*/
String resourceGroupName();
/**
* Grouping of all the definition stages.
*/
interface DefinitionStages {
/**
* A resource definition allowing a resource group to be selected.
*
* @param <T> the next stage of the resource definition
*/
interface WithGroup<T> extends
WithExistingResourceGroup<T>,
WithNewResourceGroup<T> {
}
/**
* A resource definition allowing a new resource group to be created.
*
* @param <T> the next stage of the resource definition
*/
interface WithNewResourceGroup<T> {
/**
* Creates a new resource group to put the resource in.
* <p>
* The group will be created in the same location as the resource.
* @param name the name of the new group
* @return the next stage of the resource definition
*/
T withNewResourceGroup(String name);
/**
* Creates a new resource group to put the resource in.
* <p>
* The group will be created in the same location as the resource.
* The group's name is automatically derived from the resource's name.
* @return the next stage of the resource definition
*/
T withNewResourceGroup();
/**
* Creates a new resource group to put the resource in, based on the definition specified.
* @param groupDefinition a creatable definition for a new resource group
* @return the next stage of the resource definition
*/
T withNewResourceGroup(Creatable<ResourceGroup> groupDefinition);
}
/**
* A resource definition allowing an existing resource group to be selected.
*
* @param <T> the next stage of the resource definition
*/
interface WithExistingResourceGroup<T> {
/**
* Associates the resource with an existing resource group.
* @param groupName the name of an existing resource group to put this resource in.
* @return the next stage of the resource definition
*/
T withExistingResourceGroup(String groupName);
/**
* Associates the resource with an existing resource group.
* @param group an existing resource group to put the resource in
* @return the next stage of the resource definition
*/
T withExistingResourceGroup(ResourceGroup group);
}
}
}
| mit |
P1erreGaultier/PepSIIrup-2017 | personne/src/main/java/fr/sii/atlantique/siistem/personne/model/Event.java | 4247 | package fr.sii.atlantique.siistem.personne.model;
/**
* Event Class with JPA
* @author Dorian Coqueron & Pierre Gaultier
* @version 1.0
*/
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@Entity
@Table(name="Event")
@JsonRootName("Event")
public class Event implements Serializable{
private static final long serialVersionUID = 1L;
@JsonProperty("EventId")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Eventid",unique=true, nullable=false)
private int eventId;
@JsonProperty("Name")
@Column(name = "Name")
private String name;
@JsonProperty("DateStart")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone="CET")
@Column(name = "Datestart")
private Date dateStart;
@JsonProperty("DateEnd")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone="CET")
@Column(name = "Dateend")
private Date dateEnd;
@JsonProperty("PlaceId")
@Column(name = "Placeid")
private String placeID;
@JsonProperty("Description")
@Column(name = "Description")
private String description;
@JsonProperty("Image")
@Column(name = "Image")
private String image;
@JsonProperty("IsCanceled")
@Column(name = "Iscanceled")
private int isCanceled;
@JsonProperty("Owner")
@ManyToOne
@JoinColumn(name = "Owner")
private Person owner;
@JsonProperty("EventType")
@ManyToOne
@JoinColumn(name = "Eventtype")
private EventType eventType;
public Event(){
//JPA need empty constructor
}
public Event(String name) {
this.name = name;
this.dateStart = new Date();
this.dateEnd = new Date();
this.placeID = "17";
this.description = "too long";
this.isCanceled = 0;
this.owner = new Person();
this.image = "";
}
public Event(String name, Date dateStart, Date dateEnd, String placeID, String description, int isCanceled, String image, Person owner) {
super();
this.name = name;
this.dateStart = dateStart;
this.dateEnd = dateEnd;
this.placeID = placeID;
this.description = description;
this.isCanceled = isCanceled;
this.image = image;
this.owner = owner;
}
public int getEventId() {
return eventId;
}
public void setEventId(int id){
this.eventId = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateStart() {
return dateStart;
}
public void setDateStart(Date dateStart) {
this.dateStart = dateStart;
}
public Date getDateEnd() {
return dateEnd;
}
public void setDateEnd(Date dateEnd) {
this.dateEnd = dateEnd;
}
public String getPlaceID() {
return placeID;
}
public void setPlaceID(String placeID) {
this.placeID = placeID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getIsCanceled() {
return isCanceled;
}
public void setIsCanceled(int isCanceled) {
this.isCanceled = isCanceled;
}
public Person getOwner() {
return owner;
}
public void setOwner(Person owner) {
this.owner = owner;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dateEnd == null) ? 0 : dateEnd.hashCode());
result = prime * result + ((dateStart == null) ? 0 : dateStart.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Event other = (Event) obj;
if (dateEnd == null) {
if (other.dateEnd != null)
return false;
} else if (!dateEnd.equals(other.dateEnd))
return false;
if (dateStart == null) {
if (other.dateStart != null)
return false;
} else if (!dateStart.equals(other.dateStart))
return false;
return true;
}
public boolean checkEvent() {
return name != null && dateStart != null && dateEnd != null && placeID != null && description != null && owner != null;
}
}
| mit |
leancloud/Java-WebSocket | src/main/java/org/java_websocket/AbstractWrappedByteChannel.java | 2843 | /*
* Copyright (c) 2010-2017 Nathan Rajlich
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.java_websocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SocketChannel;
public class AbstractWrappedByteChannel implements WrappedByteChannel {
private final ByteChannel channel;
public AbstractWrappedByteChannel( ByteChannel towrap ) {
this.channel = towrap;
}
public AbstractWrappedByteChannel( WrappedByteChannel towrap ) {
this.channel = towrap;
}
@Override
public int read( ByteBuffer dst ) throws IOException {
return channel.read( dst );
}
@Override
public boolean isOpen() {
return channel.isOpen();
}
@Override
public void close() throws IOException {
channel.close();
}
@Override
public int write( ByteBuffer src ) throws IOException {
return channel.write( src );
}
@Override
public boolean isNeedWrite() {
return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedWrite();
}
@Override
public void writeMore() throws IOException {
if( channel instanceof WrappedByteChannel )
( (WrappedByteChannel) channel ).writeMore();
}
@Override
public boolean isNeedRead() {
return channel instanceof WrappedByteChannel && ((WrappedByteChannel) channel).isNeedRead();
}
@Override
public int readMore( ByteBuffer dst ) throws IOException {
return channel instanceof WrappedByteChannel ? ( (WrappedByteChannel) channel ).readMore( dst ) : 0;
}
@Override
public boolean isBlocking() {
if( channel instanceof SocketChannel )
return ( (SocketChannel) channel ).isBlocking();
else if( channel instanceof WrappedByteChannel )
return ( (WrappedByteChannel) channel ).isBlocking();
return false;
}
}
| mit |
darshanhs90/Java-InterviewPrep | src/DoordashPrep/_0121BestTimeToBuyAndSellStock.java | 703 | package DoordashPrep;
public class _0121BestTimeToBuyAndSellStock {
public static void main(String[] args) {
System.out.println(maxProfit(new int[] { 7, 1, 5, 3, 6, 4 }));
System.out.println(maxProfit(new int[] { 7, 6, 4, 3, 1 }));
System.out.println(maxProfit(new int[] { 3, 2, 6, 5, 0, 3 }));
System.out.println(maxProfit(new int[] { 1, 2 }));
}
public static int maxProfit(int[] prices) {
if (prices == null || prices.length < 2)
return 0;
int minSoFar = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minSoFar) {
minSoFar = prices[i];
}
maxProfit = Math.max(maxProfit, prices[i] - minSoFar);
}
return maxProfit;
}
}
| mit |
gaborkolozsy/XChange | xchange-dsx/src/main/java/org/knowm/xchange/dsx/dto/account/DSXFiatWithdrawReturn.java | 455 | package org.knowm.xchange.dsx.dto.account;
import org.knowm.xchange.dsx.dto.DSXReturn;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author Mikhail Wall
*/
public class DSXFiatWithdrawReturn extends DSXReturn<DSXFiatWithdraw> {
public DSXFiatWithdrawReturn(@JsonProperty("success") boolean success, @JsonProperty("return") DSXFiatWithdraw value,
@JsonProperty("error") String error) {
super(success, value, error);
}
}
| mit |
openlegacy/lombok | test/transform/resource/after-delombok/BuilderSingularNoAuto.java | 5179 | import java.util.List;
class BuilderSingularNoAuto {
private List<String> things;
private List<String> widgets;
private List<String> items;
@java.beans.ConstructorProperties({"things", "widgets", "items"})
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
BuilderSingularNoAuto(final List<String> things, final List<String> widgets, final List<String> items) {
this.things = things;
this.widgets = widgets;
this.items = items;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public static class BuilderSingularNoAutoBuilder {
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
private java.util.ArrayList<String> things;
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
private java.util.ArrayList<String> widgets;
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
private java.util.ArrayList<String> items;
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
BuilderSingularNoAutoBuilder() {
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder things(final String things) {
if (this.things == null) this.things = new java.util.ArrayList<String>();
this.things.add(things);
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder things(final java.util.Collection<? extends String> things) {
if (this.things == null) this.things = new java.util.ArrayList<String>();
this.things.addAll(things);
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder clearThings() {
if (this.things != null) this.things.clear();
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder widget(final String widget) {
if (this.widgets == null) this.widgets = new java.util.ArrayList<String>();
this.widgets.add(widget);
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder widgets(final java.util.Collection<? extends String> widgets) {
if (this.widgets == null) this.widgets = new java.util.ArrayList<String>();
this.widgets.addAll(widgets);
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder clearWidgets() {
if (this.widgets != null) this.widgets.clear();
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder items(final String items) {
if (this.items == null) this.items = new java.util.ArrayList<String>();
this.items.add(items);
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder items(final java.util.Collection<? extends String> items) {
if (this.items == null) this.items = new java.util.ArrayList<String>();
this.items.addAll(items);
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAutoBuilder clearItems() {
if (this.items != null) this.items.clear();
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public BuilderSingularNoAuto build() {
java.util.List<String> things;
switch (this.things == null ? 0 : this.things.size()) {
case 0:
things = java.util.Collections.emptyList();
break;
case 1:
things = java.util.Collections.singletonList(this.things.get(0));
break;
default:
things = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(this.things));
}
java.util.List<String> widgets;
switch (this.widgets == null ? 0 : this.widgets.size()) {
case 0:
widgets = java.util.Collections.emptyList();
break;
case 1:
widgets = java.util.Collections.singletonList(this.widgets.get(0));
break;
default:
widgets = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(this.widgets));
}
java.util.List<String> items;
switch (this.items == null ? 0 : this.items.size()) {
case 0:
items = java.util.Collections.emptyList();
break;
case 1:
items = java.util.Collections.singletonList(this.items.get(0));
break;
default:
items = java.util.Collections.unmodifiableList(new java.util.ArrayList<String>(this.items));
}
return new BuilderSingularNoAuto(things, widgets, items);
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public java.lang.String toString() {
return "BuilderSingularNoAuto.BuilderSingularNoAutoBuilder(things=" + this.things + ", widgets=" + this.widgets + ", items=" + this.items + ")";
}
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public static BuilderSingularNoAutoBuilder builder() {
return new BuilderSingularNoAutoBuilder();
}
}
| mit |
Felix-Yan/ECJ | ec/app/gpsemantics/func/SemanticExtra.java | 563 | /*
Copyright 2012 by James McDermott
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.app.gpsemantics.func;
import ec.*;
import ec.gp.*;
import ec.util.*;
/*
* SemanticNode.java
*
*/
/**
* @author James McDermott
*/
public class SemanticExtra extends SemanticNode
{
char value;
int index;
public SemanticExtra(char v, int i) { value = v; index = i; }
public char value() { return value; }
public int index() { return index; }
}
| mit |
JosuaKrause/BusVis | src/main/java/infovis/gui/PainterAdapter.java | 1535 | package infovis.gui;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* Provides meaningful default implementations for a {@link Painter}.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public class PainterAdapter implements Painter {
@Override
public void draw(final Graphics2D gfx, final Context ctx) {
// draw nothing
}
@Override
public void drawHUD(final Graphics2D gfx, final Context ctx) {
// draw nothing
}
@Override
public boolean click(final Point2D p, final MouseEvent e) {
// the event is not consumed
return false;
}
@Override
public boolean clickHUD(final Point2D p) {
// the event is not consumed
return false;
}
@Override
public String getTooltip(final Point2D p) {
// no tool-tip
return null;
}
@Override
public String getTooltipHUD(final Point2D p) {
// no tool-tip
return null;
}
@Override
public boolean acceptDrag(final Point2D p) {
// the event is not consumed
return false;
}
@Override
public void drag(final Point2D start, final Point2D cur, final double dx,
final double dy) {
// do nothing
}
@Override
public void endDrag(final Point2D start, final Point2D cur, final double dx,
final double dy) {
drag(start, cur, dx, dy);
}
@Override
public void moveMouse(final Point2D cur) {
// nothing to do
}
@Override
public Rectangle2D getBoundingBox() {
return null;
}
}
| mit |
ijufumi/demo | spring-doma/src/main/java/jp/ijufumi/sample/config/Config.java | 120 | package jp.ijufumi.sample.config;
import org.springframework.stereotype.Component;
@Component
public class Config {
}
| mit |
stevenschwenke/WritingAwesomeJavaCodeWorkshop | src/test/java/de/stevenschwenke/java/writingawesomejavacodeworkshop/part3ApplyingToLegacyCode/legacy_ugly_trivia/GameRunner.java | 871 | package de.stevenschwenke.java.writingawesomejavacodeworkshop.part3ApplyingToLegacyCode.legacy_ugly_trivia;
import java.util.Random;
/**
* This is the Java implementation of the "ugly trivia game", see
* https://github.com/jbrains/trivia/blob/master/java/src/main/java/com/adaptionsoft/games/uglytrivia/Game.java
*/
public class GameRunner {
private static boolean notAWinner;
public static void main(String[] args) {
Game aGame = new Game();
aGame.add("Chet");
aGame.add("Pat");
aGame.add("Sue");
Random rand = new Random();
do {
aGame.roll(rand.nextInt(5) + 1);
if (rand.nextInt(9) == 7) {
notAWinner = aGame.wrongAnswer();
} else {
notAWinner = aGame.wasCorrectlyAnswered();
}
} while (notAWinner);
}
}
| cc0-1.0 |
MeasureAuthoringTool/MeasureAuthoringTool_Release | mat/src/main/java/mat/client/cqlworkspace/CQLLibraryEditorView.java | 5251 | package mat.client.cqlworkspace;
import java.util.List;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ButtonGroup;
import org.gwtbootstrap3.client.ui.DropDownMenu;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.gwtbootstrap3.client.ui.constants.Pull;
import org.gwtbootstrap3.client.ui.gwt.FlowPanel;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import edu.ycp.cs.dh.acegwt.client.ace.AceAnnotationType;
import mat.client.buttons.InfoDropDownMenu;
import mat.client.buttons.InfoToolBarButton;
import mat.client.buttons.InsertToolBarButton;
import mat.client.buttons.SaveButton;
import mat.client.cqlworkspace.shared.CQLEditor;
import mat.client.cqlworkspace.shared.CQLEditorPanel;
import mat.client.inapphelp.component.InAppHelp;
import mat.client.shared.MatContext;
import mat.client.shared.SkipListBuilder;
import mat.client.shared.SpacerWidget;
import mat.shared.CQLError;
public class CQLLibraryEditorView {
private static final String CQL_LIBRARY_EDITOR_ID = "cqlLibraryEditor";
private VerticalPanel cqlLibraryEditorVP = new VerticalPanel();
private HTML heading = new HTML();
private InAppHelp inAppHelp = new InAppHelp("");
private CQLEditorPanel editorPanel = new CQLEditorPanel(CQL_LIBRARY_EDITOR_ID, "CQL Library Editor", false);
private Button exportErrorFile = new Button();
private Button infoButton = new InfoToolBarButton(CQL_LIBRARY_EDITOR_ID);
private Button insertButton = new InsertToolBarButton(CQL_LIBRARY_EDITOR_ID);
private Button saveButton = new SaveButton(CQL_LIBRARY_EDITOR_ID);
private ButtonGroup infoBtnGroup;
public CQLLibraryEditorView(){
cqlLibraryEditorVP.clear();
exportErrorFile.setType(ButtonType.PRIMARY);
exportErrorFile.setIcon(IconType.DOWNLOAD);
exportErrorFile.setText("Export Error File");
exportErrorFile.setTitle("Click to download Export Error File.");
exportErrorFile.setId("Button_exportErrorFile");
}
public Button getSaveButton() {
return this.saveButton;
}
public VerticalPanel buildView(boolean isEditorEditable, boolean isPageEditable){
editorPanel = new CQLEditorPanel(CQL_LIBRARY_EDITOR_ID, "CQL Library Editor", !isEditorEditable);
cqlLibraryEditorVP.clear();
cqlLibraryEditorVP.getElement().setId("cqlLibraryEditor_Id");
heading.addStyleName("leftAligned");
cqlLibraryEditorVP.add(SharedCQLWorkspaceUtility.buildHeaderPanel(heading, inAppHelp));
cqlLibraryEditorVP.add(new SpacerWidget());
getCqlAceEditor().setText("");
getCqlAceEditor().clearAnnotations();
if(isPageEditable) {
exportErrorFile.setPull(Pull.LEFT);
cqlLibraryEditorVP.add(exportErrorFile);
}
FlowPanel fp = new FlowPanel();
buildInfoInsertBtnGroup();
fp.add(infoBtnGroup);
fp.add(insertButton);
cqlLibraryEditorVP.add(fp);
getCqlAceEditor().setReadOnly(!isEditorEditable);
getSaveButton().setEnabled(isEditorEditable);
insertButton.setEnabled(isEditorEditable);
this.editorPanel.getEditor().addDomHandler(event -> editorPanel.catchTabOutKeyCommand(event, saveButton), KeyUpEvent.getType());
editorPanel.setSize("650px", "500px");
cqlLibraryEditorVP.add(editorPanel);
saveButton.setPull(Pull.RIGHT);
cqlLibraryEditorVP.add(saveButton);
cqlLibraryEditorVP.setStyleName("cqlRightContainer");
cqlLibraryEditorVP.setWidth("700px");
cqlLibraryEditorVP.setStyleName("marginLeft15px");
return cqlLibraryEditorVP;
}
private void buildInfoInsertBtnGroup() {
DropDownMenu ddm = new InfoDropDownMenu();
ddm.getElement().getStyle().setMarginLeft(3, Unit.PX);
infoButton.setMarginLeft(-10);
infoBtnGroup = new ButtonGroup();
infoBtnGroup.getElement().setAttribute("class", "btn-group");
infoBtnGroup.add(infoButton);
infoBtnGroup.add(ddm);
infoBtnGroup.setPull(Pull.LEFT);
insertButton.setPull(Pull.RIGHT);
}
public CQLEditor getCqlAceEditor() {
return editorPanel.getEditor();
}
public void resetAll() {
editorPanel = new CQLEditorPanel(CQL_LIBRARY_EDITOR_ID, "CQL Library Editor", false);
getCqlAceEditor().setText("");
}
public void setHeading(String text,String linkName) {
String linkStr = SkipListBuilder.buildEmbeddedString(linkName);
heading.setHTML(linkStr +"<h4><b>" + text + "</b></h4>");
}
public Button getExportErrorFile() {
return exportErrorFile;
}
public void setExportErrorFile(Button exportErrorFile) {
this.exportErrorFile = exportErrorFile;
}
public void setCQLLibraryEditorAnnotations(List<CQLError> cqlErrors, String prefix, AceAnnotationType aceAnnotationType) {
for (CQLError error : cqlErrors) {
int line = error.getErrorInLine();
int column = error.getErrorAtOffeset();
this.getCqlAceEditor().addAnnotation(line - 1, column, prefix + error.getErrorMessage(), aceAnnotationType);
}
}
public InAppHelp getInAppHelp() {
return inAppHelp;
}
public void setInAppHelp(InAppHelp inAppHelp) {
this.inAppHelp = inAppHelp;
}
public Button getInsertButton() {
return insertButton;
}
public Button getInfoButton() {
return infoButton;
}
}
| cc0-1.0 |
groenda/LIMBO | dlim.generator/src/tools/descartes/dlim/PolynomialFactor.java | 2467 | /**
*/
package tools.descartes.dlim;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc --> A representation of the model object '
* <em><b>Polynomial Factor</b></em>'. <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link tools.descartes.dlim.PolynomialFactor#getFactor <em>Factor</em>}</li>
* <li>{@link tools.descartes.dlim.PolynomialFactor#getOffset <em>Offset</em>}</li>
* </ul>
* </p>
*
* @see tools.descartes.dlim.DlimPackage#getPolynomialFactor()
* @model
* @generated
*/
public interface PolynomialFactor extends EObject {
/**
* Returns the value of the '<em><b>Factor</b></em>' attribute. The default
* value is <code>"0.0"</code>. <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Factor</em>' attribute isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Factor</em>' attribute.
* @see #setFactor(double)
* @see tools.descartes.dlim.DlimPackage#getPolynomialFactor_Factor()
* @model default="0.0" derived="true"
* @generated
*/
double getFactor();
/**
* Sets the value of the '
* {@link tools.descartes.dlim.PolynomialFactor#getFactor <em>Factor</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @param value
* the new value of the '<em>Factor</em>' attribute.
* @see #getFactor()
* @generated
*/
void setFactor(double value);
/**
* Returns the value of the '<em><b>Offset</b></em>' attribute. The default
* value is <code>"0.0"</code>. <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Offset</em>' attribute isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Offset</em>' attribute.
* @see #setOffset(double)
* @see tools.descartes.dlim.DlimPackage#getPolynomialFactor_Offset()
* @model default="0.0" derived="true"
* @generated
*/
double getOffset();
/**
* Sets the value of the '
* {@link tools.descartes.dlim.PolynomialFactor#getOffset <em>Offset</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @param value
* the new value of the '<em>Offset</em>' attribute.
* @see #getOffset()
* @generated
*/
void setOffset(double value);
} // PolynomialFactor
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/handler/ChannelBridgeScenes.java | 2914 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.velux.internal.handler;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.velux.internal.handler.utils.StateUtils;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.types.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <B>Channel-specific retrieval and modification.</B>
* <P>
* This class implements the Channel <B>scenes</B> of the Thing <B>klf200</B>:
* <UL>
* <LI><I>Velux</I> <B>bridge</B> → <B>OpenHAB</B>:
* <P>
* Information retrieval by method {@link #handleRefresh}.</LI>
* </UL>
*
* @author Guenther Schreiner - Initial contribution.
*/
@NonNullByDefault
final class ChannelBridgeScenes extends ChannelHandlerTemplate {
private static final Logger LOGGER = LoggerFactory.getLogger(ChannelBridgeScenes.class);
/*
* ************************
* ***** Constructors *****
*/
// Suppress default constructor for non-instantiability
private ChannelBridgeScenes() {
throw new AssertionError();
}
/**
* Communication method to retrieve information to update the channel value.
*
* @param channelUID The item passed as type {@link ChannelUID} for which a refresh is intended.
* @param channelId The same item passed as type {@link String} for which a refresh is intended.
* @param thisBridgeHandler The Velux bridge handler with a specific communication protocol which provides
* information for this channel.
* @return newState The value retrieved for the passed channel, or <I>null</I> in case if there is no (new) value.
*/
static @Nullable State handleRefresh(ChannelUID channelUID, String channelId,
VeluxBridgeHandler thisBridgeHandler) {
LOGGER.debug("handleRefresh({},{},{}) called.", channelUID, channelId, thisBridgeHandler);
State newState = null;
if (thisBridgeHandler.bridgeParameters.scenes.autoRefresh(thisBridgeHandler.thisBridge)) {
LOGGER.trace("handleCommand(): there are some existing scenes.");
}
String sceneInfo = thisBridgeHandler.bridgeParameters.scenes.getChannel().existingScenes.toString();
LOGGER.trace("handleCommand(): found scenes {}.", sceneInfo);
sceneInfo = sceneInfo.replaceAll("[^\\p{Punct}\\w]", "_");
newState = StateUtils.createState(sceneInfo);
LOGGER.trace("handleRefresh() returns {}.", newState);
return newState;
}
}
| epl-1.0 |
alb-i986/hamcrest-junit | src/main/java/org/hamcrest/junit/internal/StacktracePrintingMatcher.java | 1670 | package org.hamcrest.junit.internal;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
/**
* A matcher that delegates to throwableMatcher and in addition appends the
* stacktrace of the actual Throwable in case of a mismatch.
*/
public class StacktracePrintingMatcher<T extends Throwable> extends
org.hamcrest.TypeSafeMatcher<T> {
private final Matcher<T> throwableMatcher;
public StacktracePrintingMatcher(Matcher<T> throwableMatcher) {
this.throwableMatcher = throwableMatcher;
}
public void describeTo(Description description) {
throwableMatcher.describeTo(description);
}
@Override
protected boolean matchesSafely(T item) {
return throwableMatcher.matches(item);
}
@Override
protected void describeMismatchSafely(T item, Description description) {
throwableMatcher.describeMismatch(item, description);
description.appendText("\nStacktrace was: ");
description.appendText(readStacktrace(item));
}
private String readStacktrace(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
public static <T extends Throwable> Matcher<T> isThrowable(
Matcher<T> throwableMatcher) {
return new StacktracePrintingMatcher<T>(throwableMatcher);
}
public static <T extends Exception> Matcher<T> isException(
Matcher<T> exceptionMatcher) {
return new StacktracePrintingMatcher<T>(exceptionMatcher);
}
}
| epl-1.0 |
522986491/yangtools | code-generator/binding-generator-impl/src/test/java/org/opendaylight/yangtools/sal/binding/generator/impl/ControllerTest.java | 1645 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.sal.binding.generator.impl;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
import org.opendaylight.yangtools.sal.binding.model.api.Type;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
public class ControllerTest {
@Test
public void controllerAugmentationTest() throws Exception {
File cn = new File(getClass().getResource("/controller-models/controller-network.yang").toURI());
File co = new File(getClass().getResource("/controller-models/controller-openflow.yang").toURI());
File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
final SchemaContext context = new YangParserImpl().parseFiles(Arrays.asList(cn, co, ietfInetTypes));
assertNotNull("Schema Context is null", context);
final BindingGenerator bindingGen = new BindingGeneratorImpl(true);
final List<Type> genTypes = bindingGen.generateTypes(context);
assertNotNull(genTypes);
assertTrue(!genTypes.isEmpty());
}
}
| epl-1.0 |
BOTlibre/BOTlibre | sdk/java/src/org/botlibre/sdk/config/AvatarMedia.java | 2939 | /******************************************************************************
*
* Copyright 2014 Paphus Solutions Inc.
*
* Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
*
* 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.botlibre.sdk.config;
import java.io.StringWriter;
import org.w3c.dom.Element;
/**
* Represents a media file for an avatar (image, video, audio).
* An avatar can have many media files that are tagged with emotions, actions, and poses.
* This object can be converted to and from XML for usage with the web API.
* The media is the short URL to the media file on the server.
*/
public class AvatarMedia extends Config {
public String mediaId;
public String name;
public String type;
public String media;
public String emotions;
public String actions;
public String poses;
public boolean hd;
public boolean talking;
public void parseXML(Element element) {
super.parseXML(element);
this.mediaId = element.getAttribute("mediaId");
this.name = element.getAttribute("name");
this.type = element.getAttribute("type");
this.media = element.getAttribute("media");
this.emotions = element.getAttribute("emotions");
this.actions = element.getAttribute("actions");
this.poses = element.getAttribute("poses");
this.hd = Boolean.valueOf(element.getAttribute("hd"));
this.talking = Boolean.valueOf(element.getAttribute("talking"));
}
public String toXML() {
StringWriter writer = new StringWriter();
writer.write("<avatar-media");
writeCredentials(writer);
if (this.mediaId != null) {
writer.write(" mediaId=\"" + this.mediaId + "\"");
}
if (this.name != null) {
writer.write(" name=\"" + this.name + "\"");
}
if (this.type != null) {
writer.write(" type=\"" + this.type + "\"");
}
if (this.emotions != null) {
writer.write(" emotions=\"" + this.emotions + "\"");
}
if (this.actions != null) {
writer.write(" actions=\"" + this.actions + "\"");
}
if (this.poses != null) {
writer.write(" poses=\"" + this.poses + "\"");
}
writer.write(" hd=\"" + this.hd + "\"");
writer.write(" talking=\"" + this.talking + "\"");
writer.write("/>");
return writer.toString();
}
public boolean isVideo() {
return this.type != null && this.type.indexOf("video") != -1;
}
public boolean isAudio() {
return this.type != null && this.type.indexOf("audio") != -1;
}
}
| epl-1.0 |
akurtakov/Pydev | plugins/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching/LaunchShortcut.java | 1054 | /**
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
/*
* Author: atotic
* Created: Aug 26, 2003
*/
package org.python.pydev.debug.ui.launching;
import org.eclipse.core.resources.IProject;
import org.python.pydev.ast.interpreter_managers.InterpreterManagersAPI;
import org.python.pydev.core.IInterpreterManager;
import org.python.pydev.debug.core.Constants;
public class LaunchShortcut extends AbstractLaunchShortcut {
@Override
protected String getLaunchConfigurationType() {
return Constants.ID_PYTHON_REGULAR_LAUNCH_CONFIGURATION_TYPE;
}
@Override
protected boolean getRequireFile() {
return true;
}
@Override
protected IInterpreterManager getInterpreterManager(IProject project) {
return InterpreterManagersAPI.getPythonInterpreterManager();
}
}
| epl-1.0 |
dragon66/pixymeta | src/pixy/image/tiff/SByteField.java | 644 | /**
* Copyright (C) 2014-2019 by Wen Yu.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Any modifications to this file must keep this entire header intact.
*/
package pixy.image.tiff;
/**
* TIFF SByte type field.
*
* @author Wen Yu, yuwen_66@yahoo.com
* @version 1.0 02/24/2013
*/
public final class SByteField extends AbstractByteField {
public SByteField(short tag, byte[] data) {
super(tag, FieldType.SBYTE, data);
}
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/internal/Oauth2LoginConfigImpl.java | 30610 | /*******************************************************************************
* Copyright (c) 2016, 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.social.internal;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.ras.annotation.Sensitive;
import com.ibm.ws.security.authentication.filter.AuthenticationFilter;
import com.ibm.ws.security.common.config.CommonConfigUtils;
import com.ibm.ws.security.common.structures.Cache;
import com.ibm.ws.security.social.SocialLoginConfig;
import com.ibm.ws.security.social.SocialLoginService;
import com.ibm.ws.security.social.SslRefInfo;
import com.ibm.ws.security.social.TraceConstants;
import com.ibm.ws.security.social.UserApiConfig;
import com.ibm.ws.security.social.error.SocialLoginException;
import com.ibm.ws.security.social.internal.utils.ClientConstants;
import com.ibm.ws.security.social.internal.utils.SocialConfigUtils;
import com.ibm.ws.security.social.internal.utils.SocialHashUtils;
import com.ibm.ws.security.social.tai.SocialLoginTAI;
import com.ibm.wsspi.kernel.service.utils.AtomicServiceReference;
import com.ibm.wsspi.kernel.service.utils.SerializableProtectedString;
@Component(name = "com.ibm.ws.security.social.oauth2login", configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true, service = SocialLoginConfig.class, property = { "service.vendor=IBM", "type=oauth2Login" })
public class Oauth2LoginConfigImpl implements SocialLoginConfig {
public static final TraceComponent tc = Tr.register(Oauth2LoginConfigImpl.class, TraceConstants.TRACE_GROUP, TraceConstants.MESSAGE_BUNDLE);
protected final boolean IS_REQUIRED = true;
protected final boolean IS_NOT_REQUIRED = false;
protected static final String KEY_UNIQUE_ID = "id";
protected String uniqueId = null;
protected Cache cache = null;
public static final String KEY_clientId = "clientId";
protected String clientId = null;
public static final String KEY_clientSecret = "clientSecret";
@Sensitive
protected String clientSecret = null;
public static final String KEY_displayName = "displayName";
protected String displayName = null;
public static final String KEY_website = "website";
protected String website = null;
public static final String KEY_authorizationEndpoint = "authorizationEndpoint";
protected String authorizationEndpoint = null;
public static final String KEY_tokenEndpoint = "tokenEndpoint";
protected String tokenEndpoint = null;
public static final String KEY_userApi = "userApi";
protected String userApi = null;
protected String[] userApis = null;
public static final String KEY_authFilterRef = "authFilterRef";
protected String authFilterRef;
protected String authFilterId;
protected AuthenticationFilter authFilter = null;
protected SSLContext sslContext = null;
protected SSLSocketFactory sslSocketFactory = null;
public static final String KEY_sslRef = "sslRef";
protected String sslRef;
public static final String KEY_keyAliasName = "keyAliasName";
protected String keyAliasName;
protected String algorithm = "AES";
public static final String KEY_scope = "scope";
protected String scope = null;
public static final String KEY_responseType = "responseType";
protected String responseType = null;
private final String DEFAULT_RESPONSE_TYPE = ClientConstants.CODE;
protected String grantType = null;
public static final String KEY_nonce = "nonce";
protected boolean nonce = false;
public static final String KEY_resource = "resource";
protected String resource = null;
public static final String KEY_isClientSideRedirectSupported = "isClientSideRedirectSupported";
protected boolean isClientSideRedirectSupported = true;
public static final String KEY_tokenEndpointAuthMethod = "tokenEndpointAuthMethod";
protected String tokenEndpointAuthMethod = null;
private final String DEFAULT_TOKEN_ENDPOINT_AUTH_METHOD = ClientConstants.METHOD_client_secret_post;
public static final String KEY_userApiNeedsSpecialHeader = "userApiNeedsSpecialHeader";
protected boolean userApiNeedsSpecialHeader = false;
public static final String KEY_redirectToRPHostAndPort = "redirectToRPHostAndPort";
protected String redirectToRPHostAndPort = null;
protected UserApiConfig[] userApiConfigs = null;
protected String userApiResponseIdentifier = null;
protected SslRefInfo sslRefInfo = null;
public static final String KEY_jwksUri = "jwksUri";
protected String jwksUri = null;
public static final String KEY_realmName = "realmName";
protected String realmName = null;
public static final String KEY_realmNameAttribute = "realmNameAttribute";
protected String realmNameAttribute = null;
public static final String KEY_userNameAttribute = "userNameAttribute";
protected String userNameAttribute = null;
private final String DEFAULT_USER_NAME_ATTRIBUTE = "email";
public static final String KEY_INTROSPECTION_TOKEN_TYPE_HINT = "introspectionTokenTypeHint";
protected String introspectionTokenTypeHint = null;
public static final String KEY_groupNameAttribute = "groupNameAttribute";
protected String groupNameAttribute = null;
public static final String KEY_userUniqueIdAttribute = "userUniqueIdAttribute";
protected String userUniqueIdAttribute = null;
public static final String KEY_mapToUserRegistry = "mapToUserRegistry";
protected boolean mapToUserRegistry = false;
public static final String KEY_requestTokenUrl = "requestTokenUrl";
protected String requestTokenUrl = null;
public static final String CFG_KEY_jwt = "jwt";
public static final String CFG_KEY_jwtRef = "builder";
public static final String CFG_KEY_jwtClaims = "claims";
protected String jwtRef = null;
protected String[] jwtClaims;
public static final String DEFAULT_JWT_BUILDER = "defaultJWT";
static final String KEY_SOCIAL_LOGIN_SERVICE = "socialLoginService";
public static final String DEFAULT_CONTEXT_ROOT = "/ibm/api/social-login";
static String contextRoot = DEFAULT_CONTEXT_ROOT;
public static final String KEY_USE_SYSPROPS_FOR_HTTPCLIENT_CONNECTONS = "useSystemPropertiesForHttpClientConnections";
protected boolean useSystemPropertiesForHttpClientConnections = false;
public static final String USER_API_TYPE_BASIC = "basic";
public static final String USER_API_TYPE_KUBE = "kube";
public static final String KEY_userApiType = "userApiType";
protected String userApiType = null;
private final String DEFAULT_USER_API_TYPE = USER_API_TYPE_BASIC;
public static final String KEY_userApiToken = "userApiToken";
protected String userApiToken = null;
public static final String KEY_accessTokenRequired = "accessTokenRequired";
protected boolean accessTokenRequired = false;
public static final String KEY_accessTokenSupported = "accessTokenSupported";
protected boolean accessTokenSupported = false;
public static final String KEY_accessTokenHeaderName = "accessTokenHeaderName";
protected String accessTokenHeaderName = null;
protected CommonConfigUtils configUtils = new CommonConfigUtils();
protected SocialConfigUtils socialConfigUtils = new SocialConfigUtils();
final AtomicServiceReference<SocialLoginService> socialLoginServiceRef = new AtomicServiceReference<SocialLoginService>(KEY_SOCIAL_LOGIN_SERVICE);
private String bundleLocation;
@Reference(service = SocialLoginService.class, name = KEY_SOCIAL_LOGIN_SERVICE, cardinality = ReferenceCardinality.MANDATORY)
protected void setSocialLoginService(ServiceReference<SocialLoginService> ref) {
this.socialLoginServiceRef.setReference(ref);
}
public static String getContextRoot() {
return contextRoot;
}
// called by SocialLoginWebappConfigImpl to set context root from server.xml
public static void setContextRoot(String ctx) {
contextRoot = ctx;
}
protected void unsetSocialLoginService(ServiceReference<SocialLoginService> ref) {
this.socialLoginServiceRef.unsetReference(ref);
}
@Activate
protected void activate(ComponentContext cc, Map<String, Object> props) throws SocialLoginException {
this.socialLoginServiceRef.activate(cc);
this.bundleLocation = cc.getBundleContext().getBundle().getLocation();
uniqueId = configUtils.getConfigAttribute(props, KEY_UNIQUE_ID);
initProps(cc, props);
Tr.info(tc, "SOCIAL_LOGIN_CONFIG_PROCESSED", uniqueId);
}
@Modified
protected void modified(ComponentContext cc, Map<String, Object> props) throws SocialLoginException {
initProps(cc, props);
Tr.info(tc, "SOCIAL_LOGIN_CONFIG_MODIFIED", uniqueId);
}
@Deactivate
protected void deactivate(ComponentContext cc) {
this.socialLoginServiceRef.deactivate(cc);
Tr.info(tc, "SOCIAL_LOGIN_CONFIG_DEACTIVATED", uniqueId);
}
public void initProps(ComponentContext cc, Map<String, Object> props) throws SocialLoginException {
checkForRequiredConfigAttributes(props);
setAllConfigAttributes(props);
initializeMembersAfterConfigAttributesPopulated(props);
debug();
}
protected void checkForRequiredConfigAttributes(Map<String, Object> props) {
if (isIntrospectConfiguration(props)) {
checkForRequiredConfigAttributesForIntrospect(props);
}
if (isConfiguredForProxyFlow(props)) {
checkForRequiredConfigAttributesForProxyFlow(props);
}
if (isKubeConfiguration(props)) {
checkForRequiredConfigAttributesForKubernetes(props);
} else {
getRequiredConfigAttribute(props, KEY_clientId);
getRequiredSerializableProtectedStringConfigAttribute(props, KEY_clientSecret);
getRequiredConfigAttribute(props, KEY_authorizationEndpoint);
//getRequiredConfigAttribute(props, KEY_scope); // removing as not all providers require it.
}
}
boolean isConfiguredForProxyFlow(Map<String, Object> props) {
return configUtils.getBooleanConfigAttribute(props, KEY_accessTokenRequired, accessTokenRequired);
}
protected void checkForRequiredConfigAttributesForProxyFlow(Map<String, Object> props) {
configUtils.getRequiredConfigAttributeWithConfigId(props, KEY_userApi, uniqueId);
}
boolean isIntrospectConfiguration(Map<String, Object> props) {
String userApiType = configUtils.getConfigAttribute(props, KEY_userApiType);
if (userApiType != null && "introspect".equals(userApiType)) {
return true;
}
return false;
}
protected void checkForRequiredConfigAttributesForIntrospect(Map<String, Object> props) {
getRequiredConfigAttribute(props, KEY_clientId);
getRequiredSerializableProtectedStringConfigAttribute(props, KEY_clientSecret);
}
boolean isKubeConfiguration(Map<String, Object> props) {
String userApiType = configUtils.getConfigAttribute(props, KEY_userApiType);
if (userApiType != null && USER_API_TYPE_KUBE.equals(userApiType)) {
return true;
}
return false;
}
protected void checkForRequiredConfigAttributesForKubernetes(Map<String, Object> props) {
getRequiredSerializableProtectedStringConfigAttribute(props, KEY_userApiToken);
configUtils.getRequiredConfigAttributeWithConfigId(props, KEY_userApi, uniqueId);
}
protected void setAllConfigAttributes(Map<String, Object> props) throws SocialLoginException {
this.clientId = configUtils.getConfigAttribute(props, KEY_clientId);
this.clientSecret = configUtils.processProtectedString(props, KEY_clientSecret);
this.authorizationEndpoint = configUtils.getConfigAttribute(props, KEY_authorizationEndpoint);
this.scope = configUtils.getConfigAttribute(props, KEY_scope);
this.useSystemPropertiesForHttpClientConnections = configUtils.getBooleanConfigAttribute(props, KEY_USE_SYSPROPS_FOR_HTTPCLIENT_CONNECTONS, false);
this.displayName = configUtils.getConfigAttribute(props, KEY_displayName);
this.website = configUtils.getConfigAttribute(props, KEY_website);
this.tokenEndpoint = configUtils.getConfigAttribute(props, KEY_tokenEndpoint);
this.jwksUri = configUtils.getConfigAttribute(props, KEY_jwksUri);
this.responseType = configUtils.getConfigAttributeWithDefaultValue(props, KEY_responseType, DEFAULT_RESPONSE_TYPE);
this.tokenEndpointAuthMethod = configUtils.getConfigAttributeWithDefaultValue(props, KEY_tokenEndpointAuthMethod, DEFAULT_TOKEN_ENDPOINT_AUTH_METHOD);
this.sslRef = configUtils.getConfigAttribute(props, KEY_sslRef);
this.authFilterRef = configUtils.getConfigAttribute(props, KEY_authFilterRef);
this.redirectToRPHostAndPort = configUtils.getConfigAttribute(props, KEY_redirectToRPHostAndPort);
this.userNameAttribute = configUtils.getConfigAttributeWithDefaultValue(props, KEY_userNameAttribute, DEFAULT_USER_NAME_ATTRIBUTE);
this.introspectionTokenTypeHint = configUtils.getConfigAttribute(props, KEY_INTROSPECTION_TOKEN_TYPE_HINT);
this.userApi = configUtils.getConfigAttribute(props, KEY_userApi);
this.realmName = configUtils.getConfigAttribute(props, KEY_realmName);
this.realmNameAttribute = configUtils.getConfigAttribute(props, KEY_realmNameAttribute);
this.groupNameAttribute = configUtils.getConfigAttribute(props, KEY_groupNameAttribute);
this.userUniqueIdAttribute = configUtils.getConfigAttribute(props, KEY_userUniqueIdAttribute);
this.mapToUserRegistry = configUtils.getBooleanConfigAttribute(props, KEY_mapToUserRegistry, this.mapToUserRegistry);
this.isClientSideRedirectSupported = configUtils.getBooleanConfigAttribute(props, KEY_isClientSideRedirectSupported, this.isClientSideRedirectSupported);
this.nonce = configUtils.getBooleanConfigAttribute(props, KEY_nonce, this.nonce);
this.userApiNeedsSpecialHeader = configUtils.getBooleanConfigAttribute(props, KEY_userApiNeedsSpecialHeader, this.userApiNeedsSpecialHeader);
this.userApiType = configUtils.getConfigAttributeWithDefaultValue(props, KEY_userApiType, DEFAULT_USER_API_TYPE);
this.userApiToken = configUtils.processProtectedString(props, KEY_userApiToken);
this.accessTokenRequired = configUtils.getBooleanConfigAttribute(props, KEY_accessTokenRequired, this.accessTokenRequired);
this.accessTokenSupported = configUtils.getBooleanConfigAttribute(props, KEY_accessTokenSupported, this.accessTokenSupported);
this.accessTokenHeaderName = configUtils.getConfigAttribute(props, KEY_accessTokenHeaderName);
if (isKubeConfiguration(props)) {
checkForRequiredAttributesForKubernetesAuthorizationCodeFlow(props);
}
}
protected void checkForRequiredAttributesForKubernetesAuthorizationCodeFlow(Map<String, Object> props) {
if (!accessTokenRequired && !accessTokenSupported) {
// If we aren't using the Kubernetes proxy configuration, we MUST have the authorizationEndpoint and tokenEndpoint
configUtils.getRequiredConfigAttributeWithConfigId(props, KEY_authorizationEndpoint, uniqueId);
configUtils.getRequiredConfigAttributeWithConfigId(props, KEY_tokenEndpoint, uniqueId);
}
}
protected void initializeMembersAfterConfigAttributesPopulated(Map<String, Object> props) throws SocialLoginException {
initializeUserApiConfigs();
initializeJwt(props);
resetLazyInitializedMembers();
setGrantType();
}
protected void initializeUserApiConfigs() throws SocialLoginException {
this.userApiConfigs = initUserApiConfigs(this.userApi);
}
protected Configuration getCustomConfiguration(String customParam) {
if (this.socialLoginServiceRef.getService() != null) {
try {
return this.socialLoginServiceRef.getService().getConfigAdmin().getConfiguration(customParam, "");
} catch (IOException e) {
}
}
return null;
}
protected void initializeJwt(Map<String, Object> props) {
Configuration jwtConfig = null;
if (this.socialLoginServiceRef.getService() != null) {
jwtConfig = handleJwtElement(props, this.socialLoginServiceRef.getService().getConfigAdmin());
}
if (jwtConfig != null) {
Dictionary<String, Object> jwtProps = jwtConfig.getProperties();
if (jwtProps != null) {
this.jwtRef = CommonConfigUtils.trim((String) jwtProps.get(CFG_KEY_jwtRef));
this.jwtClaims = CommonConfigUtils.trim((String[]) jwtProps.get(CFG_KEY_jwtClaims));
}
}
}
protected Configuration handleJwtElement(Map<String, Object> props, ConfigurationAdmin configurationAdmin) {
String jwt = configUtils.getConfigAttribute(props, CFG_KEY_jwt);
Configuration config = null;
if (jwt != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "jwt element exists");
}
try {
if (configurationAdmin != null) {
config = configurationAdmin.getConfiguration(jwt, bundleLocation);
}
} catch (IOException e) {
}
}
return config;
}
protected void resetLazyInitializedMembers() {
// Lazy re-initialize of variables
this.userApis = null;
this.sslRefInfo = null;
this.authFilter = null;
this.sslContext = null;
this.sslSocketFactory = null;
}
protected void setGrantType() {
grantType = ClientConstants.AUTHORIZATION_CODE;
if (responseType != null && responseType.contains(ClientConstants.TOKEN)) {
grantType = ClientConstants.IMPLICIT;
}
}
protected String getRequiredConfigAttribute(Map<String, Object> props, String key) {
String value = configUtils.getConfigAttribute(props, key);
if (value == null) {
logErrorForMissingRequiredAttribute(key);
}
return value;
}
@Sensitive
protected String getRequiredSerializableProtectedStringConfigAttribute(Map<String, Object> props, String key) {
String result = SocialHashUtils.decodeString((SerializableProtectedString) props.get(key));
if (result == null) {
logErrorForMissingRequiredAttribute(key);
}
return result;
}
void logErrorForMissingRequiredAttribute(String key) {
Tr.error(tc, "CONFIG_REQUIRED_ATTRIBUTE_NULL", new Object[] { key, uniqueId });
}
/**
*/
protected String defaultJwtBuilder() {
return DEFAULT_JWT_BUILDER;
}
protected void debug() {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "" + this);
Tr.debug(tc, KEY_clientId + " = " + clientId);
Tr.debug(tc, KEY_clientSecret + " is null = " + (clientSecret == null));
Tr.debug(tc, KEY_displayName + " = " + displayName);
Tr.debug(tc, KEY_website + " = " + website);
Tr.debug(tc, KEY_authorizationEndpoint + " = " + authorizationEndpoint);
Tr.debug(tc, KEY_tokenEndpoint + " = " + tokenEndpoint);
Tr.debug(tc, KEY_jwksUri + " = " + jwksUri);
Tr.debug(tc, KEY_responseType + " = " + responseType);
Tr.debug(tc, KEY_tokenEndpointAuthMethod + " = " + tokenEndpointAuthMethod);
Tr.debug(tc, KEY_sslRef + " = " + sslRef);
Tr.debug(tc, KEY_scope + " = " + scope);
Tr.debug(tc, KEY_authFilterRef + " = " + authFilterRef);
Tr.debug(tc, KEY_redirectToRPHostAndPort + " = " + redirectToRPHostAndPort);
Tr.debug(tc, KEY_userNameAttribute + " = " + userNameAttribute);
Tr.debug(tc, KEY_INTROSPECTION_TOKEN_TYPE_HINT + " = " + introspectionTokenTypeHint);
Tr.debug(tc, KEY_userApi + " = " + userApi);
Tr.debug(tc, "userApiConfigs = " + (userApiConfigs == null ? "null" : userApiConfigs.length));
Tr.debug(tc, KEY_realmName + " = " + realmName);
Tr.debug(tc, KEY_realmNameAttribute + " = " + realmNameAttribute);
Tr.debug(tc, KEY_accessTokenHeaderName + " = " + accessTokenHeaderName);
Tr.debug(tc, KEY_groupNameAttribute + " = " + groupNameAttribute);
Tr.debug(tc, KEY_userUniqueIdAttribute + " = " + userUniqueIdAttribute);
Tr.debug(tc, KEY_mapToUserRegistry + " = " + mapToUserRegistry);
Tr.debug(tc, CFG_KEY_jwtRef + " = " + jwtRef);
Tr.debug(tc, CFG_KEY_jwtClaims + " = " + ((jwtClaims == null) ? null : Arrays.toString(jwtClaims)));
Tr.debug(tc, KEY_isClientSideRedirectSupported + " = " + isClientSideRedirectSupported);
Tr.debug(tc, KEY_nonce + " = " + nonce);
Tr.debug(tc, KEY_userApiNeedsSpecialHeader + " = " + userApiNeedsSpecialHeader);
}
}
/**
* @param userApis
* @return
* @throws SocialLoginException
*/
UserApiConfig[] initUserApiConfigs(String userApi) throws SocialLoginException {
if (userApi != null) {
UserApiConfig[] results = new UserApiConfig[1];
results[0] = new UserApiConfigImpl(userApi);
return results;
} else {
return null;
}
}
/** {@inheritDoc} */
@Override
public String getUniqueId() {
return uniqueId;
}
/** {@inheritDoc} */
@Override
public AuthenticationFilter getAuthFilter() {
if (this.authFilter == null) {
this.authFilter = SocialLoginTAI.getAuthFilter(this.authFilterRef);
}
return this.authFilter;
}
/** {@inheritDoc} */
@Override
public String getClientId() {
return this.clientId;
}
/** {@inheritDoc} */
@Override
@Sensitive
public String getClientSecret() {
return this.clientSecret;
}
/** {@inheritDoc} */
@Override
public String getDisplayName() {
return this.displayName;
}
/** {@inheritDoc} */
@Override
public String getWebsite() {
return this.website;
}
/** {@inheritDoc} */
@Override
public String getAuthorizationEndpoint() {
return this.authorizationEndpoint;
}
/** {@inheritDoc} */
@Override
public String getTokenEndpoint() {
return this.tokenEndpoint;
}
/** {@inheritDoc} */
@Override
public UserApiConfig[] getUserApis() {
if (this.userApiConfigs == null) {
return null;
}
return this.userApiConfigs.clone();
}
/**
* @param userApis
* @return
* @throws SocialLoginException
*/
@Override
public String getUserApi() {
return this.userApi;
}
/*
* (non-Javadoc)
*
* @see
* com.ibm.ws.security.socialmedia.SocialLoginService#getSocialLoginCookieCache
* (java.lang.String)
*/
@Override
public Cache getSocialLoginCookieCache() {
if (cache == null) {
cache = new Cache(0, 0);
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "socialLoginCockieCache cache:" + cache);
}
return cache;
}
/** {@inheritDoc} */
@Override
public String getSslRef() {
return this.sslRef;
}
@Override
public String getScope() {
return this.scope;
}
@Override
public String getResponseType() {
return this.responseType;
}
@Override
public String getGrantType() {
return this.grantType;
}
@Override
public boolean createNonce() {
return this.nonce;
}
@Override
public String getResource() {
return this.resource;
}
@Override
public boolean isClientSideRedirectSupported() {
return isClientSideRedirectSupported;
}
@Override
public String getTokenEndpointAuthMethod() {
return this.tokenEndpointAuthMethod;
}
@Override
public String getRedirectToRPHostAndPort() {
return this.redirectToRPHostAndPort;
}
@Override
public HashMap<String, PublicKey> getPublicKeys() throws SocialLoginException {
if (this.sslRefInfo == null) {
SocialLoginService service = socialLoginServiceRef.getService();
if (service == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Social login service is not available");
}
return null;
}
sslRefInfo = createSslRefInfoImpl(service);
}
return sslRefInfo.getPublicKeys();
}
@Override
public SSLSocketFactory getSSLSocketFactory() throws SocialLoginException {
this.sslSocketFactory = socialConfigUtils.getSSLSocketFactory(uniqueId, sslContext, socialLoginServiceRef, sslRef);
return this.sslSocketFactory;
}
/** {@inheritDoc} */
@Override
public String getJwksUri() {
return this.jwksUri;
}
/** {@inheritDoc} */
@Override
public String getRealmName() {
return this.realmName;
}
/** {@inheritDoc} */
@Override
public String getRealmNameAttribute() {
return this.realmNameAttribute;
}
/** {@inheritDoc} */
@Override
public String getUserNameAttribute() {
return this.userNameAttribute;
}
/** {@inheritDoc} */
@Override
public String getIntrospectionTokenTypeHint() {
return this.introspectionTokenTypeHint;
}
/** {@inheritDoc} */
@Override
public String getGroupNameAttribute() {
return this.groupNameAttribute;
}
/** {@inheritDoc} */
@Override
public String getUserUniqueIdAttribute() {
return this.userUniqueIdAttribute;
}
/** {@inheritDoc} */
@Override
public boolean getMapToUserRegistry() {
return this.mapToUserRegistry;
}
/** {@inheritDoc} */
@Override
public String getJwtRef() {
return this.jwtRef;
}
@Override
public String[] getJwtClaims() {
if (jwtClaims != null) {
return jwtClaims.clone();
} else {
return null;
}
}
/** {@inheritDoc} */
@Override
public String getAlgorithm() {
return algorithm;
}
/**
* {@inheritDoc}
*
* @throws SocialLoginException
*/
@Override
public PublicKey getPublicKey() throws SocialLoginException {
if (this.sslRefInfo == null) {
SocialLoginService service = socialLoginServiceRef.getService();
if (service == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Social login service is not available");
}
return null;
}
sslRefInfo = createSslRefInfoImpl(service);
}
return sslRefInfo.getPublicKey();
}
/**
* {@inheritDoc}
*
* @throws SocialLoginException
*/
@Override
public PrivateKey getPrivateKey() throws SocialLoginException {
if (this.sslRefInfo == null) {
SocialLoginService service = socialLoginServiceRef.getService();
if (service == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Social login service is not available");
}
return null;
}
sslRefInfo = createSslRefInfoImpl(service);
}
return sslRefInfo.getPrivateKey();
}
/** {@inheritDoc} */
@Override
public String getRequestTokenUrl() {
return this.requestTokenUrl;
}
/** {@inheritDoc} */
@Override
public String getUserApiResponseIdentifier() {
return userApiResponseIdentifier;
}
/** {@inheritDoc} */
@Override
public boolean getUserApiNeedsSpecialHeader() {
return userApiNeedsSpecialHeader;
}
protected SslRefInfoImpl createSslRefInfoImpl(SocialLoginService socialLoginService) {
return new SslRefInfoImpl(socialLoginService.getSslSupport(), socialLoginService.getKeyStoreServiceRef(), sslRef, keyAliasName);
}
@Override
public String getResponseMode() {
return null;
}
public boolean getUseSystemPropertiesForHttpClientConnections() {
return useSystemPropertiesForHttpClientConnections;
}
public String getUserApiType() {
return userApiType;
}
@Sensitive
public String getUserApiToken() {
return userApiToken;
}
public boolean isAccessTokenRequired() {
return accessTokenRequired;
}
public boolean isAccessTokenSupported() {
return accessTokenSupported;
}
public String getAccessTokenHeaderName() {
return accessTokenHeaderName;
}
public long getApiResponseCacheTime() {
return 0;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.faulttolerance.spi/src/com/ibm/ws/microprofile/faulttolerance/spi/CircuitBreakerPolicy.java | 2586 | /*
* Copyright (c) 2017, 2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* 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.ibm.ws.microprofile.faulttolerance.spi;
import java.time.Duration;
/**
* Define the Circuit Breaker policy
*/
public interface CircuitBreakerPolicy {
/**
* Define the failure criteria
*
* @return the failure exception
*/
public Class<? extends Throwable>[] getFailOn();
@SuppressWarnings("unchecked")
public void setFailOn(Class<? extends Throwable>... failOn);
/**
* Define the skip criteria
*
* @return the skip exception
*/
Class<? extends Throwable>[] getSkipOn();
@SuppressWarnings("unchecked")
public void setSkipOn(Class<? extends Throwable>... skipOn);
/**
*
* @return The delay time after the circuit is open
*/
public Duration getDelay();
public void setDelay(Duration delay);
/**
* The number of consecutive requests in a rolling window
* that will trip the circuit.
*
* @return the number of the consecutive requests in a rolling window
*
*/
public int getRequestVolumeThreshold();
public void setRequestVolumeThreshold(int threshold);
/**
* The failure threshold to trigger the circuit to open.
* e.g. if the requestVolumeThreshold is 20 and failureRation is .50,
* more than 10 failures in 20 consecutive requests will trigger
* the circuit to open.
*
* @return The failure threshold to open the circuit
*/
public double getFailureRatio();
public void setFailureRatio(double ratio);
/**
* For an open circuit, after the delay period is reached, once the successThreshold
* is reached, the circuit is back to close again.
*
* @return The success threshold to fully close the circuit
*/
public int getSuccessThreshold();
public void setSuccessThreshold(int threshold);
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jaxrs.2.0.client_fat/test-applications/jaxrs20ltpa/src/com/ibm/ws/jaxrs20/client/LtpaClientTest/service/BasicResource.java | 866 | /*******************************************************************************
* Copyright (c) 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jaxrs20.client.LtpaClientTest.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
/**
* basic resource to test jaxrs20 client API
*/
@Path("ltpa")
public class BasicResource {
private final String prefix = "Hello LTPA Resource";
@GET
public String echo() {
return prefix;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.app.manager.war/src/com/ibm/ws/app/manager/war/internal/ZipUtils.java | 16415 | /*******************************************************************************
* Copyright (c) 2011, 2019 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.app.manager.war.internal;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.ras.annotation.Trivial;
import com.ibm.wsspi.kernel.service.utils.PathUtils;
import com.ibm.ws.artifact.zip.cache.ZipCachingProperties;
/**
* File and zip file utilities.
*/
public class ZipUtils {
private static final TraceComponent tc = Tr.register(ZipUtils.class);
// Retry parameters:
//
// Total of twice the zip.reaper.slow.pend.max.
public static final int RETRY_COUNT;
public static final long RETRY_AMOUNT = 50; // Split into 50ms wait periods.
public static final int RETRY_LIMIT = 1000; // Don't ever wait more than a second.
static {
if ( ZipCachingProperties.ZIP_CACHE_REAPER_MAX_PENDING == 0 ) {
// MAX_PENDING == 0 means the reaper cache is disabled.
// Allow just one retry for normal zip processing.
RETRY_COUNT = 1;
} else {
// The quiesce time is expected to be no greater than twice the largest
// wait time set for the zip file cache. Absent new activity, the reaper
// cache will never wait longer than twice the largest wait time.
// (The maximum wait time is more likely capped at 20% above the largest
// wait time. That is changed to 100% as an added safety margin.)
//
// The quiesce time will not be correct if the reaper thread is starved
// and is prevented from releasing zip files.
long totalAmount = ZipCachingProperties.ZIP_CACHE_REAPER_SLOW_PEND_MAX * 2;
if ( totalAmount <= 0 ) {
// The pending max is supposed to be greater than zero. Put in safe
// values just in case it isn't.
RETRY_COUNT = 1;
} else {
// The slow pending max is not expected to be set to values larger
// than tenth's of seconds. To make the limit explicit, don't accept
// a retry limit which is more than 1/2 second.
if ( totalAmount > RETRY_LIMIT ) {
totalAmount = RETRY_LIMIT; // 1/2 second * 2 == 1 second
}
// Conversion to int is safe: The total amount must be
// greater than 0 and less than or equal to 1000. The
// retry count will be greater than 1 and less then or
// equal to 20.
int retryCount = (int) (totalAmount / RETRY_AMOUNT);
if ( totalAmount % RETRY_AMOUNT > 0 ) {
retryCount++;
}
RETRY_COUNT = retryCount;
}
}
}
/**
* Attempt to recursively delete a target file.
*
* Answer null if the delete was successful. Answer the first
* file which could not be deleted if the delete failed.
*
* If the delete fails, wait 400 MS then try again. Do this
* for the entire delete operation, not for each file deletion.
*
* A test must be done to verify that the file exists before
* invoking this method: If the file does not exist, the
* delete operation will fail.
*
* @param file The file to delete recursively.
*
* @return Null if the file was deleted. The first file which
* could not be deleted if the file could not be deleted.
*/
@Trivial
public static File deleteWithRetry(File file) {
String methodName = "deleteWithRetry";
String filePath;
if ( tc.isDebugEnabled() ) {
filePath = file.getAbsolutePath();
Tr.debug(tc, methodName + ": Recursively delete [ " + filePath + " ]");
} else {
filePath = null;
}
File firstFailure = delete(file);
if ( firstFailure == null ) {
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Successful first delete [ " + filePath + " ]");
}
return null;
}
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Failed first delete [ " + filePath + " ]: Sleep up to 50 ms and retry");
}
// Extract can occur with the server running, and not long after activity
// on the previously extracted archives.
//
// If the first delete attempt failed, try again, up to a limit based on
// the expected quiesce time of the zip file cache.
File secondFailure = firstFailure;
for ( int tryNo = 0; (secondFailure != null) && tryNo < RETRY_COUNT; tryNo++ ) {
try {
Thread.sleep(RETRY_AMOUNT);
} catch ( InterruptedException e ) {
// FFDC
}
secondFailure = delete(file);
}
if ( secondFailure == null ) {
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Successful first delete [ " + filePath + " ]");
}
return null;
} else {
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Failed second delete [ " + filePath + " ]");
}
return secondFailure;
}
}
/**
* Attempt to recursively delete a file.
*
* Do not retry in case of a failure.
*
* A test must be done to verify that the file exists before
* invoking this method: If the file does not exist, the
* delete operation will fail.
*
* @param file The file to recursively delete.
*
* @return Null if the file was deleted. The first file which
* could not be deleted if the file could not be deleted.
*/
@Trivial
public static File delete(File file) {
String methodName = "delete";
String filePath;
if ( tc.isDebugEnabled() ) {
filePath = file.getAbsolutePath();
} else {
filePath = null;
}
if ( file.isDirectory() ) {
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Delete directory [ " + filePath + " ]");
}
File firstFailure = null;
File[] subFiles = file.listFiles();
if ( subFiles != null ) {
for ( File subFile : subFiles ) {
File nextFailure = delete(subFile);
if ( (nextFailure != null) && (firstFailure == null) ) {
firstFailure = nextFailure;
}
}
}
if ( firstFailure != null ) {
if ( filePath != null ) {
Tr.debug(tc, methodName +
": Cannot delete [ " + filePath + " ]" +
" Child [ " + firstFailure.getAbsolutePath() + " ] could not be deleted.");
}
return firstFailure;
}
} else {
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Delete simple file [ " + filePath + " ]");
}
}
if ( !file.delete() ) {
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Failed to delete [ " + filePath + " ]");
}
return file;
} else {
if ( filePath != null ) {
Tr.debug(tc, methodName + ": Deleted [ " + filePath + " ]");
}
return null;
}
}
//
public static final boolean IS_EAR = true;
public static final boolean IS_NOT_EAR = false;
private static final String WAR_EXTENSION = ".war";
/**
* Unpack a source archive into a target directory.
*
* If the source archive is a WAR, package web module archives as well.
*
* This operation is not smart enough to avoid unpacking WAR files
* in an application library folder. However, that is very unlikely to
* happen.
*
* @param source The source archive which is to be unpacked.
* @param target The directory into which to unpack the source archive.
* @param isEar Control parameter: Is the source archive an EAR file.
* When the source archive is an EAR, unpack nested WAR files.
* @param lastModified The last modified value to use for the expanded
* archive.
*
* @throws IOException Thrown in case of a failure.
*/
public static void unzip(
File source, File target,
boolean isEar, long lastModified) throws IOException {
byte[] transferBuffer = new byte[16 * 1024];
unzip(source, target, isEar, lastModified, transferBuffer);
}
@Trivial
public static void unzip(
File source, File target,
boolean isEar, long lastModified,
byte[] transferBuffer) throws IOException {
String methodName = "unzip";
String sourcePath = source.getAbsolutePath();
String targetPath = target.getAbsolutePath();
if ( tc.isDebugEnabled() ) {
Tr.debug(tc, methodName + ": Source [ " + sourcePath + " ] Size [ " + source.length() + " ]");
Tr.debug(tc, methodName + ": Target [ " + targetPath + " ]");
}
if ( !source.exists() ) {
throw new IOException("Source [ " + sourcePath + " ] does not exist");
} else if ( !source.isFile() ) {
throw new IOException("Source [ " + sourcePath + " ] is not a simple file");
} else if ( !target.exists() ) {
throw new IOException("Target [ " + targetPath + " ] does not exist");
} else if ( !target.isDirectory() ) {
throw new IOException("Target [ " + targetPath + " ] is not a directory");
}
List<Object[]> warData = ( isEar ? new ArrayList<Object[]>() : null );
ZipFile sourceZip = new ZipFile(source);
try {
Enumeration<? extends ZipEntry> sourceEntries = sourceZip.entries();
while ( sourceEntries.hasMoreElements() ) {
ZipEntry sourceEntry = sourceEntries.nextElement();
String sourceEntryName = sourceEntry.getName();
if ( reachesOut(sourceEntryName) ) {
Tr.error(tc, "error.file.outside.archive", sourceEntryName, sourcePath);
continue;
}
String targetFileName;
Object[] nextWarData;
if ( isEar && !sourceEntry.isDirectory() && sourceEntryName.endsWith(WAR_EXTENSION) ) {
for ( int tmpNo = 0;
sourceZip.getEntry( targetFileName = sourceEntryName + ".tmp" + tmpNo ) != null;
tmpNo++ ) {
// Empty
}
nextWarData = new Object[] { sourceEntryName, targetFileName, null };
} else {
targetFileName = sourceEntryName;
nextWarData = null;
}
File targetFile = new File(target, targetFileName);
if ( sourceEntry.isDirectory() ) {
if ( tc.isDebugEnabled() ) {
Tr.debug(tc, methodName + ": Directory [ " + sourceEntryName + " ]");
}
if ( !targetFile.exists() && !targetFile.mkdirs() ) {
throw new IOException("Failed to create directory [ + " + targetFile.getAbsolutePath() + " ]");
}
} else {
if ( tc.isDebugEnabled() ) {
Tr.debug(tc, methodName + ": Simple file [ " + sourceEntryName + " ] [ " + sourceEntry.getSize() + " ]");
}
File targetParent = targetFile.getParentFile();
if ( !targetParent.mkdirs() && !targetParent.exists() ) {
throw new IOException("Failed to create directory [ " + targetParent.getAbsolutePath() + " ]");
}
transfer(sourceZip, sourceEntry, targetFile, transferBuffer); // throws IOException
}
// If the entry doesn't provide a meaningful last modified time,
// use the parent file's last modified time.
long entryModified = sourceEntry.getTime();
if ( entryModified == -1 ) {
entryModified = lastModified;
}
targetFile.setLastModified(entryModified);
if ( nextWarData != null ) {
nextWarData[2] = Long.valueOf(entryModified);
warData.add(nextWarData);
}
}
} finally {
if ( sourceZip != null ) {
sourceZip.close();
}
}
if ( isEar ) {
for ( Object[] nextWarData : warData ) {
String unpackedWarName = (String) nextWarData[0];
String packedWarName = (String) nextWarData[1];
long warLastModified = ((Long) nextWarData[2]).longValue();
File unpackedWarFile = new File(target, unpackedWarName);
if ( !unpackedWarFile.exists() && !unpackedWarFile.mkdirs() ) {
throw new IOException("Failed to create [ " + unpackedWarFile.getAbsolutePath() + " ]");
}
File packedWarFile = new File(target, packedWarName);
unzip(packedWarFile, unpackedWarFile, IS_NOT_EAR, warLastModified, transferBuffer);
if ( !packedWarFile.delete() ) {
if ( tc.isDebugEnabled() ) {
Tr.debug(tc, methodName + ": Failed to delete temporary WAR [ " + packedWarFile.getAbsolutePath() + " ]");
}
}
}
}
// Do this last: The extraction into the target will update
// the target time stamp. We need the time stamp to be the time stamp
// of the source.
if ( tc.isDebugEnabled() ) {
Tr.debug(tc, methodName + ": Set last modified [ " + lastModified + " ]");
}
target.setLastModified(lastModified);
}
@Trivial
private static void transfer(
ZipFile sourceZip, ZipEntry sourceEntry,
File targetFile,
byte[] transferBuffer) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = sourceZip.getInputStream(sourceEntry);
outputStream = new FileOutputStream(targetFile);
int lastRead;
while ( (lastRead = inputStream.read(transferBuffer)) != -1) {
outputStream.write(transferBuffer, 0, lastRead);
}
} finally {
if ( inputStream != null ) {
inputStream.close();
}
if ( outputStream != null ) {
outputStream.close();
}
}
}
private static boolean reachesOut(String entryPath) {
if ( !entryPath.contains("..") ) {
return false;
}
String normalizedPath = PathUtils.normalizeUnixStylePath(entryPath);
return PathUtils.isNormalizedPathAbsolute(normalizedPath); // Leading ".." or "/.."
// The following is very inefficient ... and doesn't work when there
// are symbolic links.
// return targetFile.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath() + File.separator);
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.org.apache.cxf.cxf.rt.rs.mp.client.3.3/src/org/apache/cxf/microprofile/client/cdi/CDIInterceptorWrapper.java | 2578 | /**
* 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.cxf.microprofile.client.cdi;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cxf.common.logging.LogUtils;
import com.ibm.websphere.ras.annotation.Trivial;
public interface CDIInterceptorWrapper {
Logger LOG = LogUtils.getL7dLogger(CDIInterceptorWrapper.class);
class BasicCDIInterceptorWrapper implements CDIInterceptorWrapper {
BasicCDIInterceptorWrapper() {
}
@Trivial //Liberty change
@Override
public Object invoke(Object restClient, Method m, Object[] params, Callable<Object> callable)
throws Exception {
return callable.call();
}
}
static CDIInterceptorWrapper createWrapper(Class<?> restClient) {
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<CDIInterceptorWrapper>) () -> {
Object beanManager = CDIFacade.getBeanManager().orElseThrow(() -> new Exception("CDI not available"));
return new CDIInterceptorWrapperImpl(restClient, beanManager);
});
//} catch (PrivilegedActionException pae) {
} catch (Exception pae) { //Liberty change
// expected for environments where CDI is not supported
if (LOG.isLoggable(Level.FINEST)) {
LOG.log(Level.FINEST, "Unable to load CDI SPI classes, assuming no CDI is available", pae);
}
return new BasicCDIInterceptorWrapper();
}
}
Object invoke(Object restClient, Method m, Object[] params, Callable<Object> callable) throws Exception;
}
| epl-1.0 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/error/extractors/AbstractSingleUiErrorDetailsExtractor.java | 1123 | /**
* Copyright (c) 2021 Bosch.IO GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ui.error.extractors;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.eclipse.hawkbit.ui.error.UiErrorDetails;
/**
* Base class for single UI error details extractors.
*/
public abstract class AbstractSingleUiErrorDetailsExtractor implements UiErrorDetailsExtractor {
@Override
public List<UiErrorDetails> extractErrorDetailsFrom(final Throwable error) {
return findDetails(error).map(Collections::singletonList).orElseGet(Collections::emptyList);
}
/**
* Extracts single ui error details from given error.
*
* @param error
* error to extract details from
* @return ui error details if found
*/
protected abstract Optional<UiErrorDetails> findDetails(Throwable error);
}
| epl-1.0 |
clinique/openhab2 | bundles/org.openhab.binding.buienradar/src/main/java/org/openhab/binding/buienradar/internal/buienradarapi/Prediction.java | 920 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.buienradar.internal.buienradarapi;
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The {@link Prediction} interface contains a prediction of rain at a specific time.
*
* @author Edwin de Jong - Initial contribution
*/
@NonNullByDefault
public interface Prediction {
/**
* Intensity of rain in mm/hour
*/
BigDecimal getIntensity();
/**
* Date-time of prediction.
*/
ZonedDateTime getDateTime();
}
| epl-1.0 |
epsilonlabs/epsilon-static-analysis | org.eclipse.epsilon.haetae.eol.metamodel.visitor/src/org/eclipse/epsilon/eol/metamodel/visitor/RealTypeVisitor.java | 323 | package org.eclipse.epsilon.eol.metamodel.visitor;
import org.eclipse.epsilon.eol.metamodel.*;
public abstract class RealTypeVisitor<T, R> {
public boolean appliesTo(RealType realType, T context) {
return true;
}
public abstract R visit (RealType realType, T context, EolVisitorController<T, R> controller);
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/RunnableWithTimeout.java | 705 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.evohome.internal;
import java.util.concurrent.TimeoutException;
/**
* Provides an interface for a delegate that can throw a timeout
*
* @author Jasper van Zuijlen - Initial contribution
*
*/
public interface RunnableWithTimeout {
public abstract void run() throws TimeoutException;
}
| epl-1.0 |
innoq/smarthome | bundles/core/org.eclipse.smarthome.core.library/src/main/java/org/eclipse/smarthome/core/library/types/DateTimeType.java | 2571 | /**
* Copyright (c) 2014 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.core.library.types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.PrimitiveType;
import org.eclipse.smarthome.core.types.State;
public class DateTimeType implements PrimitiveType, State, Command {
public final static SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
protected Calendar calendar;
public DateTimeType() {
this(Calendar.getInstance());
}
public DateTimeType(Calendar calendar) {
this.calendar = calendar;
}
public DateTimeType(String calendarValue) {
Date date = null;
try {
date = DATE_FORMATTER.parse(calendarValue);
}
catch (ParseException fpe) {
throw new IllegalArgumentException(calendarValue + " is not in a valid format.", fpe);
}
if (date != null) {
calendar = Calendar.getInstance();
calendar.setTime(date);
}
}
public Calendar getCalendar() {
return calendar;
}
public static DateTimeType valueOf(String value) {
return new DateTimeType(value);
}
public String format(String pattern) {
try {
return String.format(pattern, calendar);
} catch (NullPointerException npe) {
return DATE_FORMATTER.format(calendar.getTime());
}
}
public String format(Locale locale, String pattern) {
return String.format(locale, pattern, calendar);
}
@Override
public String toString() {
return DATE_FORMATTER.format(calendar.getTime());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((calendar == null) ? 0 : calendar.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DateTimeType other = (DateTimeType) obj;
if (calendar == null) {
if (other.calendar != null)
return false;
} else if (!calendar.equals(other.calendar))
return false;
return true;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transaction.core_fat.startMultiEJB/test-applications/newEJBTx3/src/com/ibm/ws/transaction/ejb/third/InitNewTxBean3.java | 1135 | /*******************************************************************************
* Copyright (c) 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.transaction.ejb.third;
import static javax.ejb.TransactionAttributeType.REQUIRES_NEW;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionAttribute;
@Singleton
@Startup
@LocalBean
public class InitNewTxBean3 {
private static final Logger logger = Logger.getLogger(InitNewTxBean3.class.getName());
@PostConstruct
@TransactionAttribute(REQUIRES_NEW)
public void initTx3() {
logger.info("---- InitTx3 invoked ----");
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.wim.registry/src/com/ibm/ws/security/wim/registry/dataobject/package-info.java | 638 | /*******************************************************************************
* Copyright (c) 2017 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@org.osgi.annotation.versioning.Version("1.0.16")
package com.ibm.ws.security.wim.registry.dataobject;
| epl-1.0 |
openhab/openhab | bundles/binding/org.openhab.binding.weather/src/main/java/org/openhab/binding/weather/internal/model/common/CommonIdProvider.java | 1868 | /**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.weather.internal.model.common;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.openhab.binding.weather.internal.model.ProviderName;
import org.openhab.binding.weather.internal.model.common.adapter.ProviderNameAdapter;
import org.openhab.binding.weather.internal.model.common.adapter.ValueListAdapter;
/**
* Simple class with the JAXB mapping for a provider id configuration.
*
* @author Gerhard Riegler
* @since 1.6.0
*/
@XmlRootElement(name = "provider")
@XmlAccessorType(XmlAccessType.FIELD)
public class CommonIdProvider {
@XmlAttribute(name = "name", required = true)
@XmlJavaTypeAdapter(value = ProviderNameAdapter.class)
private ProviderName name;
@XmlAttribute(name = "ids")
@XmlJavaTypeAdapter(value = ValueListAdapter.class)
private String[] ids;
@XmlAttribute(name = "icons")
@XmlJavaTypeAdapter(value = ValueListAdapter.class)
private String[] icons;
/**
* Returns the ProviderName.
*/
public ProviderName getName() {
return name;
}
/**
* Returns the mapped ids.
*/
public String[] getIds() {
return ids;
}
/**
* Returns the mapped icons.
*/
public String[] getIcons() {
return icons;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jpa.tests.ormdiagnostics_3.0_fat/test-applications/example/src/com/ibm/ws/ormdiag/example/ejb/ExampleEJBService.java | 1124 | /*******************************************************************************
* Copyright (c) 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.ormdiag.example.ejb;
import java.util.stream.Stream;
import com.ibm.ws.ormdiag.example.jpa.ExampleEntity;
import jakarta.ejb.Stateless;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
@Stateless
public class ExampleEJBService {
@PersistenceContext
private EntityManager em;
public void addEntity(ExampleEntity entity) {
em.merge(entity);
}
public Stream<ExampleEntity> retrieveAllEntities() {
return em.createNamedQuery("findAllEntities", ExampleEntity.class).getResultStream();
}
} | epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/view/facelets/compiler/CompositeComponentUnit.java | 1587 | /*
* 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.myfaces.view.facelets.compiler;
import javax.faces.view.facelets.FaceletHandler;
import org.apache.myfaces.view.facelets.tag.composite.CompositeComponentDefinitionTagHandler;
/**
* This compilation unit is used to wrap cc:interface and cc:implementation in
* a base handler, to allow proper handling of composite component metadata.
*
* @author Leonardo Uribe (latest modification by $Author: bommel $)
* @version $Revision: 1187701 $ $Date: 2011-10-22 12:21:54 +0000 (Sat, 22 Oct 2011) $
*/
class CompositeComponentUnit extends CompilationUnit
{
public CompositeComponentUnit()
{
}
public FaceletHandler createFaceletHandler()
{
return new CompositeComponentDefinitionTagHandler(this.getNextFaceletHandler());
}
}
| epl-1.0 |
chrismathis/eclipsensis | plugins/net.sf.eclipsensis.installoptions/src/net/sf/eclipsensis/installoptions/model/InstallOptionsPassword.java | 1051 | /*******************************************************************************
* Copyright (c) 2004-2010 Sunil Kamath (IcemanK).
* All rights reserved.
* This program is made available under the terms of the Common Public License
* v1.0 which is available at http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Sunil Kamath (IcemanK) - initial API and implementation
*******************************************************************************/
package net.sf.eclipsensis.installoptions.model;
import net.sf.eclipsensis.installoptions.ini.INISection;
public class InstallOptionsPassword extends InstallOptionsText
{
private static final long serialVersionUID = -8185800757229481950L;
protected InstallOptionsPassword(INISection section)
{
super(section);
}
@Override
public String getType()
{
return InstallOptionsModel.TYPE_PASSWORD;
}
@Override
protected String getDefaultState()
{
return ""; //$NON-NLS-1$
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.insteon/src/main/java/org/openhab/binding/insteon/internal/message/Msg.java | 19302 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.insteon.internal.message;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.insteon.internal.device.InsteonAddress;
import org.openhab.binding.insteon.internal.utils.Utils;
import org.openhab.binding.insteon.internal.utils.Utils.ParsingException;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Contains an Insteon Message consisting of the raw data, and the message definition.
* For more info, see the public Insteon Developer's Guide, 2nd edition,
* and the Insteon Modem Developer's Guide.
*
* @author Bernd Pfrommer - Initial contribution
* @author Daniel Pfrommer - openHAB 1 insteonplm binding
* @author Rob Nielsen - Port to openHAB 2 insteon binding
*/
@NonNullByDefault
public class Msg {
private static final Logger logger = LoggerFactory.getLogger(Msg.class);
/**
* Represents the direction of the message from the host's view.
* The host is the machine to which the modem is attached.
*/
public enum Direction {
TO_MODEM("TO_MODEM"),
FROM_MODEM("FROM_MODEM");
private static Map<String, Direction> map = new HashMap<>();
private String directionString;
static {
map.put(TO_MODEM.getDirectionString(), TO_MODEM);
map.put(FROM_MODEM.getDirectionString(), FROM_MODEM);
}
Direction(String dirString) {
this.directionString = dirString;
}
public String getDirectionString() {
return directionString;
}
public static Direction getDirectionFromString(String dir) {
Direction direction = map.get(dir);
if (direction != null) {
return direction;
} else {
throw new IllegalArgumentException("Unable to find direction for " + dir);
}
}
}
// has the structure of all known messages
private static final Map<String, Msg> MSG_MAP = new HashMap<>();
// maps between command number and the length of the header
private static final Map<Integer, Integer> HEADER_MAP = new HashMap<>();
// has templates for all message from modem to host
private static final Map<Integer, Msg> REPLY_MAP = new HashMap<>();
private int headerLength = -1;
private byte[] data;
private MsgDefinition definition = new MsgDefinition();
private Direction direction = Direction.TO_MODEM;
private long quietTime = 0;
/**
* Constructor
*
* @param headerLength length of message header (in bytes)
* @param data byte array with message
* @param dataLength length of byte array data (in bytes)
* @param dir direction of the message (from/to modem)
*/
public Msg(int headerLength, byte[] data, int dataLength, Direction dir) {
this.headerLength = headerLength;
this.direction = dir;
this.data = new byte[dataLength];
System.arraycopy(data, 0, this.data, 0, dataLength);
}
/**
* Copy constructor, needed to make a copy of the templates when
* generating messages from them.
*
* @param m the message to make a copy of
*/
public Msg(Msg m) {
headerLength = m.headerLength;
data = m.data.clone();
// the message definition usually doesn't change, but just to be sure...
definition = new MsgDefinition(m.definition);
direction = m.direction;
}
static {
// Use xml msg loader to load configs
try {
InputStream stream = FrameworkUtil.getBundle(Msg.class).getResource("/msg_definitions.xml").openStream();
if (stream != null) {
Map<String, Msg> msgs = XMLMessageReader.readMessageDefinitions(stream);
MSG_MAP.putAll(msgs);
} else {
logger.warn("could not get message definition resource!");
}
} catch (IOException e) {
logger.warn("i/o error parsing xml insteon message definitions", e);
} catch (ParsingException e) {
logger.warn("parse error parsing xml insteon message definitions", e);
} catch (FieldException e) {
logger.warn("got field exception while parsing xml insteon message definitions", e);
}
buildHeaderMap();
buildLengthMap();
}
//
// ------------------ simple getters and setters -----------------
//
/**
* Experience has shown that if Insteon messages are sent in close succession,
* only the first one will make it. The quiet time parameter says how long to
* wait after a message before the next one can be sent.
*
* @return the time (in milliseconds) to pause after message has been sent
*/
public long getQuietTime() {
return quietTime;
}
public byte @Nullable [] getData() {
return data;
}
public int getLength() {
return data.length;
}
public int getHeaderLength() {
return headerLength;
}
public Direction getDirection() {
return direction;
}
public MsgDefinition getDefinition() {
return definition;
}
public byte getCommandNumber() {
return data.length < 2 ? -1 : data[1];
}
public boolean isPureNack() {
return data.length == 2 && data[1] == 0x15;
}
public boolean isExtended() {
if (getLength() < 2) {
return false;
}
if (!definition.containsField("messageFlags")) {
return (false);
}
try {
byte flags = getByte("messageFlags");
return ((flags & 0x10) == 0x10);
} catch (FieldException e) {
// do nothing
}
return false;
}
public boolean isUnsolicited() {
// if the message has an ACK/NACK, it is in response to our message,
// otherwise it is out-of-band, i.e. unsolicited
return !definition.containsField("ACK/NACK");
}
public boolean isEcho() {
return isPureNack() || !isUnsolicited();
}
public boolean isOfType(MsgType mt) {
try {
MsgType t = MsgType.fromValue(getByte("messageFlags"));
return (t == mt);
} catch (FieldException e) {
return false;
}
}
public boolean isBroadcast() {
return isOfType(MsgType.ALL_LINK_BROADCAST) || isOfType(MsgType.BROADCAST);
}
public boolean isCleanup() {
return isOfType(MsgType.ALL_LINK_CLEANUP);
}
public boolean isAllLink() {
return isOfType(MsgType.ALL_LINK_BROADCAST) || isOfType(MsgType.ALL_LINK_CLEANUP);
}
public boolean isAckOfDirect() {
return isOfType(MsgType.ACK_OF_DIRECT);
}
public boolean isAllLinkCleanupAckOrNack() {
return isOfType(MsgType.ALL_LINK_CLEANUP_ACK) || isOfType(MsgType.ALL_LINK_CLEANUP_NACK);
}
public boolean isX10() {
try {
int cmd = getByte("Cmd") & 0xff;
if (cmd == 0x63 || cmd == 0x52) {
return true;
}
} catch (FieldException e) {
}
return false;
}
public void setDefinition(MsgDefinition d) {
definition = d;
}
public void setQuietTime(long t) {
quietTime = t;
}
public void addField(Field f) {
definition.addField(f);
}
public @Nullable InsteonAddress getAddr(String name) {
@Nullable
InsteonAddress a = null;
try {
a = definition.getField(name).getAddress(data);
} catch (FieldException e) {
// do nothing, we'll return null
}
return a;
}
public int getHopsLeft() throws FieldException {
int hops = (getByte("messageFlags") & 0x0c) >> 2;
return hops;
}
/**
* Will put a byte at the specified key
*
* @param key the string key in the message definition
* @param value the byte to put
*/
public void setByte(@Nullable String key, byte value) throws FieldException {
Field f = definition.getField(key);
f.setByte(data, value);
}
/**
* Will put an int at the specified field key
*
* @param key the name of the field
* @param value the int to put
*/
public void setInt(String key, int value) throws FieldException {
Field f = definition.getField(key);
f.setInt(data, value);
}
/**
* Will put address bytes at the field
*
* @param key the name of the field
* @param adr the address to put
*/
public void setAddress(String key, InsteonAddress adr) throws FieldException {
Field f = definition.getField(key);
f.setAddress(data, adr);
}
/**
* Will fetch a byte
*
* @param key the name of the field
* @return the byte
*/
public byte getByte(String key) throws FieldException {
return (definition.getField(key).getByte(data));
}
/**
* Will fetch a byte array starting at a certain field
*
* @param key the name of the first field
* @param number of bytes to get
* @return the byte array
*/
public byte[] getBytes(String key, int numBytes) throws FieldException {
int offset = definition.getField(key).getOffset();
if (offset < 0 || offset + numBytes > data.length) {
throw new FieldException("data index out of bounds!");
}
byte[] section = new byte[numBytes];
byte[] data = this.data;
System.arraycopy(data, offset, section, 0, numBytes);
return section;
}
/**
* Will fetch address from field
*
* @param field the filed name to fetch
* @return the address
*/
public InsteonAddress getAddress(String field) throws FieldException {
return (definition.getField(field).getAddress(data));
}
/**
* Fetch 3-byte (24bit) from message
*
* @param key1 the key of the msb
* @param key2 the key of the second msb
* @param key3 the key of the lsb
* @return the integer
*/
public int getInt24(String key1, String key2, String key3) throws FieldException {
int i = (definition.getField(key1).getByte(data) << 16) & (definition.getField(key2).getByte(data) << 8)
& definition.getField(key3).getByte(data);
return i;
}
public String toHexString() {
return Utils.getHexString(data);
}
/**
* Sets the userData fields from a byte array
*
* @param data
*/
public void setUserData(byte[] arg) {
byte[] data = Arrays.copyOf(arg, 14); // appends zeros if short
try {
setByte("userData1", data[0]);
setByte("userData2", data[1]);
setByte("userData3", data[2]);
setByte("userData4", data[3]);
setByte("userData5", data[4]);
setByte("userData6", data[5]);
setByte("userData7", data[6]);
setByte("userData8", data[7]);
setByte("userData9", data[8]);
setByte("userData10", data[9]);
setByte("userData11", data[10]);
setByte("userData12", data[11]);
setByte("userData13", data[12]);
setByte("userData14", data[13]);
} catch (FieldException e) {
logger.warn("got field exception on msg {}:", e.getMessage());
}
}
/**
* Calculate and set the CRC with the older 1-byte method
*
* @return the calculated crc
*/
public int setCRC() {
int crc;
try {
crc = getByte("command1") + getByte("command2");
byte[] bytes = getBytes("userData1", 13); // skip userData14!
for (byte b : bytes) {
crc += b;
}
crc = ((~crc) + 1) & 0xFF;
setByte("userData14", (byte) (crc & 0xFF));
} catch (FieldException e) {
logger.warn("got field exception on msg {}:", this, e);
crc = 0;
}
return crc;
}
/**
* Calculate and set the CRC with the newer 2-byte method
*
* @return the calculated crc
*/
public int setCRC2() {
int crc = 0;
try {
byte[] bytes = getBytes("command1", 14);
for (int loop = 0; loop < bytes.length; loop++) {
int b = bytes[loop] & 0xFF;
for (int bit = 0; bit < 8; bit++) {
int fb = b & 0x01;
if ((crc & 0x8000) == 0) {
fb = fb ^ 0x01;
}
if ((crc & 0x4000) == 0) {
fb = fb ^ 0x01;
}
if ((crc & 0x1000) == 0) {
fb = fb ^ 0x01;
}
if ((crc & 0x0008) == 0) {
fb = fb ^ 0x01;
}
crc = ((crc << 1) | fb) & 0xFFFF;
b = b >> 1;
}
}
setByte("userData13", (byte) ((crc >> 8) & 0xFF));
setByte("userData14", (byte) (crc & 0xFF));
} catch (FieldException e) {
logger.warn("got field exception on msg {}:", this, e);
crc = 0;
}
return crc;
}
@Override
public String toString() {
String s = (direction == Direction.TO_MODEM) ? "OUT:" : "IN:";
// need to first sort the fields by offset
Comparator<Field> cmp = new Comparator<Field>() {
@Override
public int compare(Field f1, Field f2) {
return f1.getOffset() - f2.getOffset();
}
};
TreeSet<Field> fields = new TreeSet<>(cmp);
for (Field f : definition.getFields().values()) {
fields.add(f);
}
for (Field f : fields) {
if (f.getName().equals("messageFlags")) {
byte b;
try {
b = f.getByte(data);
MsgType t = MsgType.fromValue(b);
s += f.toString(data) + "=" + t.toString() + ":" + (b & 0x03) + ":" + ((b & 0x0c) >> 2) + "|";
} catch (FieldException e) {
logger.warn("toString error: ", e);
} catch (IllegalArgumentException e) {
logger.warn("toString msg type error: ", e);
}
} else {
s += f.toString(data) + "|";
}
}
return s;
}
/**
* Factory method to create Msg from raw byte stream received from the
* serial port.
*
* @param buf the raw received bytes
* @param msgLen length of received buffer
* @param isExtended whether it is an extended message or not
* @return message, or null if the Msg cannot be created
*/
public static @Nullable Msg createMessage(byte[] buf, int msgLen, boolean isExtended) {
if (buf.length < 2) {
return null;
}
Msg template = REPLY_MAP.get(cmdToKey(buf[1], isExtended));
if (template == null) {
return null; // cannot find lookup map
}
if (msgLen != template.getLength()) {
logger.warn("expected msg {} len {}, got {}", template.getCommandNumber(), template.getLength(), msgLen);
return null;
}
Msg msg = new Msg(template.getHeaderLength(), buf, msgLen, Direction.FROM_MODEM);
msg.setDefinition(template.getDefinition());
return (msg);
}
/**
* Finds the header length from the insteon command in the received message
*
* @param cmd the insteon command received in the message
* @return the length of the header to expect
*/
public static int getHeaderLength(byte cmd) {
Integer len = HEADER_MAP.get((int) cmd);
if (len == null) {
return (-1); // not found
}
return len;
}
/**
* Tries to determine the length of a received Insteon message.
*
* @param b Insteon message command received
* @param isExtended flag indicating if it is an extended message
* @return message length, or -1 if length cannot be determined
*/
public static int getMessageLength(byte b, boolean isExtended) {
int key = cmdToKey(b, isExtended);
Msg msg = REPLY_MAP.get(key);
if (msg == null) {
return -1;
}
return msg.getLength();
}
/**
* From bytes received thus far, tries to determine if an Insteon
* message is extended or standard.
*
* @param buf the received bytes
* @param len the number of bytes received so far
* @param headerLength the known length of the header
* @return true if it is definitely extended, false if cannot be
* determined or if it is a standard message
*/
public static boolean isExtended(byte[] buf, int len, int headerLength) {
if (headerLength <= 2) {
return false;
} // extended messages are longer
if (len < headerLength) {
return false;
} // not enough data to tell if extended
byte flags = buf[headerLength - 1]; // last byte says flags
boolean isExtended = (flags & 0x10) == 0x10; // bit 4 is the message
return (isExtended);
}
/**
* Creates Insteon message (for sending) of a given type
*
* @param type the type of message to create, as defined in the xml file
* @return reference to message created
* @throws IOException if there is no such message type known
*/
public static Msg makeMessage(String type) throws InvalidMessageTypeException {
Msg m = MSG_MAP.get(type);
if (m == null) {
throw new InvalidMessageTypeException("unknown message type: " + type);
}
return new Msg(m);
}
private static int cmdToKey(byte cmd, boolean isExtended) {
return (cmd + (isExtended ? 256 : 0));
}
private static void buildHeaderMap() {
for (Msg m : MSG_MAP.values()) {
if (m.getDirection() == Direction.FROM_MODEM) {
HEADER_MAP.put((int) m.getCommandNumber(), m.getHeaderLength());
}
}
}
private static void buildLengthMap() {
for (Msg m : MSG_MAP.values()) {
if (m.getDirection() == Direction.FROM_MODEM) {
int key = cmdToKey(m.getCommandNumber(), m.isExtended());
REPLY_MAP.put(key, m);
}
}
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/handler/IPBridgeThingHandler.java | 5085 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.knx.internal.handler;
import java.net.InetSocketAddress;
import java.text.MessageFormat;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.knx.internal.KNXBindingConstants;
import org.openhab.binding.knx.internal.client.CustomKNXNetworkLinkIP;
import org.openhab.binding.knx.internal.client.IPClient;
import org.openhab.binding.knx.internal.client.KNXClient;
import org.openhab.binding.knx.internal.client.NoOpClient;
import org.openhab.binding.knx.internal.config.IPBridgeConfiguration;
import org.openhab.core.net.NetworkAddressService;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link IPBridgeThingHandler} is responsible for handling commands, which are
* sent to one of the channels. It implements a KNX/IP Gateway, that either acts a a
* conduit for other {@link DeviceThingHandler}s, or for Channels that are
* directly defined on the bridge
*
* @author Karel Goderis - Initial contribution
* @author Simon Kaufmann - Refactoring & cleanup
*/
@NonNullByDefault
public class IPBridgeThingHandler extends KNXBridgeBaseThingHandler {
private static final String MODE_ROUTER = "ROUTER";
private static final String MODE_TUNNEL = "TUNNEL";
private final Logger logger = LoggerFactory.getLogger(IPBridgeThingHandler.class);
private @Nullable IPClient client;
private final NetworkAddressService networkAddressService;
public IPBridgeThingHandler(Bridge bridge, NetworkAddressService networkAddressService) {
super(bridge);
this.networkAddressService = networkAddressService;
}
@Override
public void initialize() {
IPBridgeConfiguration config = getConfigAs(IPBridgeConfiguration.class);
int autoReconnectPeriod = config.getAutoReconnectPeriod();
if (autoReconnectPeriod != 0 && autoReconnectPeriod < 30) {
logger.info("autoReconnectPeriod for {} set to {}s, allowed range is 0 (never) or >30", thing.getUID(),
autoReconnectPeriod);
autoReconnectPeriod = 30;
config.setAutoReconnectPeriod(autoReconnectPeriod);
}
String localSource = config.getLocalSourceAddr();
String connectionTypeString = config.getType();
int port = config.getPortNumber().intValue();
String ip = config.getIpAddress();
InetSocketAddress localEndPoint = null;
boolean useNAT = false;
int ipConnectionType;
if (MODE_TUNNEL.equalsIgnoreCase(connectionTypeString)) {
useNAT = config.getUseNAT() != null ? config.getUseNAT() : false;
ipConnectionType = CustomKNXNetworkLinkIP.TUNNELING;
} else if (MODE_ROUTER.equalsIgnoreCase(connectionTypeString)) {
useNAT = false;
if (ip == null || ip.isEmpty()) {
ip = KNXBindingConstants.DEFAULT_MULTICAST_IP;
}
ipConnectionType = CustomKNXNetworkLinkIP.ROUTING;
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
MessageFormat.format("Unknown IP connection type {0}. Known types are either 'TUNNEL' or 'ROUTER'",
connectionTypeString));
return;
}
if (ip == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"The 'ipAddress' of the gateway must be configured in 'TUNNEL' mode");
return;
}
if (config.getLocalIp() != null && !config.getLocalIp().isEmpty()) {
localEndPoint = new InetSocketAddress(config.getLocalIp(), 0);
} else {
localEndPoint = new InetSocketAddress(networkAddressService.getPrimaryIpv4HostAddress(), 0);
}
updateStatus(ThingStatus.UNKNOWN);
client = new IPClient(ipConnectionType, ip, localSource, port, localEndPoint, useNAT, autoReconnectPeriod,
thing.getUID(), config.getResponseTimeout().intValue(), config.getReadingPause().intValue(),
config.getReadRetriesLimit().intValue(), getScheduler(), this);
client.initialize();
}
@Override
public void dispose() {
super.dispose();
if (client != null) {
client.dispose();
client = null;
}
}
@Override
protected KNXClient getClient() {
KNXClient ret = client;
if (ret == null) {
return new NoOpClient();
}
return ret;
}
}
| epl-1.0 |
stzilli/kapua | message/internal/src/main/java/org/eclipse/kapua/message/internal/KapuaPayloadImpl.java | 1395 | /*******************************************************************************
* Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
* Red Hat Inc
*******************************************************************************/
package org.eclipse.kapua.message.internal;
import org.eclipse.kapua.message.KapuaPayload;
import java.util.HashMap;
import java.util.Map;
/**
* {@link KapuaPayload} implementation.
*
* @since 1.0.0
*/
public class KapuaPayloadImpl implements KapuaPayload {
private Map<String, Object> metrics;
private byte[] body;
/**
* Constructor
*/
public KapuaPayloadImpl() {
}
@Override
public Map<String, Object> getMetrics() {
if (metrics == null) {
metrics = new HashMap<>();
}
return metrics;
}
@Override
public void setMetrics(Map<String, Object> metrics) {
this.metrics = metrics;
}
@Override
public byte[] getBody() {
return body;
}
@Override
public void setBody(byte[] body) {
this.body = body;
}
}
| epl-1.0 |
stzilli/kapua | service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCacheFactoryTest.java | 1610 | /*******************************************************************************
* Copyright (c) 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.service.authorization.access.shiro;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
@Category(JUnitTests.class)
public class AccessRoleCacheFactoryTest extends Assert {
@Test
public void accessRoleCacheFactoryTest() throws Exception {
Constructor<AccessRoleCacheFactory> accessRoleCacheFactory = AccessRoleCacheFactory.class.getDeclaredConstructor();
accessRoleCacheFactory.setAccessible(true);
accessRoleCacheFactory.newInstance();
assertTrue("True expected.", Modifier.isPrivate(accessRoleCacheFactory.getModifiers()));
}
@Test
public void getInstanceTest() {
assertTrue("True expected.", AccessRoleCacheFactory.getInstance() instanceof AccessRoleCacheFactory);
assertEquals("Expected and actual values should be the same.", "AccessRoleId", AccessRoleCacheFactory.getInstance().getEntityIdCacheName());
}
} | epl-1.0 |
aubelix/liferay-samples | wip-portlet/src/main/java/fr/ippon/wip/http/hc/HttpClientSessionListener.java | 1491 | /*
* Copyright 2010,2011 Ippon Technologies
*
* This file is part of Web Integration Portlet (WIP).
* Web Integration Portlet (WIP) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Web Integration Portlet (WIP) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Web Integration Portlet (WIP). If not, see <http://www.gnu.org/licenses/>.
*/
package fr.ippon.wip.http.hc;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Implementation of HttpSessionListener. Must be declared in web.xml to release
* resources associated to a session when it is destroyed.
*
* @author François Prot
*/
public class HttpClientSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
// Nothing to do
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpClientResourceManager.getInstance().releaseSessionResources(httpSessionEvent.getSession().getId());
}
}
| gpl-2.0 |
ikantech/xmppsupport_v2 | src/com/kenai/jbosh/AbstractAttr.java | 2814 | /*
* Copyright 2009 Mike Cumings
*
* 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.kenai.jbosh;
/**
* Abstract base class for creating BOSH attribute classes. Concrete
* implementations of this class will naturally inherit the underlying type's
* behavior for {@code equals()}, {@code hashCode()}, {@code toString()}, and
* {@code compareTo()}, allowing for the easy creation of objects which extend
* existing trivial types. This was done to comply with the prefactoring rule
* declaring, "when you are being abstract, be abstract all the way".
*
* @param <T>
* type of the extension object
*/
abstract class AbstractAttr<T extends Comparable> implements Comparable {
/**
* Captured value.
*/
private final T value;
/**
* Creates a new encapsulated object instance.
*
* @param aValue
* encapsulated getValue
*/
protected AbstractAttr(final T aValue) {
value = aValue;
}
/**
* Gets the encapsulated data value.
*
* @return data value
*/
public final T getValue() {
return value;
}
// /////////////////////////////////////////////////////////////////////////
// Object method overrides:
/**
* {@inheritDoc}
*
* @param otherObj
* object to compare to
* @return true if the objects are equal, false otherwise
*/
@Override
public boolean equals(final Object otherObj) {
if (otherObj == null) {
return false;
} else if (otherObj instanceof AbstractAttr) {
AbstractAttr other = (AbstractAttr) otherObj;
return value.equals(other.value);
} else {
return false;
}
}
/**
* {@inheritDoc}
*
* @return hashCode of the encapsulated object
*/
@Override
public int hashCode() {
return value.hashCode();
}
/**
* {@inheritDoc}
*
* @return string representation of the encapsulated object
*/
@Override
public String toString() {
return value.toString();
}
// /////////////////////////////////////////////////////////////////////////
// Comparable interface:
/**
* {@inheritDoc}
*
* @param otherObj
* object to compare to
* @return -1, 0, or 1
*/
@SuppressWarnings("unchecked")
public int compareTo(final Object otherObj) {
if (otherObj == null) {
return 1;
} else {
return value.compareTo(otherObj);
}
}
}
| gpl-2.0 |
CleverCloud/Quercus | resin/src/main/java/com/caucho/log/SubHandler.java | 2558 | /*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.log;
import com.caucho.util.L10N;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Proxy for an underlying handler, e.g. to handle different
* logging levels.
*/
public class SubHandler extends Handler {
private static final L10N L = new L10N(SubHandler.class);
private Handler _handler;
SubHandler(Handler handler)
{
_handler = handler;
}
/**
* Publishes the record.
*/
public void publish(LogRecord record)
{
if (! isLoggable(record))
return;
if (_handler != null)
_handler.publish(record);
}
/**
* Flushes the buffer.
*/
public void flush()
{
if (_handler != null)
_handler.flush();
}
/**
* Closes the handler.
*/
public void close()
{
if (_handler != null)
_handler.close();
_handler = null;
}
/**
* Returns the hash code.
*/
public int hashCode()
{
if (_handler == null)
return super.hashCode();
else
return _handler.hashCode();
}
/**
* Test for equality.
*/
public boolean equals(Object o)
{
if (this == o)
return true;
else if (o == null)
return false;
if (_handler == null)
return false;
else if (o.equals(_handler))
return true;
if (! (o instanceof SubHandler))
return false;
SubHandler subHandler = (SubHandler) o;
return _handler.equals(subHandler._handler);
}
public String toString()
{
return "SubHandler[" + _handler + "]";
}
}
| gpl-2.0 |
gerryDreamer/dreamerLib | src/com/dreamer/string/package-info.java | 143 | /**
* This package provides custom string manipulation capabilities
* @see com.dreamer.string.Expressions
*/
package com.dreamer.string; | gpl-2.0 |
GregBowyer/lire | src/main/java/net/semanticmetadata/lire/indexing/tools/ParallelExtractor.java | 21231 | /*
* This file is part of the LIRE project: http://www.semanticmetadata.net/lire
* LIRE is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* LIRE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LIRE; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* We kindly ask you to refer the any or one of the following publications in
* any publication mentioning or employing Lire:
*
* Lux Mathias, Savvas A. Chatzichristofis. Lire: Lucene Image Retrieval –
* An Extensible Java CBIR Library. In proceedings of the 16th ACM International
* Conference on Multimedia, pp. 1085-1088, Vancouver, Canada, 2008
* URL: http://doi.acm.org/10.1145/1459359.1459577
*
* Lux Mathias. Content Based Image Retrieval with LIRE. In proceedings of the
* 19th ACM International Conference on Multimedia, pp. 735-738, Scottsdale,
* Arizona, USA, 2011
* URL: http://dl.acm.org/citation.cfm?id=2072432
*
* Mathias Lux, Oge Marques. Visual Information Retrieval using Java and LIRE
* Morgan & Claypool, 2013
* URL: http://www.morganclaypool.com/doi/abs/10.2200/S00468ED1V01Y201301ICR025
*
* Copyright statement:
* ====================
* (c) 2002-2013 by Mathias Lux (mathias@juggle.at)
* http://www.semanticmetadata.net/lire, http://www.lire-project.net
*
* Updated: 01.07.13 16:15
*/
package net.semanticmetadata.lire.indexing.tools;
import net.semanticmetadata.lire.DocumentBuilder;
import net.semanticmetadata.lire.imageanalysis.LireFeature;
import net.semanticmetadata.lire.indexing.parallel.WorkItem;
import net.semanticmetadata.lire.utils.ImageUtils;
import net.semanticmetadata.lire.utils.SerializationUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
/**
* The Extractor is a configurable class that extracts multiple features from multiple images
* and puts them into a data file. Main purpose is run multiple extractors at multiple machines
* and put the data files into one single index. Images are references relatively to the data file,
* so it should work fine for network file systems.
* <p/>
* File format is specified as: (12(345)+)+ with 1-5 being ...
* <p/>
* 1. Length of the file hashFunctionsFileName [4 bytes], an int n giving the number of bytes for the file hashFunctionsFileName
* 2. File hashFunctionsFileName, relative to the outfile [n bytes, see above]
* 3. Feature index [1 byte], see static members
* 4. Feature value length [4 bytes], an int k giving the number of bytes encoding the value
* 5. Feature value [k bytes, see above]
* <p/>
* The file is sent through an GZIPOutputStream, so it's compressed in addition.
* <p/>
* Note that the outfile has to be in a folder parent to all images!
*
* @author Mathias Lux, mathias@juggle.at, 08.03.13
*/
public class ParallelExtractor implements Runnable {
public static final String[] features = new String[]{
"net.semanticmetadata.lire.imageanalysis.CEDD", // 0
"net.semanticmetadata.lire.imageanalysis.FCTH", // 1
"net.semanticmetadata.lire.imageanalysis.OpponentHistogram", // 2
"net.semanticmetadata.lire.imageanalysis.joint.JointHistogram", // 3
"net.semanticmetadata.lire.imageanalysis.AutoColorCorrelogram", // 4
"net.semanticmetadata.lire.imageanalysis.ColorLayout", // 5
"net.semanticmetadata.lire.imageanalysis.EdgeHistogram", // 6
"net.semanticmetadata.lire.imageanalysis.Gabor", // 7
"net.semanticmetadata.lire.imageanalysis.JCD", // 8
"net.semanticmetadata.lire.imageanalysis.JpegCoefficientHistogram",
"net.semanticmetadata.lire.imageanalysis.ScalableColor", // 10
"net.semanticmetadata.lire.imageanalysis.SimpleColorHistogram", // 11
"net.semanticmetadata.lire.imageanalysis.Tamura", // 12
"net.semanticmetadata.lire.imageanalysis.LuminanceLayout", // 13
"net.semanticmetadata.lire.imageanalysis.PHOG", // 14
};
public static final String[] featureFieldNames = new String[]{
DocumentBuilder.FIELD_NAME_CEDD, // 0
DocumentBuilder.FIELD_NAME_FCTH, // 1
DocumentBuilder.FIELD_NAME_OPPONENT_HISTOGRAM, // 2
DocumentBuilder.FIELD_NAME_JOINT_HISTOGRAM, // 3
DocumentBuilder.FIELD_NAME_AUTOCOLORCORRELOGRAM, // 4
DocumentBuilder.FIELD_NAME_COLORLAYOUT, // 5
DocumentBuilder.FIELD_NAME_EDGEHISTOGRAM, // 6
DocumentBuilder.FIELD_NAME_GABOR, // 7
DocumentBuilder.FIELD_NAME_JCD, // 8
DocumentBuilder.FIELD_NAME_JPEGCOEFFS,
DocumentBuilder.FIELD_NAME_SCALABLECOLOR,
DocumentBuilder.FIELD_NAME_COLORHISTOGRAM,
DocumentBuilder.FIELD_NAME_TAMURA, // 12
DocumentBuilder.FIELD_NAME_LUMINANCE_LAYOUT, // 13
DocumentBuilder.FIELD_NAME_PHOG, // 14
};
static HashMap<String, Integer> feature2index;
static {
feature2index = new HashMap<String, Integer>(features.length);
for (int i = 0; i < features.length; i++) {
feature2index.put(features[i], i);
}
}
private static boolean force = false;
private static int numberOfThreads = 4;
Stack<WorkItem> images = new Stack<WorkItem>();
boolean ended = false;
int overallCount = 0;
OutputStream dos = null;
LinkedList<LireFeature> listOfFeatures;
File fileList = null;
File outFile = null;
private int monitoringInterval = 10;
private int maxSideLength = -1;
public ParallelExtractor() {
// default constructor.
listOfFeatures = new LinkedList<LireFeature>();
}
/**
* Sets the number of consumer threads that are employed for extraction
*
* @param numberOfThreads
*/
public static void setNumberOfThreads(int numberOfThreads) {
ParallelExtractor.numberOfThreads = numberOfThreads;
}
public static void main(String[] args) throws IOException {
ParallelExtractor e = new ParallelExtractor();
// parse programs args ...
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("-i")) {
// infile ...
if ((i + 1) < args.length)
e.setFileList(new File(args[i + 1]));
else printHelp();
} else if (arg.startsWith("-o")) {
// out file
if ((i + 1) < args.length)
e.setOutFile(new File(args[i + 1]));
else printHelp();
} else if (arg.startsWith("-m")) {
// out file
if ((i + 1) < args.length) {
try {
int s = Integer.parseInt(args[i + 1]);
if (s > 10)
e.setMaxSideLength(s);
} catch (NumberFormatException e1) {
e1.printStackTrace();
printHelp();
}
} else printHelp();
} else if (arg.startsWith("-f")) {
force = true;
} else if (arg.startsWith("-h")) {
// help
printHelp();
} else if (arg.startsWith("-n")) {
if ((i + 1) < args.length)
try {
ParallelExtractor.numberOfThreads = Integer.parseInt(args[i + 1]);
} catch (Exception e1) {
System.err.println("Could not set number of threads to \"" + args[i + 1] + "\".");
e1.printStackTrace();
}
else printHelp();
} else if (arg.startsWith("-c")) {
// config file ...
Properties p = new Properties();
p.load(new FileInputStream(new File(args[i + 1])));
Enumeration<?> enumeration = p.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
if (key.toLowerCase().startsWith("feature.")) {
try {
e.addFeature((LireFeature) Class.forName(p.getProperty(key)).newInstance());
} catch (Exception e1) {
System.err.println("Could not add feature named " + p.getProperty(key));
e1.printStackTrace();
}
}
}
}
}
// check if there is an infile, an outfile and some features to extract.
if (!e.isConfigured()) {
printHelp();
} else {
e.run();
}
}
private static void printHelp() {
System.out.println("Help for the ParallelExtractor class.\n" +
"=============================\n" +
"This help text is shown if you start the ParallelExtractor with the '-h' option.\n" +
"\n" +
"1. Usage\n" +
"========\n" +
"$> ParallelExtractor -i <infile> [-o <outfile>] -c <configfile> [-n <threads>] [-m <max_side_length>]\n" +
"\n" +
"Note: if you don't specify an outfile just \".data\" is appended to the infile for output.\n" +
"\n" +
"2. Config File\n" +
"==============\n" +
"The config file is a simple java Properties file. It basically gives the \n" +
"employed features as a list of properties, just like:\n" +
"\n" +
"feature.1=net.semanticmetadata.lire.imageanalysis.CEDD\n" +
"feature.2=net.semanticmetadata.lire.imageanalysis.FCTH\n" +
"\n" +
"... and so on. ");
}
/**
* Adds a feature to the extractor chain. All those features are extracted from images.
*
* @param feature
*/
public void addFeature(LireFeature feature) {
listOfFeatures.add(feature);
}
/**
* Sets the file list for processing. One image file per line is fine.
*
* @param fileList
*/
public void setFileList(File fileList) {
this.fileList = fileList;
}
/**
* Sets the outfile. The outfile has to be in a folder parent to all input images.
*
* @param outFile
*/
public void setOutFile(File outFile) {
this.outFile = outFile;
}
public int getMaxSideLength() {
return maxSideLength;
}
public void setMaxSideLength(int maxSideLength) {
this.maxSideLength = maxSideLength;
}
private boolean isConfigured() {
boolean configured = true;
if (fileList == null || !fileList.exists()) configured = false;
else if (outFile == null) {
// create an outfile ...
try {
outFile = new File(fileList.getCanonicalPath() + ".data");
System.out.println("Setting out file to " + outFile.getCanonicalFile());
} catch (IOException e) {
configured = false;
}
} else if (outFile.exists() && !force) {
System.err.println(outFile.getName() + " already exists. Please delete or choose another outfile.");
configured = false;
}
if (listOfFeatures.size() < 1) configured = false;
return configured;
}
@Override
public void run() {
// check:
if (fileList == null || !fileList.exists()) {
System.err.println("No text file with a list of images given.");
return;
}
if (listOfFeatures.size() == 0) {
System.err.println("No features to extract given.");
return;
}
try {
dos = new BufferedOutputStream(new FileOutputStream(outFile));
Thread p = new Thread(new Producer());
p.start();
LinkedList<Thread> threads = new LinkedList<Thread>();
long l = System.currentTimeMillis();
for (int i = 0; i < numberOfThreads; i++) {
Thread c = new Thread(new Consumer());
c.start();
threads.add(c);
}
Thread m = new Thread(new Monitoring());
m.start();
for (Iterator<Thread> iterator = threads.iterator(); iterator.hasNext(); ) {
iterator.next().join();
}
long l1 = System.currentTimeMillis() - l;
System.out.println("Analyzed " + overallCount + " images in " + l1 / 1000 + " seconds, ~" + (overallCount > 0 ? (l1 / overallCount) : "inf.") + " ms each.");
dos.close();
// writer.commit();
// writer.close();
// threadFinished = true;
} catch (Exception e) {
e.printStackTrace();
}
}
private void addFeatures(List features) {
for (Iterator<LireFeature> iterator = listOfFeatures.iterator(); iterator.hasNext(); ) {
LireFeature next = iterator.next();
try {
features.add(next.getClass().newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Monitoring implements Runnable {
public void run() {
long ms = System.currentTimeMillis();
try {
Thread.sleep(1000 * monitoringInterval); // wait xx seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
while (!ended) {
try {
// print the current status:
long time = System.currentTimeMillis() - ms;
System.out.println("Analyzed " + overallCount + " images in " + time / 1000 + " seconds, " + ((overallCount > 0) ? (time / overallCount) : "n.a.") + " ms each (" + images.size() + " images currently in queue).");
Thread.sleep(1000 * monitoringInterval); // wait xx seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable {
public void run() {
int tmpSize = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(fileList));
String file = null;
File next = null;
while ((file = br.readLine()) != null) {
next = new File(file);
BufferedImage img = null;
try {
int fileSize = (int) next.length();
byte[] buffer = new byte[fileSize];
FileInputStream fis = new FileInputStream(next);
fis.read(buffer);
String path = next.getCanonicalPath();
synchronized (images) {
images.add(new WorkItem(path, buffer));
tmpSize = images.size();
// if the cache is too crowded, then wait.
if (tmpSize > 500) images.wait(500);
// if the cache is too small, dont' notify.
images.notify();
}
} catch (Exception e) {
System.err.println("Could not read image " + file + ": " + e.getMessage());
}
try {
if (tmpSize > 500) Thread.sleep(1000);
// else Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
synchronized (images) {
ended = true;
images.notifyAll();
}
}
}
class Consumer implements Runnable {
WorkItem tmp = null;
LinkedList<LireFeature> features = new LinkedList<LireFeature>();
int count = 0;
boolean locallyEnded = false;
Consumer() {
addFeatures(features);
}
public void run() {
byte[] myBuffer = new byte[1024 * 1024 * 10];
int bufferCount = 0;
while (!locallyEnded) {
synchronized (images) {
// we wait for the stack to be either filled or empty & not being filled any more.
while (images.empty() && !ended) {
try {
images.wait(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// make sure the thread locally knows that the end has come (outer loop)
if (images.empty() && ended)
locallyEnded = true;
// well the last thing we want is an exception in the very last round.
if (!images.empty() && !locallyEnded) {
tmp = images.pop();
count++;
overallCount++;
}
}
try {
bufferCount = 0;
if (!locallyEnded) {
ByteArrayInputStream b = new ByteArrayInputStream(tmp.getBuffer());
BufferedImage img = ImageIO.read(b);
if (maxSideLength > 50) img = ImageUtils.scaleImage(img, maxSideLength);
byte[] tmpBytes = tmp.getFileName().getBytes();
// everything is written to a buffer and only if no exception is thrown, the image goes to index.
System.arraycopy(SerializationUtils.toBytes(tmpBytes.length), 0, myBuffer, 0, 4);
bufferCount += 4;
// dos.write(SerializationUtils.toBytes(tmpBytes.length));
System.arraycopy(tmpBytes, 0, myBuffer, bufferCount, tmpBytes.length);
bufferCount += tmpBytes.length;
// dos.write(tmpBytes);
for (LireFeature feature : features) {
feature.extract(img);
myBuffer[bufferCount] = (byte) feature2index.get(feature.getClass().getName()).intValue();
bufferCount++;
// dos.write(feature2index.get(feature.getClass().getName()));
tmpBytes = feature.getByteArrayRepresentation();
System.arraycopy(SerializationUtils.toBytes(tmpBytes.length), 0, myBuffer, bufferCount, 4);
bufferCount += 4;
// dos.write(SerializationUtils.toBytes(tmpBytes.length));
System.arraycopy(tmpBytes, 0, myBuffer, bufferCount, tmpBytes.length);
bufferCount += tmpBytes.length;
// dos.write(tmpBytes);
}
// finally write everything to the stream - in case no exception was thrown..
synchronized (dos) {
dos.write(myBuffer, 0, bufferCount);
dos.write(-1);
dos.flush();
}
}
} catch (Exception e) {
System.err.println("Error processing file " + tmp.getFileName());
e.printStackTrace();
}
}
}
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01545.java | 2076 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01545")
public class BenchmarkTest01545 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getHeader("foo");
String bar;
// Simple ? condition that assigns param to bar on false condition
int i = 106;
bar = (7*42) - i > 200 ? "This should never happen" : param;
String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
try {
java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
statement.execute( sql, new String[] { "username", "password" } );
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
}
}
| gpl-2.0 |
ricardobaumann/android | worldofgravity-master/src/org/anddev/andengine/entity/layer/tiled/tmx/TMXLayer.java | 11687 | package org.anddev.andengine.entity.layer.tiled.tmx;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.collision.RectangularShapeCollisionChecker;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader.ITMXTilePropertiesListener;
import org.anddev.andengine.entity.layer.tiled.tmx.util.constants.TMXConstants;
import org.anddev.andengine.entity.shape.RectangularShape;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.util.Base64;
import org.anddev.andengine.util.Base64InputStream;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.SAXUtils;
import org.anddev.andengine.util.StreamUtils;
import org.xml.sax.Attributes;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:27:31 - 20.07.2010
*/
public class TMXLayer extends RectangularShape implements TMXConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final TMXTiledMap mTMXTiledMap;
private final String mName;
private final int mTileColumns;
private final int mTileRows;
private final TMXTile[][] mTMXTiles;
private int mTilesAdded;
private final int mGlobalTileIDsExpected;
private final float[] mCullingVertices = new float[2 * 4];
private final TMXProperties<TMXLayerProperty> mTMXLayerProperties = new TMXProperties<TMXLayerProperty>();
// ===========================================================
// Constructors
// ===========================================================
public TMXLayer(final TMXTiledMap pTMXTiledMap, final Attributes pAttributes) {
super(0, 0, 0, 0, null);
this.mTMXTiledMap = pTMXTiledMap;
this.mName = pAttributes.getValue("", TAG_LAYER_ATTRIBUTE_NAME);
this.mTileColumns = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_LAYER_ATTRIBUTE_WIDTH);
this.mTileRows = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_LAYER_ATTRIBUTE_HEIGHT);
this.mTMXTiles = new TMXTile[this.mTileRows][this.mTileColumns];
super.mWidth = pTMXTiledMap.getTileWidth() * this.mTileColumns;
final float width = super.mWidth;
super.mBaseWidth = width;
super.mHeight = pTMXTiledMap.getTileHeight() * this.mTileRows;
final float height = super.mHeight;
super.mBaseHeight = height;
this.mRotationCenterX = width * 0.5f;
this.mRotationCenterY = height * 0.5f;
this.mScaleCenterX = this.mRotationCenterX;
this.mScaleCenterY = this.mRotationCenterY;
this.mGlobalTileIDsExpected = this.mTileColumns * this.mTileRows;
this.setVisible(SAXUtils.getIntAttribute(pAttributes, TAG_LAYER_ATTRIBUTE_VISIBLE, TAG_LAYER_ATTRIBUTE_VISIBLE_VALUE_DEFAULT) == 1);
this.setAlpha(SAXUtils.getFloatAttribute(pAttributes, TAG_LAYER_ATTRIBUTE_OPACITY, TAG_LAYER_ATTRIBUTE_OPACITY_VALUE_DEFAULT));
}
// ===========================================================
// Getter & Setter
// ===========================================================
public String getName() {
return this.mName;
}
public int getTileColumns() {
return this.mTileColumns;
}
public int getTileRows() {
return this.mTileRows;
}
public TMXTile[][] getTMXTiles() {
return this.mTMXTiles;
}
public TMXTile getTMXTile(final int pTileColumn, final int pTileRow) throws ArrayIndexOutOfBoundsException {
return this.mTMXTiles[pTileRow][pTileColumn];
}
/**
* @param pX in SceneCoordinates.
* @param pY in SceneCoordinates.
* @return the {@link TMXTile} located at <code>pX/pY</code>.
*/
public TMXTile getTMXTileAt(final float pX, final float pY) {
final float[] localCoords = this.convertSceneToLocalCoordinates(pX, pY);
final TMXTiledMap tmxTiledMap = this.mTMXTiledMap;
final int tileColumn = (int)(localCoords[VERTEX_INDEX_X] / tmxTiledMap.getTileWidth());
if(tileColumn < 0 || tileColumn > this.mTileColumns - 1) {
return null;
}
final int tileRow = (int)(localCoords[VERTEX_INDEX_Y] / tmxTiledMap.getTileWidth());
if(tileRow < 0 || tileRow > this.mTileRows - 1) {
return null;
}
return this.mTMXTiles[tileRow][tileColumn];
}
public void addTMXLayerProperty(final TMXLayerProperty pTMXLayerProperty) {
this.mTMXLayerProperties.add(pTMXLayerProperty);
}
public TMXProperties<TMXLayerProperty> getTMXLayerProperties() {
return this.mTMXLayerProperties;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
@Deprecated
public void setRotation(final float pRotation) {
}
@Override
protected void onUpdateVertexBuffer() {
/* Nothing. */
}
@Override
protected void onInitDraw(final GL10 pGL) {
super.onInitDraw(pGL);
GLHelper.enableTextures(pGL);
GLHelper.enableTexCoordArray(pGL);
}
@Override
protected void onApplyVertices(final GL10 pGL) {
if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) {
final GL11 gl11 = (GL11)pGL;
this.mTMXTiledMap.getSharedVertexBuffer().selectOnHardware(gl11);
GLHelper.vertexZeroPointer(gl11);
} else {
GLHelper.vertexPointer(pGL, this.mTMXTiledMap.getSharedVertexBuffer().getFloatBuffer());
}
}
@Override
protected void drawVertices(final GL10 pGL, final Camera pCamera) {
final TMXTile[][] tmxTiles = this.mTMXTiles;
final int tileColumns = this.mTileColumns;
final int tileRows = this.mTileRows;
final int tileWidth = this.mTMXTiledMap.getTileWidth();
final int tileHeight = this.mTMXTiledMap.getTileHeight();
final float scaledTileWidth = tileWidth * this.mScaleX;
final float scaledTileHeight = tileHeight * this.mScaleY;
final float[] cullingVertices = this.mCullingVertices;
RectangularShapeCollisionChecker.fillVertices(this, cullingVertices);
final float layerMinX = cullingVertices[VERTEX_INDEX_X];
final float layerMinY = cullingVertices[VERTEX_INDEX_Y];
final float cameraMinX = pCamera.getMinX();
final float cameraMinY = pCamera.getMinY();
final float cameraWidth = pCamera.getWidth();
final float cameraHeight = pCamera.getHeight();
/* Determine the area that is visible in the camera. */
final float firstColumnRaw = (cameraMinX - layerMinX) / scaledTileWidth;
final int firstColumn = MathUtils.bringToBounds(0, tileColumns - 1, (int)Math.floor(firstColumnRaw));
final int lastColumn = MathUtils.bringToBounds(0, tileColumns - 1, (int)Math.ceil(firstColumnRaw + cameraWidth / scaledTileWidth));
final float firstRowRaw = (cameraMinY - layerMinY) / scaledTileHeight;
final int firstRow = MathUtils.bringToBounds(0, tileRows - 1, (int)Math.floor(firstRowRaw));
final int lastRow = MathUtils.bringToBounds(0, tileRows - 1, (int)Math.floor(firstRowRaw + cameraHeight / scaledTileHeight));
final int visibleTilesTotalWidth = (lastColumn - firstColumn + 1) * tileWidth;
pGL.glTranslatef(firstColumn * tileWidth, firstRow * tileHeight, 0);
for(int row = firstRow; row <= lastRow; row++) {
final TMXTile[] tmxTileRow = tmxTiles[row];
for(int column = firstColumn; column <= lastColumn; column++) {
final TextureRegion textureRegion = tmxTileRow[column].mTextureRegion;
if(textureRegion != null) {
textureRegion.onApply(pGL);
pGL.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
pGL.glTranslatef(tileWidth, 0, 0);
}
/* Translate one row downwards and the back left to the first column.
* Just like the 'Carriage Return' + 'New Line' (\r\n) on a typewriter. */
pGL.glTranslatef(-visibleTilesTotalWidth, tileHeight, 0);
}
pGL.glLoadIdentity();
}
@Override
protected void onManagedUpdate(final float pSecondsElapsed) {
/* Nothing. */
}
// ===========================================================
// Methods
// ===========================================================
void initializeTMXTileFromXML(final Attributes pAttributes, final ITMXTilePropertiesListener pTMXTilePropertyListener) {
this.addTileByGlobalTileID(SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_TILE_ATTRIBUTE_GID), pTMXTilePropertyListener);
}
void initializeTMXTilesFromDataString(final String pDataString, final String pDataEncoding, final String pDataCompression, final ITMXTilePropertiesListener pTMXTilePropertyListener) throws IOException, IllegalArgumentException {
DataInputStream dataIn = null;
try{
InputStream in = new ByteArrayInputStream(pDataString.getBytes("UTF-8"));
/* Wrap decoding Streams if necessary. */
if(pDataEncoding != null && pDataEncoding.equals(TAG_DATA_ATTRIBUTE_ENCODING_VALUE_BASE64)) {
in = new Base64InputStream(in, Base64.DEFAULT);
}
if(pDataCompression != null){
if(pDataCompression.equals(TAG_DATA_ATTRIBUTE_COMPRESSION_VALUE_GZIP)) {
in = new GZIPInputStream(in);
} else {
throw new IllegalArgumentException("Supplied compression '" + pDataCompression + "' is not supported yet.");
}
}
dataIn = new DataInputStream(in);
while(this.mTilesAdded < this.mGlobalTileIDsExpected) {
final int globalTileID = this.readGlobalTileID(dataIn);
this.addTileByGlobalTileID(globalTileID, pTMXTilePropertyListener);
}
} finally {
StreamUtils.close(dataIn);
}
}
private void addTileByGlobalTileID(final int pGlobalTileID, final ITMXTilePropertiesListener pTMXTilePropertyListener) {
final TMXTiledMap tmxTiledMap = this.mTMXTiledMap;
final int tilesHorizontal = this.mTileColumns;
final int column = this.mTilesAdded % tilesHorizontal;
final int row = this.mTilesAdded / tilesHorizontal;
final TMXTile[][] tmxTiles = this.mTMXTiles;
final TextureRegion tmxTileTextureRegion;
if(pGlobalTileID == 0) {
tmxTileTextureRegion = null;
} else {
tmxTileTextureRegion = tmxTiledMap.getTextureRegionFromGlobalTileID(pGlobalTileID);
}
final TMXTile tmxTile = new TMXTile(pGlobalTileID, column, row, this.mTMXTiledMap.getTileWidth(), this.mTMXTiledMap.getTileHeight(), tmxTileTextureRegion);
tmxTiles[row][column] = tmxTile;
if(pGlobalTileID != 0) {
/* Notify the ITMXTilePropertiesListener if it exists. */
if(pTMXTilePropertyListener != null) {
final TMXProperties<TMXTileProperty> tmxTileProperties = tmxTiledMap.getTMXTileProperties(pGlobalTileID);
if(tmxTileProperties != null) {
pTMXTilePropertyListener.onTMXTileWithPropertiesCreated(tmxTiledMap, this, tmxTile, tmxTileProperties);
}
}
}
this.mTilesAdded++;
}
private int readGlobalTileID(final DataInputStream pDataIn) throws IOException {
final int lowestByte = pDataIn.read();
final int secondLowestByte = pDataIn.read();
final int secondHighestByte = pDataIn.read();
final int highestByte = pDataIn.read();
if(lowestByte < 0 || secondLowestByte < 0 || secondHighestByte < 0 || highestByte < 0) {
throw new IllegalArgumentException("Couldn't read global Tile ID.");
}
return lowestByte | secondLowestByte << 8 |secondHighestByte << 16 | highestByte << 24;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| gpl-2.0 |
dschultzca/RomRaider | src/main/java/com/romraider/swing/ECUEditorNumberField.java | 2595 | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2017 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.swing;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DecimalFormat;
import javax.swing.JFormattedTextField;
import com.romraider.util.NumberUtil;
public class ECUEditorNumberField extends JFormattedTextField {
private static final long serialVersionUID = 4756399956045598977L;
static DecimalFormat format = new DecimalFormat("#.####");
public ECUEditorNumberField(){
super(format);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(4);
this.addKeyListener(new KeyListener(){
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
//Get separator for the defined locale
char seperator = NumberUtil.getSeperator();
//Replace , with . or vice versa
if ((c == ',' || c == '.') && seperator != c)
e.setKeyChar(seperator);
ECUEditorNumberField field = ECUEditorNumberField.this;
String textValue = field.getText();
int dotCount = textValue.length() - textValue.replace(seperator + "", "").length();
//Only allow one dot
if(e.getKeyChar() == seperator && (dotCount == 0 || field.getSelectionStart() == 0)) return;
//Only one dash allowed at the start
else if(e.getKeyChar()== '-' && (field.getCaretPosition() == 0 || field.getSelectionStart() == 0)) return;
//Only allow numbers
else if(c >= '0' && c <= '9') return;
//Don't allow if input doesn't meet these rules
else e.consume();
}
@Override
public void keyPressed(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent arg0) {
}
});
}
}
| gpl-2.0 |
samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/messaging/saaj/packaging/mime/internet/HeaderTokenizer.java | 12766 | /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @(#)HeaderTokenizer.java 1.9 02/03/27
*/
package com.sun.xml.internal.messaging.saaj.packaging.mime.internet;
/**
* This class tokenizes RFC822 and MIME headers into the basic
* symbols specified by RFC822 and MIME. <p>
*
* This class handles folded headers (ie headers with embedded
* CRLF SPACE sequences). The folds are removed in the returned
* tokens.
*
* @version 1.9, 02/03/27
* @author John Mani
*/
public class HeaderTokenizer {
/**
* The Token class represents tokens returned by the
* HeaderTokenizer.
*/
public static class Token {
private int type;
private String value;
/**
* Token type indicating an ATOM.
*/
public static final int ATOM = -1;
/**
* Token type indicating a quoted string. The value
* field contains the string without the quotes.
*/
public static final int QUOTEDSTRING = -2;
/**
* Token type indicating a comment. The value field
* contains the comment string without the comment
* start and end symbols.
*/
public static final int COMMENT = -3;
/**
* Token type indicating end of input.
*/
public static final int EOF = -4;
/**
* Constructor.
* @param type Token type
* @param value Token value
*/
public Token(int type, String value) {
this.type = type;
this.value = value;
}
/**
* Return the type of the token. If the token represents a
* delimiter or a control character, the type is that character
* itself, converted to an integer. Otherwise, it's value is
* one of the following:
* <ul>
* <li><code>ATOM</code> A sequence of ASCII characters
* delimited by either SPACE, CTL, "(", <"> or the
* specified SPECIALS
* <li><code>QUOTEDSTRING</code> A sequence of ASCII characters
* within quotes
* <li><code>COMMENT</code> A sequence of ASCII characters
* within "(" and ")".
* <li><code>EOF</code> End of header
* </ul>
*/
public int getType() {
return type;
}
/**
* Returns the value of the token just read. When the current
* token is a quoted string, this field contains the body of the
* string, without the quotes. When the current token is a comment,
* this field contains the body of the comment.
*
* @return token value
*/
public String getValue() {
return value;
}
}
private String string; // the string to be tokenized
private boolean skipComments; // should comments be skipped ?
private String delimiters; // delimiter string
private int currentPos; // current parse position
private int maxPos; // string length
private int nextPos; // track start of next Token for next()
private int peekPos; // track start of next Token for peek()
/**
* RFC822 specials
*/
public final static String RFC822 = "()<>@,;:\\\"\t .[]";
/**
* MIME specials
*/
public final static String MIME = "()<>@,;:\\\"\t []/?=";
// The EOF Token
private final static Token EOFToken = new Token(Token.EOF, null);
/**
* Constructor that takes a rfc822 style header.
*
* @param header The rfc822 header to be tokenized
* @param delimiters Set of delimiter characters
* to be used to delimit ATOMS. These
* are usually <code>RFC822</code> or
* <code>MIME</code>
* @param skipComments If true, comments are skipped and
* not returned as tokens
*/
public HeaderTokenizer(String header, String delimiters,
boolean skipComments) {
string = (header == null) ? "" : header; // paranoia ?!
this.skipComments = skipComments;
this.delimiters = delimiters;
currentPos = nextPos = peekPos = 0;
maxPos = string.length();
}
/**
* Constructor. Comments are ignored and not returned as tokens
*
* @param header The header that is tokenized
* @param delimiters The delimiters to be used
*/
public HeaderTokenizer(String header, String delimiters) {
this(header, delimiters, true);
}
/**
* Constructor. The RFC822 defined delimiters - RFC822 - are
* used to delimit ATOMS. Also comments are skipped and not
* returned as tokens
*/
public HeaderTokenizer(String header) {
this(header, RFC822);
}
/**
* Parses the next token from this String. <p>
*
* Clients sit in a loop calling next() to parse successive
* tokens until an EOF Token is returned.
*
* @return the next Token
* @exception ParseException if the parse fails
*/
public Token next() throws ParseException {
Token tk;
currentPos = nextPos; // setup currentPos
tk = getNext();
nextPos = peekPos = currentPos; // update currentPos and peekPos
return tk;
}
/**
* Peek at the next token, without actually removing the token
* from the parse stream. Invoking this method multiple times
* will return successive tokens, until <code>next()</code> is
* called. <p>
*
* @return the next Token
* @exception ParseException if the parse fails
*/
public Token peek() throws ParseException {
Token tk;
currentPos = peekPos; // setup currentPos
tk = getNext();
peekPos = currentPos; // update peekPos
return tk;
}
/**
* Return the rest of the Header.
*
* @return String rest of header. null is returned if we are
* already at end of header
*/
public String getRemainder() {
return string.substring(nextPos);
}
/*
* Return the next token starting from 'currentPos'. After the
* parse, 'currentPos' is updated to point to the start of the
* next token.
*/
private Token getNext() throws ParseException {
// If we're already at end of string, return EOF
if (currentPos >= maxPos)
return EOFToken;
// Skip white-space, position currentPos beyond the space
if (skipWhiteSpace() == Token.EOF)
return EOFToken;
char c;
int start;
boolean filter = false;
c = string.charAt(currentPos);
// Check or Skip comments and position currentPos
// beyond the comment
while (c == '(') {
// Parsing comment ..
int nesting;
for (start = ++currentPos, nesting = 1;
nesting > 0 && currentPos < maxPos;
currentPos++) {
c = string.charAt(currentPos);
if (c == '\\') { // Escape sequence
currentPos++; // skip the escaped character
filter = true;
} else if (c == '\r')
filter = true;
else if (c == '(')
nesting++;
else if (c == ')')
nesting--;
}
if (nesting != 0)
throw new ParseException("Unbalanced comments");
if (!skipComments) {
// Return the comment, if we are asked to.
// Note that the comment start & end markers are ignored.
String s;
if (filter) // need to go thru the token again.
s = filterToken(string, start, currentPos-1);
else
s = string.substring(start,currentPos-1);
return new Token(Token.COMMENT, s);
}
// Skip any whitespace after the comment.
if (skipWhiteSpace() == Token.EOF)
return EOFToken;
c = string.charAt(currentPos);
}
// Check for quoted-string and position currentPos
// beyond the terminating quote
if (c == '"') {
for (start = ++currentPos; currentPos < maxPos; currentPos++) {
c = string.charAt(currentPos);
if (c == '\\') { // Escape sequence
currentPos++;
filter = true;
} else if (c == '\r')
filter = true;
else if (c == '"') {
currentPos++;
String s;
if (filter)
s = filterToken(string, start, currentPos-1);
else
s = string.substring(start,currentPos-1);
return new Token(Token.QUOTEDSTRING, s);
}
}
throw new ParseException("Unbalanced quoted string");
}
// Check for SPECIAL or CTL
if (c < 040 || c >= 0177 || delimiters.indexOf(c) >= 0) {
currentPos++; // re-position currentPos
char ch[] = new char[1];
ch[0] = c;
return new Token((int)c, new String(ch));
}
// Check for ATOM
for (start = currentPos; currentPos < maxPos; currentPos++) {
c = string.charAt(currentPos);
// ATOM is delimited by either SPACE, CTL, "(", <">
// or the specified SPECIALS
if (c < 040 || c >= 0177 || c == '(' || c == ' ' ||
c == '"' || delimiters.indexOf(c) >= 0)
break;
}
return new Token(Token.ATOM, string.substring(start, currentPos));
}
// Skip SPACE, HT, CR and NL
private int skipWhiteSpace() {
char c;
for (; currentPos < maxPos; currentPos++)
if (((c = string.charAt(currentPos)) != ' ') &&
(c != '\t') && (c != '\r') && (c != '\n'))
return currentPos;
return Token.EOF;
}
/* Process escape sequences and embedded LWSPs from a comment or
* quoted string.
*/
private static String filterToken(String s, int start, int end) {
StringBuffer sb = new StringBuffer();
char c;
boolean gotEscape = false;
boolean gotCR = false;
for (int i = start; i < end; i++) {
c = s.charAt(i);
if (c == '\n' && gotCR) {
// This LF is part of an unescaped
// CRLF sequence (i.e, LWSP). Skip it.
gotCR = false;
continue;
}
gotCR = false;
if (!gotEscape) {
// Previous character was NOT '\'
if (c == '\\') // skip this character
gotEscape = true;
else if (c == '\r') // skip this character
gotCR = true;
else // append this character
sb.append(c);
} else {
// Previous character was '\'. So no need to
// bother with any special processing, just
// append this character
sb.append(c);
gotEscape = false;
}
}
return sb.toString();
}
}
| gpl-2.0 |
dwaybright/StrategicAssaultSimulator | core/src/neuroph_jars/sources/Core/src/main/java/org/neuroph/nnet/ConvolutionalNetwork.java | 2992 | /**
* Copyright 2013 Neuroph Project http://neuroph.sourceforge.net
*
* 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.neuroph.nnet;
import org.neuroph.nnet.learning.ConvolutionalBackpropagation;
import org.neuroph.core.NeuralNetwork;
import org.neuroph.core.Neuron;
import org.neuroph.core.exceptions.VectorSizeMismatchException;
import org.neuroph.nnet.comp.neuron.BiasNeuron;
import org.neuroph.nnet.comp.layer.FeatureMapsLayer;
import org.neuroph.nnet.comp.layer.Layer2D;
/**
* Convolutional neural network with backpropagation algorithm modified for
* convolutional networks.
*
* TODO: provide Hiton, LeCun, AndrewNg implementation specific features
*
* @author Boris Fulurija
* @author Zoran Sevarac
*
* @see ConvolutionalBackpropagation
*/
public class ConvolutionalNetwork extends NeuralNetwork<ConvolutionalBackpropagation> {
private static final long serialVersionUID = -1393907449047650509L;
/**
* Creates empty convolutional network with ConvolutionalBackpropagation learning rule
*/
public ConvolutionalNetwork() {
this.setLearningRule(new ConvolutionalBackpropagation());
}
// This method is not used anywhere...
// public void connectLayers(FeatureMapsLayer fromLayer, FeatureMapsLayer toLayer, int fromFeatureMapIndex, int toFeatureMapIndex) {
// ConvolutionalUtils.connectFeatureMaps(fromLayer, toLayer, fromFeatureMapIndex, toFeatureMapIndex);
// }
/**
* Sets network input, to all feature maps in input layer
* @param inputVector
* @throws VectorSizeMismatchException
*/
@Override
public void setInput(double... inputVector) throws VectorSizeMismatchException {
// if (inputVector.length != getInputNeurons().length) {
// throw new
// VectorSizeMismatchException("Input vector size does not match network input dimension!");
// }
// It would be good if i could do the following:
// int i = 0;
// Layer inputLayer =getLayerAt(0);
// for (Neuron neuron : inputLayer.getNeurons()){
// neuron.setInput(inputVector[i++]);
// }
// But for that getNeuron must be non final method
FeatureMapsLayer inputLayer = (FeatureMapsLayer) getLayerAt(0);
int currentNeuron = 0;
for (int i = 0; i < inputLayer.getNumberOfMaps(); i++) {
Layer2D map = inputLayer.getFeatureMap(i);
for (Neuron neuron : map.getNeurons()) {
if (!(neuron instanceof BiasNeuron))
neuron.setInput(inputVector[currentNeuron++]);
}
}
}
} | gpl-2.0 |