repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
pulkit-mital/Social-Login_Library | pdk/src/androidTest/java/com/pinterest/android/pdk/ApplicationTest.java | 357 | package com.pinterest.android.pdk;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
TheNetStriker/openhab | bundles/action/org.openhab.action.squeezebox/src/main/java/org/openhab/action/squeezebox/internal/SqueezeboxActionService.java | 1712 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* 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.openhab.action.squeezebox.internal;
import org.openhab.core.scriptengine.action.ActionService;
import org.openhab.io.squeezeserver.SqueezeServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class registers an OSGi service for the Squeezebox action.
*
* @author Ben Jones
* @since 1.4.0
*/
public class SqueezeboxActionService implements ActionService {
private static final Logger logger = LoggerFactory.getLogger(SqueezeboxActionService.class);
public void activate() {
logger.debug("Squeezebox action service activated");
}
public void deactivate() {
logger.debug("Squeezebox action service deactivated");
}
public String getActionClassName() {
return Squeezebox.class.getCanonicalName();
}
public Class<?> getActionClass() {
return Squeezebox.class;
}
/**
* Setter for Declarative Services. Adds the SqueezeServer instance.
*
* @param squeezeServer
* Service.
*/
public void setSqueezeServer(SqueezeServer squeezeServer) {
Squeezebox.squeezeServer = squeezeServer;
}
/**
* Unsetter for Declarative Services.
*
* @param squeezeServer
* Service to remove.
*/
public void unsetSqueezeServer(SqueezeServer squeezeServer) {
Squeezebox.squeezeServer = null;
}
}
| epl-1.0 |
computergeek1507/openhab | bundles/binding/org.openhab.binding.insteonplm/src/main/java/org/openhab/binding/insteonplm/internal/driver/TcpIOStream.java | 2290 | /**
* 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.insteonplm.internal.driver;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implements IOStream for the older hubs (pre 2014).
* Also works for serial ports exposed via tcp, eg. ser2net
*
* @author Bernd Pfrommer
* @since 1.7.0
*
*/
public class TcpIOStream extends IOStream {
private static final Logger logger = LoggerFactory.getLogger(TcpIOStream.class);
private String m_host = null;
private int m_port = -1;
private Socket m_socket = null;
/**
* Constructor
*
* @param host host name of hub device
* @param port port to connect to
*/
public TcpIOStream(String host, int port) {
m_host = host;
m_port = port;
}
@Override
public boolean open() {
if (m_host == null || m_port < 0) {
logger.error("tcp connection to hub not properly configured!");
return (false);
}
try {
m_socket = new Socket(m_host, m_port);
m_in = m_socket.getInputStream();
m_out = m_socket.getOutputStream();
} catch (UnknownHostException e) {
logger.error("unknown host name: {}", m_host, e);
return (false);
} catch (IOException e) {
logger.error("cannot open connection to {} port {}: ", m_host, m_port, e);
return (false);
}
return true;
}
@Override
public void close() {
try {
if (m_in != null) {
m_in.close();
}
if (m_out != null) {
m_out.close();
}
if (m_socket != null) {
m_socket.close();
}
} catch (IOException e) {
logger.error("failed to close streams", e);
}
}
}
| epl-1.0 |
sgilda/windup | tooling/api/src/main/java/org/jboss/windup/tooling/ExecutionBuilderSetInput.java | 381 | package org.jboss.windup.tooling;
import java.nio.file.Path;
/**
* Allows setting the input path.
*
* @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a>
*/
public interface ExecutionBuilderSetInput
{
/**
* Sets the input path (application source directory, or application binary file).
*/
ExecutionBuilderSetOutput setInput(Path input);
}
| epl-1.0 |
idserda/openhab | bundles/binding/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/messages/AbstractMessage.java | 911 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* 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.openhab.binding.nest.internal.messages;
import static org.apache.commons.lang.builder.ToStringStyle.SHORT_PREFIX_STYLE;
import org.apache.commons.lang.builder.ToStringBuilder;
/**
* Base class for all messages.
*
* @author John Cocula
* @since 1.7.0
*/
public class AbstractMessage {
@Override
public String toString() {
final ToStringBuilder builder = createToStringBuilder();
return builder.toString();
}
protected final ToStringBuilder createToStringBuilder() {
return new ToStringBuilder(this, SHORT_PREFIX_STYLE);
}
}
| epl-1.0 |
aosm/gcc_os | libjava/javax/swing/table/TableColumnModel.java | 4275 | /* TableColumnModel.java --
Copyright (C) 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing.table;
// Imports
import java.util.Enumeration;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableColumnModelListener;
/**
* TableColumnModel interface
* @author Andrew Selkirk
*/
public interface TableColumnModel {
/**
* addColumn
* @param column TableColumn
*/
public void addColumn(TableColumn column);
/**
* removeColumn
* @param column TableColumn
*/
public void removeColumn(TableColumn column);
/**
* moveColumn
* @param columnIndex Index of column to move
* @param newIndex New index of column
*/
public void moveColumn(int columnIndex, int newIndex);
/**
* setColumnMargin
* @param margin Margin of column
*/
public void setColumnMargin(int margin);
/**
* getColumnCount
* @returns Column count
*/
public int getColumnCount();
/**
* getColumns
* @returns Enumeration of columns
*/
public Enumeration getColumns();
/**
* getColumnIndex
* @param columnIdentifier Column id
*/
public int getColumnIndex(Object columnIdentifier);
/**
* getColumn
* @param columnIndex Index of column
*/
public TableColumn getColumn(int columnIndex);
/**
* getColumnMargin
* @returns Column margin
*/
public int getColumnMargin();
/**
* getColumnIndexAtX
* @returns Column index as position x
*/
public int getColumnIndexAtX(int xPosition);
/**
* getTotalColumnWidth
* @returns Total column width
*/
public int getTotalColumnWidth();
/**
* setColumnSelectionAllowed
* @param value Set column selection
*/
public void setColumnSelectionAllowed(boolean value);
/**
* getColumnSelectionAllowed
* @returns true if column selection allowed, false otherwise
*/
public boolean getColumnSelectionAllowed();
/**
* getSelectedColumns
* @returns Selected columns
*/
public int[] getSelectedColumns();
/**
* getSelectedColumnCount
* @returns Count of selected columns
*/
public int getSelectedColumnCount();
/**
* setSelectionModel
* @param model ListSelectionModel
*/
public void setSelectionModel(ListSelectionModel model);
/**
* getSelectionModel
* @param column TableColumn
*/
public ListSelectionModel getSelectionModel();
/**
* addColumnModelListener
* @param listener TableColumnModelListener
*/
public void addColumnModelListener(TableColumnModelListener listener);
/**
* removeColumnModelListener
* @param listener TableColumnModelListener
*/
public void removeColumnModelListener(TableColumnModelListener listener);
} // TableColumnModel
| gpl-2.0 |
natetrue/ReplicatorG | src/replicatorg/machine/MachineStateChangeEvent.java | 687 | package replicatorg.machine;
public class MachineStateChangeEvent {
private final MachineInterface source;
private final MachineState current;
private final String message;
public MachineStateChangeEvent(MachineInterface machine2, MachineState current) {
this.source = machine2;
this.current = current;
this.message = null;
}
public MachineStateChangeEvent(MachineInterface source, MachineState current,
String message) {
this.source = source;
this.current = current;
this.message = message;
}
public MachineInterface getSource() { return source; }
public MachineState getState() { return current; }
public String getMessage() { return message; }
}
| gpl-2.0 |
xdajog/samsung_sources_i927 | libcore/luni/src/main/java/java/lang/ref/ReferenceQueue.java | 5341 | /*
* 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 java.lang.ref;
/**
* The {@code ReferenceQueue} is the container on which reference objects are
* enqueued when the garbage collector detects the reachability type specified
* for the referent.
*
* @since 1.2
*/
public class ReferenceQueue<T> {
private static final int NANOS_PER_MILLI = 1000000;
private Reference<? extends T> head;
/**
* Constructs a new instance of this class.
*/
public ReferenceQueue() {
}
/**
* Returns the next available reference from the queue, removing it in the
* process. Does not wait for a reference to become available.
*
* @return the next available reference, or {@code null} if no reference is
* immediately available
*/
@SuppressWarnings("unchecked")
public synchronized Reference<? extends T> poll() {
if (head == null) {
return null;
}
Reference<? extends T> ret;
ret = head;
if (head == head.queueNext) {
head = null;
} else {
head = head.queueNext;
}
ret.queueNext = null;
return ret;
}
/**
* Returns the next available reference from the queue, removing it in the
* process. Waits indefinitely for a reference to become available.
*
* @throws InterruptedException if the blocking call was interrupted
*/
public Reference<? extends T> remove() throws InterruptedException {
return remove(0L);
}
/**
* Returns the next available reference from the queue, removing it in the
* process. Waits for a reference to become available or the given timeout
* period to elapse, whichever happens first.
*
* @param timeoutMillis maximum time to spend waiting for a reference object
* to become available. A value of {@code 0} results in the method
* waiting indefinitely.
* @return the next available reference, or {@code null} if no reference
* becomes available within the timeout period
* @throws IllegalArgumentException if {@code timeoutMillis < 0}.
* @throws InterruptedException if the blocking call was interrupted
*/
public synchronized Reference<? extends T> remove(long timeoutMillis)
throws InterruptedException {
if (timeoutMillis < 0) {
throw new IllegalArgumentException("timeout < 0: " + timeoutMillis);
}
if (head != null) {
return poll();
}
// avoid overflow: if total > 292 years, just wait forever
if (timeoutMillis == 0 || (timeoutMillis > Long.MAX_VALUE / NANOS_PER_MILLI)) {
do {
wait(0);
} while (head == null);
return poll();
}
// guaranteed to not overflow
long nanosToWait = timeoutMillis * NANOS_PER_MILLI;
int timeoutNanos = 0;
// wait until notified or the timeout has elapsed
long startTime = System.nanoTime();
while (true) {
wait(timeoutMillis, timeoutNanos);
if (head != null) {
break;
}
long nanosElapsed = System.nanoTime() - startTime;
long nanosRemaining = nanosToWait - nanosElapsed;
if (nanosRemaining <= 0) {
break;
}
timeoutMillis = nanosRemaining / NANOS_PER_MILLI;
timeoutNanos = (int) (nanosRemaining - timeoutMillis * NANOS_PER_MILLI);
}
return poll();
}
/**
* Enqueue the reference object on the receiver.
*
* @param reference
* reference object to be enqueued.
* @return boolean true if reference is enqueued. false if reference failed
* to enqueue.
*/
synchronized void enqueue(Reference<? extends T> reference) {
if (head == null) {
reference.queueNext = reference;
} else {
reference.queueNext = head;
}
head = reference;
notify();
}
/** @hide */
public static Reference unenqueued = null;
static void add(Reference<?> list) {
synchronized (ReferenceQueue.class) {
if (unenqueued == null) {
unenqueued = list;
} else {
Reference<?> next = unenqueued.pendingNext;
unenqueued.pendingNext = list.pendingNext;
list.pendingNext = next;
}
ReferenceQueue.class.notifyAll();
}
}
}
| gpl-2.0 |
Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/flow/LabelFlowContext.java | 2100 | /*******************************************************************************
* Copyright (c) 2000, 2017 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Stephan Herrmann - Contribution for
* bug 345305 - [compiler][null] Compiler misidentifies a case of "variable can only be null"
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.flow;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.codegen.BranchLabel;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
/**
* Reflects the context of code analysis, keeping track of enclosing
* try statements, exception handlers, etc...
*/
public class LabelFlowContext extends SwitchFlowContext {
public char[] labelName;
public LabelFlowContext(FlowContext parent, ASTNode associatedNode, char[] labelName, BranchLabel breakLabel, BlockScope scope) {
super(parent, associatedNode, breakLabel, false, true);
this.labelName = labelName;
checkLabelValidity(scope);
}
void checkLabelValidity(BlockScope scope) {
// check if label was already defined above
FlowContext current = this.getLocalParent();
while (current != null) {
char[] currentLabelName;
if (((currentLabelName = current.labelName()) != null)
&& CharOperation.equals(currentLabelName, this.labelName)) {
scope.problemReporter().alreadyDefinedLabel(this.labelName, this.associatedNode);
}
current = current.getLocalParent();
}
}
@Override
public String individualToString() {
return "Label flow context [label:" + String.valueOf(this.labelName) + "]"; //$NON-NLS-2$ //$NON-NLS-1$
}
@Override
public char[] labelName() {
return this.labelName;
}
}
| gpl-3.0 |
gsys02/user | user-web/src/main/java/sys02/web/util/CorsFilter.java | 991 | package sys02.web.util;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (request.getHeader("Access-Control-Request-Method") != null
&& "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1800");// 30 min
}
filterChain.doFilter(request, response);
}
} | gpl-3.0 |
dkmorb/axoloti | src/main/java/axoloti/realunits/LFOPeriod.java | 2235 | /**
* Copyright (C) 2013, 2014 Johannes Taelman
*
* This file is part of Axoloti.
*
* Axoloti is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* Axoloti 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
* Axoloti. If not, see <http://www.gnu.org/licenses/>.
*/
package axoloti.realunits;
import axoloti.datatypes.Value;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.text.ParseException;
/**
*
* @author Johannes Taelman
*/
public class LFOPeriod implements NativeToReal {
@Override
public String ToReal(Value v) {
double hz = 440.0 * Math.pow(2.0, (v.getDouble() + 64 - 69) / 12.0) / 64;
double t = 1.0 / hz;
if (t > 1) {
return (String.format("%.2f s", t));
} else if (t > 0.1) {
return (String.format("%.1f ms", t * 1000));
} else {
return (String.format("%.2f ms", t * 1000));
}
}
@Override
public double FromReal(String s) throws ParseException {
Pattern pattern = Pattern.compile("(?<num>[\\d\\.\\-\\+]*)\\p{Space}*(?<unit>[mM]?)[sS]");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()) {
double num, mul = 1.0;
try {
num = Float.parseFloat(matcher.group("num"));
} catch (java.lang.NumberFormatException ex) {
throw new ParseException("Not LFOPeriod", 0);
}
String units = matcher.group("unit");
if (units.contains("m") || units.contains("M")) {
mul = 0.001;
}
double hz = 1.0 / (num * mul);
return ((Math.log((hz * 64) / 440.0) / Math.log(2)) * 12.0) - 64 + 69;
}
throw new ParseException("Not LFOPeriod", 0);
}
}
| gpl-3.0 |
OpenGenus/cosmos | code/string_algorithms/src/aho_corasick_algorithm/aho_corasick_algorithm.java | 1895 | import java.util.*;
public class AhoCorasick {
static final int ALPHABET_SIZE = 26;
Node[] nodes;
int nodeCount;
public static class Node {
int parent;
char charFromParent;
int suffLink = -1;
int[] children = new int[ALPHABET_SIZE];
int[] transitions = new int[ALPHABET_SIZE];
boolean leaf;
{
Arrays.fill(children, -1);
Arrays.fill(transitions, -1);
}
}
public AhoCorasick(int maxNodes) {
nodes = new Node[maxNodes];
// create root
nodes[0] = new Node();
nodes[0].suffLink = 0;
nodes[0].parent = -1;
nodeCount = 1;
}
public void addString(String s) {
int cur = 0;
for (char ch : s.toCharArray()) {
int c = ch - 'a';
if (nodes[cur].children[c] == -1) {
nodes[nodeCount] = new Node();
nodes[nodeCount].parent = cur;
nodes[nodeCount].charFromParent = ch;
nodes[cur].children[c] = nodeCount++;
}
cur = nodes[cur].children[c];
}
nodes[cur].leaf = true;
}
public int suffLink(int nodeIndex) {
Node node = nodes[nodeIndex];
if (node.suffLink == -1)
node.suffLink = node.parent == 0 ? 0 : transition(suffLink(node.parent), node.charFromParent);
return node.suffLink;
}
public int transition(int nodeIndex, char ch) {
int c = ch - 'a';
Node node = nodes[nodeIndex];
if (node.transitions[c] == -1)
node.transitions[c] = node.children[c] != -1 ? node.children[c] : (nodeIndex == 0 ? 0 : transition(suffLink(nodeIndex), ch));
return node.transitions[c];
}
public static void main(String[] args) {
AhoCorasick ahoCorasick = new AhoCorasick(1000);
ahoCorasick.addString("bc");
ahoCorasick.addString("abc");
String s = "tabcbc";
int node = 0;
List<Integer> positions = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
node = ahoCorasick.transition(node, s.charAt(i));
if (ahoCorasick.nodes[node].leaf)
positions.add(i);
}
System.out.println(positions);
}
}
| gpl-3.0 |
neonds/eid-dss | eid-dss-document-xml/src/main/java/be/fedict/eid/dss/document/xml/StyleSheetSignatureFacet.java | 4998 | /*
* eID Digital Signature Service Project.
* Copyright (C) 2011 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.eid.dss.document.xml;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.crypto.XMLStructure;
import javax.xml.crypto.dom.DOMStructure;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLObject;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import be.fedict.eid.applet.service.signer.DigestAlgo;
import be.fedict.eid.applet.service.signer.SignatureFacet;
import be.fedict.eid.dss.document.xml.jaxb.stylesheet.ObjectFactory;
import be.fedict.eid.dss.document.xml.jaxb.stylesheet.StyleSheetType;
import be.fedict.eid.dss.spi.DSSDocumentContext;
/**
* XML stylesheet signature facet.
* <p/>
* Can be used to include the XML stylesheet used to visualize the XML document.
*
* @author Frank Cornelis.
*
*/
public class StyleSheetSignatureFacet implements SignatureFacet {
public static final String REFERENCE_TYPE = "be:fedict:eid:dss:stylesheet:1.0";
private final ObjectFactory objectFactory;
private final Marshaller marshaller;
private final DSSDocumentContext documentContext;
private final DigestAlgo digestAlgo;
public StyleSheetSignatureFacet(DSSDocumentContext documentContext,
DigestAlgo digestAlgo) {
this.documentContext = documentContext;
this.digestAlgo = digestAlgo;
this.objectFactory = new ObjectFactory();
try {
JAXBContext jaxbContext = JAXBContext
.newInstance(ObjectFactory.class);
this.marshaller = jaxbContext.createMarshaller();
} catch (JAXBException e) {
throw new RuntimeException("JAXB error: " + e.getMessage(), e);
}
}
@Override
public void preSign(XMLSignatureFactory signatureFactory,
Document document, String signatureId,
List<X509Certificate> signingCertificateChain,
List<Reference> references, List<XMLObject> objects)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
String namespace = document.getDocumentElement().getNamespaceURI();
if (null == namespace) {
return;
}
byte[] stylesheetData = this.documentContext
.getXmlStyleSheet(namespace);
if (null == stylesheetData) {
return;
}
// JAXB element construction
StyleSheetType styleSheet = this.objectFactory.createStyleSheetType();
styleSheet.setValue(stylesheetData);
String styleSheetId = "stylesheet-" + UUID.randomUUID().toString();
styleSheet.setId(styleSheetId);
// marshalling
Node marshallNode = document.createElement("marshall-node");
try {
this.marshaller.marshal(
this.objectFactory.createStyleSheet(styleSheet),
marshallNode);
} catch (JAXBException e) {
throw new RuntimeException("JAXB error: " + e.getMessage(), e);
}
Node styleSheetNode = marshallNode.getFirstChild();
// fix for xmlsec
Element styleSheetElement = (Element) styleSheetNode;
styleSheetElement.setIdAttribute("Id", true);
// ds:Object
List<XMLStructure> styleSheetObjectContent = new LinkedList<XMLStructure>();
styleSheetObjectContent.add(new DOMStructure(styleSheetNode));
XMLObject styleSheetObject = signatureFactory.newXMLObject(
styleSheetObjectContent, null, null, null);
objects.add(styleSheetObject);
// ds:Reference
DigestMethod digestMethod = signatureFactory.newDigestMethod(
this.digestAlgo.getXmlAlgoId(), null);
List<Transform> transforms = new LinkedList<Transform>();
Transform exclusiveTransform = signatureFactory
.newTransform(CanonicalizationMethod.INCLUSIVE,
(TransformParameterSpec) null);
transforms.add(exclusiveTransform);
Reference reference = signatureFactory.newReference("#" + styleSheetId,
digestMethod, transforms, REFERENCE_TYPE, null);
references.add(reference);
}
@Override
public void postSign(Element signatureElement,
List<X509Certificate> signingCertificateChain) {
// empty
}
}
| gpl-3.0 |
davidbreetzke/cilib | library/src/main/java/net/sourceforge/cilib/functions/continuous/dynamic/moo/hef9/HEF9_f2.java | 3928 | /** __ __
* _____ _/ /_/ /_ Computational Intelligence Library (CIlib)
* / ___/ / / / __ \ (c) CIRG @ UP
* / /__/ / / / /_/ / http://cilib.net
* \___/_/_/_/_.___/
*/
package net.sourceforge.cilib.functions.continuous.dynamic.moo.hef9;
import net.sourceforge.cilib.algorithm.AbstractAlgorithm;
import net.sourceforge.cilib.functions.ContinuousFunction;
import net.sourceforge.cilib.problem.FunctionOptimisationProblem;
import net.sourceforge.cilib.type.types.container.Vector;
/**
* This function is the f2 function of the adapted F9 problem defined in the
* following paper: H. Li and Q. Zhang. Multiobjective optimization problems
* with complicated Pareto sets, MOEA/D and NSGA-II, IEEE Transactions on
* Evolutionary Computation, 13(2):284-302, 2009.
*
* The problem has been adapted by Helbig and Engelbrecht to make it a DMOOP.
*
*/
public class HEF9_f2 extends ContinuousFunction {
private static final long serialVersionUID = 6369118486095689078L;
//member
ContinuousFunction hef9_g;
ContinuousFunction hef9_h;
FunctionOptimisationProblem hef9_g_problem;
FunctionOptimisationProblem hef9_h_problem;
//Domain("R(-1, 1)^20")
/**
* Sets the g function with a specified problem.
* @param problem FunctionOptimisationProblem used for the g function.
*/
public void setHEF9_g(FunctionOptimisationProblem problem) {
this.hef9_g_problem = problem;
this.hef9_g = (ContinuousFunction) problem.getFunction();
}
/**
* Returns the problem used to set the g function.
* @return hef9_g_problem FunctionOptimisationProblem used for the g
* function.
*/
public FunctionOptimisationProblem getHEF9_g_problem() {
return this.hef9_g_problem;
}
/**
* Sets the g function that is used in the HEF9 problem without specifying
* the problem.
* @param hef9_g ContinuousFunction used for the g function.
*/
public void setHEF9_g(ContinuousFunction hef9_g) {
this.hef9_g = hef9_g;
}
/**
* Returns the g function that is used in the HEF9 problem.
* @return hef9_g ContinuousFunction used for the g function.
*/
public ContinuousFunction getHEF9_g() {
return this.hef9_g;
}
/**
* Sets the h function with a specified problem.
* @param problem FunctionOptimisationProblem used for the h function.
*/
public void setHEF9_h(FunctionOptimisationProblem problem) {
this.hef9_h_problem = problem;
this.hef9_h = (ContinuousFunction) problem.getFunction();
}
/**
* Returns the problem used to set the h function.
* @return hef9_h_problem FunctionOptimisationProblem used for the h
* function.
*/
public FunctionOptimisationProblem getHEF9_h_problem() {
return this.hef9_h_problem;
}
/**
* Sets the h function that is used in the HEF9 problem without specifying
* the problem.
* @param hef9_h ContinuousFunction used for the h function.
*/
public void setHEF9_h(ContinuousFunction hef9_h) {
this.hef9_h = hef9_h;
}
/**
* Sets the f1 function that is used in the HEF9 problem without specifying
* the problem.
* @return hef9_h ContinuousFunction used for the h function.
*/
public ContinuousFunction getHEF9_h() {
return this.hef9_h;
}
/**
* Evaluates the function. g*h
*/
@Override
public Double f(Vector input) {
int iteration = AbstractAlgorithm.get().getIterations();
return apply(iteration, input);
}
/**
* Evaluates the function for a specific iteration. g*h
*/
public Double apply(int iteration, Vector input) {
double g = ((HEF9_g) this.hef9_g).f(input);
double h = ((HEF9_h) this.hef9_h).apply(iteration, input);
double value = g * h;
return value;
}
}
| gpl-3.0 |
thialfihar/apg | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/operations/DeleteOperation.java | 4199 | /*
* Copyright (C) 2014-2015 Vincent Breitmoser <v.breitmoser@mugenguild.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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.operations;
import android.content.Context;
import org.sufficientlysecure.keychain.operations.results.ConsolidateResult;
import org.sufficientlysecure.keychain.operations.results.DeleteResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogType;
import org.sufficientlysecure.keychain.operations.results.OperationResult.OperationLog;
import org.sufficientlysecure.keychain.pgp.Progressable;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingData;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.ContactSyncAdapterService;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
/** An operation which implements a high level keyring delete operation.
*
* This operation takes a list of masterKeyIds as input, deleting all
* corresponding public keyrings from the database. Secret keys can
* be deleted as well, but only explicitly and individually, not as
* a list.
*
*/
public class DeleteOperation extends BaseOperation {
public DeleteOperation(Context context, ProviderHelper providerHelper, Progressable progressable) {
super(context, providerHelper, progressable);
}
public DeleteResult execute(long[] masterKeyIds, boolean isSecret) {
OperationLog log = new OperationLog();
if (masterKeyIds.length == 0) {
log.add(LogType.MSG_DEL_ERROR_EMPTY, 0);
return new DeleteResult(DeleteResult.RESULT_ERROR, log, 0, 0);
}
if (isSecret && masterKeyIds.length > 1) {
log.add(LogType.MSG_DEL_ERROR_MULTI_SECRET, 0);
return new DeleteResult(DeleteResult.RESULT_ERROR, log, 0, 0);
}
log.add(LogType.MSG_DEL, 0, masterKeyIds.length);
boolean cancelled = false;
int success = 0, fail = 0;
for (long masterKeyId : masterKeyIds) {
if (checkCancelled()) {
cancelled = true;
break;
}
int count = mProviderHelper.getContentResolver().delete(
KeyRingData.buildPublicKeyRingUri(masterKeyId), null, null
);
if (count > 0) {
log.add(LogType.MSG_DEL_KEY, 1, KeyFormattingUtils.beautifyKeyId(masterKeyId));
success += 1;
} else {
log.add(LogType.MSG_DEL_KEY_FAIL, 1, KeyFormattingUtils.beautifyKeyId(masterKeyId));
fail += 1;
}
}
if (isSecret && success > 0) {
log.add(LogType.MSG_DEL_CONSOLIDATE, 1);
ConsolidateResult sub = mProviderHelper.consolidateDatabaseStep1(mProgressable);
log.add(sub, 2);
}
int result = DeleteResult.RESULT_OK;
if (success > 0) {
// make sure new data is synced into contacts
ContactSyncAdapterService.requestSync();
log.add(LogType.MSG_DEL_OK, 0, success);
}
if (fail > 0) {
log.add(LogType.MSG_DEL_FAIL, 0, fail);
result |= DeleteResult.RESULT_WARNINGS;
if (success == 0) {
result |= DeleteResult.RESULT_ERROR;
}
}
if (cancelled) {
log.add(LogType.MSG_OPERATION_CANCELLED, 0);
result |= DeleteResult.RESULT_CANCELLED;
}
return new DeleteResult(result, log, success, fail);
}
}
| gpl-3.0 |
openMF/android-client | mifosng-android/src/main/java/com/mifos/objects/templates/loans/AmortizationTypeOptions.java | 1988 | package com.mifos.objects.templates.loans;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.SerializedName;
/**
* Created by Rajan Maurya on 16/07/16.
*/
public class AmortizationTypeOptions implements Parcelable {
@SerializedName("id")
Integer id;
@SerializedName("code")
String code;
@SerializedName("value")
String value;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "AmortizationTypeOptions{" +
"id=" + id +
", code='" + code + '\'' +
", value='" + value + '\'' +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.code);
dest.writeString(this.value);
}
public AmortizationTypeOptions() {
}
protected AmortizationTypeOptions(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.code = in.readString();
this.value = in.readString();
}
public static final Parcelable.Creator<AmortizationTypeOptions> CREATOR =
new Parcelable.Creator<AmortizationTypeOptions>() {
@Override
public AmortizationTypeOptions createFromParcel(Parcel source) {
return new AmortizationTypeOptions(source);
}
@Override
public AmortizationTypeOptions[] newArray(int size) {
return new AmortizationTypeOptions[size];
}
};
}
| mpl-2.0 |
coderaashir/android-client | mifosng-android/src/main/java/com/mifos/objects/common/InterestType.java | 1662 | package com.mifos.objects.common;
/*
* This project is licensed under the open source MPL V2.
* See https://github.com/openMF/android-client/blob/master/LICENSE.md
*/
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by rajan on 13/3/16.
*/
public class InterestType implements Parcelable {
private Integer id;
private String code;
private String value;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.code);
dest.writeString(this.value);
}
public InterestType() {
}
protected InterestType(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.code = in.readString();
this.value = in.readString();
}
public static final Parcelable.Creator<InterestType> CREATOR = new Parcelable
.Creator<InterestType>() {
@Override
public InterestType createFromParcel(Parcel source) {
return new InterestType(source);
}
@Override
public InterestType[] newArray(int size) {
return new InterestType[size];
}
};
}
| mpl-2.0 |
aihua/opennms | opennms-services/src/main/java/org/opennms/netmgt/rtc/datablock/RTCNodeSvcTime.java | 5178 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2002-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.rtc.datablock;
/**
* This contains a service lost/regained set/pair for the node - i.e each
* service lost time and the corresponding service regained time
*
* @author <A HREF="mailto:sowmya@opennms.org">Sowmya Kumaraswamy </A>
* @author <A HREF="http://www.opennms.org">OpenNMS.org </A>
*/
public class RTCNodeSvcTime {
/**
* Time at which service was lost
*/
private final long m_svcLostTime;
/**
* Time at which service was regained
*/
private long m_svcRegainedTime;
/**
* Creates a time with the lost time
*
* @param lostTime
* the time at which service was lost
*/
public RTCNodeSvcTime(long lostTime) {
this(lostTime, -1);
}
/**
* Creates the service time with both the lost and regained times
*
* @param lostTime
* the time at which service was lost
* @param regainedTime
* the time at which service was regained
*/
public RTCNodeSvcTime(long lostTime, long regainedTime) {
m_svcLostTime = lostTime;
setRegainedTime(regainedTime);
}
/**
* Set the service regained time
*
* @param t
* the time at which service was regained
*/
public void setRegainedTime(long t) {
if (t <= 0) {
m_svcRegainedTime = -1;
} else if (t < m_svcLostTime) {
throw new IllegalArgumentException("Cannot set outage end time to value less than outage start time: " + m_svcRegainedTime + " < " + m_svcLostTime);
} else {
m_svcRegainedTime = t;
}
}
/**
* Return the service lost time
*
* @return the service lost time
*/
public long getLostTime() {
return m_svcLostTime;
}
/**
* Return the service regained time
*
* @return the service regained time
*/
public long getRegainedTime() {
return m_svcRegainedTime;
}
/**
* Return true if this outage has expired.
*
* @return true if this outage has expired
*
* @param startOfRollingWindow Epoch milliseconds that indicates the
* beginning of the rolling outage window.
*/
public boolean hasExpired(long startOfRollingWindow) {
if (m_svcRegainedTime < 0) {
// service currently down, return false
return false;
} else if (m_svcRegainedTime >= startOfRollingWindow) {
// service was regained after the start of the rolling outage window, return false
return false;
} else {
return true;
}
}
/**
* Return the downtime (difference between the regained and lost times) in
* the last rolling window
*
* @return the downtime (difference between the regained and lost times) in
* the last rolling window
* @param curTime a long.
* @param rollingWindow a long.
*/
public long getDownTime(long curTime, long rollingWindow) {
// make sure the lost time is not later than current time!
if (curTime < m_svcLostTime) {
return 0;
}
// the start of the rolling window
long startTime = curTime - rollingWindow;
if (m_svcRegainedTime < 0 || m_svcRegainedTime >= curTime) {
// node yet to regain service
if (m_svcLostTime < startTime) {
// if svclosttime is less than the rolling window
// means its been down throughout
return rollingWindow; // curTime - startTime
} else {
return curTime - m_svcLostTime;
}
} else {
// node has regained service
if (m_svcLostTime < startTime) {
return m_svcRegainedTime - startTime;
} else {
return m_svcRegainedTime - m_svcLostTime;
}
}
}
}
| agpl-3.0 |
cfallin/soot | tests/soot/asm/backend/targets/Bean.java | 286 | package soot.asm.backend.targets;
public class Bean {
private int f;
public int getF() {
return this.f;
}
public void setF(int f) {
this.f = f;
}
public void checkAndSetF(int f) {
if (f >= 0) {
this.f = f;
} else {
throw new IllegalArgumentException();
}
}
}
| lgpl-2.1 |
xasx/wildfly | legacy/jacorb/src/test/java/org/jboss/as/jacorb/JacORBSubsystemTestCase.java | 8813 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jacorb;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
import java.io.IOException;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.model.test.ModelTestUtils;
import org.jboss.as.subsystem.test.AbstractSubsystemBaseTest;
import org.jboss.as.subsystem.test.AdditionalInitialization;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
/**
* <ṕ> JacORB subsystem tests. </ṕ>
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
* @author <a href="sguilhen@jboss.com">Stefan Guilhen</a>
*/
public class JacORBSubsystemTestCase extends AbstractSubsystemBaseTest {
public JacORBSubsystemTestCase() {
super(JacORBExtension.SUBSYSTEM_NAME, new JacORBExtension());
}
@Override
protected String getSubsystemXml() throws IOException {
return readResource("subsystem.xml");
}
@Override
protected String getSubsystemXsdPath() throws Exception {
return "schema/jboss-as-jacorb_2_0.xsd";
}
@Override
protected String[] getSubsystemTemplatePaths() throws IOException {
return new String[] {
"/subsystem-templates/jacorb.xml"
};
}
@Test
@Override
public void testSchemaOfSubsystemTemplates() throws Exception {
super.testSchemaOfSubsystemTemplates();
}
@Override
protected String getSubsystemXml(String configId) throws IOException {
return readResource(configId);
}
@Test
public void testExpressions() throws Exception {
standardSubsystemTest("expressions.xml");
}
@Test
public void testParseEmptySubsystem() throws Exception {
// parse the subsystem xml into operations.
String subsystemXml = "<subsystem xmlns=\"" + JacORBSubsystemParser.Namespace.CURRENT.getUriString() + "\">"
+ "</subsystem>";
List<ModelNode> operations = super.parse(subsystemXml);
// check that we have the expected number of operations.
Assert.assertEquals(1, operations.size());
// check that each operation has the correct content.
ModelNode addSubsystem = operations.get(0);
Assert.assertEquals(ADD, addSubsystem.get(OP).asString());
PathAddress addr = PathAddress.pathAddress(addSubsystem.get(OP_ADDR));
Assert.assertEquals(1, addr.size());
PathElement element = addr.getElement(0);
Assert.assertEquals(SUBSYSTEM, element.getKey());
Assert.assertEquals(JacORBExtension.SUBSYSTEM_NAME, element.getValue());
}
@Test
public void testParseSubsystemWithBadChild() throws Exception {
// try parsing a XML with an invalid element.
String subsystemXml = "<subsystem xmlns=\"" + JacORBSubsystemParser.Namespace.CURRENT.getUriString() + "\">"
+ " <invalid/>" + "</subsystem>";
try {
super.parse(subsystemXml);
Assert.fail("Should not have parsed bad child");
} catch (XMLStreamException expected) {
}
// now try parsing a valid element in an invalid position.
subsystemXml = "<subsystem xmlns=\"urn:jboss:domain:jacorb:1.0\">" + " <orb name=\"JBoss\" print-version=\"off\">"
+ " <poa/>" + " </orb>" + "</subsystem>";
try {
super.parse(subsystemXml);
Assert.fail("Should not have parsed bad child");
} catch (XMLStreamException expected) {
}
}
@Test
public void testParseSubsystemWithBadAttribute() throws Exception {
String subsystemXml = "<subsystem xmlns=\"" + JacORBSubsystemParser.Namespace.CURRENT.getUriString()
+ "\" bad=\"very_bad\">" + "</subsystem>";
try {
super.parse(subsystemXml);
Assert.fail("Should not have parsed bad attribute");
} catch (XMLStreamException expected) {
}
}
// Tests for the version 1.0 of the JacORB subsystem configuration.
@Test
public void testParseSubsystem_1_0() throws Exception {
List<ModelNode> operations = super.parse(ModelTestUtils.readResource(this.getClass(), "subsystem-1.0.xml"));
// check that we have the expected number of operations.
Assert.assertEquals(1, operations.size());
// check that each operation has the correct content.
ModelNode addSubsystem = operations.get(0);
Assert.assertEquals(ADD, addSubsystem.get(OP).asString());
PathAddress addr = PathAddress.pathAddress(addSubsystem.get(OP_ADDR));
Assert.assertEquals(1, addr.size());
PathElement element = addr.getElement(0);
Assert.assertEquals(SUBSYSTEM, element.getKey());
Assert.assertEquals(JacORBExtension.SUBSYSTEM_NAME, element.getValue());
}
@Test
public void testParseEmptySubsystem_1_0() throws Exception {
// parse the subsystem xml into operations.
String subsystemXml = "<subsystem xmlns=\"" + JacORBSubsystemParser.Namespace.JacORB_1_0.getUriString() + "\">"
+ "</subsystem>";
List<ModelNode> operations = super.parse(subsystemXml);
// check that we have the expected number of operations.
Assert.assertEquals(1, operations.size());
// check that each operation has the correct content.
ModelNode addSubsystem = operations.get(0);
Assert.assertEquals(ADD, addSubsystem.get(OP).asString());
PathAddress addr = PathAddress.pathAddress(addSubsystem.get(OP_ADDR));
Assert.assertEquals(1, addr.size());
PathElement element = addr.getElement(0);
Assert.assertEquals(SUBSYSTEM, element.getKey());
Assert.assertEquals(JacORBExtension.SUBSYSTEM_NAME, element.getValue());
}
@Test
public void testParseSubsystemWithBadInitializer_1_0() throws Exception {
String subsystemXml = "<subsystem xmlns=\"" + JacORBSubsystemParser.Namespace.JacORB_1_0.getUriString() + "\">"
+ " <initializers>invalid</initializers>" + "</subsystem>";
try {
super.parse(subsystemXml);
Assert.fail("Should not have parsed bad initializer");
} catch (XMLStreamException expected) {
}
}
@Test
public void testSubsystemWithSecurityIdentity() throws Exception {
super.standardSubsystemTest("subsystem-security-identity.xml");
}
@Test
public void testSubsystemWithSecurityClient() throws Exception {
super.standardSubsystemTest("subsystem-security-client.xml");
}
@Test
public void testSubsystemWithIORSettings() throws Exception {
super.standardSubsystemTest("subsystem-ior-settings.xml");
}
@Override
protected AdditionalInitialization createAdditionalInitialization() {
return AdditionalInitialization.ADMIN_ONLY_HC;
}
// TODO WFCORE-1353 means this doesn't have to always fail now; consider just deleting this
// @Override
// protected void validateDescribeOperation(KernelServices hc, AdditionalInitialization serverInit, ModelNode expectedModel) throws Exception {
// final ModelNode operation = createDescribeOperation();
// final ModelNode result = hc.executeOperation(operation);
// Assert.assertTrue("The subsystem describe operation must fail",
// result.hasDefined(ModelDescriptionConstants.FAILURE_DESCRIPTION));
// }
}
| lgpl-2.1 |
cloudowski/abixen-platform | abixen-platform-core/src/main/java/com/abixen/platform/core/form/PageSearchForm.java | 1038 | /**
* Copyright (c) 2010-present Abixen Systems. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.abixen.platform.core.form;
import com.abixen.platform.common.form.search.SearchField;
import com.abixen.platform.common.form.search.SearchForm;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class PageSearchForm implements SearchForm {
@SearchField
private String name;
@SearchField
private String title;
@SearchField
private String description;
} | lgpl-2.1 |
Alfresco/alfresco-repository | src/main/java/org/alfresco/traitextender/Trait.java | 1410 | /*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.traitextender;
/**
* Markup interface.<br>
* Subinterfaces represent distiguishing features of {@link Extensible} objects
* that are meant to be extended and exposed to the extending code.<br>
* Ideally they would be the only means of interaction between extensions and
* the extended modules.
*
* @author Bogdan Horje
*/
public interface Trait
{
}
| lgpl-3.0 |
j4nnis/bproxy | src/org/parosproxy/paros/extension/option/OptionsCertificatePanel.java | 44646 | /*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* 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
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2011/04/16 i18n
// ZAP: 2012/04/25 Added @Override annotation to the appropriate methods.
// ZAP: 2013/01/23 Clean up of exception handling/logging.
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2013/12/03 Issue 933: Automatically determine install dir
// ZAP: 2014/03/23 Issue 412: Enable unsafe SSL/TLS renegotiation option not saved
// ZAP: 2014/08/14 Issue 1184: Improve support for IBM JDK
// ZAP: 2016/06/28: File chooser for PKCS#12 files now also accepts .pfx files
package org.parosproxy.paros.extension.option;
//TODO: Buttons should be gray
import java.awt.CardLayout;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.security.KeyStoreException;
import java.security.ProviderException;
import java.security.cert.Certificate;
import java.util.Observable;
import java.util.Observer;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.filechooser.FileFilter;
import org.apache.log4j.Logger;
import org.jdesktop.swingx.JXHyperlink;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.OptionsParam;
import org.parosproxy.paros.view.AbstractParamPanel;
import org.zaproxy.zap.utils.ZapTextField;
import ch.csnc.extension.httpclient.PKCS11Configuration;
import ch.csnc.extension.httpclient.PKCS11Configuration.PCKS11ConfigurationBuilder;
import ch.csnc.extension.httpclient.SSLContextManager;
import ch.csnc.extension.ui.AliasTableModel;
import ch.csnc.extension.ui.CertificateView;
import ch.csnc.extension.ui.DriversView;
import ch.csnc.extension.util.DriverConfiguration;
public class OptionsCertificatePanel extends AbstractParamPanel implements Observer{
private static final long serialVersionUID = 4350957038174673492L;
// Maximum number of login attempts per smartcard
private static final int MAX_LOGIN_ATTEMPTS = 3;
private javax.swing.JButton addPkcs11Button;
private javax.swing.JButton addPkcs12Button;
private javax.swing.JScrollPane aliasScrollPane;
private javax.swing.JTable aliasTable;
private javax.swing.JButton browseButton;
private javax.swing.JLabel certificateLabel;
private javax.swing.JPanel certificatePanel;
private ZapTextField certificateTextField;
private javax.swing.JTabbedPane certificatejTabbedPane;
private javax.swing.JPanel cryptoApiPanel;
private javax.swing.JLabel cryptoApiLabel;
private javax.swing.JButton deleteButton;
private javax.swing.JButton driverButton;
private javax.swing.JComboBox<String> driverComboBox;
private javax.swing.JLabel driverLabel;
private javax.swing.JLabel fileLabel;
private ZapTextField fileTextField;
private javax.swing.JList<String> keyStoreList;
private javax.swing.JPanel keyStorePanel;
private javax.swing.JScrollPane keyStoreScrollPane;
private javax.swing.JLabel passwordPkcs11Label;
private javax.swing.JLabel passwordPkcs12Label;
private javax.swing.JPanel pkcs11Panel;
private javax.swing.JPasswordField pkcs11PasswordField;
private javax.swing.JPanel pkcs12Panel;
private javax.swing.JPasswordField pkcs12PasswordField;
private javax.swing.JButton setActiveButton;
private javax.swing.JButton showActiveCertificateButton;
private javax.swing.JButton showAliasButton;
private javax.swing.JLabel textLabel;
private javax.swing.JCheckBox useClientCertificateCheckBox;
private javax.swing.JCheckBox usePkcs11ExperimentalSliSupportCheckBox;
private javax.swing.JCheckBox enableUnsafeSSLRenegotiationCheckBox;
private SSLContextManager contextManager;
private DefaultListModel<String> keyStoreListModel;
private AliasTableModel aliasTableModel;
private DriverConfiguration driverConfig;
// Issue 182
private boolean retry = true;
// Keep track of login attempts on PKCS11 smartcards to avoid blocking the smartcard
private static int login_attempts = 0;
private static final Logger logger = Logger.getLogger(OptionsCertificatePanel.class);
public OptionsCertificatePanel() {
super();
initialize();
}
/**
* This method initializes this
*/
private void initialize() {
contextManager = Model.getSingleton().getOptionsParam().getCertificateParam().getSSLContextManager();
keyStoreListModel = new DefaultListModel<>();
aliasTableModel = new AliasTableModel(contextManager);
this.setLayout(new CardLayout());
this.setName(Constant.messages.getString("options.cert.title.cert"));
JPanel certificatePanel = getPanelCertificate();
this.add(certificatePanel, certificatePanel.getName());
driverConfig = new DriverConfiguration(new File(Constant.getZapInstall(), "xml/drivers.xml"));
updateDriverComboBox();
driverConfig.addObserver(this);
Certificate cert =contextManager.getDefaultCertificate();
if(cert!=null) {
certificateTextField.setText(cert.toString());
}
}
private void updateDriverComboBox() {
driverComboBox.removeAllItems();
for (String name : driverConfig.getNames() ) {
driverComboBox.addItem(name);
}
driverComboBox.repaint();
}
/**
* This method initializes panelCertificate
*
* @return javax.swing.JPanel
*/
private JPanel getPanelCertificate() {
if (certificatePanel == null) {
//**************************************************************************
//begin netbeans code
//**************************************************************************
certificatePanel = new javax.swing.JPanel();
certificatejTabbedPane = new javax.swing.JTabbedPane();
keyStorePanel = new javax.swing.JPanel();
setActiveButton = new javax.swing.JButton();
showAliasButton = new javax.swing.JButton();
aliasScrollPane = new javax.swing.JScrollPane();
aliasTable = new javax.swing.JTable();
deleteButton = new javax.swing.JButton();
keyStoreScrollPane = new javax.swing.JScrollPane();
keyStoreList = new javax.swing.JList<>();
pkcs12Panel = new javax.swing.JPanel();
fileLabel = new javax.swing.JLabel();
fileTextField = new ZapTextField();
browseButton = new javax.swing.JButton();
passwordPkcs12Label = new javax.swing.JLabel();
addPkcs12Button = new javax.swing.JButton();
pkcs12PasswordField = new javax.swing.JPasswordField();
pkcs11Panel = new javax.swing.JPanel();
driverLabel = new javax.swing.JLabel();
driverComboBox = new javax.swing.JComboBox<>();
driverButton = new javax.swing.JButton();
passwordPkcs11Label = new javax.swing.JLabel();
cryptoApiLabel = new javax.swing.JLabel();
addPkcs11Button = new javax.swing.JButton();
pkcs11PasswordField = new javax.swing.JPasswordField();
cryptoApiPanel = new javax.swing.JPanel();
useClientCertificateCheckBox = new javax.swing.JCheckBox();
enableUnsafeSSLRenegotiationCheckBox = new javax.swing.JCheckBox();
textLabel = new javax.swing.JLabel();
certificateLabel = new javax.swing.JLabel();
certificateTextField = new ZapTextField();
showActiveCertificateButton = new javax.swing.JButton();
usePkcs11ExperimentalSliSupportCheckBox = new javax.swing.JCheckBox();
certificatejTabbedPane.setEnabled(false);
setActiveButton.setText(Constant.messages.getString("options.cert.button.setactive"));
setActiveButton.setEnabled(false);
setActiveButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setActiveButtonActionPerformed(evt);
}
});
showAliasButton.setText("->");
showAliasButton.setEnabled(false);
showAliasButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
showAliasButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
showAliasButtonActionPerformed(evt);
}
});
aliasTable.setModel(aliasTableModel);
aliasTable.setTableHeader(null);
aliasScrollPane.setViewportView(aliasTable);
deleteButton.setText(Constant.messages.getString("options.cert.button.delete"));
deleteButton.setEnabled(false);
deleteButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
keyStoreList.setModel(keyStoreListModel);
keyStoreList.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
keyStoreListMouseClicked(evt);
}
});
keyStoreScrollPane.setViewportView(keyStoreList);
javax.swing.GroupLayout keyStorePanelLayout = new javax.swing.GroupLayout(keyStorePanel);
keyStorePanel.setLayout(keyStorePanelLayout);
keyStorePanelLayout.setHorizontalGroup(
keyStorePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, keyStorePanelLayout.createSequentialGroup()
.addGroup(keyStorePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(deleteButton)
.addComponent(keyStoreScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(keyStorePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(keyStorePanelLayout.createSequentialGroup()
.addComponent(setActiveButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
.addComponent(showAliasButton))
.addComponent(aliasScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)))
);
keyStorePanelLayout.setVerticalGroup(
keyStorePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, keyStorePanelLayout.createSequentialGroup()
.addGroup(keyStorePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(aliasScrollPane, 0, 0, Short.MAX_VALUE)
.addComponent(keyStoreScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(keyStorePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(deleteButton)
.addComponent(setActiveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(showAliasButton)))
);
keyStorePanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {deleteButton, setActiveButton, showAliasButton});
certificatejTabbedPane.addTab(Constant.messages.getString("options.cert.tab.keystore"), keyStorePanel);
fileLabel.setText(Constant.messages.getString("options.cert.label.file"));
browseButton.setText(Constant.messages.getString("options.cert.button.browse"));
browseButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseButtonActionPerformed(evt);
}
});
passwordPkcs12Label.setText(Constant.messages.getString("options.cert.label.password"));
addPkcs12Button.setText(Constant.messages.getString("options.cert.button.keystore"));
addPkcs12Button.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
addPkcs12ButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout pkcs12PanelLayout = new javax.swing.GroupLayout(pkcs12Panel);
pkcs12Panel.setLayout(pkcs12PanelLayout);
pkcs12PanelLayout.setHorizontalGroup(
pkcs12PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pkcs12PanelLayout.createSequentialGroup()
.addGroup(pkcs12PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pkcs12PanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(fileTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(browseButton))
.addGroup(pkcs12PanelLayout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(fileLabel))
.addGroup(pkcs12PanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(passwordPkcs12Label))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pkcs12PanelLayout.createSequentialGroup()
.addContainerGap(270, Short.MAX_VALUE)
.addComponent(addPkcs12Button))
.addGroup(pkcs12PanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pkcs12PasswordField, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)))
.addContainerGap())
);
pkcs12PanelLayout.setVerticalGroup(
pkcs12PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pkcs12PanelLayout.createSequentialGroup()
.addComponent(fileLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pkcs12PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(browseButton)
.addComponent(fileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(passwordPkcs12Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pkcs12PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(addPkcs12Button)
.addGap(70, 70, 70))
);
pkcs12PanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {addPkcs12Button, browseButton, fileTextField, pkcs12PasswordField});
certificatejTabbedPane.addTab(Constant.messages.getString("options.cert.tab.pkcs"), pkcs12Panel);
driverLabel.setText(Constant.messages.getString("options.cert.label.driver"));
driverButton.setText("...");
driverButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
driverButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
driverButtonActionPerformed(evt);
}
});
passwordPkcs11Label.setText(Constant.messages.getString("options.cert.label.pincode"));
addPkcs11Button.setText(Constant.messages.getString("options.cert.button.pkcs11"));
addPkcs11Button.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
addPkcs11ButtonActionPerformed(evt);
}
});
usePkcs11ExperimentalSliSupportCheckBox.setText(Constant.messages.getString("certificates.pkcs11.label.experimentalSliSupport"));
usePkcs11ExperimentalSliSupportCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
usePkcs11ExperimentalSliSupportCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
usePkcs11ExperimentalSliSupportCheckBox.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
usePkcs11ExperimentalSliSupportCheckBoxActionPerformed(evt);
}
});
javax.swing.GroupLayout pkcs11PanelLayout = new javax.swing.GroupLayout(pkcs11Panel);
pkcs11Panel.setLayout(pkcs11PanelLayout);
pkcs11PanelLayout.setHorizontalGroup(
pkcs11PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pkcs11PanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pkcs11PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pkcs11PasswordField, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE)
.addComponent(driverLabel)
.addComponent(passwordPkcs11Label)
.addGroup(pkcs11PanelLayout.createSequentialGroup()
.addComponent(driverComboBox, 0, 336, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(driverButton))
.addComponent(usePkcs11ExperimentalSliSupportCheckBox)
.addComponent(addPkcs11Button, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
pkcs11PanelLayout.setVerticalGroup(
pkcs11PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pkcs11PanelLayout.createSequentialGroup()
.addComponent(driverLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pkcs11PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(driverButton)
.addComponent(driverComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(passwordPkcs11Label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pkcs11PasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(usePkcs11ExperimentalSliSupportCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(addPkcs11Button)
.addGap(58, 58, 58))
);
pkcs11PanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {addPkcs11Button, driverButton, driverComboBox, pkcs11PasswordField});
certificatejTabbedPane.addTab(Constant.messages.getString("options.cert.tab.pkcs11"), pkcs11Panel);
javax.swing.GroupLayout cryptoApiPanelLayout = new javax.swing.GroupLayout(cryptoApiPanel);
cryptoApiPanel.setLayout(cryptoApiPanelLayout);
cryptoApiLabel.setText(Constant.messages.getString("options.cert.error.crypto"));
cryptoApiPanelLayout.setHorizontalGroup(
cryptoApiPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 389, Short.MAX_VALUE)
.addComponent(cryptoApiLabel)
);
cryptoApiPanelLayout.setVerticalGroup(
cryptoApiPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 124, Short.MAX_VALUE)
.addComponent(cryptoApiLabel)
);
certificatejTabbedPane.addTab(Constant.messages.getString("options.cert.tab.cryptoapi"), cryptoApiPanel);
useClientCertificateCheckBox.setText(Constant.messages.getString("options.cert.label.useclientcert"));
useClientCertificateCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
useClientCertificateCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
useClientCertificateCheckBox.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
useClientCertificateCheckBoxActionPerformed(evt);
}
});
enableUnsafeSSLRenegotiationCheckBox.setText(Constant.messages.getString("options.cert.label.enableunsafesslrenegotiation"));
enableUnsafeSSLRenegotiationCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
enableUnsafeSSLRenegotiationCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
enableUnsafeSSLRenegotiationCheckBox.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
enableUnsafeSSLRenegotiationCheckBoxActionPerformed(evt);
}
});
textLabel.setText(Constant.messages.getString("options.cert.label.addkeystore"));
certificateLabel.setText(Constant.messages.getString("options.cert.label.activecerts"));
certificateTextField.setEnabled(false);
showActiveCertificateButton.setText("->");
showActiveCertificateButton.setActionCommand(">");
showActiveCertificateButton.setEnabled(false);
showActiveCertificateButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
showActiveCertificateButton.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
showActiveCertificateButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout certificatePanelLayout = new javax.swing.GroupLayout(certificatePanel);
certificatePanel.setLayout(certificatePanelLayout);
certificatePanelLayout.setHorizontalGroup(
certificatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(certificatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(certificatePanelLayout.createSequentialGroup()
.addComponent(textLabel, 0, 0, Short.MAX_VALUE)
.addContainerGap())
.addGroup(certificatePanelLayout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(certificatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(certificatejTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
.addGroup(certificatePanelLayout.createSequentialGroup()
.addGroup(certificatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(enableUnsafeSSLRenegotiationCheckBox)
.addComponent(useClientCertificateCheckBox)
.addComponent(certificateLabel)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, certificatePanelLayout.createSequentialGroup()
.addComponent(certificateTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(showActiveCertificateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addContainerGap()))))
);
certificatePanelLayout.setVerticalGroup(
certificatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(certificatePanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(textLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(enableUnsafeSSLRenegotiationCheckBox)
.addComponent(useClientCertificateCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(certificatejTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(certificateLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(certificatePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(certificateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(showActiveCertificateButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
certificatePanelLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {certificateTextField, showActiveCertificateButton});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(certificatePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(certificatePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
//**************************************************************************
//end netbeans code
//**************************************************************************
}
return certificatePanel;
}
private void keyStoreListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_keyStoreListMouseClicked
int keystore = keyStoreList.getSelectedIndex();
try {
aliasTableModel.setKeystore(keystore);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"), e.toString()},
Constant.messages.getString("options.cert.error.accesskeystore"), JOptionPane.ERROR_MESSAGE);
logger.error(e.getMessage(), e);
}
}//GEN-LAST:event_keyStoreListMouseClicked
private void showActiveCertificateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showActiveCertificateButtonActionPerformed
Certificate cert = contextManager.getDefaultCertificate();
if(cert!=null) {
showCertificate(cert);
}
}//GEN-LAST:event_showActiveCertificateButtonActionPerformed
private void addPkcs11ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPkcs11ButtonActionPerformed
String name = null;
try {
final int indexSelectedDriver = driverComboBox.getSelectedIndex();
name = driverConfig.getNames().get(indexSelectedDriver);
if (name.equals("")) {
return;
}
String library = driverConfig.getPaths().get(indexSelectedDriver);
if (library.equals("")) {
return;
}
int slot = driverConfig.getSlots().get(indexSelectedDriver).intValue();
if (slot < 0) {
return;
}
int slotListIndex = driverConfig.getSlotIndexes().get(indexSelectedDriver).intValue();
if (slotListIndex < 0) {
return;
}
String kspass = new String(pkcs11PasswordField.getPassword());
if (kspass.equals("")){
kspass = null;
}
PCKS11ConfigurationBuilder confBuilder = PKCS11Configuration.builder();
confBuilder.setName(name).setLibrary(library);
if (usePkcs11ExperimentalSliSupportCheckBox.isSelected()) {
confBuilder.setSlotListIndex(slotListIndex);
} else {
confBuilder.setSlotId(slot);
}
int ksIndex = contextManager.initPKCS11(confBuilder.build(), kspass);
if (ksIndex == -1) {
logger.error("The required PKCS#11 provider is not available ("
+ SSLContextManager.SUN_PKCS11_CANONICAL_CLASS_NAME + " or "
+ SSLContextManager.IBM_PKCS11_CONONICAL_CLASS_NAME + ").");
showErrorMessageSunPkcs11ProviderNotAvailable();
return;
}
// The PCKS11 driver/smartcard was initialized properly: reset login attempts
login_attempts = 0;
keyStoreListModel.insertElementAt(contextManager.getKeyStoreDescription(ksIndex), ksIndex);
// Issue 182
retry = true;
certificatejTabbedPane.setSelectedIndex(0);
driverComboBox.setSelectedIndex(-1);
pkcs11PasswordField.setText("");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof ProviderException) {
if ("Error parsing configuration".equals(e.getCause().getMessage())) {
// There was a problem with the configuration provided:
// - Missing library.
// - Malformed configuration.
// - ...
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from "+name, e.getCause());
} else if ("Initialization failed".equals(e.getCause().getMessage())) {
// The initialisation may fail because of:
// - no smart card reader or smart card detected.
// - smart card is in use by other application.
// - ...
// Issue 182: Try to instantiate the PKCS11 provider twice if there are
// conflicts with other software (eg. Firefox), that is accessing it too.
if (retry) {
// Try two times only
retry = false;
addPkcs11ButtonActionPerformed(evt);
} else {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.pkcs11")},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
// Error message changed to explain that user should try to add it again...
retry = true;
logger.warn("Couldn't add key from "+name, e);
}
} else {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from "+name, e);
}
} else {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.error("Couldn't add key from "+name, e);
}
} catch (java.io.IOException e) {
if (e.getMessage().equals("load failed") && e.getCause().getClass().getName().equals("javax.security.auth.login.FailedLoginException")) {
// Exception due to a failed login attempt: BAD PIN or password
login_attempts++;
String attempts = " ("+login_attempts+"/"+MAX_LOGIN_ATTEMPTS+") ";
if (login_attempts == (MAX_LOGIN_ATTEMPTS-1)) {
// Last attempt before blocking the smartcard
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.wrongpassword"),
Constant.messages.getString("options.cert.error.wrongpasswordlast"), attempts},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password"+attempts+": "+name+" *LAST TRY BEFORE BLOCKING*");
} else {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.wrongpassword"), attempts},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password"+attempts+": "+name);
}
}else{
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from "+name, e);
}
} catch (KeyStoreException e) {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from "+name, e);
} catch (Exception e) {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.error("Couldn't add key from "+name, e);
}
}//GEN-LAST:event_addPkcs11ButtonActionPerformed
private void showErrorMessageSunPkcs11ProviderNotAvailable() {
final String sunReference = Constant.messages.getString("options.cert.error.pkcs11notavailable.sun.hyperlink");
final String ibmReference = Constant.messages.getString("options.cert.error.pkcs11notavailable.ibm.hyperlink");
Object[] hyperlinks = new Object[2];
try {
JXHyperlink hyperlinkLabel = new JXHyperlink();
hyperlinkLabel.setURI(URI.create(sunReference));
hyperlinkLabel.setText(Constant.messages.getString("options.cert.error.pkcs11notavailable.sun.hyperlink.text"));
hyperlinks[0] = hyperlinkLabel;
hyperlinkLabel = new JXHyperlink();
hyperlinkLabel.setURI(URI.create(ibmReference));
hyperlinkLabel.setText(Constant.messages.getString("options.cert.error.pkcs11notavailable.ibm.hyperlink.text"));
hyperlinks[1] = hyperlinkLabel;
} catch (UnsupportedOperationException e) {
// Show plain text instead of a hyperlink if the current platform doesn't support Desktop.
hyperlinks[0] = sunReference;
hyperlinks[1] = ibmReference;
}
JOptionPane.showMessageDialog(null, new Object[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.pkcs11notavailable"), hyperlinks},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
}
private void showGenericErrorMessagePkcs11CouldNotBeAdded() {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error"),
Constant.messages.getString("options.cert.error.password")},
Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
}
private void driverButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_driverButtonActionPerformed
new JDialog( new DriversView(driverConfig) ,true);
}//GEN-LAST:event_driverButtonActionPerformed
private void addPkcs12ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPkcs12ButtonActionPerformed
if (fileTextField.getText().equals("")) {
return;
}
String kspass = new String(pkcs12PasswordField.getPassword());
if (kspass.equals("")){
//pcks#12 file with empty password is not supported by java
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error.pkcs12nopass"),
Constant.messages.getString("options.cert.error.usepassfile")},
Constant.messages.getString("options.cert.error"), JOptionPane.ERROR_MESSAGE);
return;
}
try {
int ksIndex = contextManager.loadPKCS12Certificate(fileTextField.getText(), kspass);
keyStoreListModel.insertElementAt(contextManager.getKeyStoreDescription(ksIndex), ksIndex);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error.accesskeystore"),
Constant.messages.getString("options.cert.error.password")},
Constant.messages.getString("options.cert.error"), JOptionPane.ERROR_MESSAGE);
logger.error(e.getMessage(), e);
return;
}
certificatejTabbedPane.setSelectedIndex(0);
fileTextField.setText("");
pkcs12PasswordField.setText("");
}//GEN-LAST:event_addPkcs12ButtonActionPerformed
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
JFileChooser fc = new JFileChooser();
fc.setFileFilter( new FileFilter()
{
@Override
public String getDescription()
{
return Constant.messages.getString("options.cert.label.client.cert") + " (*.p12, *.pfx)";
}
@Override
public boolean accept(File f) {
return f.isDirectory() ||
f.getName().toLowerCase().endsWith( ".p12" ) ||
f.getName().toLowerCase().endsWith( ".pfx" );
}
} );
int state = fc.showOpenDialog( null );
if ( state == JFileChooser.APPROVE_OPTION )
{
fileTextField.setText(fc.getSelectedFile().toString() );
}
}//GEN-LAST:event_browseButtonActionPerformed
private void showAliasButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showAliasButtonActionPerformed
int keystore = keyStoreList.getSelectedIndex();
if(keystore>=0) {
int alias = aliasTable.getSelectedRow();
Certificate cert = contextManager.getCertificate(keystore, alias);
if (cert != null) {
showCertificate(cert);
}
}
}//GEN-LAST:event_showAliasButtonActionPerformed
/**
* Shows a second {@link JFrame} displaying the content of the certificate
*
* @param cert
*/
private void showCertificate(Certificate cert) {
if (cert != null) {
JFrame frame = new CertificateView(cert.toString());
frame.setVisible(true);
}
}
private void setActiveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setActiveButtonActionPerformed
int ks = keyStoreList.getSelectedIndex();
int alias = aliasTable.getSelectedRow();
if (ks > -1 && alias>-1) {
if (!contextManager.isKeyUnlocked(ks, alias)) {
try {
if(!contextManager.unlockKeyWithDefaultPassword(ks, alias)){
String password = getPassword();
if(!contextManager.unlockKey(ks, alias, password)){
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error.accesskeystore")},
Constant.messages.getString("options.cert.error"), JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error.accesskeystore"), e.toString()},
Constant.messages.getString("options.cert.error"), JOptionPane.ERROR_MESSAGE);
}
}
Certificate cert = contextManager.getCertificate(ks, alias);
try {
contextManager.getFingerPrint(cert);
} catch (KeyStoreException kse) {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.error.fingerprint"), kse.toString()},
Constant.messages.getString("options.cert.error"), JOptionPane.ERROR_MESSAGE);
}
try {
contextManager.setDefaultKey(ks, alias);
OptionsParamCertificate certParam = Model.getSingleton().getOptionsParam().getCertificateParam();
certParam.setActiveCertificate();
} catch (KeyStoreException e) {
logger.error(e.getMessage(), e);
}
certificateTextField.setText(contextManager.getDefaultKey());
}
}//GEN-LAST:event_setActiveButtonActionPerformed
public String getPassword() {
JPasswordField askPasswordField = new JPasswordField();
int result = JOptionPane.showConfirmDialog(this, askPasswordField,
Constant.messages.getString("options.cert.label.enterpassword"), JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
return new String(askPasswordField.getPassword());
} else return null;
}
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
int index = keyStoreList.getSelectedIndex();
if(index>=0) {
boolean isDefaultKeyStore = contextManager.removeKeyStore(index);
if(isDefaultKeyStore) {
certificateTextField.setText("");
}
keyStoreListModel.removeElementAt(keyStoreList.getSelectedIndex());
aliasTableModel.removeKeystore();
}
}//GEN-LAST:event_deleteButtonActionPerformed
private void useClientCertificateCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useClientCertificateCheckBoxActionPerformed
// The enable unsafe SSL renegotiation checkbox is independent of using a client certificate (although commonly related)
// enableUnsafeSSLRenegotiationCheckBox.setEnabled(useClientCertificateCheckBox.isSelected());
//keyStore tab
certificatejTabbedPane.setEnabled(useClientCertificateCheckBox.isSelected() );
keyStoreScrollPane.setEnabled(useClientCertificateCheckBox.isSelected());
keyStoreList.setEnabled(useClientCertificateCheckBox.isSelected());
aliasScrollPane.setEnabled(useClientCertificateCheckBox.isSelected());
aliasTable.setEnabled(useClientCertificateCheckBox.isSelected());
deleteButton.setEnabled(useClientCertificateCheckBox.isSelected() );
setActiveButton.setEnabled(useClientCertificateCheckBox.isSelected() );
showAliasButton.setEnabled(useClientCertificateCheckBox.isSelected() );
//pkcs12 tab
fileTextField.setEnabled(useClientCertificateCheckBox.isSelected() );
browseButton.setEnabled(useClientCertificateCheckBox.isSelected() );
pkcs12PasswordField.setEnabled(useClientCertificateCheckBox.isSelected() );
addPkcs12Button.setEnabled(useClientCertificateCheckBox.isSelected() );
//pkcs11 tab
driverComboBox.setEnabled(useClientCertificateCheckBox.isSelected() );
driverButton.setEnabled(useClientCertificateCheckBox.isSelected() );
pkcs11PasswordField.setEnabled(useClientCertificateCheckBox.isSelected() );
addPkcs11Button.setEnabled(useClientCertificateCheckBox.isSelected() );
usePkcs11ExperimentalSliSupportCheckBox.setEnabled(useClientCertificateCheckBox.isSelected());
usePkcs11ExperimentalSliSupportCheckBox.setSelected(Model.getSingleton().getOptionsParam().getExperimentalFeaturesParam().isExerimentalSliSupportEnabled());
//actual certificate fields
certificateTextField.setEnabled(useClientCertificateCheckBox.isSelected() );
showActiveCertificateButton.setEnabled(useClientCertificateCheckBox.isSelected() );
}//GEN-LAST:event_useClientCertificateCheckBoxActionPerformed
// Issue 90: Add GUI support for unsecure (unsafe) SSL/TLS renegotiation
private void enableUnsafeSSLRenegotiationCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
boolean enabled = enableUnsafeSSLRenegotiationCheckBox.isSelected();
if (enabled) {
JOptionPane.showMessageDialog(null, new String[] {
Constant.messages.getString("options.cert.label.enableunsafesslrenegotiationwarning")},
Constant.messages.getString("options.cert.label.enableunsafesslrenegotiation"), JOptionPane.INFORMATION_MESSAGE);
}
}
private void usePkcs11ExperimentalSliSupportCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {
Model.getSingleton().getOptionsParam().getExperimentalFeaturesParam().setSlotListIndexSupport(usePkcs11ExperimentalSliSupportCheckBox.isSelected());
}
// TODO remove
private OptionsCertificatePanel getContentPane() {
return this;
}
@Override
public void initParam(Object obj) {
OptionsParam options = (OptionsParam) obj;
OptionsParamCertificate certParam = options.getCertificateParam();
useClientCertificateCheckBox.setSelected(certParam.isUseClientCert());
//getBtnLocation().setEnabled(getChkUseClientCertificate().isSelected());
//getTxtLocation().setText(options.getCertificateParam().getClientCertLocation());
enableUnsafeSSLRenegotiationCheckBox.setSelected(certParam.isAllowUnsafeSslRenegotiation());
}
@Override
public void validateParam(Object obj) {
// no validation needed
}
@Override
public void saveParam (Object obj) throws Exception {
OptionsParam options = (OptionsParam) obj;
OptionsParamCertificate certParam = options.getCertificateParam();
certParam.setEnableCertificate(useClientCertificateCheckBox.isSelected());
certParam.setAllowUnsafeSslRenegotiation(enableUnsafeSSLRenegotiationCheckBox.isSelected());
}
@Override
public void update(Observable arg0, Object arg1) {
updateDriverComboBox();
}
@Override
public String getHelpIndex() {
// ZAP: added help index
return "ui.dialogs.options.certificate";
}
} // @jve:decl-index=0:visual-constraint="10,10"
| apache-2.0 |
treasure-data/presto | presto-main/src/test/java/io/prestosql/sql/query/TestCorrelatedJoin.java | 1334 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.sql.query;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TestCorrelatedJoin
{
private QueryAssertions assertions;
@BeforeClass
public void init()
{
assertions = new QueryAssertions();
}
@AfterClass(alwaysRun = true)
public void teardown()
{
assertions.close();
assertions = null;
}
@Test
public void testJoinInCorrelatedJoinInput()
{
assertThat(assertions.query(
"SELECT * FROM (VALUES 1) t1(a) JOIN (VALUES 2) t2(b) ON a < b, LATERAL (VALUES 3)"))
.matches("VALUES (1, 2, 3)");
}
}
| apache-2.0 |
arenadata/ambari | contrib/views/files/src/main/java/org/apache/ambari/view/filebrowser/HelpService.java | 2780 | /**
* 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.ambari.view.filebrowser;
import org.apache.ambari.view.ViewContext;
import org.apache.ambari.view.commons.hdfs.HdfsService;
import org.json.simple.JSONObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;
/**
* Help service
*/
public class HelpService extends HdfsService {
/**
* Constructor
* @param context View Context instance
*/
public HelpService(ViewContext context) {
super(context);
}
/**
* @param context
* @param viewConfigs : extra properties that needs to be included into configs
*/
public HelpService(ViewContext context, Map<String, String> viewConfigs) {
super(context, viewConfigs);
}
/**
* Version
* @return version
*/
@GET
@Path("/version")
@Produces(MediaType.TEXT_PLAIN)
public Response version() {
return Response.ok("0.0.1-SNAPSHOT").build();
}
/**
* Description
* @return description
*/
@GET
@Path("/description")
@Produces(MediaType.TEXT_PLAIN)
public Response description() {
return Response.ok("Application to work with HDFS").build();
}
/**
* Filesystem configuration
* @return filesystem configuration
*/
@GET
@Path("/filesystem")
@Produces(MediaType.TEXT_PLAIN)
public Response filesystem() {
return Response.ok(
context.getProperties().get("webhdfs.url")).build();
}
/**
* HDFS Status
* @return status
*/
@GET
@Path("/hdfsStatus")
@Produces(MediaType.APPLICATION_JSON)
public Response hdfsStatus(){
HdfsService.hdfsSmokeTest(context);
return getOKResponse();
}
private Response getOKResponse() {
JSONObject response = new JSONObject();
response.put("message", "OK");
response.put("trace", null);
response.put("status", "200");
return Response.ok().entity(response).type(MediaType.APPLICATION_JSON).build();
}
}
| apache-2.0 |
drpngx/tensorflow | tensorflow/java/src/main/java/org/tensorflow/op/core/Gradients.java | 5216 | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package org.tensorflow.op.core;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.tensorflow.Operand;
import org.tensorflow.Output;
import org.tensorflow.op.Op;
import org.tensorflow.op.Operands;
import org.tensorflow.op.Scope;
import org.tensorflow.op.annotation.Operator;
/**
* Adds operations to compute the partial derivatives of sum of {@code y}s w.r.t {@code x}s,
* i.e., {@code d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2...}
* <p>
* If {@code Options.dx()} values are set, they are as the initial symbolic partial derivatives of some loss
* function {@code L} w.r.t. {@code y}. {@code Options.dx()} must have the size of {@code y}.
* <p>
* If {@code Options.dx()} is not set, the implementation will use dx of {@code OnesLike} for all
* shapes in {@code y}.
* <p>
* The partial derivatives are returned in output {@code dy}, with the size of {@code x}.
* <p>
* Example of usage:
* <pre>{@code
* Gradients gradients = Gradients.create(scope, Arrays.asList(loss), Arrays.asList(w, b));
*
* Constant<Float> alpha = ops.constant(1.0f, Float.class);
* ApplyGradientDescent.create(scope, w, alpha, gradients.<Float>dy(0));
* ApplyGradientDescent.create(scope, b, alpha, gradients.<Float>dy(1));
* }</pre>
*/
@Operator
public class Gradients implements Op, Iterable<Operand<?>> {
/**
* Optional attributes for {@link Gradients}
*/
public static class Options {
/**
* @param dx partial derivatives of some loss function {@code L} w.r.t. {@code y}
* @return this option builder
*/
public Options dx(Iterable<Operand<?>> dx) {
this.dx = dx;
return this;
}
private Iterable<Operand<?>> dx;
private Options() {
}
}
/**
* Adds gradients computation ops to the graph according to scope.
*
* @param scope current graph scope
* @param y outputs of the function to derive
* @param x inputs of the function for which partial derivatives are computed
* @param options carries optional attributes values
* @return a new instance of {@code Gradients}
*/
public static Gradients create(Scope scope, Iterable<Operand<?>> y, Iterable<Operand<?>> x, Options... options) {
Output<?>[] dx = null;
if (options != null) {
for (Options opts : options) {
if (opts.dx != null) {
dx = Operands.asOutputs(opts.dx);
}
}
}
Output<?>[] gradOutputs = scope.graph().addGradients(Operands.asOutputs(y), Operands.asOutputs(x), dx);
return new Gradients(Arrays.asList(gradOutputs));
}
/**
* Adds gradients computation ops to the graph according to scope.
*
* This is a simplified version of {@link #create(Scope, Iterable, Iterable, Options...)} where {@code y} is
* a single output.
*
* @param scope current graph scope
* @param y output of the function to derive
* @param x inputs of the function for which partial derivatives are computed
* @param options carries optional attributes values
* @return a new instance of {@code Gradients}
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static Gradients create(Scope scope, Operand<?> y, Iterable<Operand<?>> x, Options... options) {
return create(scope, (Iterable) Arrays.asList(y), x, options);
}
/**
* @param dx partial derivatives of some loss function {@code L} w.r.t. {@code y}
* @return builder to add more options to this operation
*/
public Options dx(Iterable<Operand<?>> dx) {
return new Options().dx(dx);
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Iterator<Operand<?>> iterator() {
return (Iterator) dy.iterator();
}
/**
* Partial derivatives of {@code y}s w.r.t. {@code x}s, with the size of {@code x}
*/
public List<Output<?>> dy() {
return dy;
}
/**
* Returns a symbolic handle to one of the gradient operation output
* <p>
* Warning: Does not check that the type of the tensor matches T. It is recommended to call
* this method with an explicit type parameter rather than letting it be inferred, e.g. {@code
* gradients.<Integer>dy(0)}
*
* @param <T> The expected element type of the tensors produced by this output.
* @param index The index of the output among the gradients added by this operation
*/
@SuppressWarnings("unchecked")
public <T> Output<T> dy(int index) {
return (Output<T>) dy.get(index);
}
private List<Output<?>> dy;
private Gradients(List<Output<?>> dy) {
this.dy = dy;
}
}
| apache-2.0 |
davidpaniz/gocd-oauth-login | src/main/java/com/tw/go/plugin/util/FieldValidator.java | 154 | package com.tw.go.plugin.util;
import java.util.Map;
public interface FieldValidator {
public void validate(Map<String, Object> fieldValidation);
}
| apache-2.0 |
liveqmock/platform-tools-idea | platform/indexing-impl/src/com/intellij/util/indexing/AdditionalIndexableFileSet.java | 3187 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.intellij.util.indexing;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
/**
* @author peter
*/
public class AdditionalIndexableFileSet implements IndexableFileSet {
private volatile Set<VirtualFile> cachedFiles;
private volatile Set<VirtualFile> cachedDirectories;
private volatile IndexedRootsProvider[] myExtensions;
public AdditionalIndexableFileSet(IndexedRootsProvider... extensions) {
myExtensions = extensions;
}
private Set<VirtualFile> getDirectories() {
Set<VirtualFile> directories = cachedDirectories;
if (directories == null || filesInvalidated(directories) || filesInvalidated(cachedFiles)) {
directories = collectFilesAndDirectories();
}
return directories;
}
private THashSet<VirtualFile> collectFilesAndDirectories() {
THashSet<VirtualFile> files = new THashSet<VirtualFile>();
THashSet<VirtualFile> directories = new THashSet<VirtualFile>();
if (myExtensions == null) {
myExtensions = Extensions.getExtensions(IndexedRootsProvider.EP_NAME);
}
for (IndexedRootsProvider provider : myExtensions) {
for(VirtualFile file:IndexableSetContributor.getRootsToIndex(provider)) {
(file.isDirectory() ? directories:files).add(file);
}
}
cachedFiles = files;
cachedDirectories = directories;
return directories;
}
public static boolean filesInvalidated(Set<VirtualFile> files) {
for (VirtualFile file : files) {
if (!file.isValid()) {
return true;
}
}
return false;
}
public AdditionalIndexableFileSet() {
}
@Override
public boolean isInSet(@NotNull VirtualFile file) {
for (final VirtualFile root : getDirectories()) {
if (VfsUtilCore.isAncestor(root, file, false)) {
return true;
}
}
return cachedFiles.contains(file);
}
@Override
public void iterateIndexableFilesIn(@NotNull VirtualFile file, @NotNull final ContentIterator iterator) {
VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() {
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (!isInSet(file)) {
return false;
}
if (!file.isDirectory()) {
iterator.processFile(file);
}
return true;
}
});
}
}
| apache-2.0 |
nelsonsilva/wave-protocol | src/org/waveprotocol/wave/model/document/operation/NindoValidator.java | 5948 | /**
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.model.document.operation;
import static org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema.NO_SCHEMA_CONSTRAINTS;
import org.waveprotocol.wave.model.document.indexed.IndexedDocument;
import org.waveprotocol.wave.model.document.operation.Nindo.NindoCursor;
import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.ValidationResult;
import org.waveprotocol.wave.model.document.operation.automaton.DocOpAutomaton.ViolationCollector;
import org.waveprotocol.wave.model.document.operation.automaton.DocumentSchema;
import org.waveprotocol.wave.model.document.raw.impl.Element;
import org.waveprotocol.wave.model.document.raw.impl.Node;
import org.waveprotocol.wave.model.document.raw.impl.Text;
import org.waveprotocol.wave.model.document.util.DocProviders;
import org.waveprotocol.wave.model.document.util.EmptyDocument;
import org.waveprotocol.wave.model.util.Preconditions;
import java.util.Map;
/**
* Validates an operation against a document.
*
* @author ohler@google.com (Christian Ohler)
*/
public final class NindoValidator {
private NindoValidator() {}
private static IndexedDocument<Node, Element, Text> getEmptyDocument() {
return DocProviders.POJO.build(EmptyDocument.EMPTY_DOCUMENT, NO_SCHEMA_CONSTRAINTS);
}
/**
* Returns whether m is a well-formed document initialization and satisfies
* the given schema constraints.
*/
public static ViolationCollector validate(Nindo m, DocumentSchema s) {
return validate(getEmptyDocument(), m, s);
}
private static final class IllFormed extends RuntimeException {}
/**
* Returns whether m is well-formed, applies to doc, and preserves the given
* schema constraints. Will not modify doc.
*/
public static <N, E extends N, T extends N> ViolationCollector validate(
IndexedDocument<N, E, T> doc,
Nindo m, DocumentSchema schema) {
Preconditions.checkNotNull(schema, "Schema constraints required, if not, " +
"use DocumentSchema.NO_SCHEMA_CONSTRAINTS");
final NindoAutomaton<N, E, T> a = new NindoAutomaton<N, E, T>(schema, doc);
final ViolationCollector v = new ViolationCollector();
try {
m.apply(new NindoCursor() {
@Override
public void begin() {
// Not checking begin and finish for now since they should go away.
}
@Override
public void characters(String s) {
if (a.checkCharacters(s, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doCharacters(s);
}
@Override
public void deleteCharacters(int n) {
if (a.checkDeleteCharacters(n, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doDeleteCharacters(n);
}
@Override
public void deleteElementEnd() {
if (a.checkDeleteElementEnd(v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doDeleteElementEnd();
}
@Override
public void deleteElementStart() {
if (a.checkDeleteElementStart(v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doDeleteElementStart();
}
@Override
public void elementEnd() {
if (a.checkElementEnd(v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doElementEnd();
}
@Override
public void elementStart(String tagName, Attributes attributes) {
if (a.checkElementStart(tagName, attributes, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doElementStart(tagName, attributes);
}
@Override
public void endAnnotation(String key) {
if (a.checkEndAnnotation(key, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doEndAnnotation(key);
}
@Override
public void finish() {
// Not checking begin and finish for now since they should go away.
}
@Override
public void replaceAttributes(Attributes attributes) {
if (a.checkSetAttributes(attributes, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doSetAttributes(attributes);
}
@Override
public void skip(int n) {
if (a.checkSkip(n, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doSkip(n);
}
@Override
public void startAnnotation(String key, String value) {
if (a.checkStartAnnotation(key, value, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doStartAnnotation(key, value);
}
@Override
public void updateAttributes(Map<String, String> attributes) {
if (a.checkUpdateAttributes(attributes, v) == ValidationResult.ILL_FORMED) {
throw new IllFormed();
}
a.doUpdateAttributes(attributes);
}
});
} catch (IllFormed e) {
return v;
}
if (a.checkFinish(v) == ValidationResult.ILL_FORMED) {
return v;
}
a.doFinish();
return v;
}
}
| apache-2.0 |
mproch/apache-ode | bpel-runtime/src/main/java/org/apache/ode/bpel/intercept/FaultMessageExchangeException.java | 1644 | /*
* 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.ode.bpel.intercept;
import javax.xml.namespace.QName;
import org.apache.ode.bpel.iapi.Message;
/**
* Exception thrown by {@link org.apache.ode.bpel.intercept.MessageExchangeInterceptor}
* implementations that is used to indicate that the processing of the exchange should
* be aborted with a fault.
* @author Maciej Szefler
*/
public final class FaultMessageExchangeException extends AbortMessageExchangeException {
private static final long serialVersionUID = 1L;
private QName _faultName;
private Message _faultData;
public FaultMessageExchangeException(String errmsg, QName faultName, Message faultData) {
super(errmsg);
_faultName = faultName;
_faultData = faultData;
}
public QName getFaultName() {
return _faultName;
}
public Message getFaultData() {
return _faultData;
}
}
| apache-2.0 |
hgschmie/presto | presto-main/src/main/java/io/prestosql/cost/PlanNodeStatsEstimateMath.java | 10505 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.cost;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.Double.NaN;
import static java.lang.Double.isNaN;
import static java.lang.Double.max;
import static java.lang.Double.min;
import static java.util.stream.Stream.concat;
public final class PlanNodeStatsEstimateMath
{
private PlanNodeStatsEstimateMath() {}
/**
* Subtracts subset stats from supersets stats.
* It is assumed that each NDV from subset has a matching NDV in superset.
*/
public static PlanNodeStatsEstimate subtractSubsetStats(PlanNodeStatsEstimate superset, PlanNodeStatsEstimate subset)
{
if (superset.isOutputRowCountUnknown() || subset.isOutputRowCountUnknown()) {
return PlanNodeStatsEstimate.unknown();
}
double supersetRowCount = superset.getOutputRowCount();
double subsetRowCount = subset.getOutputRowCount();
double outputRowCount = max(supersetRowCount - subsetRowCount, 0);
// everything will be filtered out after applying negation
if (outputRowCount == 0) {
return createZeroStats(superset);
}
PlanNodeStatsEstimate.Builder result = PlanNodeStatsEstimate.builder();
result.setOutputRowCount(outputRowCount);
superset.getSymbolsWithKnownStatistics().forEach(symbol -> {
SymbolStatsEstimate supersetSymbolStats = superset.getSymbolStatistics(symbol);
SymbolStatsEstimate subsetSymbolStats = subset.getSymbolStatistics(symbol);
SymbolStatsEstimate.Builder newSymbolStats = SymbolStatsEstimate.builder();
// for simplicity keep the average row size the same as in the input
// in most cases the average row size doesn't change after applying filters
newSymbolStats.setAverageRowSize(supersetSymbolStats.getAverageRowSize());
// nullsCount
double supersetNullsCount = supersetSymbolStats.getNullsFraction() * supersetRowCount;
double subsetNullsCount = subsetSymbolStats.getNullsFraction() * subsetRowCount;
double newNullsCount = max(supersetNullsCount - subsetNullsCount, 0);
newSymbolStats.setNullsFraction(min(newNullsCount, outputRowCount) / outputRowCount);
// distinctValuesCount
double supersetDistinctValues = supersetSymbolStats.getDistinctValuesCount();
double subsetDistinctValues = subsetSymbolStats.getDistinctValuesCount();
double newDistinctValuesCount;
if (isNaN(supersetDistinctValues) || isNaN(subsetDistinctValues)) {
newDistinctValuesCount = NaN;
}
else if (supersetDistinctValues == 0) {
newDistinctValuesCount = 0;
}
else if (subsetDistinctValues == 0) {
newDistinctValuesCount = supersetDistinctValues;
}
else {
double supersetNonNullsCount = supersetRowCount - supersetNullsCount;
double subsetNonNullsCount = subsetRowCount - subsetNullsCount;
double supersetValuesPerDistinctValue = supersetNonNullsCount / supersetDistinctValues;
double subsetValuesPerDistinctValue = subsetNonNullsCount / subsetDistinctValues;
if (supersetValuesPerDistinctValue <= subsetValuesPerDistinctValue) {
newDistinctValuesCount = max(supersetDistinctValues - subsetDistinctValues, 0);
}
else {
newDistinctValuesCount = supersetDistinctValues;
}
}
newSymbolStats.setDistinctValuesCount(newDistinctValuesCount);
// range
newSymbolStats.setLowValue(supersetSymbolStats.getLowValue());
newSymbolStats.setHighValue(supersetSymbolStats.getHighValue());
result.addSymbolStatistics(symbol, newSymbolStats.build());
});
return result.build();
}
public static PlanNodeStatsEstimate capStats(PlanNodeStatsEstimate stats, PlanNodeStatsEstimate cap)
{
if (stats.isOutputRowCountUnknown() || cap.isOutputRowCountUnknown()) {
return PlanNodeStatsEstimate.unknown();
}
PlanNodeStatsEstimate.Builder result = PlanNodeStatsEstimate.builder();
double cappedRowCount = min(stats.getOutputRowCount(), cap.getOutputRowCount());
result.setOutputRowCount(cappedRowCount);
stats.getSymbolsWithKnownStatistics().forEach(symbol -> {
SymbolStatsEstimate symbolStats = stats.getSymbolStatistics(symbol);
SymbolStatsEstimate capSymbolStats = cap.getSymbolStatistics(symbol);
SymbolStatsEstimate.Builder newSymbolStats = SymbolStatsEstimate.builder();
// for simplicity keep the average row size the same as in the input
// in most cases the average row size doesn't change after applying filters
newSymbolStats.setAverageRowSize(symbolStats.getAverageRowSize());
newSymbolStats.setDistinctValuesCount(min(symbolStats.getDistinctValuesCount(), capSymbolStats.getDistinctValuesCount()));
newSymbolStats.setLowValue(max(symbolStats.getLowValue(), capSymbolStats.getLowValue()));
newSymbolStats.setHighValue(min(symbolStats.getHighValue(), capSymbolStats.getHighValue()));
double numberOfNulls = stats.getOutputRowCount() * symbolStats.getNullsFraction();
double capNumberOfNulls = cap.getOutputRowCount() * capSymbolStats.getNullsFraction();
double cappedNumberOfNulls = min(numberOfNulls, capNumberOfNulls);
double cappedNullsFraction = cappedRowCount == 0 ? 1 : cappedNumberOfNulls / cappedRowCount;
newSymbolStats.setNullsFraction(cappedNullsFraction);
result.addSymbolStatistics(symbol, newSymbolStats.build());
});
return result.build();
}
private static PlanNodeStatsEstimate createZeroStats(PlanNodeStatsEstimate stats)
{
PlanNodeStatsEstimate.Builder result = PlanNodeStatsEstimate.builder();
result.setOutputRowCount(0);
stats.getSymbolsWithKnownStatistics().forEach(symbol -> result.addSymbolStatistics(symbol, SymbolStatsEstimate.zero()));
return result.build();
}
@FunctionalInterface
private interface RangeAdditionStrategy
{
StatisticRange add(StatisticRange leftRange, StatisticRange rightRange);
}
public static PlanNodeStatsEstimate addStatsAndSumDistinctValues(PlanNodeStatsEstimate left, PlanNodeStatsEstimate right)
{
return addStats(left, right, StatisticRange::addAndSumDistinctValues);
}
public static PlanNodeStatsEstimate addStatsAndMaxDistinctValues(PlanNodeStatsEstimate left, PlanNodeStatsEstimate right)
{
return addStats(left, right, StatisticRange::addAndMaxDistinctValues);
}
public static PlanNodeStatsEstimate addStatsAndCollapseDistinctValues(PlanNodeStatsEstimate left, PlanNodeStatsEstimate right)
{
return addStats(left, right, StatisticRange::addAndCollapseDistinctValues);
}
private static PlanNodeStatsEstimate addStats(PlanNodeStatsEstimate left, PlanNodeStatsEstimate right, RangeAdditionStrategy strategy)
{
if (left.isOutputRowCountUnknown() || right.isOutputRowCountUnknown()) {
return PlanNodeStatsEstimate.unknown();
}
PlanNodeStatsEstimate.Builder statsBuilder = PlanNodeStatsEstimate.builder();
double newRowCount = left.getOutputRowCount() + right.getOutputRowCount();
concat(left.getSymbolsWithKnownStatistics().stream(), right.getSymbolsWithKnownStatistics().stream())
.distinct()
.forEach(symbol -> {
SymbolStatsEstimate symbolStats = SymbolStatsEstimate.zero();
if (newRowCount > 0) {
symbolStats = addColumnStats(
left.getSymbolStatistics(symbol),
left.getOutputRowCount(),
right.getSymbolStatistics(symbol),
right.getOutputRowCount(),
newRowCount,
strategy);
}
statsBuilder.addSymbolStatistics(symbol, symbolStats);
});
return statsBuilder.setOutputRowCount(newRowCount).build();
}
private static SymbolStatsEstimate addColumnStats(SymbolStatsEstimate leftStats, double leftRows, SymbolStatsEstimate rightStats, double rightRows, double newRowCount, RangeAdditionStrategy strategy)
{
checkArgument(newRowCount > 0, "newRowCount must be greater than zero");
StatisticRange leftRange = StatisticRange.from(leftStats);
StatisticRange rightRange = StatisticRange.from(rightStats);
StatisticRange sum = strategy.add(leftRange, rightRange);
double nullsCountRight = rightStats.getNullsFraction() * rightRows;
double nullsCountLeft = leftStats.getNullsFraction() * leftRows;
double totalSizeLeft = (leftRows - nullsCountLeft) * leftStats.getAverageRowSize();
double totalSizeRight = (rightRows - nullsCountRight) * rightStats.getAverageRowSize();
double newNullsFraction = (nullsCountLeft + nullsCountRight) / newRowCount;
double newNonNullsRowCount = newRowCount * (1.0 - newNullsFraction);
// FIXME, weights to average. left and right should be equal in most cases anyway
double newAverageRowSize = newNonNullsRowCount == 0 ? 0 : ((totalSizeLeft + totalSizeRight) / newNonNullsRowCount);
return SymbolStatsEstimate.builder()
.setStatisticsRange(sum)
.setAverageRowSize(newAverageRowSize)
.setNullsFraction(newNullsFraction)
.build();
}
}
| apache-2.0 |
gradle/gradle | subprojects/ide/src/testFixtures/groovy/org/gradle/plugins/ide/fixtures/IdeWorkspaceFixture.java | 773 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.plugins.ide.fixtures;
public abstract class IdeWorkspaceFixture {
public abstract void assertContains(IdeProjectFixture project);
}
| apache-2.0 |
stoksey69/googleads-java-lib | modules/ads_lib/src/main/java/com/google/api/ads/adwords/lib/selectorfields/v201506/cm/PromotionField.java | 3061 | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.adwords.lib.selectorfields.v201506.cm;
import com.google.api.ads.adwords.lib.selectorfields.EntityField;
import com.google.api.ads.adwords.lib.selectorfields.Filterable;
/**
* A {@code Enum} to facilitate the selection of fields for {@code Promotion}.
*/
public enum PromotionField implements EntityField {
// Fields constants definitions
/**
* Monthly budget for this promotion.
*/
Budget(false),
/**
* Whether call tracking should be enabled.
* Default is 'False'.
*/
CallTrackingEnabled(false),
/**
* IDs of the campaigns associated with this promotion.
*/
CampaignIds(false),
/**
* Creatives of this promotion.
*/
Creatives(false),
/**
* Destination URL to be used for this promotion.
*/
DestinationUrl(false),
/**
* Name of this promotion.
*/
Name(false),
/**
* Phone number associated with this promotion.
*/
PhoneNumber(false),
/**
* Text of the product service.
* <p>Please note that only {@link com.google.ads.api.services.common.selector.Operator.EQUALS} is supported.
*/
@Filterable
ProductServiceText(true),
/**
* Targeting criteria of this promotion.
* The following criteria are supported: <ul> <li>{@link com.google.ads.api.services.express.common.criterion.ProductService}</li> <li>{@link com.google.ads.api.services.campaignmgmt.common.criterion.Language}</li> <li>{@link com.google.ads.api.services.campaignmgmt.common.criterion.Location}</li> <li>{@link com.google.ads.api.services.campaignmgmt.common.criterion.Proximity}</li> </ul> <p>Please note that {@link com.google.ads.api.services.common.geo.Address} is not supported in {@link com.google.ads.api.services.campaignmgmt.common.criterion.Proximity}.
* Please use {@link com.google.ads.api.services.common.geo.GeoPoint} instead.
*/
PromotionCriteria(false),
/**
* ID of this promotion.
*/
@Filterable
PromotionId(true),
/**
* Remaining budget for the current month.
*/
RemainingBudget(false),
/**
* Status of this promotion.
*/
@Filterable
Status(true),
/**
* Whether the street address of the business should be visible.
* Default is 'True'.
*/
StreetAddressVisible(false),
;
private final boolean isFilterable;
private PromotionField(boolean isFilterable) {
this.isFilterable = isFilterable;
}
public boolean isFilterable() {
return this.isFilterable;
}
}
| apache-2.0 |
emsouza/archiva | archiva-modules/plugins/audit/src/main/java/org/apache/archiva/audit/AuditLog.java | 2166 | package org.apache.archiva.audit;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.archiva.metadata.model.facets.AuditEvent;
import org.apache.archiva.repository.events.AuditListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
/**
* AuditLog - Audit Log.
*
*
*
*/
@Service("auditListener#logging")
public class AuditLog
implements AuditListener
{
public static final Logger logger = LoggerFactory.getLogger( "org.apache.archiva.AuditLog" );
private static final String NONE = "-";
private static final char DELIM = ' ';
/**
* Creates a log message in the following format ...
* "{repository_id} {user_id} {remote_ip} \"{resource}\" \"{action}\""
*/
@Override
public void auditEvent( AuditEvent event )
{
StringBuilder msg = new StringBuilder();
msg.append( checkNull( event.getRepositoryId() ) ).append( DELIM );
msg.append( event.getUserId() ).append( DELIM );
msg.append( checkNull( event.getRemoteIP() ) ).append( DELIM );
msg.append( '\"' ).append( checkNull( event.getResource() ) ).append( '\"' ).append( DELIM );
msg.append( '\"' ).append( event.getAction() ).append( '\"' );
logger.info( msg.toString() );
}
private String checkNull( String s )
{
return s != null ? s : NONE;
}
}
| apache-2.0 |
cguillot/resty-gwt | restygwt/src/test/java/org/fusesource/restygwt/client/FileSystemHelperTest.java | 2910 | /**
* Copyright (C) 2009-2012 the original author or authors.
* See the notice.md file 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 org.fusesource.restygwt.client;
import junit.framework.TestCase;
import org.fusesource.restygwt.client.FileSystemHelper;
public class FileSystemHelperTest extends TestCase {
public void testFileSystemHelper() {
// Scenarios:
// 1. Request goes to filesystem, we are running on filesystem
String mockedBaseUrl = "file:///myLocation";
String uriRequested = "file:///myJson.json";
assertTrue(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
// 2. Request goes to relative path => we are running on filesystem
mockedBaseUrl = "file:///myLocation";
uriRequested = "../../myJson.json";
assertTrue(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
// 3. Request goes to absolute path => we are running on filesystem
mockedBaseUrl = "file:///myLocation";
uriRequested = "/myJson.json";
assertTrue(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
// 4. Request goes to absolute path => we are running on filesystem
mockedBaseUrl = "file:///myLocation";
uriRequested = "file:///myJson.json";
assertTrue(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
// 5. Request goes to absolute path => we are running on http
mockedBaseUrl = "http://myLocation";
uriRequested = "/myJson.json";
assertFalse(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
// 6. Request goes to relative path => we are running on http
mockedBaseUrl = "http://myLocation";
uriRequested = "../../myJson.json";
assertFalse(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
// 7. Request goes to relative path => we are running on http
mockedBaseUrl = "http://myLocation";
uriRequested = "../../myJson.json";
assertFalse(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
// 8. Request goes to absolute http => we are running on http
mockedBaseUrl = "http://myLocation";
uriRequested = "http://myJson.json";
assertFalse(FileSystemHelper.isRequestGoingToFileSystem(mockedBaseUrl,uriRequested));
}
}
| apache-2.0 |
benmccann/playframework | documentation/manual/working/javaGuide/main/forms/code/javaguide/forms/u2/User.java | 512 | /*
* Copyright (C) Lightbend Inc. <https://www.lightbend.com>
*/
package javaguide.forms.u2;
import play.data.validation.Constraints.Required;
// #user
public class User {
@Required protected String email;
protected String password;
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}
// #user
| apache-2.0 |
ElectroJunkie/box-android-sdk-v2-master | BoxAndroidLibraryV2/src/com/box/boxandroidlibv2/dao/BoxAndroidOAuthData.java | 1823 | package com.box.boxandroidlibv2.dao;
import java.util.Map;
import android.os.Parcel;
import android.os.Parcelable;
import com.box.boxjavalibv2.dao.BoxOAuthToken;
/**
* Data used for OAuth.
*/
public class BoxAndroidOAuthData extends BoxOAuthToken implements Parcelable {
public BoxAndroidOAuthData() {
super();
}
/**
* Constructor.
*
* @param in
* parcel
* @throws BoxNullObjectException
* exception
*/
private BoxAndroidOAuthData(final Parcel in) {
super(new BoxParcel(in));
}
/**
* Copy constructor, this does deep copy for all the fields.
*
* @param obj
*/
public BoxAndroidOAuthData(BoxOAuthToken obj) {
super(obj);
}
/**
* Copy constructor, this does deep copy for all the fields.
*
* @param obj
*/
public BoxAndroidOAuthData(BoxAndroidOAuthData obj) {
super(obj);
}
/**
* Instantiate the object from a map. Each entry in the map reflects to a field.
*
* @param map
*/
public BoxAndroidOAuthData(Map<String, Object> map) {
super(map);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(final Parcel dest, final int flags) {
super.writeToParcel(new BoxParcel(dest), flags);
}
public static final Parcelable.Creator<BoxAndroidOAuthData> CREATOR = new Parcelable.Creator<BoxAndroidOAuthData>() {
@Override
public BoxAndroidOAuthData createFromParcel(final Parcel source) {
return new BoxAndroidOAuthData(source);
}
@Override
public BoxAndroidOAuthData[] newArray(final int size) {
return new BoxAndroidOAuthData[size];
}
};
}
| apache-2.0 |
JSDemos/android-sdk-20 | src/java/net/PlainSocketImpl.java | 17238 | /*
* 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 java.net;
import dalvik.system.CloseGuard;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketImpl;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteOrder;
import java.util.Arrays;
import libcore.io.ErrnoException;
import libcore.io.IoBridge;
import libcore.io.Libcore;
import libcore.io.Memory;
import libcore.io.Streams;
import static libcore.io.OsConstants.*;
/**
* @hide used in java.nio.
*/
public class PlainSocketImpl extends SocketImpl {
// For SOCKS support. A SOCKS bind() uses the last
// host connected to in its request.
private static InetAddress lastConnectedAddress;
private static int lastConnectedPort;
private boolean streaming = true;
private boolean shutdownInput;
private Proxy proxy;
private final CloseGuard guard = CloseGuard.get();
public PlainSocketImpl(FileDescriptor fd) {
this.fd = fd;
if (fd.valid()) {
guard.open("close");
}
}
public PlainSocketImpl(Proxy proxy) {
this(new FileDescriptor());
this.proxy = proxy;
}
public PlainSocketImpl() {
this(new FileDescriptor());
}
public PlainSocketImpl(FileDescriptor fd, int localport, InetAddress addr, int port) {
this.fd = fd;
this.localport = localport;
this.address = addr;
this.port = port;
if (fd.valid()) {
guard.open("close");
}
}
@Override
protected void accept(SocketImpl newImpl) throws IOException {
if (usingSocks()) {
((PlainSocketImpl) newImpl).socksBind();
((PlainSocketImpl) newImpl).socksAccept();
return;
}
try {
InetSocketAddress peerAddress = new InetSocketAddress();
FileDescriptor clientFd = Libcore.os.accept(fd, peerAddress);
// TODO: we can't just set newImpl.fd to clientFd because a nio SocketChannel may
// be sharing the FileDescriptor. http://b//4452981.
newImpl.fd.setInt$(clientFd.getInt$());
newImpl.address = peerAddress.getAddress();
newImpl.port = peerAddress.getPort();
} catch (ErrnoException errnoException) {
if (errnoException.errno == EAGAIN) {
throw new SocketTimeoutException(errnoException);
}
throw errnoException.rethrowAsSocketException();
}
// Reset the client's inherited read timeout to the Java-specified default of 0.
newImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(0));
newImpl.localport = IoBridge.getSocketLocalPort(newImpl.fd);
}
private boolean usingSocks() {
return proxy != null && proxy.type() == Proxy.Type.SOCKS;
}
public void initLocalPort(int localPort) {
this.localport = localPort;
}
public void initRemoteAddressAndPort(InetAddress remoteAddress, int remotePort) {
this.address = remoteAddress;
this.port = remotePort;
}
private void checkNotClosed() throws IOException {
if (!fd.valid()) {
throw new SocketException("Socket is closed");
}
}
@Override
protected synchronized int available() throws IOException {
checkNotClosed();
// we need to check if the input has been shutdown. If so
// we should return that there is no data to be read
if (shutdownInput) {
return 0;
}
return IoBridge.available(fd);
}
@Override protected void bind(InetAddress address, int port) throws IOException {
IoBridge.bind(fd, address, port);
this.address = address;
if (port != 0) {
this.localport = port;
} else {
this.localport = IoBridge.getSocketLocalPort(fd);
}
}
@Override
protected synchronized void close() throws IOException {
guard.close();
IoBridge.closeSocket(fd);
}
@Override
protected void connect(String aHost, int aPort) throws IOException {
connect(InetAddress.getByName(aHost), aPort);
}
@Override
protected void connect(InetAddress anAddr, int aPort) throws IOException {
connect(anAddr, aPort, 0);
}
/**
* Connects this socket to the specified remote host address/port.
*
* @param anAddr
* the remote host address to connect to
* @param aPort
* the remote port to connect to
* @param timeout
* a timeout where supported. 0 means no timeout
* @throws IOException
* if an error occurs while connecting
*/
private void connect(InetAddress anAddr, int aPort, int timeout) throws IOException {
InetAddress normalAddr = anAddr.isAnyLocalAddress() ? InetAddress.getLocalHost() : anAddr;
if (streaming && usingSocks()) {
socksConnect(anAddr, aPort, 0);
} else {
IoBridge.connect(fd, normalAddr, aPort, timeout);
}
super.address = normalAddr;
super.port = aPort;
}
@Override
protected void create(boolean streaming) throws IOException {
this.streaming = streaming;
this.fd = IoBridge.socket(streaming);
}
@Override protected void finalize() throws Throwable {
try {
if (guard != null) {
guard.warnIfOpen();
}
close();
} finally {
super.finalize();
}
}
@Override protected synchronized InputStream getInputStream() throws IOException {
checkNotClosed();
return new PlainSocketInputStream(this);
}
private static class PlainSocketInputStream extends InputStream {
private final PlainSocketImpl socketImpl;
public PlainSocketInputStream(PlainSocketImpl socketImpl) {
this.socketImpl = socketImpl;
}
@Override public int available() throws IOException {
return socketImpl.available();
}
@Override public void close() throws IOException {
socketImpl.close();
}
@Override public int read() throws IOException {
return Streams.readSingleByte(this);
}
@Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
return socketImpl.read(buffer, byteOffset, byteCount);
}
}
@Override public Object getOption(int option) throws SocketException {
return IoBridge.getSocketOption(fd, option);
}
@Override protected synchronized OutputStream getOutputStream() throws IOException {
checkNotClosed();
return new PlainSocketOutputStream(this);
}
private static class PlainSocketOutputStream extends OutputStream {
private final PlainSocketImpl socketImpl;
public PlainSocketOutputStream(PlainSocketImpl socketImpl) {
this.socketImpl = socketImpl;
}
@Override public void close() throws IOException {
socketImpl.close();
}
@Override public void write(int oneByte) throws IOException {
Streams.writeSingleByte(this, oneByte);
}
@Override public void write(byte[] buffer, int offset, int byteCount) throws IOException {
socketImpl.write(buffer, offset, byteCount);
}
}
@Override
protected void listen(int backlog) throws IOException {
if (usingSocks()) {
// Do nothing for a SOCKS connection. The listen occurs on the
// server during the bind.
return;
}
try {
Libcore.os.listen(fd, backlog);
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsSocketException();
}
}
@Override
public void setOption(int option, Object value) throws SocketException {
IoBridge.setSocketOption(fd, option, value);
}
/**
* Gets the SOCKS proxy server port.
*/
private int socksGetServerPort() {
// get socks server port from proxy. It is unnecessary to check
// "socksProxyPort" property, since proxy setting should only be
// determined by ProxySelector.
InetSocketAddress addr = (InetSocketAddress) proxy.address();
return addr.getPort();
}
/**
* Gets the InetAddress of the SOCKS proxy server.
*/
private InetAddress socksGetServerAddress() throws UnknownHostException {
String proxyName;
// get socks server address from proxy. It is unnecessary to check
// "socksProxyHost" property, since all proxy setting should be
// determined by ProxySelector.
InetSocketAddress addr = (InetSocketAddress) proxy.address();
proxyName = addr.getHostName();
if (proxyName == null) {
proxyName = addr.getAddress().getHostAddress();
}
return InetAddress.getByName(proxyName);
}
/**
* Connect using a SOCKS server.
*/
private void socksConnect(InetAddress applicationServerAddress, int applicationServerPort, int timeout) throws IOException {
try {
IoBridge.connect(fd, socksGetServerAddress(), socksGetServerPort(), timeout);
} catch (Exception e) {
throw new SocketException("SOCKS connection failed", e);
}
socksRequestConnection(applicationServerAddress, applicationServerPort);
lastConnectedAddress = applicationServerAddress;
lastConnectedPort = applicationServerPort;
}
/**
* Request a SOCKS connection to the application server given. If the
* request fails to complete successfully, an exception is thrown.
*/
private void socksRequestConnection(InetAddress applicationServerAddress,
int applicationServerPort) throws IOException {
socksSendRequest(Socks4Message.COMMAND_CONNECT,
applicationServerAddress, applicationServerPort);
Socks4Message reply = socksReadReply();
if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
}
}
/**
* Perform an accept for a SOCKS bind.
*/
public void socksAccept() throws IOException {
Socks4Message reply = socksReadReply();
if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
}
}
/**
* Shutdown the input portion of the socket.
*/
@Override
protected void shutdownInput() throws IOException {
shutdownInput = true;
try {
Libcore.os.shutdown(fd, SHUT_RD);
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsSocketException();
}
}
/**
* Shutdown the output portion of the socket.
*/
@Override
protected void shutdownOutput() throws IOException {
try {
Libcore.os.shutdown(fd, SHUT_WR);
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsSocketException();
}
}
/**
* Bind using a SOCKS server.
*/
private void socksBind() throws IOException {
try {
IoBridge.connect(fd, socksGetServerAddress(), socksGetServerPort());
} catch (Exception e) {
throw new IOException("Unable to connect to SOCKS server", e);
}
// There must be a connection to an application host for the bind to work.
if (lastConnectedAddress == null) {
throw new SocketException("Invalid SOCKS client");
}
// Use the last connected address and port in the bind request.
socksSendRequest(Socks4Message.COMMAND_BIND, lastConnectedAddress,
lastConnectedPort);
Socks4Message reply = socksReadReply();
if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
}
// A peculiarity of socks 4 - if the address returned is 0, use the
// original socks server address.
if (reply.getIP() == 0) {
address = socksGetServerAddress();
} else {
// IPv6 support not yet required as
// currently the Socks4Message.getIP() only returns int,
// so only works with IPv4 4byte addresses
byte[] replyBytes = new byte[4];
Memory.pokeInt(replyBytes, 0, reply.getIP(), ByteOrder.BIG_ENDIAN);
address = InetAddress.getByAddress(replyBytes);
}
localport = reply.getPort();
}
/**
* Send a SOCKS V4 request.
*/
private void socksSendRequest(int command, InetAddress address, int port) throws IOException {
Socks4Message request = new Socks4Message();
request.setCommandOrResult(command);
request.setPort(port);
request.setIP(address.getAddress());
request.setUserId("default");
getOutputStream().write(request.getBytes(), 0, request.getLength());
}
/**
* Read a SOCKS V4 reply.
*/
private Socks4Message socksReadReply() throws IOException {
Socks4Message reply = new Socks4Message();
int bytesRead = 0;
while (bytesRead < Socks4Message.REPLY_LENGTH) {
int count = getInputStream().read(reply.getBytes(), bytesRead,
Socks4Message.REPLY_LENGTH - bytesRead);
if (count == -1) {
break;
}
bytesRead += count;
}
if (Socks4Message.REPLY_LENGTH != bytesRead) {
throw new SocketException("Malformed reply from SOCKS server");
}
return reply;
}
@Override
protected void connect(SocketAddress remoteAddr, int timeout) throws IOException {
InetSocketAddress inetAddr = (InetSocketAddress) remoteAddr;
connect(inetAddr.getAddress(), inetAddr.getPort(), timeout);
}
@Override
protected boolean supportsUrgentData() {
return true;
}
@Override
protected void sendUrgentData(int value) throws IOException {
try {
byte[] buffer = new byte[] { (byte) value };
Libcore.os.sendto(fd, buffer, 0, 1, MSG_OOB, null, 0);
} catch (ErrnoException errnoException) {
throw errnoException.rethrowAsSocketException();
}
}
/**
* For PlainSocketInputStream.
*/
private int read(byte[] buffer, int offset, int byteCount) throws IOException {
if (byteCount == 0) {
return 0;
}
Arrays.checkOffsetAndCount(buffer.length, offset, byteCount);
if (shutdownInput) {
return -1;
}
int readCount = IoBridge.recvfrom(true, fd, buffer, offset, byteCount, 0, null, false);
// Return of zero bytes for a blocking socket means a timeout occurred
if (readCount == 0) {
throw new SocketTimeoutException();
}
// Return of -1 indicates the peer was closed
if (readCount == -1) {
shutdownInput = true;
}
return readCount;
}
/**
* For PlainSocketOutputStream.
*/
private void write(byte[] buffer, int offset, int byteCount) throws IOException {
Arrays.checkOffsetAndCount(buffer.length, offset, byteCount);
if (streaming) {
while (byteCount > 0) {
int bytesWritten = IoBridge.sendto(fd, buffer, offset, byteCount, 0, null, 0);
byteCount -= bytesWritten;
offset += bytesWritten;
}
} else {
// Unlike writes to a streaming socket, writes to a datagram
// socket are all-or-nothing, so we don't need a loop here.
// http://code.google.com/p/android/issues/detail?id=15304
IoBridge.sendto(fd, buffer, offset, byteCount, 0, address, port);
}
}
}
| apache-2.0 |
keepmemo/objcio | issue-11-android-101-master/Android/AndroidForiOS/app/src/main/java/com/example/androidforios/app/data/managers/DataManager.java | 3158 | package com.example.androidforios.app.data.managers;
import android.content.Context;
import com.example.androidforios.app.data.model.TripList;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONObject;
import android.content.res.AssetManager;
import android.support.v4.content.AsyncTaskLoader;
/**
* Created by stephen.barnes on 3/23/14.
*/
public class DataManager {
private static final DataManager INSTANCE = new DataManager();
public static DataManager getSharedInstance() { return INSTANCE; }
public static String stringFromAssetFolder(String fileName, Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(fileName);
return readStream(file);
}
/**
* Utility method for pulling plain text from an InputStream object
* @param in InputStream object retrieved from an HttpResponse
* @return String contents of stream
*/
public static String readStream(InputStream in)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch(Exception ex) { }
finally
{
safeClose(in);
safeClose(reader);
}
return sb.toString();
}
/**
* Safely closes the given {@link Closeable} without throwing
* any exceptions due to null pointers or {@link IOException}s.
* @param closeable The {@link Closeable} to close.
*/
public static void safeClose(Closeable closeable)
{
if(closeable != null)
{
try
{
closeable.close();
}
catch (IOException e) { }
}
}
/**
* Asynchronously load a JSON file with MBTA subway data in the background.
*
* @author Stephen Barnes
*/
public static class SubwayLineLoader extends AsyncTaskLoader<TripList> {
protected TripList.LineType mLineType;
public SubwayLineLoader(Context context, TripList.LineType lineType) {
super(context);
mLineType = lineType;
}
@Override
public TripList loadInBackground() {
TripList tripList = new TripList();
try {
String subwayLineJSONString = stringFromAssetFolder(mLineType.getFileName(), this.getContext());
try {
JSONObject jsonData = new JSONObject(subwayLineJSONString);
tripList.importDataFromJSON(jsonData.getJSONObject("TripList"));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return tripList;
}
}
}
| apache-2.0 |
android-ia/platform_tools_idea | plugins/git4idea/src/git4idea/ui/GitUnstashDialog.java | 16827 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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 git4idea.ui;
import com.intellij.CommonBundle;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.DocumentAdapter;
import com.intellij.util.Consumer;
import git4idea.*;
import git4idea.branch.GitBranchUtil;
import git4idea.commands.*;
import git4idea.config.GitVersionSpecialty;
import git4idea.i18n.GitBundle;
import git4idea.merge.GitConflictResolver;
import git4idea.repo.GitRepository;
import git4idea.stash.GitStashUtils;
import git4idea.util.GitUIUtil;
import git4idea.validators.GitBranchNameValidator;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The unstash dialog
*/
public class GitUnstashDialog extends DialogWrapper {
/**
* Git root selector
*/
private JComboBox myGitRootComboBox;
/**
* The current branch label
*/
private JLabel myCurrentBranch;
/**
* The view stash button
*/
private JButton myViewButton;
/**
* The drop stash button
*/
private JButton myDropButton;
/**
* The clear stashes button
*/
private JButton myClearButton;
/**
* The pop stash checkbox
*/
private JCheckBox myPopStashCheckBox;
/**
* The branch text field
*/
private JTextField myBranchTextField;
/**
* The root panel of the dialog
*/
private JPanel myPanel;
/**
* The stash list
*/
private JList myStashList;
/**
* If this checkbox is selected, the index is reinstated as well as working tree
*/
private JCheckBox myReinstateIndexCheckBox;
/**
* Set of branches for the current root
*/
private final HashSet<String> myBranches = new HashSet<String>();
/**
* The project
*/
private final Project myProject;
private GitVcs myVcs;
private static final Logger LOG = Logger.getInstance(GitUnstashDialog.class);
/**
* A constructor
*
* @param project the project
* @param roots the list of the roots
* @param defaultRoot the default root to select
*/
public GitUnstashDialog(final Project project, final List<VirtualFile> roots, final VirtualFile defaultRoot) {
super(project, true);
setModal(false);
myProject = project;
myVcs = GitVcs.getInstance(project);
setTitle(GitBundle.getString("unstash.title"));
setOKButtonText(GitBundle.getString("unstash.button.apply"));
setCancelButtonText(CommonBundle.getCloseButtonText());
GitUIUtil.setupRootChooser(project, roots, defaultRoot, myGitRootComboBox, myCurrentBranch);
myStashList.setModel(new DefaultListModel());
refreshStashList();
myGitRootComboBox.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
refreshStashList();
updateDialogState();
}
});
myStashList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(final ListSelectionEvent e) {
updateDialogState();
}
});
myBranchTextField.getDocument().addDocumentListener(new DocumentAdapter() {
protected void textChanged(final DocumentEvent e) {
updateDialogState();
}
});
myPopStashCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateDialogState();
}
});
myClearButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if (Messages.YES == Messages.showYesNoDialog(GitUnstashDialog.this.getContentPane(),
GitBundle.message("git.unstash.clear.confirmation.message"),
GitBundle.message("git.unstash.clear.confirmation.title"), Messages.getWarningIcon())) {
GitLineHandler h = new GitLineHandler(myProject, getGitRoot(), GitCommand.STASH);
h.addParameters("clear");
GitHandlerUtil.doSynchronously(h, GitBundle.getString("unstash.clearing.stashes"), h.printableCommandLine());
refreshStashList();
updateDialogState();
}
}
});
myDropButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
final StashInfo stash = getSelectedStash();
if (Messages.YES == Messages.showYesNoDialog(GitUnstashDialog.this.getContentPane(),
GitBundle.message("git.unstash.drop.confirmation.message", stash.getStash(), stash.getMessage()),
GitBundle.message("git.unstash.drop.confirmation.title", stash.getStash()), Messages.getQuestionIcon())) {
final ModalityState current = ModalityState.current();
ProgressManager.getInstance().run(new Task.Modal(myProject, "Removing stash " + stash.getStash(), false) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final GitSimpleHandler h = dropHandler(stash.getStash());
try {
h.run();
h.unsilence();
}
catch (final VcsException ex) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
GitUIUtil.showOperationError(myProject, ex, h.printableCommandLine());
}
}, current);
}
}
});
refreshStashList();
updateDialogState();
}
}
private GitSimpleHandler dropHandler(String stash) {
GitSimpleHandler h = new GitSimpleHandler(myProject, getGitRoot(), GitCommand.STASH);
h.addParameters("drop");
addStashParameter(h, stash);
return h;
}
});
myViewButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
final VirtualFile root = getGitRoot();
String resolvedStash;
String selectedStash = getSelectedStash().getStash();
try {
GitSimpleHandler h = new GitSimpleHandler(project, root, GitCommand.REV_LIST);
h.setSilent(true);
h.addParameters("--timestamp", "--max-count=1");
addStashParameter(h, selectedStash);
h.endOptions();
final String output = h.run();
resolvedStash = GitRevisionNumber.parseRevlistOutputAsRevisionNumber(h, output).asString();
}
catch (VcsException ex) {
GitUIUtil.showOperationError(myProject, ex, "resolving revision");
return;
}
GitUtil.showSubmittedFiles(myProject, resolvedStash, root, true, false);
}
});
init();
updateDialogState();
}
/**
* Adds {@code stash@{x}} parameter to the handler, quotes it if needed.
*/
private void addStashParameter(@NotNull GitHandler handler, @NotNull String stash) {
if (GitVersionSpecialty.NEEDS_QUOTES_IN_STASH_NAME.existsIn(myVcs.getVersion())) {
handler.addParameters(GeneralCommandLine.inescapableQuote(stash));
}
else {
handler.addParameters(stash);
}
}
/**
* Update state dialog depending on the current state of the fields
*/
private void updateDialogState() {
String branch = myBranchTextField.getText();
if (branch.length() != 0) {
setOKButtonText(GitBundle.getString("unstash.button.branch"));
myPopStashCheckBox.setEnabled(false);
myPopStashCheckBox.setSelected(true);
myReinstateIndexCheckBox.setEnabled(false);
myReinstateIndexCheckBox.setSelected(true);
if (!GitBranchNameValidator.INSTANCE.checkInput(branch)) {
setErrorText(GitBundle.getString("unstash.error.invalid.branch.name"));
setOKActionEnabled(false);
return;
}
if (myBranches.contains(branch)) {
setErrorText(GitBundle.getString("unstash.error.branch.exists"));
setOKActionEnabled(false);
return;
}
}
else {
if (!myPopStashCheckBox.isEnabled()) {
myPopStashCheckBox.setSelected(false);
}
myPopStashCheckBox.setEnabled(true);
setOKButtonText(
myPopStashCheckBox.isSelected() ? GitBundle.getString("unstash.button.pop") : GitBundle.getString("unstash.button.apply"));
if (!myReinstateIndexCheckBox.isEnabled()) {
myReinstateIndexCheckBox.setSelected(false);
}
myReinstateIndexCheckBox.setEnabled(true);
}
if (myStashList.getModel().getSize() == 0) {
myViewButton.setEnabled(false);
myDropButton.setEnabled(false);
myClearButton.setEnabled(false);
setErrorText(null);
setOKActionEnabled(false);
return;
}
else {
myClearButton.setEnabled(true);
}
if (myStashList.getSelectedIndex() == -1) {
myViewButton.setEnabled(false);
myDropButton.setEnabled(false);
setErrorText(null);
setOKActionEnabled(false);
return;
}
else {
myViewButton.setEnabled(true);
myDropButton.setEnabled(true);
}
setErrorText(null);
setOKActionEnabled(true);
}
/**
* Refresh stash list
*/
private void refreshStashList() {
final DefaultListModel listModel = (DefaultListModel)myStashList.getModel();
listModel.clear();
VirtualFile root = getGitRoot();
GitStashUtils.loadStashStack(myProject, root, new Consumer<StashInfo>() {
@Override
public void consume(StashInfo stashInfo) {
listModel.addElement(stashInfo);
}
});
myBranches.clear();
GitRepository repository = GitUtil.getRepositoryManager(myProject).getRepositoryForRoot(root);
if (repository != null) {
myBranches.addAll(GitBranchUtil.convertBranchesToNames(repository.getBranches().getLocalBranches()));
}
else {
LOG.error("Repository is null for root " + root);
}
myStashList.setSelectedIndex(0);
}
/**
* @return the selected git root
*/
private VirtualFile getGitRoot() {
return (VirtualFile)myGitRootComboBox.getSelectedItem();
}
/**
* @return unstash handler
*/
private GitLineHandler handler() {
GitLineHandler h = new GitLineHandler(myProject, getGitRoot(), GitCommand.STASH);
String branch = myBranchTextField.getText();
if (branch.length() == 0) {
h.addParameters(myPopStashCheckBox.isSelected() ? "pop" : "apply");
if (myReinstateIndexCheckBox.isSelected()) {
h.addParameters("--index");
}
}
else {
h.addParameters("branch", branch);
}
String selectedStash = getSelectedStash().getStash();
addStashParameter(h, selectedStash);
return h;
}
/**
* @return selected stash
* @throws NullPointerException if no stash is selected
*/
private StashInfo getSelectedStash() {
return (StashInfo)myStashList.getSelectedValue();
}
/**
* {@inheritDoc}
*/
protected JComponent createCenterPanel() {
return myPanel;
}
/**
* {@inheritDoc}
*/
@Override
protected String getDimensionServiceKey() {
return getClass().getName();
}
/**
* {@inheritDoc}
*/
@Override
protected String getHelpId() {
return "reference.VersionControl.Git.Unstash";
}
@Override
public JComponent getPreferredFocusedComponent() {
return myStashList;
}
@Override
protected void doOKAction() {
VirtualFile root = getGitRoot();
GitLineHandler h = handler();
final AtomicBoolean conflict = new AtomicBoolean();
h.addLineListener(new GitLineHandlerAdapter() {
public void onLineAvailable(String line, Key outputType) {
if (line.contains("Merge conflict")) {
conflict.set(true);
}
}
});
int rc = GitHandlerUtil.doSynchronously(h, GitBundle.getString("unstash.unstashing"), h.printableCommandLine(), false);
ServiceManager.getService(myProject, GitPlatformFacade.class).hardRefresh(root);
if (conflict.get()) {
boolean conflictsResolved = new UnstashConflictResolver(myProject, root, getSelectedStash()).merge();
LOG.info("loadRoot " + root + ", conflictsResolved: " + conflictsResolved);
} else if (rc != 0) {
GitUIUtil.showOperationErrors(myProject, h.errors(), h.printableCommandLine());
}
super.doOKAction();
}
public static void showUnstashDialog(Project project, List<VirtualFile> gitRoots, VirtualFile defaultRoot) {
new GitUnstashDialog(project, gitRoots, defaultRoot).show();
// d is not modal=> everything else in doOKAction.
}
private static class UnstashConflictResolver extends GitConflictResolver {
private final VirtualFile myRoot;
private final StashInfo myStashInfo;
public UnstashConflictResolver(Project project, VirtualFile root, StashInfo stashInfo) {
super(project, ServiceManager.getService(Git.class), ServiceManager.getService(GitPlatformFacade.class),
Collections.singleton(root), makeParams(stashInfo));
myRoot = root;
myStashInfo = stashInfo;
}
private static Params makeParams(StashInfo stashInfo) {
Params params = new Params();
params.setErrorNotificationTitle("Unstashed with conflicts");
params.setMergeDialogCustomizer(new UnstashMergeDialogCustomizer(stashInfo));
return params;
}
@Override
protected void notifyUnresolvedRemain() {
GitVcs.IMPORTANT_ERROR_NOTIFICATION.createNotification("Conflicts were not resolved during unstash",
"Unstash is not complete, you have unresolved merges in your working tree<br/>" +
"<a href='resolve'>Resolve</a> conflicts.",
NotificationType.WARNING, new NotificationListener() {
@Override
public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
if (event.getDescription().equals("resolve")) {
new UnstashConflictResolver(myProject, myRoot, myStashInfo).mergeNoProceed();
}
}
}
}).notify(myProject);
}
}
private static class UnstashMergeDialogCustomizer extends MergeDialogCustomizer {
private final StashInfo myStashInfo;
public UnstashMergeDialogCustomizer(StashInfo stashInfo) {
myStashInfo = stashInfo;
}
@Override
public String getMultipleFileMergeDescription(Collection<VirtualFile> files) {
return "<html>Conflicts during unstashing <code>" + myStashInfo.getStash() + "\"" + myStashInfo.getMessage() + "\"</code></html>";
}
@Override
public String getLeftPanelTitle(VirtualFile file) {
return "Local changes";
}
@Override
public String getRightPanelTitle(VirtualFile file, VcsRevisionNumber lastRevisionNumber) {
return "Changes from stash";
}
}
}
| apache-2.0 |
tadayosi/switchyard | core/test/src/main/java/org/switchyard/test/MockHandler.java | 6034 | /*
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.switchyard.test;
import java.util.concurrent.LinkedBlockingQueue;
import junit.framework.TestCase;
import org.switchyard.BaseHandler;
import org.switchyard.Exchange;
import org.switchyard.ExchangePattern;
import org.switchyard.HandlerException;
/**
* Mock Handler.
*
* @author <a href="mailto:tom.fennelly@gmail.com">tom.fennelly@gmail.com</a>
*/
public class MockHandler extends BaseHandler {
private enum Behavior {
FORWARD_IN_TO_OUT, // send the in message as a reply
FORWARD_IN_TO_FAULT, // send the in message as a fault
REPLY_WITH_OUT, // reply with a specific message as out
REPLY_WITH_FAULT}; // reply with a specific message as fault
/**
* Messages.
*/
private final LinkedBlockingQueue<Exchange> _messages =
new LinkedBlockingQueue<Exchange>();
/**
* Faults.
*/
private final LinkedBlockingQueue<Exchange> _faults =
new LinkedBlockingQueue<Exchange>();
/**
* Default sleep.
*/
private static final int DEFAULT_SLEEP_MS = 100;
/**
* Default wait timeout.
*/
private static final int DEFAULT_WAIT_TIMEOUT = 5000;
/**
* Wait timeout value.
*/
private long _waitTimeout = DEFAULT_WAIT_TIMEOUT; // default of 5 seconds
/**
* Specific content for reply messages/faults.
*/
private Object _replyContent;
/**
* Handler behavior for replies.
*/
private Behavior _behavior;
/**
* Constructor.
*/
public MockHandler() {
}
/**
* @return wait timeout
*/
public long getWaitTimeout() {
return _waitTimeout;
}
/**
* @param waitTimeout wait timeout
*/
public void setWaitTimeout(long waitTimeout) {
_waitTimeout = waitTimeout;
}
/**
* Message getter.
* @return messages messages
*/
public LinkedBlockingQueue<Exchange> getMessages() {
return _messages;
}
/**
* Fault getter.
* @return faults faults
*/
public LinkedBlockingQueue<Exchange> getFaults() {
return _faults;
}
/**
* Forward input to output.
* @return MockHandler mockhandler
*/
public MockHandler forwardInToOut() {
_behavior = Behavior.FORWARD_IN_TO_OUT;
return this;
}
/**
* Forward input to fault.
* @return MockHandler mockhandler
*/
public MockHandler forwardInToFault() {
_behavior = Behavior.FORWARD_IN_TO_FAULT;
return this;
}
/**
* Reply with an out message using the specified content.
* @param content content to reply with
* @return this handler
*/
public MockHandler replyWithOut(Object content) {
_behavior = Behavior.REPLY_WITH_OUT;
_replyContent = content;
return this;
}
/**
* Reply with a fault message using the specified content.
* @param content content to reply with
* @return this handler
*/
public MockHandler replyWithFault(Object content) {
_behavior = Behavior.REPLY_WITH_FAULT;
_replyContent = content;
return this;
}
@Override
public void handleMessage(final Exchange exchange) throws HandlerException {
_messages.offer(exchange);
if (_behavior == null || exchange.getContract().getProviderOperation().getExchangePattern().equals(ExchangePattern.IN_ONLY)) {
return;
}
switch (_behavior) {
case FORWARD_IN_TO_OUT :
exchange.send(exchange.getMessage().copy());
break;
case FORWARD_IN_TO_FAULT :
exchange.sendFault(exchange.getMessage().copy());
break;
case REPLY_WITH_OUT :
exchange.send(exchange.createMessage().setContent(_replyContent));
break;
case REPLY_WITH_FAULT :
exchange.sendFault(exchange.createMessage().setContent(_replyContent));
break;
}
}
@Override
public void handleFault(final Exchange exchange) {
_faults.offer(exchange);
}
/**
* Wait for a message.
* @return MockHandler mockhandler
*/
public MockHandler waitForOKMessage() {
waitFor(_messages, 1);
return this;
}
/**
* Wait for a number of messages.
* @return MockHandler mockhandler
*/
public MockHandler waitForFaultMessage() {
waitFor(_faults, 1);
return this;
}
/**
* Wait for a number of messages.
* @param eventQueue event queue
* @param numMessages number of messages
*/
private void waitFor(final LinkedBlockingQueue<Exchange> eventQueue,
final int numMessages) {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() < start + _waitTimeout) {
if (eventQueue.size() >= numMessages) {
return;
}
sleep();
}
TestCase.fail("Timed out waiting on event queue length to be "
+ numMessages + " or greater.");
}
/**
* Sleep.
*/
private void sleep() {
try {
Thread.sleep(DEFAULT_SLEEP_MS);
} catch (InterruptedException e) {
TestCase.fail("Failed to sleep: " + e.getMessage());
}
}
}
| apache-2.0 |
smarthi/incubator-samoa | samoa-api/src/main/java/org/apache/samoa/learners/InstanceContent.java | 4350 | package org.apache.samoa.learners;
/*
* #%L
* SAMOA
* %%
* Copyright (C) 2014 - 2015 Apache Software Foundation
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/**
* License
*/
import net.jcip.annotations.Immutable;
import org.apache.samoa.core.SerializableInstance;
import org.apache.samoa.instances.Instance;
import java.io.Serializable;
/**
* The Class InstanceContent.
*/
@Immutable
final public class InstanceContent implements Serializable {
private static final long serialVersionUID = -8620668863064613841L;
private long instanceIndex;
private int classifierIndex;
private int evaluationIndex;
private SerializableInstance instance;
private boolean isTraining;
private boolean isTesting;
private boolean isLast = false;
public InstanceContent() {
}
/**
* Instantiates a new instance event.
*
* @param index
* the index
* @param instance
* the instance
* @param isTraining
* the is training
*/
public InstanceContent(long index, Instance instance,
boolean isTraining, boolean isTesting) {
if (instance != null) {
this.instance = new SerializableInstance(instance);
}
this.instanceIndex = index;
this.isTraining = isTraining;
this.isTesting = isTesting;
}
/**
* Gets the single instance of InstanceEvent.
*
* @return the instance.
*/
public Instance getInstance() {
return instance;
}
/**
* Gets the instance index.
*
* @return the index of the data vector.
*/
public long getInstanceIndex() {
return instanceIndex;
}
/**
* Gets the class id.
*
* @return the true class of the vector.
*/
public int getClassId() {
// return classId;
return (int) instance.classValue();
}
/**
* Checks if is training.
*
* @return true if this is training data.
*/
public boolean isTraining() {
return isTraining;
}
/**
* Set training flag.
*
* @param training
* flag.
*/
public void setTraining(boolean training) {
this.isTraining = training;
}
/**
* Checks if is testing.
*
* @return true if this is testing data.
*/
public boolean isTesting() {
return isTesting;
}
/**
* Set testing flag.
*
* @param testing
* flag.
*/
public void setTesting(boolean testing) {
this.isTesting = testing;
}
/**
* Gets the classifier index.
*
* @return the classifier index
*/
public int getClassifierIndex() {
return classifierIndex;
}
/**
* Sets the classifier index.
*
* @param classifierIndex
* the new classifier index
*/
public void setClassifierIndex(int classifierIndex) {
this.classifierIndex = classifierIndex;
}
/**
* Gets the evaluation index.
*
* @return the evaluation index
*/
public int getEvaluationIndex() {
return evaluationIndex;
}
/**
* Sets the evaluation index.
*
* @param evaluationIndex
* the new evaluation index
*/
public void setEvaluationIndex(int evaluationIndex) {
this.evaluationIndex = evaluationIndex;
}
/**
* Sets the instance index.
*
* @param instanceIndex
* the new evaluation index
*/
public void setInstanceIndex(long instanceIndex) {
this.instanceIndex = instanceIndex;
}
public boolean isLastEvent() {
return isLast;
}
public void setLast(boolean isLast) {
this.isLast = isLast;
}
@Override
public String toString() {
return String
.format(
"InstanceContent [instanceIndex=%s, classifierIndex=%s, evaluationIndex=%s, instance=%s, isTraining=%s, isTesting=%s, isLast=%s]",
instanceIndex, classifierIndex, evaluationIndex, instance, isTraining, isTesting, isLast);
}
}
| apache-2.0 |
tadayosi/switchyard | core/common/core/src/main/java/org/switchyard/common/type/classpath/AbstractTypeFilter.java | 3104 | /*
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.switchyard.common.type.classpath;
import java.util.ArrayList;
import java.util.List;
import org.jboss.logging.Logger;
import org.switchyard.common.type.Classes;
/**
* Abstract Java type filter.
*
* @author <a href="mailto:tom.fennelly@gmail.com">tom.fennelly@gmail.com</a>
*/
public abstract class AbstractTypeFilter implements Filter {
private Logger _logger;
private List<Class<?>> _classes = new ArrayList<Class<?>>();
/**
* Protected constructor.
*/
protected AbstractTypeFilter() {
_logger = Logger.getLogger(getClass());
}
/**
* {@inheritDoc}
*/
@Override
public boolean continueScanning() {
return true;
}
/**
* Is the Java type a filter match.
* @param clazz The Java type to be checked.
* @return true if the Java type is a match, otherwise false.
*/
public abstract boolean matches(Class<?> clazz);
/**
* Get the set of filtered (i.e. matching) types.
* @return The set of filtered (i.e. matching) types.
*/
public List<Class<?>> getMatchedTypes() {
return _classes;
}
/**
* Clear the current set of matched types.
*/
public void clear() {
_classes.clear();
}
/**
* Filter the specified resource.
* @param resourceName The classpath resource file name.
*/
public void filter(String resourceName) {
if (resourceName.endsWith(".class")) {
String className = toClassName(resourceName);
try {
// Assumption here is that these classes are on the scanner's classpath...
Class<?> clazz = Classes.forName(className, getClass());
if (matches(clazz)) {
_classes.add(clazz);
}
} catch (Throwable throwable) {
_logger.debug("Resource '" + resourceName + "' presented to '" + InstanceOfFilter.class.getName() + "', but not loadable by classloader. Ignoring.", throwable);
}
}
}
private String toClassName(String resourceName) {
if (resourceName.startsWith("/")) {
resourceName = resourceName.substring(1);
}
if (resourceName.endsWith(".class")) {
resourceName = resourceName.substring(0, resourceName.length() - ".class".length());
}
resourceName = resourceName.replace('/', '.');
return resourceName;
}
}
| apache-2.0 |
yingyun001/ovirt-engine | frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/profiles/NewVnicProfileModel.java | 1802 | package org.ovirt.engine.ui.uicommonweb.models.profiles;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VnicProfileParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.IModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
public class NewVnicProfileModel extends VnicProfileModel {
public NewVnicProfileModel(IModel sourceModel,
Version dcCompatibilityVersion,
boolean customPropertiesVisible,
Guid dcId) {
super(sourceModel, dcCompatibilityVersion, customPropertiesVisible, dcId, null);
setTitle(ConstantsManager.getInstance().getConstants().newVnicProfileTitle());
setHelpTag(HelpTag.new_vnic_profile);
setHashName("new_vnic_profile"); //$NON-NLS-1$
getPortMirroring().setEntity(false);
getPassthrough().setEntity(false);
}
public NewVnicProfileModel(IModel sourceModel, Version dcCompatibilityVersion, Guid dcId) {
this(sourceModel, dcCompatibilityVersion, true, dcId);
}
public NewVnicProfileModel() {
this(null, null, false, null);
}
@Override
protected void initCustomProperties() {
// Do nothing
}
@Override
protected VdcActionType getVdcActionType() {
return VdcActionType.AddVnicProfile;
}
@Override
protected VdcActionParametersBase getActionParameters() {
VnicProfileParameters parameters = new VnicProfileParameters(getProfile());
parameters.setPublicUse(getPublicUse().getEntity());
return parameters;
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/sun/misc/JavaIOAccess.java | 1426 | /*
* 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.
*/
package sun.misc;
import java.io.Console;
import java.nio.charset.Charset;
public interface JavaIOAccess {
public Console console();
public Runnable consoleRestoreHook();
public Charset charset();
}
| apache-2.0 |
madhav123/gkmaster | serviceInterfaces/src/main/java/org/mifos/dto/domain/ReportCategoryDto.java | 1125 | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.dto.domain;
public class ReportCategoryDto {
private final Integer id;
private final String name;
public ReportCategoryDto(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return this.id;
}
public String getName() {
return this.name;
}
}
| apache-2.0 |
medicayun/medicayundicom | dcm4jboss-all/tags/DCM4CHEE_2_14_2_TAGA/dcm4jboss-ejb/src/java/org/dcm4chex/archive/ejb/session/StudyReconciliationBean.java | 7596 | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), available at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* TIANI Medgraph AG.
* Portions created by the Initial Developer are Copyright (C) 2003-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunter.zeilinger@tiani.com>
* Franz Willer <franz.willer@gwi-ag.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chex.archive.ejb.session;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import org.dcm4che.data.Dataset;
import org.dcm4che.dict.Status;
import org.dcm4che.net.DcmServiceException;
import org.dcm4chex.archive.ejb.interfaces.PatientUpdateLocal;
import org.dcm4chex.archive.ejb.interfaces.PatientUpdateLocalHome;
import org.dcm4chex.archive.ejb.interfaces.SeriesLocal;
import org.dcm4chex.archive.ejb.interfaces.StudyLocal;
import org.dcm4chex.archive.ejb.interfaces.StudyLocalHome;
import org.dcm4chex.archive.exceptions.NonUniquePatientException;
import org.dcm4chex.archive.exceptions.PatientMergedException;
/**
* @author gunter.zeilinger@tiani.com
* @version $Revision: 8056 $ $Date: 2008-11-12 21:31:15 +0800 (周三, 12 11月 2008) $
* @since Jun 6, 2005
*
* @ejb.bean name="StudyReconciliation" type="Stateless" view-type="remote"
* jndi-name="ejb/StudyReconciliation"
*
* @ejb.transaction-type type="Container"
* @ejb.transaction type="Required"
*
* @ejb.ejb-ref ejb-name="Patient" view-type="local" ref-name="ejb/Patient"
* @ejb.ejb-ref ejb-name="Study" view-type="local" ref-name="ejb/Study"
* @ejb.ejb-ref ejb-name="Series" view-type="local" ref-name="ejb/Series"
* @ejb.ejb-ref ejb-name="Instance" view-type="local" ref-name="ejb/Instance"
* @ejb.ejb-ref ejb-name="PatientUpdate" view-type="local" ref-name="ejb/PatientUpdate"
*
* @ejb.env-entry name="AttributeFilterConfigURL" type="java.lang.String"
* value="resource:dcm4chee-attribute-filter.xml"
*/
public abstract class StudyReconciliationBean implements SessionBean {
private static final Logger log = Logger.getLogger(StudyReconciliationBean.class);
private StudyLocalHome studyHome;
private PatientUpdateLocal patientUpdate;
public void setSessionContext(SessionContext arg0) throws EJBException,
RemoteException {
Context jndiCtx = null;
try {
jndiCtx = new InitialContext();
studyHome = (StudyLocalHome) jndiCtx
.lookup("java:comp/env/ejb/Study");
patientUpdate = ((PatientUpdateLocalHome) jndiCtx
.lookup("java:comp/env/ejb/PatientUpdate")).create();
} catch (NamingException e) {
throw new EJBException(e);
} catch (CreateException e) {
throw new EJBException(e);
} finally {
if (jndiCtx != null) {
try {
jndiCtx.close();
} catch (NamingException ignore) {
}
}
}
}
public void unsetSessionContext() {
studyHome = null;
}
private StudyLocal getStudy(String suid)
throws FinderException, DcmServiceException {
try {
return studyHome.findByStudyIuid(suid);
} catch (ObjectNotFoundException e) {
throw new DcmServiceException(Status.NoSuchSOPClass, suid);
}
}
/**
* @throws FinderException
* @ejb.interface-method
*/
public Collection getStudyIuidsWithStatus(int status,Timestamp createdBefore, int limit) throws FinderException {
Collection col = studyHome.findStudiesWithStatus( status, createdBefore, limit );
ArrayList studyIuids = new ArrayList();
for ( Iterator iter = col.iterator() ; iter.hasNext() ;) {
studyIuids.add( ((StudyLocal) iter.next()).getStudyIuid());
}
return studyIuids;
}
/**
* @throws DcmServiceException
* @throws FinderException
* @ejb.interface-method
*/
public void updateStatus(Collection studyIuids, int status) throws FinderException, DcmServiceException {
if ( studyIuids == null ) return;
for ( Iterator iter = studyIuids.iterator() ; iter.hasNext() ;) {
getStudy((String) iter.next()).setStudyStatus(status);
}
}
/**
* @throws DcmServiceException
* @throws FinderException
* @ejb.interface-method
*/
public void updateStatus(String studyIuid, int status) throws FinderException, DcmServiceException {
if ( studyIuid == null ) return;
getStudy(studyIuid).setStudyStatus(status);
}
/**
* @ejb.interface-method
*/
public void updatePatient(Dataset attrs)
throws FinderException, CreateException {
patientUpdate.updatePatient(attrs);
}
/**
* @ejb.interface-method
*/
public void mergePatient(Dataset dominant, Dataset prior)
throws FinderException, CreateException {
patientUpdate.mergePatient(dominant, prior);
}
/**
* @throws DcmServiceException
* @throws FinderException
* @ejb.interface-method
*/
public void updateStudyAndSeries(String studyIuid, int studyStatus, Map map) throws FinderException, DcmServiceException {
if ( studyIuid == null ) return;
StudyLocal study = getStudy(studyIuid);
study.setStudyStatus(studyStatus);
if ( map != null && !map.isEmpty()) {
Iterator iter = study.getSeries().iterator();
Dataset ds, dsOrig;
SeriesLocal sl;
do {
sl = (SeriesLocal)iter.next();
ds = sl.getAttributes(false);
dsOrig = (Dataset)map.get(sl.getSeriesIuid());
ds.putAll(dsOrig);
sl.setAttributes(ds);
} while ( iter.hasNext() );
ds = study.getAttributes(false);
ds.putAll(dsOrig);
study.setAttributes(ds);
study.updateModalitiesInStudy();
study.updateSOPClassesInStudy();
}
}
}
| apache-2.0 |
txazo/struts2 | src/main/java/org/apache/struts2/views/freemarker/tags/SetModel.java | 1368 | /*
* $Id$
*
* 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.struts2.views.freemarker.tags;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.components.Component;
import org.apache.struts2.components.Set;
import com.opensymphony.xwork2.util.ValueStack;
/**
* @see Set
*/
public class SetModel extends TagModel {
public SetModel(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
super(stack, req, res);
}
protected Component getBean() {
return new Set(stack);
}
}
| apache-2.0 |
shawijayasekera/component-dep | components/mediator/src/main/java/com/wso2telco/dep/mediator/impl/payment/AmountRefundHandler.java | 8972 | /*******************************************************************************
* Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
*
* WSO2.Telco Inc. licences this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.wso2telco.dep.mediator.impl.payment;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.json.JSONObject;
import org.wso2.carbon.utils.CarbonUtils;
import com.wso2telco.core.dbutils.fileutils.FileReader;
import com.wso2telco.dep.mediator.MSISDNConstants;
import com.wso2telco.dep.mediator.OperatorEndpoint;
import com.wso2telco.dep.mediator.ResponseHandler;
import com.wso2telco.dep.mediator.internal.AggregatorValidator;
import com.wso2telco.dep.mediator.internal.ApiUtils;
import com.wso2telco.dep.mediator.internal.Type;
import com.wso2telco.dep.mediator.internal.UID;
import com.wso2telco.dep.mediator.mediationrule.OriginatingCountryCalculatorIDD;
import com.wso2telco.dep.mediator.service.PaymentService;
import com.wso2telco.dep.mediator.util.FileNames;
import com.wso2telco.dep.oneapivalidation.exceptions.CustomException;
import com.wso2telco.dep.oneapivalidation.service.IServiceValidate;
import com.wso2telco.dep.oneapivalidation.service.impl.payment.ValidateRefund;
import com.wso2telco.dep.subscriptionvalidator.util.ValidatorUtils;
/**
*
* @author User
*/
public class AmountRefundHandler implements PaymentHandler {
private static Log log = LogFactory.getLog(AmountRefundHandler.class);
private static final String API_TYPE = "payment";
private OriginatingCountryCalculatorIDD occi;
private ResponseHandler responseHandler;
private PaymentExecutor executor;
private PaymentService dbservice;
private ApiUtils apiUtils;
private PaymentUtil paymentUtil;
public AmountRefundHandler(PaymentExecutor executor) {
this.executor = executor;
occi = new OriginatingCountryCalculatorIDD();
responseHandler = new ResponseHandler();
dbservice = new PaymentService();
apiUtils = new ApiUtils();
paymentUtil = new PaymentUtil();
}
@Override
public boolean validate(String httpMethod, String requestPath,
JSONObject jsonBody, MessageContext context) throws Exception {
if (!httpMethod.equalsIgnoreCase("POST")) {
((Axis2MessageContext) context).getAxis2MessageContext()
.setProperty("HTTP_SC", 405);
throw new Exception("Method not allowed");
}
IServiceValidate validator = new ValidateRefund();
validator.validateUrl(requestPath);
validator.validate(jsonBody.toString());
return true;
}
@Override
public boolean handle(MessageContext context) throws Exception {
String requestid = UID.getUniqueID(Type.PAYMENT.getCode(), context,
executor.getApplicationid());
HashMap<String, String> jwtDetails = apiUtils
.getJwtTokenDetails(context);
OperatorEndpoint endpoint = null;
String clientCorrelator = null;
FileReader fileReader = new FileReader();
String file = CarbonUtils.getCarbonConfigDirPath() + File.separator + FileNames.MEDIATOR_CONF_FILE.getFileName();
Map<String, String> mediatorConfMap = fileReader.readPropertyFile(file);
String hub_gateway_id = mediatorConfMap.get("hub_gateway_id");
log.debug("Hub / Gateway Id : " + hub_gateway_id);
String appId = jwtDetails.get("applicationid");
log.debug("Application Id : " + appId);
String subscriber = jwtDetails.get("subscriber");
log.debug("Subscriber Name : " + subscriber);
JSONObject jsonBody = executor.getJsonBody();
String endUserId = jsonBody.getJSONObject("amountTransaction")
.getString("endUserId");
String msisdn = endUserId.substring(5);
context.setProperty(MSISDNConstants.USER_MSISDN, msisdn);
// OperatorEndpoint endpoint = null;
if (ValidatorUtils.getValidatorForSubscription(context).validate(
context)) {
endpoint = occi.getAPIEndpointsByMSISDN(
endUserId.replace("tel:", ""), API_TYPE,
executor.getSubResourcePath(), false,
executor.getValidoperators());
}
String sending_add = endpoint.getEndpointref().getAddress();
log.debug("sending endpoint found: " + sending_add);
/*
* JSONObject clientclr = jsonBody.getJSONObject("amountTransaction");
* String originalClientCorrelator =
* clientclr.getString("clientCorrelator");
* clientclr.put("clientCorrelator", originalClientCorrelator + ":" +
* requestid);
*/
JSONObject objAmountTransaction = jsonBody
.getJSONObject("amountTransaction");
if (!objAmountTransaction.isNull("clientCorrelator")) {
clientCorrelator = nullOrTrimmed(objAmountTransaction.get(
"clientCorrelator").toString());
}
if (clientCorrelator == null || clientCorrelator.equals("")) {
log.debug("clientCorrelator not provided by application and hub/plugin generating clientCorrelator on behalf of application");
String hashString = apiUtils.getHashString(jsonBody.toString());
log.debug("hashString : " + hashString);
objAmountTransaction.put("clientCorrelator", hashString + "-"
+ requestid + ":" + hub_gateway_id + ":" + appId);
} else {
log.debug("clientCorrelator provided by application");
objAmountTransaction.put("clientCorrelator", clientCorrelator + ":"
+ hub_gateway_id + ":" + appId);
}
JSONObject chargingdmeta = objAmountTransaction.getJSONObject(
"paymentAmount").getJSONObject("chargingMetaData");
/* String subscriber = paymentUtil.storeSubscription(context); */
boolean isaggrigator = PaymentUtil.isAggregator(context);
if (isaggrigator) {
// JSONObject chargingdmeta =
// clientclr.getJSONObject("paymentAmount").getJSONObject("chargingMetaData");
if (!chargingdmeta.isNull("onBehalfOf")) {
new AggregatorValidator().validateMerchant(
Integer.valueOf(executor.getApplicationid()),
endpoint.getOperator(), subscriber,
chargingdmeta.getString("onBehalfOf"));
}
}
// validate payment categoreis
List<String> validCategoris = dbservice.getValidPayCategories();
PaymentUtil.validatePaymentCategory(chargingdmeta, validCategoris);
String responseStr = executor.makeRequest(endpoint, sending_add,
jsonBody.toString(), true, context, false);
// Payment Error Exception Correction
String base = PaymentUtil.str_piece(
PaymentUtil.str_piece(responseStr, '{', 2), ':', 1);
String errorReturn = "\"" + "requestError" + "\"";
executor.removeHeaders(context);
if (base.equals(errorReturn)) {
executor.handlePluginException(responseStr);
}
responseStr = makeRefundResponse(responseStr, requestid,
clientCorrelator);
// set response re-applied
executor.setResponse(context, responseStr);
((Axis2MessageContext) context).getAxis2MessageContext().setProperty(
"messageType", "application/json");
((Axis2MessageContext) context).getAxis2MessageContext().setProperty(
"ContentType", "application/json");
return true;
}
private String makeRefundResponse(String responseStr, String requestid,
String clientCorrelator) {
String jsonResponse = null;
try {
FileReader fileReader = new FileReader();
String file = CarbonUtils.getCarbonConfigDirPath() + File.separator + FileNames.MEDIATOR_CONF_FILE.getFileName();
Map<String, String> mediatorConfMap = fileReader.readPropertyFile(file);
String ResourceUrlPrefix = mediatorConfMap.get("hubGateway");
JSONObject jsonObj = new JSONObject(responseStr);
JSONObject objAmountTransaction = jsonObj
.getJSONObject("amountTransaction");
objAmountTransaction.put("clientCorrelator", clientCorrelator);
objAmountTransaction.put("resourceURL", ResourceUrlPrefix
+ executor.getResourceUrl() + "/" + requestid);
jsonResponse = jsonObj.toString();
} catch (Exception e) {
log.error("Error in formatting amount refund response : "
+ e.getMessage());
throw new CustomException("SVC1000", "", new String[] { null });
}
log.debug("Formatted amount refund response : " + jsonResponse);
return jsonResponse;
}
/**
* + * Ensure the input value is either a null value or a trimmed string +
*/
public static String nullOrTrimmed(String s) {
String rv = null;
if (s != null && s.trim().length() > 0) {
rv = s.trim();
}
return rv;
}
} | apache-2.0 |
IvanNikolaychuk/pentaho-kettle | plugins/kettle-xml-plugin/src/org/pentaho/di/ui/trans/steps/getxmldata/LoopNodesImportProgressDialog.java | 8396 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2015 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.trans.steps.getxmldata;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.steps.getxmldata.GetXMLDataMeta;
import org.pentaho.di.trans.steps.getxmldata.IgnoreDTDEntityResolver;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
/**
* Takes care of displaying a dialog that will handle the wait while we're finding out loop nodes for an XML file
*
* @author Samatar
* @since 07-apr-2010
*/
public class LoopNodesImportProgressDialog {
private static Class<?> PKG = GetXMLDataMeta.class; // for i18n purposes, needed by Translator2!!
private Shell shell;
private GetXMLDataMeta meta;
private String[] Xpaths;
private String filename;
private String xml;
private String url;
private String encoding;
private ArrayList<String> listpath;
private int nr;
/**
* Creates a new dialog that will handle the wait while we're finding out loop nodes for an XML file
*/
public LoopNodesImportProgressDialog( Shell shell, GetXMLDataMeta meta, String filename, String encoding ) {
this.shell = shell;
this.meta = meta;
this.Xpaths = null;
this.filename = filename;
this.encoding = encoding;
this.listpath = new ArrayList<String>();
this.nr = 0;
this.xml = null;
this.url = null;
}
public LoopNodesImportProgressDialog( Shell shell, GetXMLDataMeta meta, String xmlSource, boolean useUrl ) {
this.shell = shell;
this.meta = meta;
this.Xpaths = null;
this.filename = null;
this.encoding = null;
this.listpath = new ArrayList<String>();
this.nr = 0;
if ( useUrl ) {
this.xml = null;
this.url = xmlSource;
} else {
this.xml = xmlSource;
this.url = null;
}
}
public String[] open() {
IRunnableWithProgress op = new IRunnableWithProgress() {
public void run( IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException {
try {
Xpaths = doScan( monitor );
} catch ( Exception e ) {
e.printStackTrace();
throw new InvocationTargetException( e, BaseMessages.getString( PKG,
"GetXMLDateLoopNodesImportProgressDialog.Exception.ErrorScanningFile", filename, e.toString() ) );
}
}
};
try {
ProgressMonitorDialog pmd = new ProgressMonitorDialog( shell );
pmd.run( true, true, op );
} catch ( InvocationTargetException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG,
"GetXMLDateLoopNodesImportProgressDialog.ErrorScanningFile.Title" ), BaseMessages.getString( PKG,
"GetXMLDateLoopNodesImportProgressDialog.ErrorScanningFile.Message" ), e );
} catch ( InterruptedException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG,
"GetXMLDateLoopNodesImportProgressDialog.ErrorScanningFile.Title" ), BaseMessages.getString( PKG,
"GetXMLDateLoopNodesImportProgressDialog.ErrorScanningFile.Message" ), e );
}
return Xpaths;
}
@SuppressWarnings( "unchecked" )
private String[] doScan( IProgressMonitor monitor ) throws Exception {
monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile",
filename ), 1 );
SAXReader reader = new SAXReader();
monitor.worked( 1 );
if ( monitor.isCanceled() ) {
return null;
}
// Validate XML against specified schema?
if ( meta.isValidating() ) {
reader.setValidation( true );
reader.setFeature( "http://apache.org/xml/features/validation/schema", true );
} else {
// Ignore DTD
reader.setEntityResolver( new IgnoreDTDEntityResolver() );
}
monitor.worked( 1 );
monitor
.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument" ), 1 );
if ( monitor.isCanceled() ) {
return null;
}
InputStream is = null;
try {
Document document = null;
if ( !Const.isEmpty( filename ) ) {
is = KettleVFS.getInputStream( filename );
document = reader.read( is, encoding );
} else {
if ( !Const.isEmpty( xml ) ) {
document = reader.read( new StringReader( xml ) );
} else {
document = reader.read( new URL( url ) );
}
}
monitor.worked( 1 );
monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened" ),
1 );
monitor.worked( 1 );
monitor.beginTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode" ), 1 );
if ( monitor.isCanceled() ) {
return null;
}
List<Node> nodes = document.selectNodes( document.getRootElement().getName() );
monitor.worked( 1 );
monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes" ) );
if ( monitor.isCanceled() ) {
return null;
}
for ( Node node : nodes ) {
if ( monitor.isCanceled() ) {
return null;
}
if ( !listpath.contains( node.getPath() ) ) {
nr++;
monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes",
String.valueOf( nr ) ) );
monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.AddingNode", node
.getPath() ) );
listpath.add( node.getPath() );
addLoopXPath( node, monitor );
}
}
monitor.worked( 1 );
} finally {
try {
if ( is != null ) {
is.close();
}
} catch ( Exception e ) { /* Ignore */
}
}
String[] list_xpath = listpath.toArray( new String[listpath.size()] );
monitor.setTaskName( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned" ) );
monitor.done();
return list_xpath;
}
private void addLoopXPath( Node node, IProgressMonitor monitor ) {
Element ce = (Element) node;
monitor.worked( 1 );
// List child
for ( int j = 0; j < ce.nodeCount(); j++ ) {
if ( monitor.isCanceled() ) {
return;
}
Node cnode = ce.node( j );
if ( !Const.isEmpty( cnode.getName() ) ) {
Element cce = (Element) cnode;
if ( !listpath.contains( cnode.getPath() ) ) {
nr++;
monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes",
String.valueOf( nr ) ) );
monitor.subTask( BaseMessages.getString( PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.AddingNode",
cnode.getPath() ) );
listpath.add( cnode.getPath() );
}
// let's get child nodes
if ( cce.nodeCount() > 1 ) {
addLoopXPath( cnode, monitor );
}
}
}
}
}
| apache-2.0 |
treasure-data/presto | presto-raptor-legacy/src/main/java/io/prestosql/plugin/raptor/legacy/storage/OrcFileWriter.java | 14021 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.plugin.raptor.legacy.storage;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.json.JsonCodec;
import io.airlift.slice.Slice;
import io.prestosql.plugin.raptor.legacy.util.SyncingFileSystem;
import io.prestosql.spi.Page;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.classloader.ThreadContextClassLoader;
import io.prestosql.spi.type.DecimalType;
import io.prestosql.spi.type.Type;
import io.prestosql.spi.type.TypeId;
import io.prestosql.spi.type.VarbinaryType;
import io.prestosql.spi.type.VarcharType;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.IOConstants;
import org.apache.hadoop.hive.ql.io.orc.OrcFile;
import org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat;
import org.apache.hadoop.hive.ql.io.orc.OrcSerde;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.SettableStructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.hive.shims.ShimLoader;
import org.apache.hadoop.util.VersionInfo;
import org.apache.orc.NullMemoryManager;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.airlift.json.JsonCodec.jsonCodec;
import static io.prestosql.plugin.raptor.legacy.RaptorErrorCode.RAPTOR_ERROR;
import static io.prestosql.plugin.raptor.legacy.storage.Row.extractRow;
import static io.prestosql.plugin.raptor.legacy.storage.StorageType.arrayOf;
import static io.prestosql.plugin.raptor.legacy.storage.StorageType.mapOf;
import static io.prestosql.plugin.raptor.legacy.util.Types.isArrayType;
import static io.prestosql.plugin.raptor.legacy.util.Types.isMapType;
import static io.prestosql.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
import static io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter;
import static org.apache.hadoop.hive.ql.io.orc.CompressionKind.SNAPPY;
import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category.LIST;
import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category.MAP;
import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category.PRIMITIVE;
import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardListObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardMapObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.getStandardStructObjectInspector;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector;
import static org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory.getPrimitiveTypeInfo;
public class OrcFileWriter
implements Closeable
{
static {
// make sure Hadoop version is loaded from correct class loader
try (ThreadContextClassLoader ignored = new ThreadContextClassLoader(VersionInfo.class.getClassLoader())) {
ShimLoader.getHadoopShims();
}
}
private static final Configuration CONFIGURATION = new Configuration(false);
private static final Constructor<? extends RecordWriter> WRITER_CONSTRUCTOR = getOrcWriterConstructor();
private static final JsonCodec<OrcFileMetadata> METADATA_CODEC = jsonCodec(OrcFileMetadata.class);
private final List<Type> columnTypes;
private final OrcSerde serializer;
private final RecordWriter recordWriter;
private final SettableStructObjectInspector tableInspector;
private final List<StructField> structFields;
private final Object orcRow;
private boolean closed;
private long rowCount;
private long uncompressedSize;
public OrcFileWriter(List<Long> columnIds, List<Type> columnTypes, File target)
{
this(columnIds, columnTypes, target, true);
}
@VisibleForTesting
OrcFileWriter(List<Long> columnIds, List<Type> columnTypes, File target, boolean writeMetadata)
{
this.columnTypes = ImmutableList.copyOf(requireNonNull(columnTypes, "columnTypes is null"));
checkArgument(columnIds.size() == columnTypes.size(), "ids and types mismatch");
checkArgument(isUnique(columnIds), "ids must be unique");
List<StorageType> storageTypes = ImmutableList.copyOf(toStorageTypes(columnTypes));
Iterable<String> hiveTypeNames = storageTypes.stream().map(StorageType::getHiveTypeName).collect(toList());
List<String> columnNames = columnIds.stream()
.map(Objects::toString)
.collect(toImmutableList());
Properties properties = new Properties();
properties.setProperty(IOConstants.COLUMNS, Joiner.on(',').join(columnNames));
properties.setProperty(IOConstants.COLUMNS_TYPES, Joiner.on(':').join(hiveTypeNames));
serializer = createSerializer(properties);
recordWriter = createRecordWriter(new Path(target.toURI()), columnIds, columnTypes, writeMetadata);
tableInspector = getStandardStructObjectInspector(columnNames, getJavaObjectInspectors(storageTypes));
structFields = ImmutableList.copyOf(tableInspector.getAllStructFieldRefs());
orcRow = tableInspector.create();
}
public void appendPages(List<Page> pages)
{
for (Page page : pages) {
for (int position = 0; position < page.getPositionCount(); position++) {
appendRow(extractRow(page, position, columnTypes));
}
}
}
public void appendPages(List<Page> inputPages, int[] pageIndexes, int[] positionIndexes)
{
checkArgument(pageIndexes.length == positionIndexes.length, "pageIndexes and positionIndexes do not match");
for (int i = 0; i < pageIndexes.length; i++) {
Page page = inputPages.get(pageIndexes[i]);
appendRow(extractRow(page, positionIndexes[i], columnTypes));
}
}
public void appendRow(Row row)
{
List<Object> columns = row.getColumns();
checkArgument(columns.size() == columnTypes.size());
for (int channel = 0; channel < columns.size(); channel++) {
tableInspector.setStructFieldData(orcRow, structFields.get(channel), columns.get(channel));
}
try {
recordWriter.write(serializer.serialize(orcRow, tableInspector));
}
catch (IOException e) {
throw new PrestoException(RAPTOR_ERROR, "Failed to write record", e);
}
rowCount++;
uncompressedSize += row.getSizeInBytes();
}
@Override
public void close()
{
if (closed) {
return;
}
closed = true;
try {
recordWriter.close(false);
}
catch (IOException e) {
throw new PrestoException(RAPTOR_ERROR, "Failed to close writer", e);
}
}
public long getRowCount()
{
return rowCount;
}
public long getUncompressedSize()
{
return uncompressedSize;
}
private static OrcSerde createSerializer(Properties properties)
{
OrcSerde serde = new OrcSerde();
serde.initialize(CONFIGURATION, properties);
return serde;
}
private static RecordWriter createRecordWriter(Path target, List<Long> columnIds, List<Type> columnTypes, boolean writeMetadata)
{
try (FileSystem fileSystem = new SyncingFileSystem(CONFIGURATION)) {
OrcFile.WriterOptions options = OrcFile.writerOptions(CONFIGURATION)
.memory(new NullMemoryManager())
.fileSystem(fileSystem)
.compress(SNAPPY);
if (writeMetadata) {
options.callback(createFileMetadataCallback(columnIds, columnTypes));
}
return WRITER_CONSTRUCTOR.newInstance(target, options);
}
catch (ReflectiveOperationException | IOException e) {
throw new PrestoException(RAPTOR_ERROR, "Failed to create writer", e);
}
}
private static OrcFile.WriterCallback createFileMetadataCallback(List<Long> columnIds, List<Type> columnTypes)
{
return new OrcFile.WriterCallback()
{
@Override
public void preStripeWrite(OrcFile.WriterContext context)
{}
@Override
public void preFooterWrite(OrcFile.WriterContext context)
{
ImmutableMap.Builder<Long, TypeId> columnTypesMap = ImmutableMap.builder();
for (int i = 0; i < columnIds.size(); i++) {
columnTypesMap.put(columnIds.get(i), columnTypes.get(i).getTypeId());
}
byte[] bytes = METADATA_CODEC.toJsonBytes(new OrcFileMetadata(columnTypesMap.build()));
context.getWriter().addUserMetadata(OrcFileMetadata.KEY, ByteBuffer.wrap(bytes));
}
};
}
private static Constructor<? extends RecordWriter> getOrcWriterConstructor()
{
try {
String writerClassName = OrcOutputFormat.class.getName() + "$OrcRecordWriter";
Constructor<? extends RecordWriter> constructor = OrcOutputFormat.class.getClassLoader()
.loadClass(writerClassName).asSubclass(RecordWriter.class)
.getDeclaredConstructor(Path.class, OrcFile.WriterOptions.class);
constructor.setAccessible(true);
return constructor;
}
catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
private static List<ObjectInspector> getJavaObjectInspectors(List<StorageType> types)
{
return types.stream()
.map(StorageType::getHiveTypeName)
.map(TypeInfoUtils::getTypeInfoFromTypeString)
.map(OrcFileWriter::getJavaObjectInspector)
.collect(toList());
}
private static ObjectInspector getJavaObjectInspector(TypeInfo typeInfo)
{
Category category = typeInfo.getCategory();
if (category == PRIMITIVE) {
return getPrimitiveJavaObjectInspector(getPrimitiveTypeInfo(typeInfo.getTypeName()));
}
if (category == LIST) {
ListTypeInfo listTypeInfo = (ListTypeInfo) typeInfo;
return getStandardListObjectInspector(getJavaObjectInspector(listTypeInfo.getListElementTypeInfo()));
}
if (category == MAP) {
MapTypeInfo mapTypeInfo = (MapTypeInfo) typeInfo;
return getStandardMapObjectInspector(
getJavaObjectInspector(mapTypeInfo.getMapKeyTypeInfo()),
getJavaObjectInspector(mapTypeInfo.getMapValueTypeInfo()));
}
throw new PrestoException(GENERIC_INTERNAL_ERROR, "Unhandled storage type: " + category);
}
private static <T> boolean isUnique(Collection<T> items)
{
return new HashSet<>(items).size() == items.size();
}
private static List<StorageType> toStorageTypes(List<Type> columnTypes)
{
return columnTypes.stream().map(OrcFileWriter::toStorageType).collect(toList());
}
private static StorageType toStorageType(Type type)
{
if (type instanceof DecimalType) {
DecimalType decimalType = (DecimalType) type;
return StorageType.decimal(decimalType.getPrecision(), decimalType.getScale());
}
Class<?> javaType = type.getJavaType();
if (javaType == boolean.class) {
return StorageType.BOOLEAN;
}
if (javaType == long.class) {
return StorageType.LONG;
}
if (javaType == double.class) {
return StorageType.DOUBLE;
}
if (javaType == Slice.class) {
if (type instanceof VarcharType) {
return StorageType.STRING;
}
if (type.equals(VarbinaryType.VARBINARY)) {
return StorageType.BYTES;
}
}
if (isArrayType(type)) {
return arrayOf(toStorageType(type.getTypeParameters().get(0)));
}
if (isMapType(type)) {
return mapOf(toStorageType(type.getTypeParameters().get(0)), toStorageType(type.getTypeParameters().get(1)));
}
throw new PrestoException(NOT_SUPPORTED, "No storage type for type: " + type);
}
}
| apache-2.0 |
tadayosi/switchyard | components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedRuntimeEnvironmentBuilder.java | 24620 | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//package org.jbpm.runtime.manager.impl;
package org.switchyard.component.common.knowledge.config.builder.patch;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManagerFactory;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.compiler.kie.builder.impl.KieContainerImpl;
import org.drools.core.marshalling.impl.ClassObjectMarshallingStrategyAcceptor;
import org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy;
import org.drools.core.util.StringUtils;
import org.jbpm.process.core.timer.GlobalSchedulerService;
import org.jbpm.process.instance.event.DefaultSignalManagerFactory;
import org.jbpm.process.instance.impl.DefaultProcessInstanceManagerFactory;
import org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory;
import org.jbpm.runtime.manager.impl.KModuleRegisterableItemsFactory;
import org.jbpm.runtime.manager.impl.SimpleRuntimeEnvironment;
import org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorManager;
import org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorMerger;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.marshalling.ObjectMarshallingStrategy;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.manager.RegisterableItemsFactory;
import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder;
import org.kie.api.runtime.manager.RuntimeEnvironmentBuilderFactory;
import org.kie.api.task.UserGroupCallback;
import org.kie.internal.runtime.conf.DeploymentDescriptor;
import org.kie.internal.runtime.conf.MergeMode;
import org.kie.internal.runtime.conf.NamedObjectModel;
import org.kie.internal.runtime.conf.ObjectModel;
import org.kie.internal.runtime.conf.ObjectModelResolver;
import org.kie.internal.runtime.conf.ObjectModelResolverProvider;
import org.kie.internal.runtime.conf.PersistenceMode;
import org.kie.internal.runtime.manager.Mapper;
import org.kie.internal.runtime.manager.RuntimeEnvironment;
import org.kie.scanner.MavenRepository;
/**
* Builder implementation that follows fluent approach to build <code>RuntimeEnvironments</code>.
* Comes with short cut methods to get predefined configurations of the <code>RuntimeEnvironment</code>:
* <ul>
* <li>getDefault() - returns preconfigured environment with enabled persistence</li>
* <li>getDefaultInMemory() - returns preconfigured environment with disabled persistence for runtime engine</li>
* <li>getDefault(ReleaseId) - returns preconfigured environment with enabled persistence that is tailored for kjar</li>
* <li>getDefault(ReleaseId, String, String) - returns preconfigured environment with enabled persistence that is tailored for kjar and allows to specify kbase and ksession name</li>
* <li>getDefault(String, String, String) - returns preconfigured environment with enabled persistence that is tailored for kjar</li>
* <li>getDefault(String, String, String, String, String) - returns preconfigured environment with enabled persistence that is tailored for kjar and allows to specify kbase and ksession name</li>
* <li>getEmpty() - completely empty environment for self configuration</li>
* <li>getClasspathKModuleDefault() - returns preconfigured environment with enabled persistence based on classpath kiecontainer</li>
* <li>getClasspathKModuleDefault(String, String) - returns preconfigured environment with enabled persistence based on classpath kiecontainer</li>
* </ul>
*
*/
//public class RuntimeEnvironmentBuilder implements RuntimeEnvironmentBuilderFactory, org.kie.api.runtime.manager.RuntimeEnvironmentBuilder{
public class PatchedRuntimeEnvironmentBuilder implements RuntimeEnvironmentBuilderFactory, org.kie.api.runtime.manager.RuntimeEnvironmentBuilder {
private static final class PatchedRuntimeEnvironment extends SimpleRuntimeEnvironment {
private final Set<String> _names = Collections.synchronizedSet(new HashSet<String>());
private PatchedRuntimeEnvironment() {
super(new DefaultRegisterableItemsFactory());
}
@Override
public void addToEnvironment(String name, Object value) {
if (name != null && name.startsWith("org.switchyard")) {
_names.add(name);
}
super.addToEnvironment(name, value);
}
@Override
protected Environment copyEnvironment() {
Environment copy = super.copyEnvironment();
for (String name : _names) {
addIfPresent(name, copy);
}
return copy;
}
}
private static final String DEFAULT_KBASE_NAME = "defaultKieBase";
/**
* Gets the SimpleRuntimeEnvironment.
* @return the SimpleRuntimeEnvironment
*/
public SimpleRuntimeEnvironment getRuntimeEnvironment() {
return _runtimeEnvironment;
}
private SimpleRuntimeEnvironment _runtimeEnvironment;
/**
* Creates a new PatchedRuntimeEnvironmentBuilder.
*/
public PatchedRuntimeEnvironmentBuilder() {
// PATCHED from: this.runtimeEnvironment = new SimpleRuntimeEnvironment();
_runtimeEnvironment = new PatchedRuntimeEnvironment();
}
private PatchedRuntimeEnvironmentBuilder(SimpleRuntimeEnvironment runtimeEnvironment) {
_runtimeEnvironment = runtimeEnvironment;
}
/**
* Provides completely empty <code>RuntimeEnvironmentBuilder</code> instance that allows to manually
* set all required components instead of relying on any defaults.
* @return new instance of <code>RuntimeEnvironmentBuilder</code>
*/
public static RuntimeEnvironmentBuilder getEmpty() {
return new PatchedRuntimeEnvironmentBuilder();
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getDefault() {
// PATCHED from: return new RuntimeEnvironmentBuilder(new DefaultRuntimeEnvironment());
return new PatchedRuntimeEnvironmentBuilder(new PatchedRuntimeEnvironment());
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* but it does not have persistence for process engine configured so it will only store process instances in memory
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getDefaultInMemory() {
// PATCHED from: RuntimeEnvironmentBuilder builder = new RuntimeEnvironmentBuilder(new DefaultRuntimeEnvironment(null, false));
RuntimeEnvironmentBuilder builder = new PatchedRuntimeEnvironmentBuilder(new PatchedRuntimeEnvironment());
builder
.addConfiguration("drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName())
.addConfiguration("drools.processInstanceManagerFactory", DefaultProcessInstanceManagerFactory.class.getName());
return builder;
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* This one is tailored to works smoothly with kjars as the notion of kbase and ksessions
* @param groupId group id of kjar
* @param artifactId artifact id of kjar
* @param version version number of kjar
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version) {
return getDefault(groupId, artifactId, version, null, null);
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* This one is tailored to works smoothly with kjars as the notion of kbase and ksessions
* @param groupId group id of kjar
* @param artifactId artifact id of kjar
* @param version version number of kjar
* @param kbaseName name of the kbase defined in kmodule.xml stored in kjar
* @param ksessionName name of the ksession define in kmodule.xml stored in kjar
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version, String kbaseName, String ksessionName) {
KieServices ks = KieServices.Factory.get();
return getDefault(ks.newReleaseId(groupId, artifactId, version), kbaseName, ksessionName);
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* This one is tailored to works smoothly with kjars as the notion of kbase and ksessions
* @param releaseId <code>ReleaseId</code> that described the kjar
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getDefault(ReleaseId releaseId) {
return getDefault(releaseId, null, null);
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* This one is tailored to works smoothly with kjars as the notion of kbase and ksessions
* @param releaseId <code>ReleaseId</code> that described the kjar
* @param kbaseName name of the kbase defined in kmodule.xml stored in kjar
* @param ksessionName name of the ksession define in kmodule.xml stored in kjar
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getDefault(ReleaseId releaseId, String kbaseName, String ksessionName) {
MavenRepository repository = MavenRepository.getMavenRepository();
repository.resolveArtifact(releaseId.toExternalForm());
KieServices ks = KieServices.Factory.get();
KieContainer kieContainer = ks.newKieContainer(releaseId);
DeploymentDescriptorManager descriptorManager = new DeploymentDescriptorManager();
List<DeploymentDescriptor> descriptorHierarchy = descriptorManager.getDeploymentDescriptorHierarchy(kieContainer);
DeploymentDescriptorMerger merger = new DeploymentDescriptorMerger();
DeploymentDescriptor descriptor = merger.merge(descriptorHierarchy, MergeMode.MERGE_COLLECTIONS);
if (StringUtils.isEmpty(kbaseName)) {
KieBaseModel defaultKBaseModel = ((KieContainerImpl)kieContainer).getKieProject().getDefaultKieBaseModel();
if (defaultKBaseModel != null) {
kbaseName = defaultKBaseModel.getName();
} else {
kbaseName = DEFAULT_KBASE_NAME;
}
}
InternalKieModule module = (InternalKieModule) ((KieContainerImpl)kieContainer).getKieModuleForKBase(kbaseName);
if (module == null) {
throw new IllegalStateException("Cannot find kbase, either it does not exist or there are multiple default kbases in kmodule.xml");
}
KieBase kbase = kieContainer.getKieBase(kbaseName);
RuntimeEnvironmentBuilder builder = null;
if (descriptor.getPersistenceMode() == PersistenceMode.NONE) {
builder = getDefaultInMemory();
} else {
builder = getDefault();
}
Map<String, Object> contaxtParams = new HashMap<String, Object>();
contaxtParams.put("classLoader", kieContainer.getClassLoader());
// populate various properties of the builder
/*
if (descriptor.getPersistenceUnit() != null) {
EntityManagerFactory emf = EntityManagerFactoryManager.get().getOrCreate(descriptor.getPersistenceUnit());
builder.entityManagerFactory(emf);
contaxtParams.put("entityManagerFactory", emf);
}
*/
// process object models that are globally configured (environment entries, session configuration)
for (NamedObjectModel model : descriptor.getEnvironmentEntries()) {
Object entry = getInstanceFromModel(model, kieContainer, contaxtParams);
builder.addEnvironmentEntry(model.getName(), entry);
}
for (NamedObjectModel model : descriptor.getConfiguration()) {
Object entry = getInstanceFromModel(model, kieContainer, contaxtParams);
builder.addConfiguration(model.getName(), (String) entry);
}
ObjectMarshallingStrategy[] mStrategies = new ObjectMarshallingStrategy[descriptor.getMarshallingStrategies().size() + 1];
int index = 0;
for (ObjectModel model : descriptor.getMarshallingStrategies()) {
Object strategy = getInstanceFromModel(model, kieContainer, contaxtParams);
mStrategies[index] = (ObjectMarshallingStrategy)strategy;
index++;
}
// lastly add the main default strategy
mStrategies[index] = new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT);
builder.addEnvironmentEntry(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, mStrategies);
builder.addEnvironmentEntry("KieDeploymentDescriptor", descriptor)
.knowledgeBase(kbase)
.classLoader(kieContainer.getClassLoader())
.registerableItemsFactory(new KModuleRegisterableItemsFactory(kieContainer, ksessionName));
return builder;
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* It relies on KieClasspathContainer that requires to have kmodule.xml present in META-INF folder which
* defines the kjar itself.
* Expects to use default kbase and ksession from kmodule.
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getClasspathKmoduleDefault() {
return getClasspathKmoduleDefault(null, null);
}
/**
* Provides default configuration of <code>RuntimeEnvironmentBuilder</code> that is based on.
* <ul>
* <li>DefaultRuntimeEnvironment</li>
* </ul>
* It relies on KieClasspathContainer that requires to have kmodule.xml present in META-INF folder which
* defines the kjar itself.
* @param kbaseName name of the kbase defined in kmodule.xml
* @param ksessionName name of the ksession define in kmodule.xml
* @return new instance of <code>RuntimeEnvironmentBuilder</code> that is already preconfigured with defaults
*
*/
public static RuntimeEnvironmentBuilder getClasspathKmoduleDefault(String kbaseName, String ksessionName) {
return setupClasspathKmoduleBuilder(KieServices.Factory.get().getKieClasspathContainer(), kbaseName, ksessionName);
}
private static RuntimeEnvironmentBuilder setupClasspathKmoduleBuilder(KieContainer kieContainer,
String kbaseName,
String ksessionName) {
if (StringUtils.isEmpty(kbaseName)) {
KieBaseModel defaultKBaseModel = ((KieContainerImpl)kieContainer).getKieProject().getDefaultKieBaseModel();
if (defaultKBaseModel != null) {
kbaseName = defaultKBaseModel.getName();
} else {
kbaseName = DEFAULT_KBASE_NAME;
}
}
InternalKieModule module = (InternalKieModule) ((KieContainerImpl)kieContainer).getKieModuleForKBase(kbaseName);
if (module == null) {
throw new IllegalStateException("Cannot find kbase with name " + kbaseName);
}
KieBase kbase = kieContainer.getKieBase(kbaseName);
return getDefault()
.knowledgeBase(kbase)
.classLoader(kieContainer.getClassLoader())
.registerableItemsFactory(new KModuleRegisterableItemsFactory(kieContainer, ksessionName));
}
/**
* Sets persistenceEnabled.
* @param persistenceEnabled persistenceEnabled
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder persistence(boolean persistenceEnabled) {
_runtimeEnvironment.setUsePersistence(persistenceEnabled);
return this;
}
/**
* Sets entityManagerFactory.
* @param emf entityManagerFactory
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder entityManagerFactory(Object emf) {
if (emf == null) {
return this;
}
if (!(emf instanceof EntityManagerFactory)) {
throw new IllegalArgumentException("Argument is not of type EntityManagerFactory");
}
_runtimeEnvironment.setEmf((EntityManagerFactory) emf);
return this;
}
/**
* Adds and asset.
* @param asset asset
* @param type type
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder addAsset(Resource asset, ResourceType type) {
if (asset == null || type == null) {
return this;
}
_runtimeEnvironment.addAsset(asset, type);
return this;
}
/**
* Adds an environmentEntry name/value pair.
* @param name name
* @param value value
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder addEnvironmentEntry(String name, Object value) {
if (name == null || value == null) {
return this;
}
_runtimeEnvironment.addToEnvironment(name, value);
return this;
}
/**
* Adds a configuration name/value pair.
* @param name name
* @param value value
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder addConfiguration(String name, String value) {
if (name == null || value == null) {
return this;
}
_runtimeEnvironment.addToConfiguration(name, value);
return this;
}
/**
* Sets the knowledgeBase.
* @param kbase knowledgeBase
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder knowledgeBase(KieBase kbase) {
if (kbase == null) {
return this;
}
_runtimeEnvironment.setKieBase(kbase);
return this;
}
/**
* Sets the userGroupCallback.
* @param callback userGroupCallback
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder userGroupCallback(UserGroupCallback callback) {
if (callback == null) {
return this;
}
_runtimeEnvironment.setUserGroupCallback(callback);
return this;
}
/**
* Sets the mapper.
* @param mapper mapper
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder mapper(Mapper mapper) {
if (mapper == null) {
return this;
}
_runtimeEnvironment.setMapper(mapper);
return this;
}
/**
* Sets the registerableItemsFactory.
* @param factory registerableItemsFactory
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder registerableItemsFactory(RegisterableItemsFactory factory) {
if (factory == null) {
return this;
}
_runtimeEnvironment.setRegisterableItemsFactory(factory);
return this;
}
/**
* Inits and returns the RuntimeEnvironment.
* @return the RuntimeEnvironment
*/
public RuntimeEnvironment get() {
_runtimeEnvironment.init();
return _runtimeEnvironment;
}
/**
* Sets the schedulerService.
* @param globalScheduler schedulerService
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder schedulerService(Object globalScheduler) {
if (globalScheduler == null) {
return this;
}
if (!(globalScheduler instanceof GlobalSchedulerService)) {
throw new IllegalArgumentException("Argument is not of type GlobalSchedulerService");
}
_runtimeEnvironment.setSchedulerService((GlobalSchedulerService) globalScheduler);
return this;
}
/**
* Sets the classLoader.
* @param cl classLoader
* @return this RuntimeEnvironmentBuilder
*/
public RuntimeEnvironmentBuilder classLoader(ClassLoader cl) {
if (cl == null) {
return this;
}
_runtimeEnvironment.setClassLoader(cl);
return this;
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newEmptyBuilder() {
return PatchedRuntimeEnvironmentBuilder.getEmpty();
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder() {
return PatchedRuntimeEnvironmentBuilder.getDefault();
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultInMemoryBuilder() {
return PatchedRuntimeEnvironmentBuilder.getDefaultInMemory();
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(String groupId, String artifactId, String version) {
return PatchedRuntimeEnvironmentBuilder.getDefault(groupId, artifactId, version);
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(String groupId, String artifactId, String version, String kbaseName, String ksessionName) {
return PatchedRuntimeEnvironmentBuilder.getDefault(groupId, artifactId, version, kbaseName, ksessionName);
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(ReleaseId releaseId) {
return PatchedRuntimeEnvironmentBuilder.getDefault(releaseId);
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(ReleaseId releaseId, String kbaseName, String ksessionName) {
return PatchedRuntimeEnvironmentBuilder.getDefault(releaseId, kbaseName, ksessionName);
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newClasspathKmoduleDefaultBuilder() {
return newClasspathKmoduleDefaultBuilder(null, null);
}
@Override
public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newClasspathKmoduleDefaultBuilder(String kbaseName, String ksessionName) {
return setupClasspathKmoduleBuilder(KieServices.Factory.get().newKieClasspathContainer(), kbaseName, ksessionName);
}
protected static Object getInstanceFromModel(ObjectModel model, KieContainer kieContainer, Map<String, Object> contaxtParams) {
ObjectModelResolver resolver = ObjectModelResolverProvider.get(model.getResolver());
return resolver.getInstance(model, kieContainer.getClassLoader(), contaxtParams);
}
}
| apache-2.0 |
droolsjbpm/droolsjbpm-tools | drools-eclipse/org.guvnor.eclipse.webdav/src/client/org/eclipse/webdav/http/client/Message.java | 4818 | /*
* 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.eclipse.webdav.http.client;
import java.io.*;
import org.eclipse.webdav.IContext;
import org.eclipse.webdav.client.Policy;
import org.eclipse.webdav.client.WebDAVFactory;
import org.eclipse.webdav.internal.kernel.utils.Assert;
/**
* A common superclass for HTTP messages. There are two kinds of HTTP
* message; requests and responses. They both have in common a context
* and an input stream. This class factors out these similarities.
* <p>
* <b>Note:</b> This class/interface is part of an interim API that is still under
* development and expected to change significantly before reaching stability.
* It is being made available at this early stage to solicit feedback from pioneering
* adopters on the understanding that any code that uses this API will almost
* certainly be broken (repeatedly) as the API evolves.
* </p>
*/
public abstract class Message {
protected static BufferPool bufferPool = new BufferPool();
protected InputStream is;
protected boolean inputRead = false;
protected boolean hasInputStream = false;
protected IContext context;
/**
* Creates a message.
*
* @param context the message header, or <code>null</code> for an empty
* header
* @param is an input stream containing the message's body, or
* <code>null</code> for an empty body
*/
public Message(IContext context, InputStream is) {
this.context = context;
if (context == null)
this.context = WebDAVFactory.contextFactory.newContext();
this.is = is;
if (is == null)
this.is = new ByteArrayInputStream(new byte[0]);
}
/**
* Closes this message to free up any system resources. All messages
* must be closed before finalization.
*
* @exception IOException if there is an I/O error
*/
public void close() throws IOException {
is.close();
}
/**
* Returns the content length of this message's body, or -1 if the
* content length is unknown.
*
* @return the content length of this message's body
*/
public long getContentLength() {
long contentLength = context.getContentLength();
if (contentLength != -1)
return contentLength;
if (is instanceof ByteArrayInputStream)
return ((ByteArrayInputStream) is).available();
return -1;
}
/**
* Returns this message's context.
*
* @return this message's context
*/
public IContext getContext() {
return context;
}
/**
* Returns this message's input stream.
*
* @return this message's input stream
*/
public InputStream getInputStream() {
hasInputStream = true;
return is;
}
public String toString() {
return context.toString();
}
/**
* Writes this messages body to the given output stream. This method may
* only be called once during the lifetime of this message.
*
* @param os an output stream
* @exception IOException if there is an I/O error
*/
public void write(OutputStream os) throws IOException {
Assert.isTrue(!inputRead);
Assert.isTrue(!hasInputStream);
int bytesRead = 0;
int totalBytesRead = 0;
byte[] buffer = bufferPool.getBuffer();
long contentLength = getContentLength();
try {
while (bytesRead != -1 && (contentLength == -1 || contentLength > totalBytesRead)) {
if (contentLength == -1) {
bytesRead = is.read(buffer);
} else {
bytesRead = is.read(buffer, 0, (int) Math.min(buffer.length, contentLength - totalBytesRead));
}
if (bytesRead == -1) {
if (contentLength >= 0) {
throw new IOException(Policy.bind("exception.unexpectedEndStream")); //$NON-NLS-1$
}
} else {
totalBytesRead += bytesRead;
os.write(buffer, 0, bytesRead);
}
}
} finally {
bufferPool.putBuffer(buffer);
inputRead = true;
}
}
}
| apache-2.0 |
mbrukman/gcloud-java | google-cloud-video-intelligence/src/main/java/com/google/cloud/videointelligence/v1beta1/package-info.java | 1475 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A client to Google Cloud Video Intelligence API.
*
* <p>The interfaces provided are listed below, along with usage samples.
*
* <p>============================== VideoIntelligenceServiceClient ==============================
*
* <p>Service Description: Service that implements Google Cloud Video Intelligence API.
*
* <p>Sample for VideoIntelligenceServiceClient:
*
* <pre>
* <code>
* try (VideoIntelligenceServiceClient videoIntelligenceServiceClient = VideoIntelligenceServiceClient.create()) {
* String inputUri = "gs://demomaker/cat.mp4";
* Feature featuresElement = Feature.LABEL_DETECTION;
* List<Feature> features = Arrays.asList(featuresElement);
* AnnotateVideoResponse response = videoIntelligenceServiceClient.annotateVideoAsync(inputUri, features);
* }
* </code>
* </pre>
*/
package com.google.cloud.videointelligence.v1beta1;
| apache-2.0 |
jpountz/elasticsearch | core/src/main/java/org/elasticsearch/common/cli/Terminal.java | 5813 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.common.cli;
import org.apache.commons.cli.CommandLine;
import org.elasticsearch.common.SuppressForbidden;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Locale;
/**
*
*/
@SuppressForbidden(reason = "System#out")
public abstract class Terminal {
public static final String DEBUG_SYSTEM_PROPERTY = "es.cli.debug";
public static final Terminal DEFAULT = ConsoleTerminal.supported() ? new ConsoleTerminal() : new SystemTerminal();
public static enum Verbosity {
SILENT(0), NORMAL(1), VERBOSE(2);
private final int level;
private Verbosity(int level) {
this.level = level;
}
public boolean enabled(Verbosity verbosity) {
return level >= verbosity.level;
}
public static Verbosity resolve(CommandLine cli) {
if (cli.hasOption("s")) {
return SILENT;
}
if (cli.hasOption("v")) {
return VERBOSE;
}
return NORMAL;
}
}
private Verbosity verbosity = Verbosity.NORMAL;
private final boolean isDebugEnabled;
public Terminal() {
this(Verbosity.NORMAL);
}
public Terminal(Verbosity verbosity) {
this.verbosity = verbosity;
this.isDebugEnabled = "true".equals(System.getProperty(DEBUG_SYSTEM_PROPERTY, "false"));
}
public void verbosity(Verbosity verbosity) {
this.verbosity = verbosity;
}
public Verbosity verbosity() {
return verbosity;
}
public abstract String readText(String text, Object... args);
public abstract char[] readSecret(String text, Object... args);
protected abstract void printStackTrace(Throwable t);
public void println() {
println(Verbosity.NORMAL);
}
public void println(String msg, Object... args) {
println(Verbosity.NORMAL, msg, args);
}
public void print(String msg, Object... args) {
print(Verbosity.NORMAL, msg, args);
}
public void println(Verbosity verbosity) {
println(verbosity, "");
}
public void println(Verbosity verbosity, String msg, Object... args) {
print(verbosity, msg + System.lineSeparator(), args);
}
public void print(Verbosity verbosity, String msg, Object... args) {
if (this.verbosity.enabled(verbosity)) {
doPrint(msg, args);
}
}
public void printError(String msg, Object... args) {
println(Verbosity.SILENT, "ERROR: " + msg, args);
}
public void printError(Throwable t) {
printError("%s", t.toString());
if (isDebugEnabled) {
printStackTrace(t);
}
}
public void printWarn(String msg, Object... args) {
println(Verbosity.SILENT, "WARN: " + msg, args);
}
protected abstract void doPrint(String msg, Object... args);
public abstract PrintWriter writer();
private static class ConsoleTerminal extends Terminal {
final Console console = System.console();
static boolean supported() {
return System.console() != null;
}
@Override
public void doPrint(String msg, Object... args) {
console.printf(msg, args);
console.flush();
}
@Override
public String readText(String text, Object... args) {
return console.readLine(text, args);
}
@Override
public char[] readSecret(String text, Object... args) {
return console.readPassword(text, args);
}
@Override
public PrintWriter writer() {
return console.writer();
}
@Override
public void printStackTrace(Throwable t) {
t.printStackTrace(console.writer());
}
}
@SuppressForbidden(reason = "System#out")
private static class SystemTerminal extends Terminal {
private final PrintWriter printWriter = new PrintWriter(System.out);
@Override
public void doPrint(String msg, Object... args) {
System.out.print(String.format(Locale.ROOT, msg, args));
}
@Override
public String readText(String text, Object... args) {
print(text, args);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
return reader.readLine();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public char[] readSecret(String text, Object... args) {
return readText(text, args).toCharArray();
}
@Override
public void printStackTrace(Throwable t) {
t.printStackTrace(printWriter);
}
@Override
public PrintWriter writer() {
return printWriter;
}
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/projectModel-api/src/com/intellij/openapi/module/ModuleUtilCore.java | 9182 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.module;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileSystemItem;
import com.intellij.util.PathUtilRt;
import com.intellij.util.graph.Graph;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class ModuleUtilCore {
public static final Key<Module> KEY_MODULE = new Key<>("Module");
public static boolean projectContainsFile(@NotNull Project project, @NotNull VirtualFile file, boolean isLibraryElement) {
ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project);
if (isLibraryElement) {
List<OrderEntry> orders = projectFileIndex.getOrderEntriesForFile(file);
for(OrderEntry orderEntry:orders) {
if (orderEntry instanceof JdkOrderEntry || orderEntry instanceof LibraryOrderEntry) {
return true;
}
}
return false;
}
else {
return projectFileIndex.isInContent(file);
}
}
@NotNull
public static String getModuleNameInReadAction(@NotNull final Module module) {
return ReadAction.compute(module::getName);
}
public static boolean isModuleDisposed(@NotNull PsiElement element) {
if (!element.isValid()) return true;
final Project project = element.getProject();
ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project);
final PsiFile file = element.getContainingFile();
if (file == null) return true;
VirtualFile vFile = file.getVirtualFile();
final Module module = vFile == null ? null : projectFileIndex.getModuleForFile(vFile);
// element may be in library
return module == null ? !projectFileIndex.isInLibraryClasses(vFile) : module.isDisposed();
}
/**
* @return module where {@code containingFile} is located,
* null for project files outside module content roots or library files
*/
@Nullable
public static Module findModuleForFile(@Nullable PsiFile containingFile) {
if (containingFile != null) {
VirtualFile vFile = containingFile.getVirtualFile();
if (vFile != null) {
return findModuleForFile(vFile, containingFile.getProject());
}
}
return null;
}
/**
* @return module where {@code file} is located,
* null for project files outside module content roots or library files
*/
@Nullable
public static Module findModuleForFile(@NotNull VirtualFile file, @NotNull Project project) {
if (project.isDefault()) {
return null;
}
return ProjectFileIndex.getInstance(project).getModuleForFile(file);
}
/**
* @return module where containing file of the {@code element} is located.
*
* For {@link com.intellij.psi.PsiDirectory}, corresponding virtual file is checked directly.
* If this virtual file belongs to a library and this library is attached to the exactly one module, then this module will be returned.
*/
@Nullable
public static Module findModuleForPsiElement(@NotNull PsiElement element) {
PsiFile containingFile = element.getContainingFile();
if (!Objects.requireNonNullElse(containingFile, element).isValid()) {
return null;
}
Project project = (containingFile == null ? element : containingFile).getProject();
if (project.isDefault()) return null;
final ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(project);
if (element instanceof PsiFileSystemItem && (!(element instanceof PsiFile) || element.getContext() == null)) {
VirtualFile vFile = ((PsiFileSystemItem)element).getVirtualFile();
if (vFile == null) {
vFile = containingFile == null ? null : containingFile.getOriginalFile().getVirtualFile();
if (vFile == null) {
return element.getUserData(KEY_MODULE);
}
}
if (fileIndex.isInLibrary(vFile)) {
final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(vFile);
if (orderEntries.isEmpty()) {
return null;
}
if (orderEntries.size() == 1) {
return orderEntries.get(0).getOwnerModule();
}
Set<Module> modules = new HashSet<>();
for (OrderEntry orderEntry : orderEntries) {
modules.add(orderEntry.getOwnerModule());
}
final Module[] candidates = modules.toArray(Module.EMPTY_ARRAY);
Arrays.sort(candidates, ModuleManager.getInstance(project).moduleDependencyComparator());
return candidates[0];
}
return fileIndex.getModuleForFile(vFile);
}
if (containingFile != null) {
PsiElement context;
while ((context = containingFile.getContext()) != null) {
final PsiFile file = context.getContainingFile();
if (file == null) break;
containingFile = file;
}
if (containingFile.getUserData(KEY_MODULE) != null) {
return containingFile.getUserData(KEY_MODULE);
}
final PsiFile originalFile = containingFile.getOriginalFile();
if (originalFile.getUserData(KEY_MODULE) != null) {
return originalFile.getUserData(KEY_MODULE);
}
final VirtualFile virtualFile = originalFile.getVirtualFile();
if (virtualFile != null) {
return fileIndex.getModuleForFile(virtualFile);
}
}
return element.getUserData(KEY_MODULE);
}
//ignores export flag
public static void getDependencies(@NotNull Module module, @NotNull Set<? super Module> modules) {
if (modules.contains(module)) return;
modules.add(module);
Module[] dependencies = ModuleRootManager.getInstance(module).getDependencies();
for (Module dependency : dependencies) {
getDependencies(dependency, modules);
}
}
/**
* collect transitive module dependants
* @param module to find dependencies on
* @param result resulted set
*/
public static void collectModulesDependsOn(@NotNull final Module module, @NotNull Set<? super Module> result) {
if (!result.add(module)) {
return;
}
final ModuleManager moduleManager = ModuleManager.getInstance(module.getProject());
final List<Module> dependentModules = moduleManager.getModuleDependentModules(module);
for (final Module dependentModule : dependentModules) {
final OrderEntry[] orderEntries = ModuleRootManager.getInstance(dependentModule).getOrderEntries();
for (OrderEntry o : orderEntries) {
if (o instanceof ModuleOrderEntry) {
final ModuleOrderEntry orderEntry = (ModuleOrderEntry)o;
if (orderEntry.getModule() == module) {
if (orderEntry.isExported()) {
collectModulesDependsOn(dependentModule, result);
}
else {
result.add(dependentModule);
}
break;
}
}
}
}
}
@NotNull
public static List<Module> getAllDependentModules(@NotNull Module module) {
List<Module> list = new ArrayList<>();
Graph<Module> graph = ModuleManager.getInstance(module.getProject()).moduleGraph();
for (Iterator<Module> i = graph.getOut(module); i.hasNext();) {
list.add(i.next());
}
return list;
}
public static boolean visitMeAndDependentModules(@NotNull final Module module, @NotNull ModuleVisitor visitor) {
if (!visitor.visit(module)) {
return false;
}
final List<Module> list = getAllDependentModules(module);
for (Module dependentModule : list) {
if (!visitor.visit(dependentModule)) {
return false;
}
}
return true;
}
public static boolean moduleContainsFile(@NotNull final Module module, @NotNull VirtualFile file, boolean isLibraryElement) {
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
if (isLibraryElement) {
OrderEntry orderEntry = moduleRootManager.getFileIndex().getOrderEntryForFile(file);
return orderEntry instanceof JdkOrderEntry || orderEntry instanceof LibraryOrderEntry;
}
else {
return moduleRootManager.getFileIndex().isInContent(file);
}
}
public static boolean isModuleFile(@NotNull Module module, @NotNull VirtualFile file) {
return VfsUtilCore.pathEqualsTo(file, module.getModuleFilePath());
}
public static boolean isModuleDir(@NotNull Module module, @NotNull VirtualFile dir) {
return VfsUtilCore.pathEqualsTo(dir, getModuleDirPath(module));
}
@NotNull
public static String getModuleDirPath(@NotNull Module module) {
return PathUtilRt.getParentPath(module.getModuleFilePath());
}
@FunctionalInterface
public interface ModuleVisitor {
/**
* @param module module to be visited.
* @return false to stop visiting.
*/
boolean visit(@NotNull Module module);
}
}
| apache-2.0 |
nikeshmhr/unitime | JavaSource/org/unitime/timetable/model/Exam.java | 64044 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.model;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.unitime.localization.impl.Localization;
import org.unitime.localization.messages.ExaminationMessages;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.defaults.ApplicationProperty;
import org.unitime.timetable.model.base.BaseExam;
import org.unitime.timetable.model.dao.DepartmentalInstructorDAO;
import org.unitime.timetable.model.dao.ExamDAO;
import org.unitime.timetable.model.dao.ExamEventDAO;
import org.unitime.timetable.model.dao.StudentDAO;
import org.unitime.timetable.model.dao._RootDAO;
import org.unitime.timetable.solver.exam.ui.ExamAssignment;
import org.unitime.timetable.solver.exam.ui.ExamAssignmentInfo;
import org.unitime.timetable.solver.exam.ui.ExamInfo;
import org.unitime.timetable.solver.exam.ui.ExamRoomInfo;
import org.unitime.timetable.util.Constants;
/**
* @author Tomas Muller, Stephanie Schluttenhofer
*/
public class Exam extends BaseExam implements Comparable<Exam> {
private static final long serialVersionUID = 1L;
protected static ExaminationMessages MSG = Localization.create(ExaminationMessages.class);
/*[CONSTRUCTOR MARKER BEGIN]*/
public Exam () {
super();
}
/**
* Constructor for primary key
*/
public Exam (java.lang.Long uniqueId) {
super(uniqueId);
}
/*[CONSTRUCTOR MARKER END]*/
public static final int sSeatingTypeNormal = 0;
public static final int sSeatingTypeExam = 1;
public static final String sSeatingTypes[] = new String[] {MSG.seatingNormal(), MSG.seatingExam()};
public String generateName() {
StringBuffer sb = new StringBuffer();
ExamOwner prev = null;
TreeSet owners = new TreeSet(getOwners());
if (ApplicationProperty.ExaminationNameExpandCrossListedOfferingsToCourses.isTrue()) {
HashSet dummies = new HashSet();
for (Iterator i=owners.iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
if (owner.getOwnerType() == ExamOwner.sOwnerTypeCourse) continue;
InstructionalOffering offering = (InstructionalOffering)owner.getCourse().getInstructionalOffering();
if (offering.getCourseOfferings().size() > 1) {
i.remove();
for (Iterator j=offering.getCourseOfferings().iterator(); j.hasNext();) {
CourseOffering course = (CourseOffering)j.next();
ExamOwner dummy = new ExamOwner();
dummy.setOwnerId(owner.getOwnerId());
dummy.setOwnerType(owner.getOwnerType());
dummy.setCourse(course);
dummies.add(dummy);
}
}
}
owners.addAll(dummies);
}
for (Iterator i=owners.iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
Object ownerObject = owner.getOwnerObject();
if (prev!=null && prev.getCourse().getSubjectArea().equals(owner.getCourse().getSubjectArea())) {
//same subject area
if (prev.getCourse().equals(owner.getCourse()) && prev.getOwnerType().equals(owner.getOwnerType())) {
//same course number
switch (owner.getOwnerType()) {
case ExamOwner.sOwnerTypeClass :
Class_ clazz = (Class_)ownerObject;
if (prev.getOwnerType()==ExamOwner.sOwnerTypeClass && ((Class_)prev.getOwnerObject()).getSchedulingSubpart().equals(clazz.getSchedulingSubpart()))
sb.append(owner.genName(ApplicationProperties.getProperty("tmtbl.exam.name.sameSubpart."+ExamOwner.sOwnerTypes[owner.getOwnerType()])));
else
sb.append(owner.genName(ApplicationProperties.getProperty("tmtbl.exam.name.sameCourse."+ExamOwner.sOwnerTypes[owner.getOwnerType()])));
break;
case ExamOwner.sOwnerTypeConfig :
sb.append(owner.genName(ApplicationProperties.getProperty("tmtbl.exam.name.sameCourse."+ExamOwner.sOwnerTypes[owner.getOwnerType()])));
break;
}
} else {
//different course number
sb.append(owner.genName(ApplicationProperties.getProperty("tmtbl.exam.name.sameSubject."+ExamOwner.sOwnerTypes[owner.getOwnerType()])));
}
} else {
//different subject area
if (prev!=null) sb.append(prev.genName(ApplicationProperty.ExamNameSeparator.value()));
sb.append(owner.genName(ApplicationProperties.getProperty("tmtbl.exam.name."+ExamOwner.sOwnerTypes[owner.getOwnerType()])));
}
prev = owner;
}
String suffix = (prev==null?"":prev.genName(ApplicationProperty.ExamNameSuffix.value()));
int limit = ApplicationProperty.ExamNameMaxLength.intValue() - suffix.length();
return (sb.toString().length()<=limit?sb.toString():sb.toString().substring(0,limit-3)+"...")+suffix;
}
public String getLabel() {
String name = getName();
if (name!=null) return name;
return generateName();
}
public String htmlLabel(){
return getLabel();
}
public Vector getOwnerObjects() {
Vector ret = new Vector();
for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
ret.add(owner.getOwnerObject());
}
return ret;
}
public ExamOwner firstOwner() {
ExamOwner ret = null;
for (Iterator i=getOwners().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
if (ret == null || ret.compareTo(owner)>0)
ret = owner;
}
return ret;
}
public static List findAll(Long sessionId, ExamType examType) {
return findAll(sessionId, examType.getUniqueId());
}
public static List findAll(Long sessionId, Long examTypeId) {
return new ExamDAO().getSession().createQuery(
"select x from Exam x where x.session.uniqueId=:sessionId and x.examType.uniqueId=:examTypeId"
)
.setLong("sessionId", sessionId)
.setLong("examTypeId", examTypeId)
.setCacheable(true)
.list();
}
public static List findAllMidterm(Long sessionId) {
return new ExamDAO().getSession().createQuery(
"select x from Exam x where x.session.uniqueId=:sessionId and x.examType.type=:type"
)
.setLong("sessionId", sessionId)
.setInteger("type", ExamType.sExamTypeMidterm)
.setCacheable(true)
.list();
}
public static List findAllFinal(Long sessionId) {
return new ExamDAO().getSession().createQuery(
"select x from Exam x where x.session.uniqueId=:sessionId and x.examType.type=:type"
)
.setLong("sessionId", sessionId)
.setInteger("type", ExamType.sExamTypeFinal)
.setCacheable(true)
.list();
}
public static List findExamsOfSubjectArea(Long subjectAreaId, Long examTypeId) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o where " +
"o.course.subjectArea.uniqueId=:subjectAreaId and x.examType.uniqueId=:examTypeId")
.setLong("subjectAreaId", subjectAreaId)
.setLong("examTypeId", examTypeId)
.setCacheable(true)
.list();
}
public static List findExamsOfSubjectAreaIncludeCrossLists(Long subjectAreaId, Long examTypeId) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o inner join o.course.instructionalOffering.courseOfferings co where " +
"co.subjectArea.uniqueId=:subjectAreaId and x.examType.uniqueId=:examTypeId")
.setLong("subjectAreaId", subjectAreaId)
.setLong("examTypeId", examTypeId)
.setCacheable(true)
.list();
}
public static List findExamsOfCourseOffering(Long courseOfferingId, Long examTypeId) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o where " +
"o.course.uniqueId=:courseOfferingId and x.examType.uniqueId=:examTypeId")
.setLong("courseOfferingId", courseOfferingId)
.setLong("examTypeId", examTypeId)
.setCacheable(true)
.list();
}
public static List findExamsOfCourse(Long subjectAreaId, String courseNbr, Long examTypeId) {
if (courseNbr==null || courseNbr.trim().length()==0) return findExamsOfSubjectArea(subjectAreaId, examTypeId);
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o where " +
"o.course.subjectArea.uniqueId=:subjectAreaId and x.examType.uniqueId=:examTypeId and "+
(courseNbr.indexOf('*')>=0?"o.course.courseNbr like :courseNbr":"o.course.courseNbr=:courseNbr"))
.setLong("subjectAreaId", subjectAreaId)
.setString("courseNbr", courseNbr.trim().replaceAll("\\*", "%"))
.setLong("examTypeId", examTypeId)
.setCacheable(true)
.list();
}
public Set<Student> getStudents() {
HashSet<Student> students = new HashSet();
for (Iterator i=getOwners().iterator();i.hasNext();)
students.addAll(((ExamOwner)i.next()).getStudents());
return students;
}
public Collection<StudentClassEnrollment> getStudentClassEnrollments() {
HashSet<StudentClassEnrollment> enrollments = new HashSet();
for (ExamOwner owner: getOwners())
enrollments.addAll(owner.getStudentClassEnrollments());
return enrollments;
}
public Set<Long> getStudentIds() {
HashSet<Long> studentIds = new HashSet();
for (Iterator i=getOwners().iterator();i.hasNext();)
studentIds.addAll(((ExamOwner)i.next()).getStudentIds());
return studentIds;
}
public Hashtable<Long, Set<Exam>> getStudentExams() {
Hashtable<Long, Set<Exam>> studentExams = new Hashtable<Long, Set<Exam>>();
for (Iterator i=getOwners().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
owner.computeStudentExams(studentExams);
}
return studentExams;
}
public Hashtable<Assignment, Set<Long>> getStudentAssignments() {
Hashtable<Assignment, Set<Long>> studentAssignments = new Hashtable<Assignment, Set<Long>>();
for (Iterator i=getOwners().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
owner.computeStudentAssignments(studentAssignments);
}
return studentAssignments;
}
public Hashtable<Meeting, Set<Long>> getOverlappingStudentMeetings(Long periodId) {
Hashtable<Meeting, Set<Long>> studentMeetings = new Hashtable<Meeting, Set<Long>>();
for (Iterator i=getOwners().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
owner.computeOverlappingStudentMeetings(studentMeetings, periodId);
}
return studentMeetings;
}
public int countStudents() {
int nrStudents = 0;
for (Iterator i=getOwners().iterator();i.hasNext();)
nrStudents += ((ExamOwner)i.next()).countStudents();
return nrStudents;
}
public int getLimit() {
int limit = 0;
for (Iterator i=getOwners().iterator();i.hasNext();)
limit += ((ExamOwner)i.next()).getLimit();
return limit;
}
public int getSize() {
if (getExamSize()!=null) return getExamSize().intValue();
int size = 0;
for (Iterator i=getOwners().iterator();i.hasNext();)
size += ((ExamOwner)i.next()).getSize();
return size;
}
public Set effectivePreferences(Class type) {
if (DistributionPref.class.equals(type)) {
TreeSet prefs = new TreeSet();
try {
if (getDistributionObjects()==null) return prefs;
for (Iterator j=getDistributionObjects().iterator();j.hasNext();) {
DistributionPref p = ((DistributionObject)j.next()).getDistributionPref();
prefs.add(p);
}
} catch (ObjectNotFoundException e) {
new _RootDAO().getSession().refresh(this);
for (Iterator j=getDistributionObjects().iterator();j.hasNext();) {
DistributionPref p = ((DistributionObject)j.next()).getDistributionPref();
prefs.add(p);
}
}
return prefs;
} else return super.effectivePreferences(type);
}
public Set getAvailableRooms() {
return Location.findAllExamLocations(getSession().getUniqueId(), getExamType());
}
public SubjectArea firstSubjectArea() {
for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
return owner.getCourse().getSubjectArea();
}
return null;
}
public CourseOffering firstCourseOffering() {
for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
return owner.getCourse();
}
return null;
}
public Department firstDepartment() {
for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
return owner.getCourse().getDepartment();
}
return null;
}
public String toString() {
return getLabel();
}
public int compareTo(Exam exam) {
Iterator i1 = new TreeSet(getOwners()).iterator();
Iterator i2 = new TreeSet(exam.getOwners()).iterator();
while (i1.hasNext() && i2.hasNext()) {
ExamOwner o1 = (ExamOwner)i1.next();
ExamOwner o2 = (ExamOwner)i2.next();
int cmp = o1.compareTo(o2);
if (cmp!=0) return cmp;
}
return (i1.hasNext()?1:i2.hasNext()?-1:getUniqueId().compareTo(exam.getUniqueId()));
}
public void deleteDependentObjects(org.hibernate.Session hibSession, boolean updateExam) {
boolean deleted = false;
if (getDistributionObjects()==null) return;
for (Iterator i=getDistributionObjects().iterator();i.hasNext();) {
DistributionObject relatedObject = (DistributionObject)i.next();
DistributionPref distributionPref = relatedObject.getDistributionPref();
distributionPref.getDistributionObjects().remove(relatedObject);
Integer seqNo = relatedObject.getSequenceNumber();
hibSession.delete(relatedObject);
deleted = true;
if (distributionPref.getDistributionObjects().isEmpty()) {
PreferenceGroup owner = distributionPref.getOwner();
owner.getPreferences().remove(distributionPref);
getPreferences().remove(distributionPref);
hibSession.saveOrUpdate(owner);
hibSession.delete(distributionPref);
} else {
if (seqNo!=null) {
for (Iterator j=distributionPref.getDistributionObjects().iterator();j.hasNext();) {
DistributionObject dObj = (DistributionObject)j.next();
if (seqNo.compareTo(dObj.getSequenceNumber())<0) {
dObj.setSequenceNumber(new Integer(dObj.getSequenceNumber().intValue()-1));
hibSession.saveOrUpdate(dObj);
}
}
}
if (updateExam)
hibSession.saveOrUpdate(distributionPref);
}
i.remove();
}
ExamEvent event = getEvent();
if (event!=null) {
hibSession.delete(event);
deleted = true;
}
if (deleted && updateExam)
hibSession.saveOrUpdate(this);
}
public static void deleteFromExams(org.hibernate.Session hibSession, Integer ownerType, Long ownerId) {
for (Iterator i=hibSession.createQuery("select o from Exam x inner join x.owners o where "+
"o.ownerType=:ownerType and o.ownerId=:ownerId")
.setInteger("ownerType", ownerType)
.setLong("ownerId", ownerId).list().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
Exam exam = owner.getExam();
exam.getOwners().remove(owner);
hibSession.delete(owner);
if (exam.getOwners().isEmpty()) {
exam.deleteDependentObjects(hibSession, false);
hibSession.delete(exam);
} else {
hibSession.saveOrUpdate(exam);
}
}
}
public static void deleteFromExams(org.hibernate.Session hibSession, Class_ clazz) {
deleteFromExams(hibSession, ExamOwner.sOwnerTypeClass, clazz.getUniqueId());
}
public static void deleteFromExams(org.hibernate.Session hibSession, InstrOfferingConfig config) {
deleteFromExams(hibSession, ExamOwner.sOwnerTypeConfig, config.getUniqueId());
}
public static void deleteFromExams(org.hibernate.Session hibSession, InstructionalOffering offering) {
deleteFromExams(hibSession, ExamOwner.sOwnerTypeOffering, offering.getUniqueId());
}
public static void deleteFromExams(org.hibernate.Session hibSession, CourseOffering course) {
deleteFromExams(hibSession, ExamOwner.sOwnerTypeCourse, course.getUniqueId());
}
public static List findAll(int ownerType, Long ownerId) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o where "+
"o.ownerType=:ownerType and o.ownerId=:ownerId").
setInteger("ownerType", ownerType).
setLong("ownerId", ownerId).
setCacheable(true).list();
}
public static List findAllRelated(String type, Long id) {
if ("Class_".equals(type)) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o inner join o.course co "+
"inner join co.instructionalOffering io "+
"inner join io.instrOfferingConfigs ioc " +
"inner join ioc.schedulingSubparts ss "+
"inner join ss.classes c where "+
"c.uniqueId=:classId and ("+
"(o.ownerType="+ExamOwner.sOwnerTypeCourse+" and o.ownerId=co.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeOffering+" and o.ownerId=io.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeConfig+" and o.ownerId=ioc.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeClass+" and o.ownerId=c.uniqueId) "+
")").
setLong("classId", id).setCacheable(true).list();
} else if ("SchedulingSubpart".equals(type)) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o inner join o.course co "+
"inner join co.instructionalOffering io "+
"inner join io.instrOfferingConfigs ioc " +
"inner join ioc.schedulingSubparts ss "+
"left outer join ss.classes c where "+
"ss.uniqueId=:subpartId and ("+
"(o.ownerType="+ExamOwner.sOwnerTypeCourse+" and o.ownerId=co.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeOffering+" and o.ownerId=io.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeConfig+" and o.ownerId=ioc.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeClass+" and o.ownerId=c.uniqueId) "+
")").
setLong("subpartId", id).setCacheable(true).list();
} else if ("CourseOffering".equals(type)) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o inner join o.course co "+
"left outer join co.instructionalOffering io "+
"left outer join io.instrOfferingConfigs ioc " +
"left outer join ioc.schedulingSubparts ss "+
"left outer join ss.classes c where "+
"co.uniqueId=:courseOfferingId and ("+
"(o.ownerType="+ExamOwner.sOwnerTypeCourse+" and o.ownerId=co.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeOffering+" and o.ownerId=io.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeConfig+" and o.ownerId=ioc.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeClass+" and o.ownerId=c.uniqueId) "+
")").
setLong("courseOfferingId", id).setCacheable(true).list();
} else if ("InstructionalOffering".equals(type)) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o inner join o.course co "+
"inner join co.instructionalOffering io "+
"left outer join io.instrOfferingConfigs ioc " +
"left outer join ioc.schedulingSubparts ss "+
"left outer join ss.classes c where "+
"io.uniqueId=:instructionalOfferingId and ("+
"(o.ownerType="+ExamOwner.sOwnerTypeCourse+" and o.ownerId=co.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeOffering+" and o.ownerId=io.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeConfig+" and o.ownerId=ioc.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeClass+" and o.ownerId=c.uniqueId) "+
")").
setLong("instructionalOfferingId", id).setCacheable(true).list();
} else if ("InstrOfferingConfig".equals(type)) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o inner join o.course co "+
"inner join co.instructionalOffering io "+
"inner join io.instrOfferingConfigs ioc " +
"left outer join ioc.schedulingSubparts ss "+
"left outer join ss.classes c where "+
"ioc.uniqueId=:instrOfferingConfigId and ("+
"(o.ownerType="+ExamOwner.sOwnerTypeCourse+" and o.ownerId=co.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeOffering+" and o.ownerId=io.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeConfig+" and o.ownerId=ioc.uniqueId) or "+
"(o.ownerType="+ExamOwner.sOwnerTypeClass+" and o.ownerId=c.uniqueId) "+
")").
setLong("instrOfferingConfigId", id).setCacheable(true).list();
} else if ("DepartmentalInstructor".equals(type)) {
return new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.instructors xi, DepartmentalInstructor i where "+
"i.uniqueId=:instructorId and (xi.uniqueId=i.uniqueId or ("+
"i.externalUniqueId is not null and i.externalUniqueId=xi.externalUniqueId " +
"and xi.department.session = i.department.session))").
setLong("instructorId", id).setCacheable(true).list();
} else if ("ExamEvent".equals(type)) {
List ret = new ArrayList();
ExamEvent event = new ExamEventDAO().get(id);
if (event!=null && event.getExam()!=null) ret.add(event.getExam());
return ret;
} else throw new RuntimeException("Unsupported type "+type);
}
public static boolean hasTimetable(Long sessionId, Integer examType) {
if (sessionId == null) return false;
if (examType==null) return hasTimetable(sessionId);
return ((Number)new ExamDAO().getSession().
createQuery("select count(x) from Exam x " +
"where x.session.uniqueId=:sessionId and " +
"x.assignedPeriod!=null and x.examType.type=:examType").
setLong("sessionId",sessionId).setInteger("examType",examType).setCacheable(true).uniqueResult()).longValue()>0;
}
public static boolean hasTimetable(Long sessionId) {
if (sessionId == null) return false;
return ((Number)new ExamDAO().getSession().
createQuery("select count(x) from Exam x " +
"where x.session.uniqueId=:sessionId and " +
"x.assignedPeriod!=null").
setLong("sessionId",sessionId).setCacheable(true).uniqueResult()).longValue()>0;
}
public static boolean hasMidtermExams(Long sessionId) {
if (sessionId == null) return false;
return ((Number)new ExamDAO().getSession().
createQuery("select count(p) from ExamPeriod p " +
"where p.session.uniqueId=:sessionId and "+
"p.examType.type = "+ExamType.sExamTypeMidterm).
setLong("sessionId", sessionId).setCacheable(true).uniqueResult()).longValue()>0;
}
public static boolean hasFinalExams(Long sessionId) {
if (sessionId == null) return false;
return ((Number)new ExamDAO().getSession().
createQuery("select count(p) from ExamPeriod p " +
"where p.session.uniqueId=:sessionId and "+
"p.examType.type = "+ExamType.sExamTypeFinal).
setLong("sessionId", sessionId).setCacheable(true).uniqueResult()).longValue()>0;
}
public static boolean hasExamsOfType(Long sessionId, ExamType type) {
if (sessionId == null) return false;
return ((Number)new ExamDAO().getSession().
createQuery("select count(p) from ExamPeriod p " +
"where p.session.uniqueId=:sessionId and "+
"p.examType.uniqueid = :typeId").
setLong("sessionId", sessionId).setLong("typeId", type.getUniqueId()).setCacheable(true).uniqueResult()).longValue()>0;
}
public static Collection<ExamAssignmentInfo> findAssignedExams(Long sessionId, Long examTypeId) {
Vector<ExamAssignmentInfo> ret = new Vector<ExamAssignmentInfo>();
List exams = new ExamDAO().getSession().createQuery(
"select x from Exam x where "+
"x.session.uniqueId=:sessionId and x.assignedPeriod!=null and x.examType.uniqueId=:examTypeId").
setLong("sessionId", sessionId).
setLong("examTypeId", examTypeId).
setCacheable(true).list();
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
ret.add(new ExamAssignmentInfo(exam));
}
return ret;
}
public static Collection<ExamInfo> findUnassignedExams(Long sessionId, Long examTypeId) {
Vector<ExamInfo> ret = new Vector<ExamInfo>();
List exams = new ExamDAO().getSession().createQuery(
"select x from Exam x where "+
"x.session.uniqueId=:sessionId and x.assignedPeriod=null and x.examType.uniqueId=:examTypeId").
setLong("sessionId", sessionId).
setLong("examTypeId", examTypeId).
setCacheable(true).list();
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
ret.add(new ExamInfo(exam));
}
return ret;
}
public static Collection<ExamAssignmentInfo> findAssignedExams(Long sessionId, Long subjectAreaId, Long examTypeId) {
if (subjectAreaId==null || subjectAreaId<0) return findAssignedExams(sessionId, examTypeId);
Vector<ExamAssignmentInfo> ret = new Vector<ExamAssignmentInfo>();
List exams = new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o where " +
"o.course.subjectArea.uniqueId=:subjectAreaId and "+
"x.examType.uniqueId=:examTypeId and "+
"x.session.uniqueId=:sessionId and x.assignedPeriod!=null").
setLong("sessionId", sessionId).
setLong("examTypeId", examTypeId).
setLong("subjectAreaId", subjectAreaId).
setCacheable(true).list();
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
ret.add(new ExamAssignmentInfo(exam));
}
return ret;
}
public static Collection<ExamInfo> findUnassignedExams(Long sessionId, Long subjectAreaId, Long examTypeId) {
if (subjectAreaId==null || subjectAreaId<0) return findUnassignedExams(sessionId,examTypeId);
Vector<ExamInfo> ret = new Vector<ExamInfo>();
List exams = new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.owners o where " +
"o.course.subjectArea.uniqueId=:subjectAreaId and "+
"x.examType.uniqueId=:examTypeId and "+
"x.session.uniqueId=:sessionId and x.assignedPeriod=null").
setLong("sessionId", sessionId).
setLong("examTypeId", examTypeId).
setLong("subjectAreaId", subjectAreaId).
setCacheable(true).list();
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
ret.add(new ExamInfo(exam));
}
return ret;
}
public static Collection<ExamAssignmentInfo> findAssignedExamsOfLocation(Long locationId, Long examTypeId) throws Exception {
Vector<ExamAssignmentInfo> ret = new Vector<ExamAssignmentInfo>();
List exams = new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.assignedRooms r where " +
"r.uniqueId=:locationId and x.assignedPeriod!=null and "+
"x.examType.uniqueId=:examTypeId").
setLong("locationId", locationId).
setLong("examTypeId", examTypeId).
setCacheable(true).list();
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
ret.add(new ExamAssignmentInfo(exam));
}
return ret;
}
public static Collection<ExamAssignmentInfo> findAssignedExamsOfInstructor(Long instructorId, Long examTypeId) throws Exception {
Vector<ExamAssignmentInfo> ret = new Vector<ExamAssignmentInfo>();
List exams = new ExamDAO().getSession().createQuery(
"select distinct x from Exam x inner join x.instructors i where " +
"i.uniqueId=:instructorId and x.assignedPeriod!=null and "+
"x.examType.uniqueId=:examTypeId").
setLong("instructorId", instructorId).
setLong("examTypeId", examTypeId).
setCacheable(true).list();
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
ret.add(new ExamAssignmentInfo(exam));
}
return ret;
}
public String assign(ExamAssignmentInfo assignment, String managerExternalId, Session hibSession) {
Transaction tx = null;
try {
tx = hibSession.beginTransaction();
ExamAssignment oldAssignment = new ExamAssignment(this);
setAssignedPeriod(assignment.getPeriod(hibSession));
if (getAssignedRooms()==null) setAssignedRooms(new HashSet());
getAssignedRooms().clear();
for (ExamRoomInfo room : assignment.getRooms())
getAssignedRooms().add(room.getLocation(hibSession));
setAssignedPreference(assignment.getAssignedPreferenceString());
HashSet otherExams = new HashSet();
for (Iterator j=getConflicts().iterator();j.hasNext();) {
ExamConflict conf = (ExamConflict)j.next();
for (Iterator i=conf.getExams().iterator();i.hasNext();) {
Exam x = (Exam)i.next();
if (!x.equals(this)) {
x.getConflicts().remove(conf);
otherExams.add(x);
}
}
hibSession.delete(conf);
j.remove();
}
for (Iterator i=assignment.getDirectConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.DirectConflict dc = (ExamAssignmentInfo.DirectConflict)i.next();
if (dc.getOtherExam()==null) continue;
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeDirect);
conf.setStudents(getStudents(hibSession, dc.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = dc.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getBackToBackConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.BackToBackConflict btb = (ExamAssignmentInfo.BackToBackConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(btb.isDistance()?ExamConflict.sConflictTypeBackToBackDist:ExamConflict.sConflictTypeBackToBack);
conf.setDistance(btb.getDistance());
conf.setStudents(getStudents(hibSession, btb.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = btb.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getMoreThanTwoADaysConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.MoreThanTwoADayConflict m2d = (ExamAssignmentInfo.MoreThanTwoADayConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeMoreThanTwoADay);
conf.setStudents(getStudents(hibSession, m2d.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
for (Iterator j=m2d.getOtherExams().iterator();j.hasNext();) {
Exam otherExam = (Exam)((ExamInfo)j.next()).getExam(hibSession);
otherExam.getConflicts().add(conf);
otherExams.add(otherExam);
}
}
for (Iterator i=assignment.getInstructorDirectConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.DirectConflict dc = (ExamAssignmentInfo.DirectConflict)i.next();
if (dc.getOtherExam()==null) continue;
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeDirect);
conf.setInstructors(getInstructors(hibSession, dc.getStudents()));
conf.setNrInstructors(conf.getInstructors().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = dc.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getInstructorBackToBackConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.BackToBackConflict btb = (ExamAssignmentInfo.BackToBackConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(btb.isDistance()?ExamConflict.sConflictTypeBackToBackDist:ExamConflict.sConflictTypeBackToBack);
conf.setDistance(btb.getDistance());
conf.setInstructors(getInstructors(hibSession, btb.getStudents()));
conf.setNrInstructors(conf.getInstructors().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = btb.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getInstructorMoreThanTwoADaysConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.MoreThanTwoADayConflict m2d = (ExamAssignmentInfo.MoreThanTwoADayConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeMoreThanTwoADay);
conf.setInstructors(getInstructors(hibSession, m2d.getStudents()));
conf.setNrInstructors(conf.getInstructors().size());
hibSession.save(conf);
getConflicts().add(conf);
for (Iterator j=m2d.getOtherExams().iterator();j.hasNext();) {
Exam otherExam = (Exam)((ExamInfo)j.next()).getExam(hibSession);
otherExam.getConflicts().add(conf);
otherExams.add(otherExam);
}
}
ExamEvent event = generateEvent(getEvent(),true);
if (event!=null) {
event.setEventName(assignment.getExamName());
event.setMinCapacity(assignment.getNrStudents());
event.setMaxCapacity(assignment.getNrStudents());
EventContact contact = EventContact.findByExternalUniqueId(managerExternalId);
if (contact==null) {
TimetableManager manager = TimetableManager.findByExternalId(managerExternalId);
contact = new EventContact();
contact.setFirstName(manager.getFirstName());
contact.setMiddleName(manager.getMiddleName());
contact.setLastName(manager.getLastName());
contact.setExternalUniqueId(manager.getExternalUniqueId());
contact.setEmailAddress(manager.getEmailAddress());
hibSession.save(contact);
}
event.setMainContact(contact);
hibSession.saveOrUpdate(event);
}
hibSession.update(this);
for (Iterator i=otherExams.iterator();i.hasNext();)
hibSession.update((Exam)i.next());
SubjectArea subject = null;
Department dept = null;
for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
subject = owner.getCourse().getSubjectArea();
dept = subject.getDepartment();
break;
}
ChangeLog.addChange(hibSession,
TimetableManager.findByExternalId(managerExternalId),
getSession(),
this,
assignment.getExamName()+" ("+
(oldAssignment.getPeriod()==null?"N/A":oldAssignment.getPeriodAbbreviation()+" "+oldAssignment.getRoomsName(", "))+
" → "+assignment.getPeriodAbbreviation()+" "+assignment.getRoomsName(", ")+")",
ChangeLog.Source.EXAM_INFO,
ChangeLog.Operation.ASSIGN,
subject,
dept);
tx.commit();
return null;
} catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
return "Assignment of "+assignment.getExamName()+" to "+assignment.getPeriodAbbreviation()+" "+assignment.getRoomsName(", ")+" failed, reason: "+e.getMessage();
}
}
public String unassign(String managerExternalId, Session hibSession) {
Transaction tx = null;
try {
if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
tx = hibSession.beginTransaction();
ExamAssignment oldAssignment = new ExamAssignment(this);
setAssignedPeriod(null);
if (getAssignedRooms()==null) setAssignedRooms(new HashSet());
getAssignedRooms().clear();
setAssignedPreference(null);
HashSet otherExams = new HashSet();
for (Iterator j=getConflicts().iterator();j.hasNext();) {
ExamConflict conf = (ExamConflict)j.next();
for (Iterator i=conf.getExams().iterator();i.hasNext();) {
Exam x = (Exam)i.next();
if (!x.equals(this)) {
x.getConflicts().remove(conf);
otherExams.add(x);
}
}
hibSession.delete(conf);
j.remove();
}
ExamEvent event = getEvent();
if (event!=null) hibSession.delete(event);
hibSession.update(this);
for (Iterator i=otherExams.iterator();i.hasNext();)
hibSession.update((Exam)i.next());
SubjectArea subject = null;
Department dept = null;
for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
subject = owner.getCourse().getSubjectArea();
dept = subject.getDepartment();
break;
}
ChangeLog.addChange(hibSession,
TimetableManager.findByExternalId(managerExternalId),
getSession(),
this,
getName()+" ("+
(oldAssignment.getPeriod()==null?"N/A":oldAssignment.getPeriodAbbreviation()+" "+oldAssignment.getRoomsName(", "))+
" → N/A)",
ChangeLog.Source.EXAM_INFO,
ChangeLog.Operation.UNASSIGN,
subject,
dept);
if (tx!=null) tx.commit();
return null;
} catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
return "Unassignment of "+getName()+" failed, reason: "+e.getMessage();
}
}
protected HashSet getStudents(org.hibernate.Session hibSession, Collection studentIds) {
HashSet students = new HashSet();
if (studentIds==null || studentIds.isEmpty()) return students;
for (Iterator i=studentIds.iterator();i.hasNext();) {
Long studentId = (Long)i.next();
Student student = new StudentDAO().get(studentId, hibSession);
if (student!=null) students.add(student);
}
return students;
}
protected HashSet getInstructors(org.hibernate.Session hibSession, Collection instructorIds) {
HashSet instructors = new HashSet();
if (instructorIds==null || instructorIds.isEmpty()) return instructors;
for (Iterator i=instructorIds.iterator();i.hasNext();) {
Long instructorId = (Long)i.next();
DepartmentalInstructor instructor = new DepartmentalInstructorDAO().get(instructorId, hibSession);
if (instructor!=null) instructors.add(instructor);
}
return instructors;
}
public int examOffset() {
return (getPrintOffset() == null ? 0 : getPrintOffset());
}
public ExamEvent generateEvent(ExamEvent event, boolean createNoRoomMeetings) {
ExamPeriod period = getAssignedPeriod();
if (period==null) return null;
if (event==null) {
if (getSession().getStatusType().isTestSession()) return null;
event = (getExamType().getType()==ExamType.sExamTypeFinal?new FinalExamEvent():new MidtermExamEvent());
event.setExam(this);
setEvent(event);
}
if (event.getMeetings()!=null)
event.getMeetings().clear();
else
event.setMeetings(new HashSet());
boolean created = false;
for (Iterator i=getAssignedRooms().iterator();i.hasNext();) {
Location location = (Location)i.next();
if (location.getPermanentId()!=null) {
Meeting m = new Meeting();
m.setMeetingDate(period.getStartDate());
m.setStartPeriod(period.getExamEventStartSlot());
m.setStartOffset(period.getExamEventStartOffsetForExam(this));
m.setStopPeriod(period.getExamEventStopSlot());
m.setStopOffset(period.getExamEventStopOffsetForExam(this));
m.setClassCanOverride(false);
m.setLocationPermanentId(location.getPermanentId());
m.setStatus(Meeting.Status.APPROVED);
m.setApprovalDate(new Date());
m.setEvent(event);
event.getMeetings().add(m);
created = true;
}
}
if (!created && createNoRoomMeetings) {
Meeting m = new Meeting();
m.setMeetingDate(period.getStartDate());
m.setStartPeriod(period.getExamEventStartSlot());
m.setStartOffset(period.getExamEventStartOffsetForExam(this));
m.setStopPeriod(period.getExamEventStopSlot());
m.setStopOffset(period.getExamEventStopOffsetForExam(this));
m.setClassCanOverride(false);
m.setLocationPermanentId(null);
m.setStatus(Meeting.Status.APPROVED);
m.setApprovalDate(new Date());
m.setEvent(event);
event.getMeetings().add(m);
}
return event;
}
public ExamPeriod getAveragePeriod() {
return ExamPeriod.findByIndex(getSession().getUniqueId(), getExamType(), getAvgPeriod());
}
public static Exam findByIdRolledForwardFrom(Long sessionId, Long uniqueIdRolledForwardFrom) {
return (Exam)new ExamDAO().
getSession().
createQuery("select e from Exam e where e.session.uniqueId=:sessionId and e.uniqueIdRolledForwardFrom=:uniqueIdRolledForwardFrom").
setLong("sessionId", sessionId.longValue()).
setLong("uniqueIdRolledForwardFrom", uniqueIdRolledForwardFrom.longValue()).
setCacheable(true).
uniqueResult();
}
public void generateDefaultPreferences(boolean override) {
Set allPeriods = ExamPeriod.findAll(getSession().getUniqueId(), getExamType());
if (getPreferences()==null) setPreferences(new HashSet());
//Prefer overlapping period for evening classes
PreferenceLevel eveningPref = PreferenceLevel.getPreferenceLevel(ApplicationProperty.ExamDefaultsEveningClassPreference.value(getExamType().getReference()));
if (!PreferenceLevel.sNeutral.equals(eveningPref.getPrefProlog()) && (override || getPreferences(ExamPeriodPref.class).isEmpty())) {
int firstEveningPeriod = ApplicationProperty.ExamDefaultsEveningClassStart.intValue(getExamType().getReference());
HashSet<ExamPeriod> periods = new HashSet();
for (Iterator i=getOwners().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
if (ExamOwner.sOwnerTypeClass!=owner.getOwnerType()) continue;
Event event = ((Class_)owner.getOwnerObject()).getEvent();
if (event==null) continue;
for (Iterator j=event.getMeetings().iterator();j.hasNext();) {
Meeting meeting = (Meeting)j.next();
if (meeting.getStopPeriod()<=firstEveningPeriod) continue;
ExamPeriod lastPeriod = null;
for (Iterator k=allPeriods.iterator();k.hasNext();) {
ExamPeriod period = (ExamPeriod)k.next();
if (period.getDayOfWeek()!=meeting.getDayOfWeek()) continue;
if (lastPeriod==null || lastPeriod.getStartSlot()<period.getStartSlot())
lastPeriod = period;
}
if (lastPeriod!=null) periods.add(lastPeriod);
}
}
if (!periods.isEmpty()) {
for (Iterator i=getPreferences(ExamPeriodPref.class).iterator();i.hasNext();) {
ExamPeriodPref pref = (ExamPeriodPref)i.next();
if (periods.contains(pref.getExamPeriod())) {
periods.remove(pref.getExamPeriod());
if (!pref.getPrefLevel().equals(eveningPref)) {
pref.setPrefLevel(eveningPref);
}
} else {
getPreferences().remove(pref);
}
}
for (ExamPeriod period : periods) {
ExamPeriodPref pref = new ExamPeriodPref();
pref.setPrefLevel(eveningPref);
pref.setOwner(this);
pref.setExamPeriod(period);
getPreferences().add(pref);
}
}
}
//Prefer original room
PreferenceLevel originalPref = PreferenceLevel.getPreferenceLevel(ApplicationProperty.ExamDefaultsOriginalRoomPreference.value(getExamType().getReference()));
if (!PreferenceLevel.sNeutral.equals(originalPref.getPrefProlog()) && (override || getPreferences(RoomPref.class).isEmpty())) {
HashSet<Location> locations = new HashSet();
for (Iterator i=getOwners().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
if (ExamOwner.sOwnerTypeClass!=owner.getOwnerType()) continue;
Event event = ((Class_)owner.getOwnerObject()).getEvent();
if (event==null) continue;
for (Iterator j=event.getMeetings().iterator();j.hasNext();) {
Meeting meeting = (Meeting)j.next();
if (meeting.getLocation()!=null && meeting.getLocation().isExamEnabled(getExamType())) locations.add(meeting.getLocation());
}
}
if (!locations.isEmpty()) {
for (Iterator i=getPreferences(RoomPref.class).iterator();i.hasNext();) {
RoomPref pref = (RoomPref)i.next();
if (locations.contains(pref.getRoom())) {
locations.remove(pref.getRoom());
if (!pref.getPrefLevel().equals(originalPref)) {
pref.setPrefLevel(originalPref);
}
} else {
getPreferences().remove(pref);
}
}
for (Location location : locations) {
RoomPref pref = new RoomPref();
pref.setPrefLevel(originalPref);
pref.setOwner(this);
pref.setRoom(location);
getPreferences().add(pref);
}
}
}
//Prefer original building
PreferenceLevel originalBuildingPref = PreferenceLevel.getPreferenceLevel(ApplicationProperty.ExamDefaultsOriginalBuildingPreference.value(getExamType().getReference()));
boolean examRoomsOnly = ApplicationProperty.ExamDefaultsOriginalBuildingOnlyForExamRooms.isTrue(getExamType().getReference());
if (!PreferenceLevel.sNeutral.equals(originalBuildingPref.getPrefProlog()) && (override || getPreferences(BuildingPref.class).isEmpty())) {
HashSet<Building> buildings = new HashSet<Building>();
for (Iterator i=getOwners().iterator();i.hasNext();) {
ExamOwner owner = (ExamOwner)i.next();
if (ExamOwner.sOwnerTypeClass!=owner.getOwnerType()) continue;
Event event = ((Class_)owner.getOwnerObject()).getEvent();
if (event==null) continue;
for (Iterator j=event.getMeetings().iterator();j.hasNext();) {
Meeting meeting = (Meeting)j.next();
Location location = meeting.getLocation();
if (location == null || !(location instanceof Room)) continue;
if (examRoomsOnly && !location.isExamEnabled(getExamType())) continue;
buildings.add(((Room)location).getBuilding());
}
}
if (!buildings.isEmpty()) {
for (Iterator i=getPreferences(BuildingPref.class).iterator();i.hasNext();) {
BuildingPref pref = (BuildingPref)i.next();
if (buildings.contains(pref.getBuilding())) {
buildings.remove(pref.getBuilding());
if (!pref.getPrefLevel().equals(originalBuildingPref)) {
pref.setPrefLevel(originalBuildingPref);
}
} else {
getPreferences().remove(pref);
}
}
for (Building building : buildings) {
BuildingPref pref = new BuildingPref();
pref.setPrefLevel(originalBuildingPref);
pref.setOwner(this);
pref.setBuilding(building);
getPreferences().add(pref);
}
}
}
}
private ExamEvent iEvent = null;
public ExamEvent getEvent() {
if (getUniqueId()==null) return null;
if (iEvent==null)
iEvent = (ExamEvent)new ExamDAO().getSession().createQuery(
"select e from ExamEvent e left join fetch e.meetings m where e.exam.uniqueId=:examId").
setLong("examId", getUniqueId()).
setCacheable(true).uniqueResult();
return iEvent;
}
public void setEvent(ExamEvent event) {
iEvent = event;
}
public void updateConflicts(Session hibSession) throws Exception {
Transaction tx = null;
try {
if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
tx = hibSession.beginTransaction();
HashSet otherExams = new HashSet();
for (Iterator j=getConflicts().iterator();j.hasNext();) {
ExamConflict conf = (ExamConflict)j.next();
for (Iterator i=conf.getExams().iterator();i.hasNext();) {
Exam x = (Exam)i.next();
if (!x.equals(this)) {
x.getConflicts().remove(conf);
otherExams.add(x);
}
}
hibSession.delete(conf);
j.remove();
}
ExamAssignmentInfo assignment = new ExamAssignmentInfo(this, false);
for (Iterator i=assignment.getDirectConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.DirectConflict dc = (ExamAssignmentInfo.DirectConflict)i.next();
if (dc.getOtherExam()==null) continue;
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeDirect);
conf.setStudents(getStudents(hibSession, dc.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = dc.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getBackToBackConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.BackToBackConflict btb = (ExamAssignmentInfo.BackToBackConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(btb.isDistance()?ExamConflict.sConflictTypeBackToBackDist:ExamConflict.sConflictTypeBackToBack);
conf.setDistance(btb.getDistance());
conf.setStudents(getStudents(hibSession, btb.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = btb.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getMoreThanTwoADaysConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.MoreThanTwoADayConflict m2d = (ExamAssignmentInfo.MoreThanTwoADayConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeMoreThanTwoADay);
conf.setStudents(getStudents(hibSession, m2d.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
for (Iterator j=m2d.getOtherExams().iterator();j.hasNext();) {
Exam otherExam = (Exam)((ExamInfo)j.next()).getExam(hibSession);
otherExam.getConflicts().add(conf);
otherExams.add(otherExam);
}
}
for (Iterator i=assignment.getInstructorDirectConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.DirectConflict dc = (ExamAssignmentInfo.DirectConflict)i.next();
if (dc.getOtherExam()==null) continue;
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeDirect);
conf.setStudents(getInstructors(hibSession, dc.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = dc.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getInstructorBackToBackConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.BackToBackConflict btb = (ExamAssignmentInfo.BackToBackConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(btb.isDistance()?ExamConflict.sConflictTypeBackToBackDist:ExamConflict.sConflictTypeBackToBack);
conf.setDistance(btb.getDistance());
conf.setStudents(getInstructors(hibSession, btb.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
Exam other = btb.getOtherExam().getExam(hibSession);
other.getConflicts().add(conf);
otherExams.add(other);
}
for (Iterator i=assignment.getInstructorMoreThanTwoADaysConflicts().iterator();i.hasNext();) {
ExamAssignmentInfo.MoreThanTwoADayConflict m2d = (ExamAssignmentInfo.MoreThanTwoADayConflict)i.next();
ExamConflict conf = new ExamConflict();
conf.setConflictType(ExamConflict.sConflictTypeMoreThanTwoADay);
conf.setStudents(getInstructors(hibSession, m2d.getStudents()));
conf.setNrStudents(conf.getStudents().size());
hibSession.save(conf);
getConflicts().add(conf);
for (Iterator j=m2d.getOtherExams().iterator();j.hasNext();) {
Exam otherExam = (Exam)((ExamInfo)j.next()).getExam(hibSession);
otherExam.getConflicts().add(conf);
otherExams.add(otherExam);
}
}
hibSession.update(this);
for (Iterator i=otherExams.iterator();i.hasNext();)
hibSession.update((Exam)i.next());
if (tx!=null) tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
}
public Date getEndTime(ExamPeriod period) {
Calendar c = Calendar.getInstance(Locale.US);
c.setTime(getSession().getExamBeginDate());
c.add(Calendar.DAY_OF_YEAR, period.getDateOffset());
int min = period.getStartSlot()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN + examOffset() + getLength();
c.set(Calendar.HOUR, min/60); c.set(Calendar.MINUTE, min%60);
return c.getTime();
}
public Date getStartTime(ExamPeriod period) {
Calendar c = Calendar.getInstance(Locale.US);
c.setTime(getSession().getExamBeginDate());
c.add(Calendar.DAY_OF_YEAR, period.getDateOffset());
int min = period.getStartSlot()*Constants.SLOT_LENGTH_MIN + Constants.FIRST_SLOT_TIME_MIN + examOffset();
c.set(Calendar.HOUR, min/60); c.set(Calendar.MINUTE, min%60);
return c.getTime();
}
@Override
public Department getDepartment() { return null; }
public DepartmentStatusType effectiveStatusType() {
return getStatusType() == null ? getSession().getStatusType() : getStatusType();
}
public boolean canView() {
DepartmentStatusType type = effectiveStatusType();
return type != null && (getExamType().getType() == ExamType.sExamTypeFinal ? type.canNoRoleReportExamFinal() : type.canNoRoleReportExamMidterm());
}
}
| apache-2.0 |
BeatCoding/droolsjbpm-integration | kie-examples-api/kie-maven-example/src/main/java/org/kie/example/api/kiemavenexample/Message.java | 1975 | /*
* Copyright 2015 JBoss Inc
*
* 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.example.api.kiemavenexample;
public class Message {
private String name;
private String text;
public Message(String name, String text) {
this.text = text;
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Message[name='" + name + "' text='" + text + "'";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((text == null) ? 0 : text.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; }
Message other = (Message) obj;
if (name == null) {
if (other.name != null) { return false; }
} else if (!name.equals(other.name)) { return false; }
if (text == null) {
if (other.text != null) { return false; }
} else if (!text.equals(other.text)) { return false; }
return true;
}
}
| apache-2.0 |
madhav123/gkmaster | appdomain/src/main/java/org/mifos/accounts/financial/business/service/activity/accountingentry/CustomerPenaltyAdjustmentAccountingEntry.java | 2111 | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.accounts.financial.business.service.activity.accountingentry;
import org.mifos.accounts.financial.business.FinancialActionTypeEntity;
import org.mifos.accounts.financial.exceptions.FinancialException;
import org.mifos.accounts.financial.util.helpers.FinancialActionCache;
import org.mifos.accounts.financial.util.helpers.FinancialActionConstants;
import org.mifos.accounts.financial.util.helpers.FinancialConstants;
import org.mifos.customers.business.CustomerTrxnDetailEntity;
public class CustomerPenaltyAdjustmentAccountingEntry extends BaseAccountingEntry {
@Override
protected void applySpecificAccountActionEntry() throws FinancialException {
CustomerTrxnDetailEntity customertrxn = (CustomerTrxnDetailEntity) financialActivity.getAccountTrxn();
FinancialActionTypeEntity finActionMiscPenalty = FinancialActionCache
.getFinancialAction(FinancialActionConstants.MISCPENALTYPOSTING);
addAccountEntryDetails(customertrxn.getMiscPenaltyAmount(), finActionMiscPenalty,
getGLcode(finActionMiscPenalty.getApplicableDebitCharts()), FinancialConstants.CREDIT);
addAccountEntryDetails(customertrxn.getMiscPenaltyAmount(), finActionMiscPenalty,
getGLcode(finActionMiscPenalty.getApplicableCreditCharts()), FinancialConstants.DEBIT);
}
}
| apache-2.0 |
hurricup/intellij-community | plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/descriptors/JavaFxBuiltInTagDescriptor.java | 9504 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* 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.jetbrains.plugins.javaFX.fxml.descriptors;
import com.intellij.codeInsight.daemon.Validator;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.xml.XmlAttributeDescriptor;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.XmlElementsGroup;
import com.intellij.xml.XmlNSDescriptor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.javaFX.fxml.FxmlConstants;
import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: anna
*/
public class JavaFxBuiltInTagDescriptor implements XmlElementDescriptor, Validator<XmlTag> {
private final String myName;
private final XmlTag myXmlTag;
public JavaFxBuiltInTagDescriptor(String name, XmlTag tag) {
myName = name;
myXmlTag = tag;
}
@Override
public String getQualifiedName() {
return getName();
}
@Override
public String getDefaultName() {
return getName();
}
@Override
public XmlElementDescriptor[] getElementsDescriptors(XmlTag context) {
return XmlElementDescriptor.EMPTY_ARRAY;
}
@Nullable
@Override
public XmlElementDescriptor getElementDescriptor(XmlTag childTag, XmlTag contextTag) {
if (FxmlConstants.FX_DEFINE.equals(myName)) {
return JavaFxClassTagDescriptorBase.createTagDescriptor(childTag);
}
return null;
}
@Override
public XmlAttributeDescriptor[] getAttributesDescriptors(@Nullable XmlTag context) {
final List<XmlAttributeDescriptor> descriptors = new ArrayList<>();
final List<String> builtInAttributeNames = FxmlConstants.FX_BUILT_IN_TAG_SUPPORTED_ATTRIBUTES.get(getName());
if (builtInAttributeNames != null) {
for (String attrName : builtInAttributeNames) {
descriptors.add(JavaFxBuiltInAttributeDescriptor.create(attrName, getName()));
}
}
JavaFxClassTagDescriptorBase.collectStaticAttributesDescriptors(context, descriptors);
final XmlTag referencedTag = getReferencedTag(myXmlTag);
if (referencedTag != null) {
final XmlElementDescriptor referencedDescriptor = referencedTag.getDescriptor();
if (referencedDescriptor != null) {
final XmlAttributeDescriptor[] attributesDescriptors = referencedDescriptor.getAttributesDescriptors(referencedTag);
if (attributesDescriptors != null) {
Collections.addAll(descriptors, attributesDescriptors);
}
}
}
final XmlTag includedRoot = getIncludedRoot(context);
if (includedRoot != null) {
final XmlElementDescriptor includedRootDescriptor = includedRoot.getDescriptor();
if (includedRootDescriptor instanceof JavaFxClassTagDescriptorBase) {
((JavaFxClassTagDescriptorBase)includedRootDescriptor).collectInstanceProperties(descriptors);
}
}
return descriptors.isEmpty() ? XmlAttributeDescriptor.EMPTY : descriptors.toArray(XmlAttributeDescriptor.EMPTY);
}
@Nullable
@Override
public XmlAttributeDescriptor getAttributeDescriptor(@NonNls String attributeName, @Nullable XmlTag context) {
final List<String> defaultAttributeList = FxmlConstants.FX_BUILT_IN_TAG_SUPPORTED_ATTRIBUTES.get(getName());
if (defaultAttributeList != null) {
if (defaultAttributeList.contains(attributeName)) {
return JavaFxBuiltInAttributeDescriptor.create(attributeName, getName());
}
final PsiMethod propertySetter = JavaFxPsiUtil.findStaticPropertySetter(attributeName, context);
if (propertySetter != null) {
return new JavaFxStaticSetterAttributeDescriptor(propertySetter, attributeName);
}
final XmlTag referencedTag = getReferencedTag(myXmlTag);
if (referencedTag != null) {
final XmlElementDescriptor referencedDescriptor = referencedTag.getDescriptor();
if (referencedDescriptor != null) {
return referencedDescriptor.getAttributeDescriptor(attributeName, referencedTag);
}
}
if (context != null && FxmlConstants.FX_INCLUDE.equals(getName())) {
final XmlTag includedRoot = getIncludedRoot(context);
if (includedRoot != null) {
final XmlElementDescriptor includedRootDescriptor = includedRoot.getDescriptor();
if (includedRootDescriptor != null) {
return includedRootDescriptor.getAttributeDescriptor(attributeName, includedRoot);
}
}
}
}
return null;
}
@Nullable
public static XmlTag getReferencedTag(XmlTag tag) {
final String tagName = tag.getName();
if (FxmlConstants.FX_REFERENCE.equals(tagName) || FxmlConstants.FX_COPY.equals(tagName)) {
final XmlAttribute attribute = tag.getAttribute(FxmlConstants.SOURCE);
if (attribute != null) {
final XmlAttributeValue valueElement = attribute.getValueElement();
if (valueElement != null) {
final PsiReference reference = valueElement.getReference();
if (reference != null) {
final PsiElement resolve = reference.resolve();
if (resolve instanceof XmlAttributeValue) {
return PsiTreeUtil.getParentOfType(resolve, XmlTag.class);
}
}
}
}
}
return null;
}
public static XmlTag getIncludedRoot(XmlTag context) {
if (context == null) return null;
final XmlAttribute xmlAttribute = context.getAttribute(FxmlConstants.SOURCE);
if (xmlAttribute != null) {
final XmlAttributeValue valueElement = xmlAttribute.getValueElement();
if (valueElement != null) {
final PsiReference reference = valueElement.getReference();
if (reference != null) {
final PsiElement resolve = reference.resolve();
if (resolve instanceof XmlFile) {
final XmlTag rootTag = ((XmlFile)resolve).getRootTag();
if (rootTag != null) {
return rootTag;
}
}
}
}
}
return null;
}
@Nullable
@Override
public XmlAttributeDescriptor getAttributeDescriptor(XmlAttribute attribute) {
return getAttributeDescriptor(attribute.getName(), attribute.getParent());
}
@Override
public XmlNSDescriptor getNSDescriptor() {
return null;
}
@Nullable
@Override
public XmlElementsGroup getTopGroup() {
return null;
}
@Override
public int getContentType() {
return CONTENT_TYPE_UNKNOWN;
}
@Nullable
@Override
public String getDefaultValue() {
return null;
}
@Override
public PsiElement getDeclaration() {
return myXmlTag;
}
@Override
public String getName(PsiElement context) {
return getName();
}
@Override
public String getName() {
return myName;
}
@Override
public void init(PsiElement element) {
}
@Override
public Object[] getDependences() {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@Override
public void validate(@NotNull XmlTag context, @NotNull ValidationHost host) {
final XmlTag referencedTag = getReferencedTag(context);
if (referencedTag != null) {
final XmlElementDescriptor descriptor = referencedTag.getDescriptor();
if (descriptor != null) {
final PsiElement declaration = descriptor.getDeclaration();
if (declaration instanceof PsiClass) {
final PsiClass psiClass = (PsiClass)declaration;
JavaFxPsiUtil.isClassAcceptable(context.getParentTag(), psiClass, (errorMessage, errorType) ->
host.addMessage(context.getNavigationElement(), errorMessage, errorType));
final String contextName = context.getName();
if (FxmlConstants.FX_COPY.equals(contextName)) {
boolean copyConstructorFound = false;
for (PsiMethod constructor : psiClass.getConstructors()) {
final PsiParameter[] parameters = constructor.getParameterList().getParameters();
if (parameters.length == 1 && psiClass == PsiUtil.resolveClassInType(parameters[0].getType())) {
copyConstructorFound = true;
break;
}
}
if (!copyConstructorFound) {
host.addMessage(context.getNavigationElement(), "Copy constructor not found for \'" + psiClass.getName() + "\'",
ValidationHost.ErrorType.ERROR);
}
}
}
}
}
}
@Override
public String toString() {
final String source = myXmlTag != null ? myXmlTag.getAttributeValue(FxmlConstants.SOURCE) : null;
return "<" + myName + (source != null ? " -> " + source : "") + ">";
}
}
| apache-2.0 |
wangscript/lforum | src/main/java/com/javaeye/lonlysky/lforum/SystemInitListener.java | 1562 | package com.javaeye.lonlysky.lforum;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.javaeye.lonlysky.lforum.config.impl.ConfigLoader;
import com.javaeye.lonlysky.lforum.entity.global.Config;
/**
* <b>系统初始化监听器</b><br>
* 目的:加载全局配置文件并保存到Context范围内
*
* @author 黄磊
*
*/
public class SystemInitListener implements ServletContextListener {
private static final Logger logger = LoggerFactory.getLogger(SystemInitListener.class);
private Config config; // 系统配置文件
/**
* 销毁函数
*/
public void contextDestroyed(ServletContextEvent contextEvent) {
ServletContext context = contextEvent.getServletContext();
if (config != null) {
config = null;
}
if (context.getAttribute(GlobalsKeys.WEB_CONFIG) != null) {
context.removeAttribute(GlobalsKeys.WEB_CONFIG);
}
}
/**
* 初始化加载
*/
public void contextInitialized(ServletContextEvent contextEvent) {
logger.info("开始加载系统配置...");
ServletContext context = contextEvent.getServletContext();
// 读取全局配置文件
if (config == null) {
String appPath = context.getRealPath("/");
ConfigLoader loader = new ConfigLoader(appPath);
config = loader.initConfig();
}
context.setAttribute(GlobalsKeys.WEB_CONFIG, config);
logger.info("系统配置加载成功...");
}
}
| apache-2.0 |
appbank2020/GitRobot | src/org/kohsuke/github/GHIssue.java | 7712 | /*
* The MIT License
*
* Copyright (c) 2011, Eric Maupin, Kohsuke Kawaguchi
*
* 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.kohsuke.github;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Represents an issue on GitHub.
*
* @author Eric Maupin
* @author Kohsuke Kawaguchi
* @see GHRepository#getIssue(int)
* @see GitHub#searchIssues()
* @see GHIssueSearchBuilder
*/
public class GHIssue extends GHObject {
GitHub root;
GHRepository owner;
// API v3
protected GHUser assignee;
protected String state;
protected int number;
protected String closed_at;
protected int comments;
protected String body;
// for backward compatibility with < 1.63, this collection needs to hold instances of Label, not GHLabel
protected List<Label> labels;
protected GHUser user;
protected String title, html_url;
protected GHIssue.PullRequest pull_request;
protected GHMilestone milestone;
protected GHUser closed_by;
/**
* @deprecated use {@link GHLabel}
*/
public static class Label extends GHLabel {
}
/*package*/ GHIssue wrap(GHRepository owner) {
this.owner = owner;
if(milestone != null) milestone.wrap(owner);
return wrap(owner.root);
}
/*package*/ GHIssue wrap(GitHub root) {
this.root = root;
if(assignee != null) assignee.wrapUp(root);
if(user != null) user.wrapUp(root);
if(closed_by != null) closed_by.wrapUp(root);
return this;
}
/*package*/ static GHIssue[] wrap(GHIssue[] issues, GHRepository owner) {
for (GHIssue i : issues)
i.wrap(owner);
return issues;
}
/**
* Repository to which the issue belongs.
*/
public GHRepository getRepository() {
return owner;
}
/**
* The description of this pull request.
*/
public String getBody() {
return body;
}
/**
* ID.
*/
public int getNumber() {
return number;
}
/**
* The HTML page of this issue,
* like https://github.com/jenkinsci/jenkins/issues/100
*/
public URL getHtmlUrl() {
return GitHub.parseURL(html_url);
}
public String getTitle() {
return title;
}
public GHIssueState getState() {
return Enum.valueOf(GHIssueState.class, state.toUpperCase(Locale.ENGLISH));
}
public Collection<GHLabel> getLabels() throws IOException {
if(labels == null){
return Collections.emptyList();
}
return Collections.<GHLabel>unmodifiableList(labels);
}
public Date getClosedAt() {
return GitHub.parseDate(closed_at);
}
public URL getApiURL(){
return GitHub.parseURL(url);
}
/**
* Updates the issue by adding a comment.
*/
public void comment(String message) throws IOException {
new Requester(root).with("body",message).to(getIssuesApiRoute() + "/comments");
}
private void edit(String key, Object value) throws IOException {
new Requester(root)._with(key, value).method("PATCH").to(getApiRoute());
}
private void editIssue(String key, Object value) throws IOException {
new Requester(root)._with(key, value).method("PATCH").to(getIssuesApiRoute());
}
/**
* Closes this issue.
*/
public void close() throws IOException {
edit("state", "closed");
}
/**
* Reopens this issue.
*/
public void reopen() throws IOException {
edit("state", "open");
}
public void setTitle(String title) throws IOException {
edit("title",title);
}
public void setBody(String body) throws IOException {
edit("body",body);
}
public void assignTo(GHUser user) throws IOException {
editIssue("assignee",user.getLogin());
}
public void setLabels(String... labels) throws IOException {
editIssue("labels",labels);
}
/**
* Obtains all the comments associated with this issue.
*
* @see #listComments()
*/
public List<GHIssueComment> getComments() throws IOException {
return listComments().asList();
}
/**
* Obtains all the comments associated with this issue.
*/
public PagedIterable<GHIssueComment> listComments() throws IOException {
return new PagedIterable<GHIssueComment>() {
public PagedIterator<GHIssueComment> iterator() {
return new PagedIterator<GHIssueComment>(root.retrieve().asIterator(getIssuesApiRoute() + "/comments", GHIssueComment[].class)) {
protected void wrapUp(GHIssueComment[] page) {
for (GHIssueComment c : page)
c.wrapUp(GHIssue.this);
}
};
}
};
}
protected String getApiRoute() {
return getIssuesApiRoute();
}
protected String getIssuesApiRoute() {
return "/repos/"+owner.getOwnerName()+"/"+owner.getName()+"/issues/"+number;
}
public GHUser getAssignee() {
return assignee;
}
/**
* User who submitted the issue.
*/
public GHUser getUser() {
return user;
}
/**
* Reports who has closed the issue.
*
* <p>
* Note that GitHub doesn't always seem to report this information
* even for an issue that's already closed. See
* https://github.com/kohsuke/github-api/issues/60.
*/
public GHUser getClosedBy() {
if(!"closed".equals(state)) return null;
if(closed_by != null) return closed_by;
//TODO closed_by = owner.getIssue(number).getClosed_by();
return closed_by;
}
public int getCommentsCount(){
return comments;
}
/**
* Returns non-null if this issue is a shadow of a pull request.
*/
public PullRequest getPullRequest() {
return pull_request;
}
public boolean isPullRequest() {
return pull_request!=null;
}
public GHMilestone getMilestone() {
return milestone;
}
public static class PullRequest{
private String diff_url, patch_url, html_url;
public URL getDiffUrl() {
return GitHub.parseURL(diff_url);
}
public URL getPatchUrl() {
return GitHub.parseURL(patch_url);
}
public URL getUrl() {
return GitHub.parseURL(html_url);
}
}
}
| apache-2.0 |
chanakaudaya/developer-studio | esb/org.wso2.developerstudio.eclipse.artifact.proxyservice/src/org/wso2/developerstudio/eclipse/artifact/proxyservice/ui/wizard/ProxyServiceProjectCreationWizard.java | 14647 | /*
* Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.artifact.proxyservice.ui.wizard;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.Repository;
import org.apache.maven.model.RepositoryPolicy;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.Activator;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.model.ProxyServiceModel;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.model.ProxyServiceModel.TargetEPType;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.utils.ProxyServiceImageUtils;
import org.wso2.developerstudio.eclipse.artifact.proxyservice.utils.PsArtifactConstants;
import org.wso2.developerstudio.eclipse.capp.maven.utils.MavenConstants;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.wso2.developerstudio.eclipse.maven.util.MavenUtils;
import org.wso2.developerstudio.eclipse.platform.core.templates.ArtifactTemplate;
import org.wso2.developerstudio.eclipse.platform.ui.editor.Openable;
import org.wso2.developerstudio.eclipse.platform.ui.startup.ESBGraphicalEditor;
import org.wso2.developerstudio.eclipse.platform.ui.wizard.AbstractWSO2ProjectCreationWizard;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;
public class ProxyServiceProjectCreationWizard extends AbstractWSO2ProjectCreationWizard {
private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID);
private final ProxyServiceModel psModel;
private IFile proxyServiceFile;
private ESBProjectArtifact esbProjectArtifact;
private List<File> fileLst = new ArrayList<File>();
private IProject esbProject;
public ProxyServiceProjectCreationWizard() {
this.psModel = new ProxyServiceModel();
setModel(this.psModel);
setWindowTitle(PsArtifactConstants.PS_WIZARD_WINDOW_TITLE);
setDefaultPageImageDescriptor(ProxyServiceImageUtils.getInstance().getImageDescriptor("proxy-service-wizard.png"));
}
protected boolean isRequireProjectLocationSection() {
return false;
}
protected boolean isRequiredWorkingSet() {
return false;
}
public boolean performFinish() {
try {
boolean isNewArtifact = true;
String templateContent = "";
String template = "";
ProxyServiceModel proxyServiceModel = (ProxyServiceModel) getModel();
esbProject = proxyServiceModel.getProxyServiceSaveLocation().getProject();
IContainer location = esbProject.getFolder("src" + File.separator + "main" +
File.separator +
"synapse-config" +
File.separator +
"proxy-services");
File pomfile = esbProject.getFile("pom.xml").getLocation().toFile();
if(!pomfile.exists()){
getModel().getMavenInfo().setPackageName("synapse/proxy-service");
createPOM(pomfile);
}
updatePom();
esbProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
String groupId = getMavenGroupId(pomfile) + ".proxy-service";
//Adding the metadata about the proxy service to the metadata store.
esbProjectArtifact=new ESBProjectArtifact();
esbProjectArtifact.fromFile(esbProject.getFile("artifact.xml").getLocation().toFile());
if (getModel().getSelectedOption().equals(PsArtifactConstants.WIZARD_OPTION_IMPORT_OPTION)) {
proxyServiceFile = location.getFile(new Path(getModel().getImportFile().getName()));
if(proxyServiceFile.exists()){
if(!MessageDialog.openQuestion(getShell(), "WARNING", "Do you like to override exsiting project in the workspace")){
return false;
}
isNewArtifact = false;
}
copyImportFile(location,isNewArtifact,groupId);
} else {
ArtifactTemplate selectedTemplate = psModel.getSelectedTemplate();
templateContent = FileUtils.getContentAsString(selectedTemplate.getTemplateDataStream());
if(selectedTemplate.getName().equals(PsArtifactConstants.CUSTOM_PROXY)){
template = createProxyTemplate(templateContent, PsArtifactConstants.CUSTOM_PROXY);
}else if(selectedTemplate.getName().equals(PsArtifactConstants.LOGGING_PROXY)){
template = createProxyTemplate(templateContent, PsArtifactConstants.LOGGING_PROXY);
}else if(selectedTemplate.getName().equals(PsArtifactConstants.PASS_THROUGH_PROXY)){
template = createProxyTemplate(templateContent, PsArtifactConstants.PASS_THROUGH_PROXY);
}else if(selectedTemplate.getName().equals(PsArtifactConstants.SECURE_PROXY)){
template = createProxyTemplate(templateContent, PsArtifactConstants.SECURE_PROXY);
}else if(selectedTemplate.getName().equals(PsArtifactConstants.TRANSFORMER_PROXY)){
template = createProxyTemplate(templateContent, PsArtifactConstants.TRANSFORMER_PROXY);
}else if(selectedTemplate.getName().equals(PsArtifactConstants.WSDL_BASED_PROXY)){
template = createProxyTemplate(templateContent, PsArtifactConstants.WSDL_BASED_PROXY);
}else{
template = createProxyTemplate(templateContent, "");
}
proxyServiceFile = location.getFile(new Path(proxyServiceModel.getProxyServiceName() + ".xml"));
File destFile = proxyServiceFile.getLocation().toFile();
FileUtils.createFile(destFile, template);
fileLst.add(destFile);
String relativePath = FileUtils.getRelativePath(
esbProject.getLocation().toFile(),
new File(location.getLocation().toFile(), proxyServiceModel
.getProxyServiceName() + ".xml")).replaceAll(Pattern.quote(File.separator), "/");
esbProjectArtifact.addESBArtifact(createArtifact(
proxyServiceModel.getProxyServiceName(), groupId, "1.0.0", relativePath));
}
esbProjectArtifact.toFile();
esbProject.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
if(fileLst.size()>0){
openEditor(fileLst.get(0));
}
} catch (CoreException e) {
log.error("CoreException has occurred", e);
} catch (Exception e) {
log.error("An unexpected error has occurred", e);
}
return true;
}
public void updatePom() throws Exception{
File mavenProjectPomLocation = esbProject.getFile("pom.xml").getLocation().toFile();
MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation);
boolean pluginExists = MavenUtils.checkOldPluginEntry(mavenProject,
"org.wso2.maven", "wso2-esb-proxy-plugin",
MavenConstants.WSO2_ESB_PROXY_VERSION);
if(pluginExists){
return ;
}
Plugin plugin = MavenUtils.createPluginEntry(mavenProject, "org.wso2.maven", "wso2-esb-proxy-plugin", MavenConstants.WSO2_ESB_PROXY_VERSION, true);
PluginExecution pluginExecution = new PluginExecution();
pluginExecution.addGoal("pom-gen");
pluginExecution.setPhase("process-resources");
pluginExecution.setId("proxy");
Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode();
Xpp3Dom artifactLocationNode = MavenUtils.createXpp3Node(configurationNode, "artifactLocation");
artifactLocationNode.setValue(".");
Xpp3Dom typeListNode = MavenUtils.createXpp3Node(configurationNode, "typeList");
typeListNode.setValue("${artifact.types}");
pluginExecution.setConfiguration(configurationNode);
plugin.addExecution(pluginExecution);
Repository repo = new Repository();
repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/");
repo.setId("wso2-nexus");
RepositoryPolicy releasePolicy=new RepositoryPolicy();
releasePolicy.setEnabled(true);
releasePolicy.setUpdatePolicy("daily");
releasePolicy.setChecksumPolicy("ignore");
repo.setReleases(releasePolicy);
if (!mavenProject.getRepositories().contains(repo)) {
mavenProject.getModel().addRepository(repo);
mavenProject.getModel().addPluginRepository(repo);
}
MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation);
}
public void copyImportFile(IContainer location,boolean isNewArtifact,String groupId) throws IOException {
File destFile = null;
List<OMElement> availablePSList = psModel.getSelectedProxyList();
String relativePath;
if(availablePSList.size()>0){
for(OMElement proxy:availablePSList){
String name = proxy.getAttributeValue(new QName("name"));
destFile = new File(location.getLocation().toFile(), name + ".xml");
FileUtils.createFile(destFile, proxy.toString());
fileLst.add(destFile);
if(isNewArtifact){
relativePath = FileUtils.getRelativePath(location.getProject().getLocation()
.toFile(), new File(location.getLocation().toFile(), name + ".xml"));
esbProjectArtifact.addESBArtifact(createArtifact(name,groupId,"1.0.0",relativePath) );
}
}
}
else{
File importFile = getModel().getImportFile();
String name = importFile.getName().replaceAll(".xml$","");
proxyServiceFile = location.getFile(new Path(importFile.getName()));
destFile = proxyServiceFile.getLocation().toFile();
FileUtils.copy(importFile, destFile);
fileLst.add(destFile);
if(isNewArtifact){
relativePath = FileUtils.getRelativePath(location.getProject().getLocation()
.toFile(), new File(location.getLocation().toFile(), name + ".xml"));
esbProjectArtifact.addESBArtifact(createArtifact(name,groupId,"1.0.0",relativePath) );
}
}
}
public IResource getCreatedResource() {
return proxyServiceFile;
}
public String createProxyTemplate(String templateContent, String type) throws IOException{
templateContent = templateContent.replaceAll("\\{", "<");
templateContent = templateContent.replaceAll("\\}", ">");
String newContent= StringUtils.replace(templateContent,"<proxy.name>", psModel.getProxyServiceName());
if(TargetEPType.REGISTRY==psModel.getTargetEPType()){
newContent = StringUtils.replace(newContent,"<endpoint.key.def>", " endpoint=\"" + psModel.getEndPointkey() + "\"");
newContent = StringUtils.replace(newContent,"<endpoint.def>","");
} else if(TargetEPType.PREDEFINED==psModel.getTargetEPType()){
newContent = StringUtils.replace(newContent,"<endpoint.key.def>", " endpoint=\"" + psModel.getPredefinedEndPoint() + "\"");
newContent = StringUtils.replace(newContent,"<endpoint.def>","");
} else{
String endPointDef = "<endpoint\n";
endPointDef +="\t\tname=\"endpoint_urn_uuid_";
endPointDef +=UUID.randomUUID().toString();
endPointDef +="\">\n\t\t<address uri=\"";
endPointDef += psModel.getEndPointUrl();
endPointDef +="\" />\n\t\t</endpoint>";
newContent = StringUtils.replace(newContent,"<endpoint.key.def>","");
newContent = StringUtils.replace(newContent,"<endpoint.def>",endPointDef);
}
if(type.equals(PsArtifactConstants.CUSTOM_PROXY)){
//TODO: add additional conf
}else if(type.equals(PsArtifactConstants.LOGGING_PROXY)){
newContent = StringUtils.replace(newContent,"<reqloglevel>", psModel.getRequestLogLevel());
newContent = StringUtils.replace(newContent,"<resloglevel>", psModel.getResponseLogLevel());
}else if(type.equals(PsArtifactConstants.PASS_THROUGH_PROXY)){
//TODO: add additional conf
}else if(type.equals(PsArtifactConstants.SECURE_PROXY)){
newContent = StringUtils.replace(newContent,"<sec.policy>", psModel.getSecPolicy());
}else if(type.equals(PsArtifactConstants.TRANSFORMER_PROXY)){
newContent = StringUtils.replace(newContent,"<xslt.key>", psModel.getRequestXSLT());
if(psModel.isTransformResponses() && !psModel.getResponseXSLT().equals("")) {
String responseXSLT = "<xslt key=\"";
responseXSLT += psModel.getResponseXSLT();
responseXSLT += "\" />";
newContent = StringUtils.replace(newContent, "<xsltres.key.def>", responseXSLT);
} else {
newContent = StringUtils.replace(newContent, "<xsltres.key.def>", "");
}
}else if(type.equals(PsArtifactConstants.WSDL_BASED_PROXY)){
newContent = StringUtils.replace(newContent,"<wsdl.service>", psModel.getWsdlService());
newContent = StringUtils.replace(newContent,"<wsdl.port>", psModel.getWsdlPort());
newContent = StringUtils.replace(newContent,"<wsdl.url>", psModel.getWsdlUri());
}
return newContent;
}
public void openEditor(File file){
try {
refreshDistProjects();
/* IFile dbsFile = ResourcesPlugin
.getWorkspace()
.getRoot()
.getFileForLocation(
Path.fromOSString(file.getAbsolutePath()));
IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),dbsFile);*/
String location = proxyServiceFile.getParent().getFullPath()+"/";
String source = FileUtils.getContentAsString(file);
Openable openable = ESBGraphicalEditor.getOpenable();
openable.editorOpen(file.getName(),"proxy",location+"proxy_", source);
} catch (Exception e) {
log.error("cannot open the Editor", e);
}
}
private ESBArtifact createArtifact(String name,String groupId,String version,String path){
ESBArtifact artifact=new ESBArtifact();
artifact.setName(name);
artifact.setVersion(version);
artifact.setType("synapse/proxy-service");
artifact.setServerRole("EnterpriseServiceBus");
artifact.setGroupId(groupId);
artifact.setFile(path);
return artifact;
}
}
| apache-2.0 |
facebook/buck | test/com/facebook/buck/android/AndroidBinaryBuilder.java | 8046 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.android;
import static com.facebook.buck.jvm.java.JavaCompilationConstants.DEFAULT_JAVAC_OPTIONS;
import static com.facebook.buck.jvm.java.JavaCompilationConstants.DEFAULT_JAVA_CONFIG;
import static com.facebook.buck.jvm.java.JavaCompilationConstants.DEFAULT_JAVA_OPTIONS;
import com.facebook.buck.android.AndroidBinaryDescription.AbstractAndroidBinaryDescriptionArg;
import com.facebook.buck.android.FilterResourcesSteps.ResourceFilter;
import com.facebook.buck.android.ResourcesFilter.ResourceCompressionMode;
import com.facebook.buck.android.aapt.RDotTxtEntry;
import com.facebook.buck.android.toolchain.AndroidPlatformTarget;
import com.facebook.buck.android.toolchain.DxToolchain;
import com.facebook.buck.android.toolchain.ndk.impl.TestNdkCxxPlatformsProviderFactory;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.config.FakeBuckConfig;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.targetgraph.AbstractNodeBuilder;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.core.toolchain.impl.ToolchainProviderBuilder;
import com.facebook.buck.cxx.toolchain.CxxPlatformUtils;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.jvm.java.JavaCompilationConstants;
import com.facebook.buck.jvm.java.toolchain.JavaOptionsProvider;
import com.facebook.buck.jvm.java.toolchain.JavaToolchain;
import com.facebook.buck.jvm.java.toolchain.JavacOptionsProvider;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public class AndroidBinaryBuilder
extends AbstractNodeBuilder<
AndroidBinaryDescriptionArg.Builder,
AndroidBinaryDescriptionArg,
AndroidBinaryDescription,
AndroidBinary> {
private AndroidBinaryBuilder(BuildTarget target) {
this(FakeBuckConfig.builder().build(), target);
}
private AndroidBinaryBuilder(BuckConfig buckConfig, BuildTarget target) {
super(
new AndroidBinaryDescription(
DEFAULT_JAVA_CONFIG,
new ProGuardConfig(buckConfig),
new AndroidBuckConfig(buckConfig, Platform.detect()),
buckConfig,
CxxPlatformUtils.DEFAULT_CONFIG,
new DxConfig(buckConfig),
createToolchainProviderForAndroidBinary(),
new AndroidBinaryGraphEnhancerFactory(),
new AndroidBinaryFactory(new AndroidBuckConfig(buckConfig, Platform.detect()))),
target,
new FakeProjectFilesystem(),
createToolchainProviderForAndroidBinary());
}
public static ToolchainProvider createToolchainProviderForAndroidBinary() {
return new ToolchainProviderBuilder()
.withToolchain(
AndroidPlatformTarget.DEFAULT_NAME, TestAndroidPlatformTargetFactory.create())
.withToolchain(TestNdkCxxPlatformsProviderFactory.createDefaultNdkPlatformsProvider())
.withToolchain(
DxToolchain.DEFAULT_NAME, DxToolchain.of(MoreExecutors.newDirectExecutorService()))
.withToolchain(
JavaOptionsProvider.DEFAULT_NAME,
JavaOptionsProvider.of(DEFAULT_JAVA_OPTIONS, DEFAULT_JAVA_OPTIONS))
.withToolchain(
JavacOptionsProvider.DEFAULT_NAME, JavacOptionsProvider.of(DEFAULT_JAVAC_OPTIONS))
.withToolchain(JavaToolchain.DEFAULT_NAME, JavaCompilationConstants.DEFAULT_JAVA_TOOLCHAIN)
.build();
}
public static AndroidBinaryBuilder createBuilder(BuildTarget buildTarget) {
return new AndroidBinaryBuilder(buildTarget);
}
public AndroidBinaryBuilder setManifest(SourcePath manifest) {
getArgForPopulating().setManifest(manifest);
return this;
}
public AndroidBinaryBuilder setOriginalDeps(ImmutableSortedSet<BuildTarget> originalDeps) {
getArgForPopulating().setDeps(originalDeps);
return this;
}
public AndroidBinaryBuilder setKeystore(BuildTarget keystore) {
getArgForPopulating().setKeystore(keystore);
getArgForPopulating().addDeps(keystore);
return this;
}
public AndroidBinaryBuilder setPackageType(String packageType) {
getArgForPopulating().setPackageType(Optional.of(packageType));
return this;
}
public AndroidBinaryBuilder setShouldSplitDex(boolean shouldSplitDex) {
getArgForPopulating().setUseSplitDex(shouldSplitDex);
return this;
}
public AndroidBinaryBuilder setDexCompression(DexStore dexStore) {
getArgForPopulating().setDexCompression(Optional.of(dexStore));
return this;
}
public AndroidBinaryBuilder setLinearAllocHardLimit(long limit) {
getArgForPopulating().setLinearAllocHardLimit(limit);
return this;
}
public AndroidBinaryBuilder setPrimaryDexScenarioOverflowAllowed(boolean allowed) {
getArgForPopulating().setPrimaryDexScenarioOverflowAllowed(allowed);
return this;
}
public AndroidBinaryBuilder setBuildTargetsToExcludeFromDex(
Set<BuildTarget> buildTargetsToExcludeFromDex) {
getArgForPopulating().setNoDx(buildTargetsToExcludeFromDex);
return this;
}
public AndroidBinaryBuilder setResourceCompressionMode(
ResourceCompressionMode resourceCompressionMode) {
getArgForPopulating().setResourceCompression(resourceCompressionMode);
return this;
}
public AndroidBinaryBuilder setResourceFilter(ResourceFilter resourceFilter) {
List<String> rawFilters = ImmutableList.copyOf(resourceFilter.getFilter());
getArgForPopulating().setResourceFilter(rawFilters);
return this;
}
public AndroidBinaryBuilder setIntraDexReorderResources(
boolean enableReorder, SourcePath reorderTool, SourcePath reorderData) {
getArgForPopulating().setReorderClassesIntraDex(enableReorder);
getArgForPopulating().setDexReorderToolFile(Optional.of(reorderTool));
getArgForPopulating().setDexReorderDataDumpFile(Optional.of(reorderData));
return this;
}
public AndroidBinaryBuilder setNoDx(Set<BuildTarget> noDx) {
getArgForPopulating().setNoDx(noDx);
return this;
}
public AndroidBinaryBuilder setDuplicateResourceBehavior(
AbstractAndroidBinaryDescriptionArg.DuplicateResourceBehaviour value) {
getArgForPopulating().setDuplicateResourceBehavior(value);
return this;
}
public AndroidBinaryBuilder setBannedDuplicateResourceTypes(Set<RDotTxtEntry.RType> value) {
getArgForPopulating().setBannedDuplicateResourceTypes(value);
return this;
}
public AndroidBinaryBuilder setAllowedDuplicateResourceTypes(Set<RDotTxtEntry.RType> value) {
getArgForPopulating().setAllowedDuplicateResourceTypes(value);
return this;
}
public AndroidBinaryBuilder setPostFilterResourcesCmd(Optional<StringWithMacros> command) {
getArgForPopulating().setPostFilterResourcesCmd(command);
return this;
}
public AndroidBinaryBuilder setPreprocessJavaClassesBash(StringWithMacros command) {
getArgForPopulating().setPreprocessJavaClassesBash(command);
return this;
}
public AndroidBinaryBuilder setProguardConfig(SourcePath path) {
getArgForPopulating().setProguardConfig(path);
return this;
}
}
| apache-2.0 |
idea4bsd/idea4bsd | plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/UnnecessaryFinalOnLocalVariableOrParameterInspectionTest.java | 1221 | /*
* Copyright 2000-2012 JetBrains s.r.o.
*
* 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.siyeh.ig.style;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.testFramework.IdeaTestUtil;
import com.siyeh.ig.IGInspectionTestCase;
public class UnnecessaryFinalOnLocalVariableOrParameterInspectionTest extends IGInspectionTestCase {
@Override
protected Sdk getTestProjectSdk() {
// effectively final rules are different in jdk 8
return IdeaTestUtil.getMockJdk17();
}
public void test() throws Exception {
doTest("com/siyeh/igtest/style/unnecessary_final_on_local_variable_or_parameter",
new UnnecessaryFinalOnLocalVariableOrParameterInspection());
}
}
| apache-2.0 |
xmhubj/selenium | java/client/src/org/openqa/selenium/logging/LoggingPreferences.java | 3110 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.logging;
import org.openqa.selenium.Beta;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
/**
* Represents the logging preferences.
*
* Sample usage:
* DesiredCapabilities caps = DesiredCapabilities.firefox();
* LoggingPreferences logs = new LoggingPreferences();
* logs.enable(LogType.DRIVER, Level.INFO);
* caps.setCapability(CapabilityType.LOGGING_PREFS, logs);
*
* WebDriver driver = new FirefoxDriver(caps);
*/
public class LoggingPreferences implements Serializable {
private static final long serialVersionUID = 6708028456766320675L;
// Mapping the {@link LogType} to {@link Level}
private final Map<String, Level> prefs = new HashMap<>();
/**
* Enables logging for the given log type at the specified level and above.
* @param logType String the logType. Can be any of {@link LogType}.
* @param level {@link Level} the level.
*/
public void enable(String logType, Level level) {
prefs.put(logType, level);
}
/**
* @return the set of log types for which logging has been enabled.
*/
public Set<String> getEnabledLogTypes() {
return new HashSet<>(prefs.keySet());
}
/**
* @param logType The log type.
* @return the {@link Level} for the given {@link LogType} if enabled.
* Otherwise returns {@link Level#OFF}.
*/
public Level getLevel(String logType) {
return prefs.get(logType) == null ? Level.OFF : prefs.get(logType);
}
/**
* Adds the given logging preferences giving them precedence over existing
* preferences.
*
* @param prefs The logging preferences to add.
* @return A references to this object.
*/
public LoggingPreferences addPreferences(LoggingPreferences prefs) {
if (prefs == null) {
return this;
}
for (String logType : prefs.getEnabledLogTypes()) {
enable(logType, prefs.getLevel(logType));
}
return this;
}
@Beta
public Map<String, Object> toJson() {
TreeMap<String, Object> converted = new TreeMap<>();
for (String logType : getEnabledLogTypes()) {
converted.put(logType, LogLevelMapping.getName(getLevel(logType)));
}
return converted;
}
}
| apache-2.0 |
troyel/dhis2-core | dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/program/message/DefaultProgramMessageService.java | 12366 | package org.hisp.dhis.program.message;
/*
* Copyright (c) 2004-2017, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.DeliveryChannel;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.IllegalQueryException;
import org.hisp.dhis.organisationunit.OrganisationUnitService;
import org.hisp.dhis.outboundmessage.BatchResponseStatus;
import org.hisp.dhis.outboundmessage.OutboundMessageBatch;
import org.hisp.dhis.outboundmessage.OutboundMessageBatchService;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramInstance;
import org.hisp.dhis.program.ProgramInstanceService;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.program.ProgramStageInstanceService;
import org.hisp.dhis.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author Zubair <rajazubair.asghar@gmail.com>
*/
@Transactional
public class DefaultProgramMessageService
implements ProgramMessageService
{
private static final Log log = LogFactory.getLog( DefaultProgramMessageService.class );
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
@Autowired
protected IdentifiableObjectManager manager;
@Autowired
private ProgramMessageStore programMessageStore;
@Autowired
private OrganisationUnitService organisationUnitService;
@Autowired
private TrackedEntityInstanceService trackedEntityInstanceService;
@Autowired
private ProgramInstanceService programInstanceService;
@Autowired
private ProgramService programService;
@Autowired
private ProgramStageInstanceService programStageInstanceService;
@Autowired
private OutboundMessageBatchService messageBatchService;
@Autowired
private CurrentUserService currentUserService;
@Autowired
private List<DeliveryChannelStrategy> strategies;
@Autowired
private List<MessageBatchCreatorService> batchCreators;
// -------------------------------------------------------------------------
// Implementation methods
// -------------------------------------------------------------------------
@Override
public ProgramMessageQueryParams getFromUrl( Set<String> ou, String piUid, String psiUid,
ProgramMessageStatus messageStatus, Integer page, Integer pageSize, Date afterDate, Date beforeDate )
{
ProgramMessageQueryParams params = new ProgramMessageQueryParams();
if ( piUid != null )
{
if ( manager.exists( ProgramInstance.class, piUid ) )
{
params.setProgramInstance( manager.get( ProgramInstance.class, piUid ) );
}
else
{
throw new IllegalQueryException( "ProgramInstance does not exist." );
}
}
if ( psiUid != null )
{
if ( manager.exists( ProgramStageInstance.class, psiUid ) )
{
params.setProgramStageInstance( manager.get( ProgramStageInstance.class, psiUid ) );
}
else
{
throw new IllegalQueryException( "ProgramStageInstance does not exist." );
}
}
params.setOrganisationUnit( ou );
params.setMessageStatus( messageStatus );
params.setPage( page );
params.setPageSize( pageSize );
params.setAfterDate( afterDate );
params.setBeforeDate( beforeDate );
return params;
}
@Override
public boolean exists( String uid )
{
return programMessageStore.exists( uid );
}
@Override
public ProgramMessage getProgramMessage( int id )
{
return programMessageStore.get( id );
}
@Override
public ProgramMessage getProgramMessage( String uid )
{
return programMessageStore.getByUid( uid );
}
@Override
public List<ProgramMessage> getAllProgramMessages()
{
return programMessageStore.getAll();
}
@Override
public List<ProgramMessage> getProgramMessages( ProgramMessageQueryParams params )
{
hasAccess( params, currentUserService.getCurrentUser() );
validateQueryParameters( params );
return programMessageStore.getProgramMessages( params );
}
@Override
public int saveProgramMessage( ProgramMessage programMessage )
{
programMessageStore.save( programMessage );
return programMessage.getId();
}
@Override
public void updateProgramMessage( ProgramMessage programMessage )
{
programMessageStore.update( programMessage );
}
@Override
public void deleteProgramMessage( ProgramMessage programMessage )
{
programMessageStore.delete( programMessage );
}
@Override
public BatchResponseStatus sendMessages( List<ProgramMessage> programMessages )
{
List<ProgramMessage> populatedProgramMessages = programMessages.stream()
.map( this::setAttributesBasedOnStrategy )
.collect( Collectors.toList() );
List<OutboundMessageBatch> batches = createBatches( populatedProgramMessages );
BatchResponseStatus status = new BatchResponseStatus( messageBatchService.sendBatches( batches ) );
saveProgramMessages( programMessages, status );
return status;
}
@Override
public void hasAccess( ProgramMessageQueryParams params, User user )
{
ProgramInstance programInstance = null;
Set<Program> programs = new HashSet<>();
if ( params.hasProgramInstance() )
{
programInstance = params.getProgramInstance();
}
if ( params.hasProgramStageInstance() )
{
programInstance = params.getProgramStageInstance().getProgramInstance();
}
programs = programService.getUserPrograms( user );
if ( user != null && !programs.contains( programInstance.getProgram() ) )
{
throw new IllegalQueryException( "User does not have access to the required program" );
}
}
@Override
public void validateQueryParameters( ProgramMessageQueryParams params )
{
String violation = null;
if ( !params.hasProgramInstance() && !params.hasProgramStageInstance() )
{
violation = "Program instance or program stage instance must be provided";
}
if ( violation != null )
{
log.warn( "Parameter validation failed: " + violation );
throw new IllegalQueryException( violation );
}
}
@Override
public void validatePayload( ProgramMessage message )
{
String violation = null;
ProgramMessageRecipients recipients = message.getRecipients();
if ( message.getText() == null )
{
violation = "Message content must be provided";
}
if ( message.getDeliveryChannels() == null || message.getDeliveryChannels().isEmpty() )
{
violation = "Delivery channel must be specified";
}
if ( message.getProgramInstance() == null && message.getProgramStageInstance() == null )
{
violation = "Program instance or program stage instance must be specified";
}
if ( recipients.getTrackedEntityInstance() != null && trackedEntityInstanceService
.getTrackedEntityInstance( recipients.getTrackedEntityInstance().getUid() ) == null )
{
violation = "Tracked entity does not exist";
}
if ( recipients.getOrganisationUnit() != null
&& organisationUnitService.getOrganisationUnit( recipients.getOrganisationUnit().getUid() ) == null )
{
violation = "Organisation unit does not exist";
}
if ( violation != null )
{
log.info( "Message validation failed: " + violation );
throw new IllegalQueryException( violation );
}
}
// ---------------------------------------------------------------------
// Supportive Methods
// ---------------------------------------------------------------------
private void saveProgramMessages( List<ProgramMessage> messageBatch, BatchResponseStatus status )
{
messageBatch.parallelStream()
.filter( pm -> pm.isStoreCopy() )
.map( pm -> setParameters( pm, status ) )
.map( pm -> saveProgramMessage( pm ) );
}
private ProgramMessage setParameters( ProgramMessage message, BatchResponseStatus status )
{
message.setProgramInstance( getProgramInstance( message ) );
message.setProgramStageInstance( getProgramStageInstance( message ) );
message.setProcessedDate( new Date() );
message.setMessageStatus( status.isOk() ? ProgramMessageStatus.SENT : ProgramMessageStatus.FAILED );
return message;
}
private List<OutboundMessageBatch> createBatches( List<ProgramMessage> programMessages )
{
return batchCreators.stream()
.map( bc -> bc.getMessageBatch( programMessages ) )
.filter( bc -> !bc.getMessages().isEmpty() )
.collect( Collectors.toList() );
}
private ProgramInstance getProgramInstance( ProgramMessage programMessage )
{
if ( programMessage.getProgramInstance() != null )
{
return programInstanceService.getProgramInstance( programMessage.getProgramInstance().getUid() );
}
return null;
}
private ProgramStageInstance getProgramStageInstance( ProgramMessage programMessage )
{
if ( programMessage.getProgramStageInstance() != null )
{
return programStageInstanceService
.getProgramStageInstance( programMessage.getProgramStageInstance().getUid() );
}
return null;
}
private ProgramMessage setAttributesBasedOnStrategy( ProgramMessage message )
{
Set<DeliveryChannel> channels = message.getDeliveryChannels();
for ( DeliveryChannel channel : channels )
{
strategies.stream()
.filter( st -> st.getDeliveryChannel().equals( channel ) )
.map( st -> st.setAttributes( message ) );
}
return message;
}
} | bsd-3-clause |
jsachs/infer | infer/tests/build_systems/differential_skip_anonymous_class_renamings/src/SimpleInterfaceExample.java | 449 | /*
* Copyright (c) 2017 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
// This example tests the skip_anonymous_class_renamings filter
public interface SimpleInterfaceExample {
public String getString();
}
| bsd-3-clause |
jmxtrans/embedded-jmxtrans | src/test/java/org/jmxtrans/embedded/spring/EmbeddedJmxTransBeanDefinitionParser1Test.java | 2216 | /*
* Copyright (c) 2010-2013 the original author or authors
*
* 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.jmxtrans.embedded.spring;
import org.jmxtrans.embedded.EmbeddedJmxTrans;
import org.jmxtrans.embedded.Query;
import org.jmxtrans.embedded.TestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
/**
* @author <a href="mailto:cleclerc@xebia.fr">Cyrille Le Clerc</a>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "test-spring-configuration-1.xml")
public class EmbeddedJmxTransBeanDefinitionParser1Test {
@Autowired
EmbeddedJmxTrans embeddedJmxTrans;
@Test
public void test() {
Map<String, Query> queries = TestUtils.indexQueriesByAliasOrName(embeddedJmxTrans.getQueries());
Query tomcatProcessorQuery = queries.get("tomcat.global-request-processor.http-nio");
assertNotNull(tomcatProcessorQuery);
}
}
| mit |
conveyal/gtfs-editor | app/jobs/ProcessGisUpload.java | 11306 | package jobs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.geotools.data.FeatureSource;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.collection.FilteringSimpleFeatureCollection;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.onebusaway.gtfs.impl.GtfsDaoImpl;
import org.onebusaway.gtfs.serialization.GtfsReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.FeatureType;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.geotools.data.FileDataStoreFinder;
import com.mchange.v2.c3p0.impl.DbAuth;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.operation.linemerge.LineMerger;
import models.transit.Agency;
import models.transit.Route;
import models.transit.ServiceCalendar;
import models.transit.Stop;
import models.transit.StopTime;
import models.transit.Trip;
import play.Logger;
import play.Play;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
import utils.FeatureAttributeFormatter;
public class ProcessGisUpload extends Job {
/*
private Long _gisUploadId;
public ProcessGisUpload(Long gisUploadId)
{
this._gisUploadId = gisUploadId;
}
public void doJob() {
String uploadName = "gis_" + this._gisUploadId;
File uploadedFile = new File(Play.configuration.getProperty("application.publicGisDataDirectory"), uploadName + ".zip");
File outputPath = new File(Play.configuration.getProperty("application.publicGisDataDirectory"), uploadName);
try
{
GisUpload gisUpload = null;
while(gisUpload == null)
{
gisUpload = GisUpload.findById(this._gisUploadId);
Thread.sleep(1000);
Logger.info("Waiting for gisUpload object...");
}
File shapeFile = null;
// unpack the zip if needed
if(!outputPath.exists())
{
outputPath.mkdir();
FileInputStream fileInputStream = new FileInputStream(uploadedFile);
ZipInputStream zipInput = new ZipInputStream(fileInputStream);
ZipEntry zipEntry = null;
while ((zipEntry = zipInput.getNextEntry()) != null)
{
if(zipEntry.isDirectory())
{
Logger.info("Unexpected directory: ", zipEntry.getName());
}
else
{
Logger.info("Unzipping", zipEntry.getName());
File entryFile = new File(outputPath, zipEntry.getName());
FileOutputStream unzippedFileOut = new FileOutputStream(entryFile);
int length;
byte[] buffer = new byte[1000];
while ((length = zipInput.read(buffer))>0)
{
unzippedFileOut.write(buffer, 0, length);
}
zipInput.closeEntry();
unzippedFileOut.close();
}
}
zipInput.close();
}
// find the shapefile
for(File dirFile : outputPath.listFiles())
{
if(FilenameUtils.getExtension(dirFile.getName()).toLowerCase().equals("shp"))
{
if(shapeFile == null)
shapeFile = dirFile;
else
Logger.warn("Zip contains more than one shapefile--ignoring others.");
}
}
// (re)load the shapefile data
if(shapeFile != null)
{
// remove existing imports
if(gisUpload.type == GisUploadType.ROUTES)
{
List<GisRoute> routes = GisRoute.find("gisUpload = ?", gisUpload).fetch();
for(GisRoute route : routes)
{
route.clear();
route.delete();
}
}
else if(gisUpload.type == GisUploadType.STOPS)
GisStop.delete("gisUpload = ?", gisUpload);
// remove existing updload field mappings
GisUploadField.delete("gisUpload = ?", gisUpload);
FileDataStore store = FileDataStoreFinder.getDataStore(shapeFile);
SimpleFeatureSource featureSource = store.getFeatureSource();
SimpleFeatureCollection featureCollection = featureSource.getFeatures();
SimpleFeatureIterator featureIterator = featureCollection.features();
List<AttributeDescriptor> attributeDescriptors = featureSource.getSchema().getAttributeDescriptors();
// update field listing
Long position = new Long(0);
for(AttributeDescriptor attribute : attributeDescriptors)
{
GisUploadField field = new GisUploadField();
field.fieldName = attribute.getName().toString();
field.fieldType = attribute.getType().getName().getLocalPart();
field.fieldPosition = position;
field.gisUpload = gisUpload;
field.save();
position++;
}
CoordinateReferenceSystem dataCRS = featureSource.getSchema().getCoordinateReferenceSystem();
String code = "EPSG:4326";
CRSAuthorityFactory crsAuthorityFactory = CRS.getAuthorityFactory(true);
CoordinateReferenceSystem mapCRS = crsAuthorityFactory.createCoordinateReferenceSystem(code);
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform(dataCRS, mapCRS, lenient);
while (featureIterator.hasNext())
{
SimpleFeature feature = featureIterator.next();
GeometryType geomType = feature.getFeatureType().getGeometryDescriptor().getType();
// handle appropriate shape/upload type
if(gisUpload.type == GisUploadType.ROUTES)
{
if(geomType.getBinding() != MultiLineString.class)
{
Logger.error("Unexpected geometry type: ", geomType);
continue;
}
MultiLineString multiLineString = (MultiLineString)JTS.transform((Geometry)feature.getDefaultGeometry(), transform);
GisRoute route = new GisRoute();
route.gisUpload = gisUpload;
route.agency = gisUpload.agency;
route.oid = feature.getID();
route.originalShape = multiLineString;
route.originalShape.setSRID(4326);
if(gisUpload.fieldName != null)
{
FeatureAttributeFormatter attribFormatter = new FeatureAttributeFormatter(gisUpload.fieldName);
route.routeName = attribFormatter.format(feature);
}
if(gisUpload.fieldId != null)
{
FeatureAttributeFormatter attribFormatter = new FeatureAttributeFormatter(gisUpload.fieldId);
route.routeId = attribFormatter.format(feature);
}
if(gisUpload.fieldDescription != null)
{
FeatureAttributeFormatter attribFormatter = new FeatureAttributeFormatter(gisUpload.fieldDescription);
route.description = attribFormatter.format(feature);
}
route.save();
route.processSegments();
}
else if(gisUpload.type == GisUploadType.STOPS)
{
if(geomType.getBinding() != Point.class)
{
Logger.error("Unexpected geometry type: ", geomType);
continue;
}
GisStop stop = new GisStop();
stop.gisUpload = gisUpload;
stop.agency = gisUpload.agency;
stop.oid = feature.getID();
stop.shape = (Point)JTS.transform((Geometry)feature.getDefaultGeometry(), transform);
stop.shape.setSRID(4326);
if(gisUpload.fieldName != null)
{
FeatureAttributeFormatter attribFormatter = new FeatureAttributeFormatter(gisUpload.fieldName);
stop.stopName = attribFormatter.format(feature);
}
if(gisUpload.fieldId != null)
{
FeatureAttributeFormatter attribFormatter = new FeatureAttributeFormatter(gisUpload.fieldId);
stop.stopId = attribFormatter.format(feature);
}
if(gisUpload.fieldDescription != null)
{
FeatureAttributeFormatter attribFormatter = new FeatureAttributeFormatter(gisUpload.fieldDescription);
stop.description = attribFormatter.format(feature);
}
stop.save();
}
}
}
else
{
Logger.error("Zip didn't contain a valid shapefile.");
}
}
catch(Exception e)
{
Logger.error("Unable to process GIS Upload: ", e.toString());
e.printStackTrace();
}
}
*/
}
| mit |
amkimian/Rapture | Libs/RaptureWebServlet/src/main/java/rapture/server/web/servlet/WidgetServlet.java | 2324 | /**
* The MIT License (MIT)
*
* Copyright (c) 2011-2016 Incapture Technologies LLC
*
* 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 rapture.server.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import rapture.common.DispatchReturn;
import rapture.common.shared.widget.DispatchWidgetFunction;
@WebServlet("/widget")
@MultipartConfig
public class WidgetServlet extends BaseServlet {
private static final long serialVersionUID = -42L;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
StandardCallInfo call = processFunctionalRequest(req);
DispatchWidgetFunction widgetDispatch = DispatchWidgetFunction.valueOf(call.getFunctionName());
DispatchReturn response;
try {
response = widgetDispatch.executeDispatch(call.getContent(), req, resp);
} catch (Exception e) {
response = handleUnexpectedException(e);
}
sendResponseAppropriately(response.getContext(), req, resp, response.getResponse());
}
}
| mit |
OneMoreCheckin/mobile-app | phonegap/2.6.0/blackberry/framework/ext/src/org/apache/cordova/capture/AudioCaptureListener.java | 2845 | /*
* 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.cordova.capture;
import net.rim.device.api.io.file.FileSystemJournal;
import net.rim.device.api.io.file.FileSystemJournalEntry;
import net.rim.device.api.io.file.FileSystemJournalListener;
/**
* Listens for audio recording files that are added to file system.
* <p>
* Audio recordings are added to the file system when the user stops the
* recording. The audio recording file extension is '.amr'. Therefore, we listen
* for the <code>FileSystemJournalEntry.FILE_ADDED</code> event, capturing when
* the new file is written.
* <p>
* The file system notifications will arrive on the application event thread.
* When it receives a notification, it adds the image file path to a MediaQueue
* so that the capture thread can process the file.
*/
public class AudioCaptureListener implements FileSystemJournalListener {
/**
* Used to track file system changes.
*/
private long lastUSN = 0;
/**
* Queue to send media files to for processing.
*/
private MediaQueue queue = null;
/**
* Constructor.
*/
AudioCaptureListener(MediaQueue queue) {
this.queue = queue;
}
public void fileJournalChanged() {
// next sequence number file system will use
long USN = FileSystemJournal.getNextUSN();
for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
if (entry == null) {
break;
}
// has audio recording file has been added to the file system?
String path = entry.getPath();
if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED
&& path.endsWith(".amr")) {
// add file path to the capture queue
queue.add("file://" + path);
break;
}
}
// remember the file journal change number,
// so we don't search the same events again and again
lastUSN = USN;
}
}
| mit |
v5developer/maven-framework-project | spring-jdbc-tutorials/src/main/java/org/spring/jdbc/tutorials/CustomerMappingSqlQuery.java | 879 | package org.spring.jdbc.tutorials;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.DataSource;
import org.spring.jdbc.tutorials.model.Customer;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.MappingSqlQuery;
public class CustomerMappingSqlQuery extends MappingSqlQuery<Customer> {
public CustomerMappingSqlQuery(DataSource dataSource) {
super(dataSource, "select CUST_ID, NAME, AGE from customer where CUST_ID = ?");
super.declareParameter(new SqlParameter("id", Types.INTEGER));
compile();
}
@Override
protected Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setCustId(rs.getInt("CUST_ID"));
customer.setName(rs.getString("NAME"));
customer.setAge(rs.getInt("AGE"));
return customer;
}
}
| mit |
cardinalblue/braintree_android | BraintreeApi/src/main/java/com/braintreepayments/api/exceptions/UnexpectedException.java | 434 | package com.braintreepayments.api.exceptions;
/**
* Thrown when an unrecognized error occurs while communicating with the Braintree gateway.
* This may represent an {@link java.io.IOException} or an unexpected HTTP response.
*/
public class UnexpectedException extends BraintreeException {
public UnexpectedException(String message) {
super(message);
}
public UnexpectedException() {
super();
}
}
| mit |
fracta/ift6561_simulation_stochastique | homeworks/homework_2/src/homework_2/AsianDelta.java | 2493 | package homework_2;
import umontreal.iro.lecuyer.stat.Tally;
import umontreal.iro.lecuyer.rng.RandomStream;
public class AsianDelta {
// f'(x) = f(x + d) - f(x) / d as d -> 0
Asian process1; // f(x)
Asian process2; // f(x + d)
double delta;
/**
* Computes the forward finite difference of the delta parameter (greeks) of
* the Asian option.
*
* @param shortRate
* compound rate of bank account
* @param volatility
* of the Standard Brownian Motion
* @param strikePrice
* K, price agreed upon to buy the asset at time T
* @param initialPrice
* initial price of the asset
* @param T
* number of observation times
* @param observationTimes
* vector of observation times
* @param delta
* delta on the initial price
*/
public AsianDelta(double shortRate, double volatility, double strikePrice,
double initialPrice, int T, double[] observationTimes, double delta) {
assert delta >= 0;
this.delta = delta;
this.process1 = new Asian(shortRate, volatility, strikePrice,
initialPrice, T, observationTimes);
this.process2 = new Asian(shortRate, volatility, strikePrice,
initialPrice + delta, T, observationTimes);
}
/**
* Simulates the system(s0) and the system(s0 + delta) to get difference
* f(x+d) - f(x), using common random numbers
*
* @param n
* number of runs
* @param collector
* statistical collector
* @param prng
* pseudo-random number generator
*/
public void simulateDiffCRN(int n, Tally collector, RandomStream prng) {
collector.init();
prng.resetNextSubstream();
double observations1[] = this.process1.simulateRuns(n, prng);
double observations2[] = this.process2.simulateRuns(n, prng);
for (int i = 0; i < n; i++) {
collector.add(((observations2[i] - observations1[i])/ this.delta));
}
}
/**
* Simulates the system(s0) and the system(s0 + delta) to get difference
* f(x+d) - f(x), not using common random numbers
*
* @param n
* number of runs
* @param collector
* statistical collector
* @param prng
* pseudo-random number generator
*/
public void simulateDiffIRN(int n, Tally collector, RandomStream prng) {
collector.init();
prng.resetNextSubstream();
for(int i = 0; i < n; i++)
{
collector.add(((this.process2.simulateOneRun(prng) - this.process1.simulateOneRun(prng))/this.delta));
}
}
}
| cc0-1.0 |
RallySoftware/eclipselink.runtime | jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/AbstractSelectStatement.java | 14840 | /*******************************************************************************
* Copyright (c) 2006, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation
*
******************************************************************************/
package org.eclipse.persistence.jpa.jpql.parser;
import java.util.Collection;
import java.util.List;
import org.eclipse.persistence.jpa.jpql.WordParser;
/**
* A query is an operation that retrieves data from one or more tables or views. In this reference,
* a top-level <code><b>SELECT</b></code> statement is called a query, and a query nested within
* another SQL statement is called a subquery.
*
* @see SelectStatement
* @see SimpleSelectStatement
*
* @version 2.5
* @since 2.3
* @author Pascal Filion
*/
public abstract class AbstractSelectStatement extends AbstractExpression {
/**
* The <code><b>FROM</b></code> clause of this select statement.
*/
private AbstractExpression fromClause;
/**
* The <code><b>GROUP BY</b></code> clause of this select statement.
*/
private AbstractExpression groupByClause;
/**
* Determines whether there is a whitespace after the identifier <code><b>FROM</b></code>.
*/
private boolean hasSpaceAfterFrom;
/**
* Determines whether there is a whitespace after the identifier <code><b>GROUP BY</b></code>.
*/
private boolean hasSpaceAfterGroupBy;
/**
* Determines whether there is a whitespace after the identifier <code><b>SELECT</b></code>.
*/
private boolean hasSpaceAfterSelect;
/**
* Determines whether there is a whitespace after the identifier <code><b>WHERE</b></code>.
*/
private boolean hasSpaceAfterWhere;
/**
* The <code><b>HAVING</b></code> clause of this select statement.
*/
private AbstractExpression havingClause;
/**
* The <code><b>SELECT</b></code> clause of this select statement.
*/
private AbstractExpression selectClause;
/**
* The <code><b>WHERE</b></code> clause of this select statement.
*/
private AbstractExpression whereClause;
/**
* Creates a new <code>AbstractSelectStatement</code>.
*
* @param parent The parent of this expression
*/
protected AbstractSelectStatement(AbstractExpression parent) {
super(parent);
}
/**
* {@inheritDoc}
*/
public void acceptChildren(ExpressionVisitor visitor) {
getSelectClause().accept(visitor);
getFromClause().accept(visitor);
getWhereClause().accept(visitor);
getGroupByClause().accept(visitor);
getHavingClause().accept(visitor);
}
/**
* {@inheritDoc}
*/
@Override
protected void addChildrenTo(Collection<Expression> children) {
children.add(getSelectClause());
children.add(getFromClause());
children.add(getWhereClause());
children.add(getGroupByClause());
children.add(getHavingClause());
}
/**
* {@inheritDoc}
*/
@Override
protected void addOrderedChildrenTo(List<Expression> children) {
// SELECT clause
if (selectClause != null) {
children.add(selectClause);
}
// Space between SELECT and FROM clauses
if (hasSpaceAfterSelect) {
children.add(buildStringExpression(SPACE));
}
// FROM clause
if (fromClause != null) {
children.add(fromClause);
}
// Space between the FROM clause and an optional clause
if (hasSpaceAfterFrom) {
children.add(buildStringExpression(SPACE));
}
// WHERE clause
if (whereClause != null) {
children.add(whereClause);
}
// Space between WHERE clause and another optional clause
if (hasSpaceAfterWhere) {
children.add(buildStringExpression(SPACE));
}
// GROUP BY clause
if (groupByClause != null) {
children.add(groupByClause);
}
// Space between GROUP BY clause and another optional clause
if (hasSpaceAfterGroupBy) {
children.add(buildStringExpression(SPACE));
}
// HAVING clause
if (havingClause != null) {
children.add(havingClause);
}
}
/**
* Creates the expression representing the from clause of this select statement.
*
* @return A new from clause, <code>null</code> can't be returned
*/
protected abstract AbstractFromClause buildFromClause();
/**
* Creates the expression representing the select clause of this select statement.
*
* @return A new from clause, <code>null</code> can't be returned
*/
protected abstract AbstractSelectClause buildSelectClause();
/**
* {@inheritDoc}
*/
@Override
public JPQLQueryBNF findQueryBNF(Expression expression) {
if ((selectClause != null) && selectClause.isAncestor(expression)) {
return selectClause.getQueryBNF();
}
if ((fromClause != null) && fromClause.isAncestor(expression)) {
return fromClause.getQueryBNF();
}
if ((whereClause != null) && whereClause.isAncestor(expression)) {
return whereClause.getQueryBNF();
}
if ((groupByClause != null) && groupByClause.isAncestor(expression)) {
return groupByClause.getQueryBNF();
}
if ((havingClause != null) && havingClause.isAncestor(expression)) {
return havingClause.getQueryBNF();
}
return super.findQueryBNF(expression);
}
/**
* Returns the {@link Expression} representing the <b>FROM</b> clause.
*
* @return The expression representing the <b>FROM</b> clause
*/
public final Expression getFromClause() {
if (fromClause == null) {
fromClause = buildNullExpression();
}
return fromClause;
}
/**
* Returns the {@link Expression} representing the <b>GROUP BY</b> clause.
*
* @return The expression representing the <b>GROUP BY</b> clause
*/
public final Expression getGroupByClause() {
if (groupByClause == null) {
groupByClause = buildNullExpression();
}
return groupByClause;
}
/**
* Returns the {@link Expression} representing the <b>HAVING</b> clause.
*
* @return The expression representing the <b>HAVING</b> clause
*/
public final Expression getHavingClause() {
if (havingClause == null) {
havingClause = buildNullExpression();
}
return havingClause;
}
/**
* Returns the {@link AbstractSelectClause} representing the <b>SELECT</b> clause.
*
* @return The expression representing the <b>SELECT</b> clause
*/
public final Expression getSelectClause() {
if (selectClause == null) {
selectClause = buildNullExpression();
}
return selectClause;
}
/**
* Returns the {@link Expression} representing the <b>WHERE</b> clause.
*
* @return The expression representing the <b>WHERE</b> clause
*/
public final Expression getWhereClause() {
if (whereClause == null) {
whereClause = buildNullExpression();
}
return whereClause;
}
/**
* Determines whether the <b>FROM</b> clause was parsed or not.
*
* @return <code>true</code> if the query that got parsed had the <b>FROM</b> clause
*/
public final boolean hasFromClause() {
return fromClause != null &&
!fromClause.isNull();
}
/**
* Determines whether the <b>GROUP BY</b> clause was parsed or not.
*
* @return <code>true</code> if the query that got parsed had the <b>GROUP BY</b> clause
*/
public final boolean hasGroupByClause() {
return groupByClause != null &&
!groupByClause.isNull();
}
/**
* Determines whether the <b>HAVING</b> clause was parsed or not.
*
* @return <code>true</code> if the query that got parsed had the <b>HAVING</b> clause
*/
public final boolean hasHavingClause() {
return havingClause != null &&
!havingClause.isNull();
}
/**
* Determines whether the <b>SELECT</b> clause was parsed or not.
*
* @return <code>true</code> if the query that got parsed had the <b>HAVING</b> clause
* @since 2.5
*/
public final boolean hasSelectClause() {
return selectClause != null &&
!selectClause.isNull();
}
/**
* Determines whether a whitespace was found after the <b>FROM</b> clause. In some cases, the
* space is owned by a child of the <b>FROM</b> clause.
*
* @return <code>true</code> if there was a whitespace after the <b>FROM</b> clause and owned by
* this expression; <code>false</code> otherwise
*/
public final boolean hasSpaceAfterFrom() {
return hasSpaceAfterFrom;
}
/**
* Determines whether a whitespace was found after the <b>GROUP BY</b> clause. In some cases, the
* space is owned by a child of the <b>GROUP BY</b> clause.
*
* @return <code>true</code> if there was a whitespace after the <b>GROUP BY</b> clause and owned
* by this expression; <code>false</code> otherwise
*/
public final boolean hasSpaceAfterGroupBy() {
return hasSpaceAfterGroupBy;
}
/**
* Determines whether a whitespace was found after the <b>SELECT</b> clause. In some cases, the
* space is owned by a child of the <b>SELECT</b> clause.
*
* @return <code>true</code> if there was a whitespace after the <b>SELECT</b> clause and owned
* by this expression; <code>false</code> otherwise
*/
public final boolean hasSpaceAfterSelect() {
return hasSpaceAfterSelect;
}
/**
* Determines whether a whitespace was found after the <b>WHERE</b> clause. In some cases, the
* space is owned by a child of the <b>WHERE</b> clause.
*
* @return <code>true</code> if there was a whitespace after the <b>WHERE</b> clause and owned by
* this expression; <code>false</code> otherwise
*/
public final boolean hasSpaceAfterWhere() {
return hasSpaceAfterWhere;
}
/**
* Determines whether the <b>WHERE</b> clause is defined.
*
* @return <code>true</code> if the query that got parsed had the <b>WHERE</b> clause
*/
public final boolean hasWhereClause() {
return whereClause != null &&
!whereClause.isNull();
}
/**
* {@inheritDoc}
*/
@Override
protected void parse(WordParser wordParser, boolean tolerant) {
// Parse 'SELECT' clause
if (wordParser.startsWithIdentifier(SELECT)) {
selectClause = buildSelectClause();
selectClause.parse(wordParser, tolerant);
hasSpaceAfterSelect = wordParser.skipLeadingWhitespace() > 0;
}
// Parse 'FROM' clause
if (wordParser.startsWithIdentifier(FROM)) {
fromClause = buildFromClause();
fromClause.parse(wordParser, tolerant);
hasSpaceAfterFrom = wordParser.skipLeadingWhitespace() > 0;
}
// Parse 'WHERE' clause
if (wordParser.startsWithIdentifier(WHERE)) {
whereClause = new WhereClause(this);
whereClause.parse(wordParser, tolerant);
hasSpaceAfterWhere = wordParser.skipLeadingWhitespace() > 0;
}
// Parse 'GROUP BY' clause
if (wordParser.startsWithIdentifier(GROUP_BY)) {
groupByClause = new GroupByClause(this);
groupByClause.parse(wordParser, tolerant);
hasSpaceAfterGroupBy = wordParser.skipLeadingWhitespace() > 0;
}
// Parse 'HAVING' clause
if (wordParser.startsWithIdentifier(HAVING)) {
havingClause = new HavingClause(this);
havingClause.parse(wordParser, tolerant);
}
if (!wordParser.isTail() && !shouldManageSpaceAfterClause()) {
if (hasSpaceAfterFrom &&
whereClause == null &&
groupByClause == null &&
havingClause == null) {
hasSpaceAfterFrom = false;
wordParser.moveBackward(1);
}
else if (hasSpaceAfterWhere &&
groupByClause == null &&
havingClause == null) {
hasSpaceAfterWhere = false;
wordParser.moveBackward(1);
}
else if (hasSpaceAfterGroupBy &&
havingClause == null) {
hasSpaceAfterGroupBy = false;
wordParser.moveBackward(1);
}
}
}
/**
* Determines whether the whitespace following the <code><b>HAVING</b></code> clause should be
* managed by this expression or not.
*
* @return <code>true</code> by default to keep the whitespace part of this expression;
* <code>false</code> to let the parent handle it
*/
protected boolean shouldManageSpaceAfterClause() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
protected void toParsedText(StringBuilder writer, boolean actual) {
// SELECT clause
if (selectClause != null) {
selectClause.toParsedText(writer, actual);
}
if (hasSpaceAfterSelect) {
writer.append(SPACE);
}
// FROM clause
if (fromClause != null) {
fromClause.toParsedText(writer, actual);
}
if (hasSpaceAfterFrom) {
writer.append(SPACE);
}
// WHERE clause
if (whereClause != null) {
whereClause.toParsedText(writer, actual);
}
if (hasSpaceAfterWhere) {
writer.append(SPACE);
}
// GROUP BY clause
if (groupByClause != null) {
groupByClause.toParsedText(writer, actual);
}
if (hasSpaceAfterGroupBy) {
writer.append(SPACE);
}
// HAVING clause
if (havingClause != null) {
havingClause.toParsedText(writer, actual);
}
}
}
| epl-1.0 |
gazarenkov/che-sketch | wsagent/che-core-api-languageserver-shared/src/main/java/org/eclipse/che/api/languageserver/shared/lsapi/ServerCapabilitiesDTO.java | 3426 | /**
* Copyright (c) 2016 TypeFox GmbH (http://www.typefox.io) 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.che.api.languageserver.shared.lsapi;
import io.typefox.lsapi.ServerCapabilities;
import io.typefox.lsapi.TextDocumentSyncKind;
import org.eclipse.che.dto.shared.DTO;
/**
* @author Sven Efftinge
*/
@DTO
public interface ServerCapabilitiesDTO extends ServerCapabilities {
/**
* Defines how text documents are synced.
*/
void setTextDocumentSync(final TextDocumentSyncKind textDocumentSync);
/**
* The server provides hover support.
*/
void setHoverProvider(final Boolean hoverProvider);
/**
* The server provides completion support. Overridden to return the DTO
* type.
*/
CompletionOptionsDTO getCompletionProvider();
/**
* The server provides completion support.
*/
void setCompletionProvider(final CompletionOptionsDTO completionProvider);
/**
* The server provides signature help support. Overridden to return the DTO
* type.
*/
SignatureHelpOptionsDTO getSignatureHelpProvider();
/**
* The server provides signature help support.
*/
void setSignatureHelpProvider(final SignatureHelpOptionsDTO signatureHelpProvider);
/**
* The server provides goto definition support.
*/
void setDefinitionProvider(final Boolean definitionProvider);
/**
* The server provides find references support.
*/
void setReferencesProvider(final Boolean referencesProvider);
/**
* The server provides document highlight support.
*/
void setDocumentHighlightProvider(final Boolean documentHighlightProvider);
/**
* The server provides document symbol support.
*/
void setDocumentSymbolProvider(final Boolean documentSymbolProvider);
/**
* The server provides workspace symbol support.
*/
void setWorkspaceSymbolProvider(final Boolean workspaceSymbolProvider);
/**
* The server provides code actions.
*/
void setCodeActionProvider(final Boolean codeActionProvider);
/**
* The server provides code lens. Overridden to return the DTO type.
*/
CodeLensOptionsDTO getCodeLensProvider();
/**
* The server provides code lens.
*/
void setCodeLensProvider(final CodeLensOptionsDTO codeLensProvider);
/**
* The server provides document formatting.
*/
void setDocumentFormattingProvider(final Boolean documentFormattingProvider);
/**
* The server provides document range formatting.
*/
void setDocumentRangeFormattingProvider(final Boolean documentRangeFormattingProvider);
/**
* The server provides document formatting on typing. Overridden to return
* the DTO type.
*/
DocumentOnTypeFormattingOptionsDTO getDocumentOnTypeFormattingProvider();
/**
* The server provides document formatting on typing.
*/
void setDocumentOnTypeFormattingProvider(
final DocumentOnTypeFormattingOptionsDTO documentOnTypeFormattingProvider);
/**
* The server provides rename support.
*/
void setRenameProvider(final Boolean renameProvider);
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | utils/eclipselink.dbws.builder.test.oracle/src/dbws/testing/shadowddlgeneration/oldjpub/Util.java | 13213 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Mike Norman - from Proof-of-concept, become production code
******************************************************************************/
package dbws.testing.shadowddlgeneration.oldjpub;
//javase imports
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Util {
public static final int CASE_SAME = 1;
public static final int CASE_UPPER = 2;
public static final int CASE_LOWER = 3;
public static final int CASE_MIXED = 4;
public static final int CASE_OPPOSITE = 5;
public static final String ALL_OBJECTS = "ALL_OBJECTS";
public static final String ALL_ARGUMENTS = "ALL_ARGUMENTS";
public static final String USER_ARGUMENTS = "USER_ARGUMENTS";
public static final String ALL_TYPES = "ALL_TYPES";
public static final String ALL_TYPE_ATTRS = "ALL_TYPE_ATTRS";
public static final String ALL_COLL_TYPES = "ALL_COLL_TYPES";
public static final int SCHEMA_ALWAYS = 1;
public static final int SCHEMA_IF_NEEDED = 2;
public static final int SCHEMA_FROM_INTYPE = 3;
public static final int SCHEMA_OMIT = 4;
public static final String DUAL = "DUAL";
public static final String PACKAGE_NAME = "PACKAGE_NAME";
public static final String OBJECT_NAME = "OBJECT_NAME";
public static final String ARGUMENT_NAME = "ARGUMENT_NAME";
public static final String DATA_LEVEL = "DATA_LEVEL";
public static final String POSITION = "POSITION";
public static final String SEQUENCE = "SEQUENCE";
public static final String OWNER = "OWNER";
public static final String OVERLOAD = "OVERLOAD";
public static final String NOT_NULL = "NOT NULL";
public static final String IS_NULL = "IS NULL";
public static final int METHODS_NONE = 1;
public static final int METHODS_NAMED = 2;
public static final int METHODS_ALL = 4;
public static final int METHODS_ALWAYS = 8;
public static final int METHODS_OVERLOAD = 16;
public static final int METHODS_UNIQUE = 32;
public static final int METHODS_RETRY = 64;
public static final int METHODS_PARAM_INTERFACE = 128;
public static final int JDBC_USERTYPES = 16;
public static final int USERTYPES_MASK = JDBC_USERTYPES;
public static final String TOPLEVEL = "TOPLEVEL";
public static final int IS_OBJECT = 1;
public static final int IS_COLLECTION = 2;
public static final int IS_TYPE = 3;
public static final int IS_PACKAGE = 4;
public static final int IS_TYPE_OR_PACKAGE = IS_TYPE | IS_PACKAGE;
private static final int IS_TOPLEVEL_FUNCTION_ONLY = 8;
public static final int IS_TOPLEVEL = IS_TOPLEVEL_FUNCTION_ONLY | IS_PACKAGE;
private static final int IS_SQLSTATEMENT_ONLY = 16;
public static final int IS_SQLSTATEMENTS = IS_TYPE | IS_TOPLEVEL_FUNCTION_ONLY
| IS_SQLSTATEMENT_ONLY;
public static final String TYPE_NAME = "TYPE_NAME";
public static final String ATTR_NAME = "ATTR_NAME";
public static final String ATTR_TYPE_NAME = "ATTR_TYPE_NAME";
public static final String ELEM_TYPE_NAME = "ELEM_TYPE_NAME";
public static final String ALL_TYPE_METHODS = "ALL_TYPE_METHODS";
public static final String ALL_METHOD_RESULTS = "ALL_METHOD_RESULTS";
public static final String ALL_METHOD_PARAMS = "ALL_METHOD_PARAMS";
public static final String ALL_QUEUE_TABLES = "ALL_QUEUE_TABLES";
public static final String ALL_SYNONYMS = "ALL_SYNONYMS";
public static final String ALL_TAB_PRIVS = "ALL_TAB_PRIVS";
public static final String TABLE_OWNER = "TABLE_OWNER";
public static final String TABLE_NAME = "TABLE_NAME";
public static final String TABLE_SCHEMA = "TABLE_SCHEMA";
public static final String PRIVILEGE = "PRIVILEGE";
public static final String GRANTEE = "GRANTEE";
public static final String SYNONYM_NAME = "SYNONYM_NAME";
public static final String SUPERTYPE_NAME = "SUPERTYPE_NAME";
public static final int MAX_IDENTIFIER_LENGTH = 29;
public static final String DEFAULT_VARCHAR_LEN = "4000";
public static final String DEFAULT_RAW_LEN = "1000";
public static final String DEFAULT_LONG_LEN = "32767";
private static Map<String, String> m_defaultTypeLen = new HashMap<String, String>();
static {
m_defaultTypeLen.put("VARCHAR", DEFAULT_VARCHAR_LEN);
m_defaultTypeLen.put("VARCHAR2", DEFAULT_VARCHAR_LEN);
m_defaultTypeLen.put("NVARCHAR2", DEFAULT_VARCHAR_LEN);
m_defaultTypeLen.put("RAW", DEFAULT_RAW_LEN);
m_defaultTypeLen.put("LONG", DEFAULT_LONG_LEN);
m_defaultTypeLen.put("LONG_CHAR", DEFAULT_LONG_LEN);
m_defaultTypeLen.put("LONG_RAW", DEFAULT_LONG_LEN);
}
public static String getDefaultTypeLen(String type) {
return (String)m_defaultTypeLen.get(type.toUpperCase().replace(' ', '_'));
}
public static String printTypeWithLength(String type, int length, int precision, int scale) {
if (type == null) {
return "<unsupported type>";
}
if (type.equalsIgnoreCase("NCHAR")) {
type = "CHAR";
}
if (type.equalsIgnoreCase("NVARCHAR2")) {
type = "VARCHAR2";
}
if (type.equalsIgnoreCase("NCLOB")) {
type = "CLOB";
}
if (length != 0) {
if (type.equals("NUMBER")) {
if (precision != 0 && scale != 0) {
return type + "(" + precision + ", " + scale + ")";
}
else if (precision != 0) {
return type + "(" + precision + ")";
}
}
else if (type.equals("FLOAT")) {
if (precision != 0) {
return type + "(" + precision + ")";
}
}
else if (type.equals("NCHAR") || type.equals("NVARCHAR2")) {
return type + "(" + (length / 2) + ")";
}
else {
return type + "(" + length + ")";
}
}
if (getDefaultTypeLen(type) == null) {
return type;
}
else {
return type + "(" + getDefaultTypeLen(type) + ")";
}
}
public static String getWrappedType(String s) {
if (m_wrappedTypes == null) {
initWrappedTypes();
}
return (String)m_wrappedTypes.get(s);
}
public static String getWrappedType(Class<?> c) {
if (m_wrappedTypes == null) {
initWrappedTypes();
}
return (String)m_wrappedTypes.get(c);
}
public static boolean isWrappedType(String s) {
if (m_wrappedTypes == null) {
initWrappedTypes();
}
return m_wrappedTypes.get(s) != null;
}
private static void initWrappedTypes() {
m_wrappedTypes = new HashMap<Object, Object>();
m_wrappedTypes.put("java.lang.Boolean", "boolean");
m_wrappedTypes.put("Boolean", "boolean");
m_wrappedTypes.put(Boolean.class, "boolean");
m_wrappedTypes.put("java.lang.Byte", "byte");
m_wrappedTypes.put("Byte", "byte");
m_wrappedTypes.put(Byte.class, "byte");
m_wrappedTypes.put("java.lang.Short", "short");
m_wrappedTypes.put("Short", "short");
m_wrappedTypes.put(Short.class, "short");
m_wrappedTypes.put("java.lang.Integer", "int");
m_wrappedTypes.put("Integer", "int");
m_wrappedTypes.put(Integer.class, "int");
m_wrappedTypes.put("java.lang.Long", "long");
m_wrappedTypes.put("Long", "long");
m_wrappedTypes.put(Long.class, "long");
m_wrappedTypes.put("java.lang.Character", "char");
m_wrappedTypes.put("Character", "char");
m_wrappedTypes.put(Character.class, "char");
m_wrappedTypes.put("java.lang.Float", "float");
m_wrappedTypes.put("Float", "float");
m_wrappedTypes.put(Float.class, "float");
m_wrappedTypes.put("java.lang.Double", "double");
m_wrappedTypes.put("Double", "double");
m_wrappedTypes.put(Double.class, "double");
}
private static Map<Object, Object> m_wrappedTypes = null;
/*
* Common utilities
*/
private static Map<String, String> uniqueResultTypeNames = new HashMap<String, String>();
public static String uniqueResultTypeName(String methodName, String suffix) {
String resultTypeName = methodName + suffix;
int count = 0;
while (uniqueResultTypeNames.containsKey(resultTypeName)) {
resultTypeName = methodName + (count++) + suffix;
}
uniqueResultTypeNames.put(resultTypeName, resultTypeName);
return resultTypeName;
}
public static String quote(String text) {
return "\"" + escapeQuote(text) + "\"";
}
public static String escapeQuote(String text) {
if (text == null) {
return text;
}
String textQuoted = "";
if (text.startsWith("\"")) {
textQuoted += "\\\"";
}
StringTokenizer stn = new StringTokenizer(text, "\"");
while (stn.hasMoreTokens()) {
String token = stn.nextToken();
textQuoted += token;
if (stn.hasMoreTokens()) {
textQuoted += "\\\"";
}
}
if (text.endsWith("\"")) {
textQuoted += "\\\"";
}
return textQuoted;
}
public static String getSchema(String schema, String type) {
if (schema == null || schema.equals("")) {
if (type.indexOf('.') >= 0) {
return type.substring(0, type.indexOf('.'));
}
}
return schema;
}
public static String getType(String schema, String type) {
if (schema == null || schema.equals("")) {
if (type.indexOf('.') >= 0) {
return type.substring(type.indexOf('.') + 1);
}
}
return type;
}
public static String unreserveSql(String word) {
String unreserve = (String)m_sqlReservedMap.get(word.toUpperCase());
if (unreserve == null) {
unreserve = word;
}
return unreserve;
}
private static final String[] SQL_RESERVED = new String[]{"ALL", "ALTER", "AND", "ANY",
"ARRAY", "AS", "ASC", "AT", "AUTHID", "AVG", "BEGIN", "BETWEEN", "BINARY_INTEGER", "BODY",
"BOOLEAN", "BULK", "BY", "CASE", "CHAR", "CHAR_BASE", "CHECK", "CLOSE", "CLUSTER",
"COALESCE", "COLLECT", "COMMENT", "COMMIT", "COMPRESS", "CONNECT", "CONSTANT", "CREATE",
"CURRENT", "CURRVAL", "CURSOR", "DATE", "DAY", "DECLARE", "DECIMAL", "DEFAULT", "DELETE",
"DESC", "DISTINCT", "DO", "DROP", "ELSE", "ELSIF", "END", "EXCEPTION", "EXCLUSIVE",
"EXECUTE", "EXISTS", "EXIT", "EXTENDS", "EXTRACT", "FALSE", "FETCH", "FLOAT", "FOR",
"FORALL", "FROM", "FUNCTION", "GOTO", "GROUP", "HAVING", "HEAP", "HOUR", "IF", "IMMEDIATE",
"IN", "INDEX", "INDICATOR", "INSERT", "INTEGER", "INTERFACE", "INTERSECT", "INTERVAL",
"INTO", "IS", "ISOLATION", "JAVA", "LEVEL", "LIKE", "LIMITED", "LOCK", "LONG", "LOOP",
"MAX", "MIN", "MINUS", "MINUTE", "MLSLABEL", "MOD", "MODE", "MONTH", "NATURAL", "NATURALN",
"NEW", "NEXTVAL", "NOCOPY", "NOT", "NOWAIT", "NULL", "NULLIF", "NUMBER", "NUMBER_BASE",
"OCIROWID", "OF", "ON", "OPAQUE", "OPEN", "OPERATOR", "OPTION", "OR", "ORDER",
"ORGANIZATION", "OTHERS", "OUT", "PACKAGE", "PARTITION", "PCTFREE", "PLS_INTEGER",
"POSITIVE", "POSITIVEN", "PRAGMA", "PRIOR", "PRIVATE", "PROCEDURE", "PUBLIC", "RAISE",
"RANGE", "RAW", "REAL", "RECORD", "REF", "RELEASE", "RETURN", "REVERSE", "ROLLBACK", "ROW",
"ROWID", "ROWNUM", "ROWTYPE", "SAVEPOINT", "SECOND", "SELECT", "SEPARATE", "SET", "SHARE",
"SMALLINT", "SPACE", "SQL", "SQLCODE", "SQLERRM", "START", "STDDEV", "SUBTYPE",
"SUCCESSFUL", "SUM", "SYNONYM", "SYSDATE", "TABLE", "THEN", "TIME", "TIMESTAMP",
"TIMEZONE_REGION", "TIMEZONE_ABBR", "TIMEZONE_MINUTE", "TIMEZONE_HOUR", "TO", "TRIGGER",
"TRUE", "TYPE", "UID", "UNION", "UNIQUE", "UPDATE", "USE", "USER", "VALIDATE", "VALUES",
"VARCHAR", "VARCHAR2", "VARIANCE", "VIEW", "WHEN", "WHENEVER", "WHERE", "WHILE", "WITH",
"WORK", "WRITE", "YEAR", "ZONE"};
private static Map<String, String> m_sqlReservedMap;
static {
m_sqlReservedMap = new HashMap<String, String>();
for (int i = 0; i < SQL_RESERVED.length; i++) {
m_sqlReservedMap
.put(SQL_RESERVED[i].toUpperCase(), SQL_RESERVED[i].toUpperCase() + "_");
}
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/sessions/factories/model/pool/ConnectionPoolConfig.java | 1821 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.sessions.factories.model.pool;
import org.eclipse.persistence.internal.sessions.factories.model.login.LoginConfig;
/**
* INTERNAL:
*/
public class ConnectionPoolConfig {
protected String m_name;
private Integer m_maxConnections;
private Integer m_minConnections;
private LoginConfig m_loginConfig;
public ConnectionPoolConfig() {
}
public void setName(String name) {
m_name = name;
}
public String getName() {
return m_name;
}
public void setMaxConnections(Integer maxConnections) {
m_maxConnections = maxConnections;
}
public Integer getMaxConnections() {
return m_maxConnections;
}
public void setMinConnections(Integer minConnections) {
m_minConnections = minConnections;
}
public Integer getMinConnections() {
return m_minConnections;
}
public void setLoginConfig(LoginConfig loginConfig) {
m_loginConfig = loginConfig;
}
public LoginConfig getLoginConfig() {
return m_loginConfig;
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/partitioned/PhoneNumber.java | 3234 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.partitioned;
import java.io.*;
import javax.persistence.*;
import org.eclipse.persistence.annotations.Partitioned;
import org.eclipse.persistence.queries.FetchGroupTracker;
/**
* <p>
* <b>Purpose</b>: Describes an Employee's phone number.
* <p>
* <b>Description</b>: Used in a 1:M relationship from an employee.
*/
@Entity
@Table(name = "PART_PHONENUMBER")
@IdClass(PhoneNumberPK.class)
@Partitioned("ValuePartitioningByLOCATION")
public class PhoneNumber implements Serializable {
@Column(name = "NUMB")
private String number;
@Id
@Column(name = "TYPE")
private String type;
@Id
@ManyToOne
@JoinColumns({
@JoinColumn(name = "OWNER_ID", referencedColumnName = "EMP_ID"),
@JoinColumn(name = "LOCATION", referencedColumnName = "LOCATION")})
private Employee owner;
@Column(name = "AREA_CODE")
private String areaCode;
public PhoneNumber() {
this("", "###", "#######");
}
public PhoneNumber(String type, String theAreaCode, String theNumber) {
this.type = type;
this.areaCode = theAreaCode;
this.number = theNumber;
this.owner = null;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public Employee getOwner() {
return owner;
}
public void setOwner(Employee owner) {
this.owner = owner;
}
/**
* Example: Phone[Work]: (613) 225-8812
*/
public String toString() {
StringWriter writer = new StringWriter();
writer.write("PhoneNumber[");
writer.write(getType());
writer.write("]: (");
if (!(this instanceof FetchGroupTracker)) {
writer.write(getAreaCode());
writer.write(") ");
int numberLength = this.getNumber().length();
writer.write(getNumber().substring(0, Math.min(3, numberLength)));
if (numberLength > 3) {
writer.write("-");
writer.write(getNumber().substring(3, Math.min(7, numberLength)));
}
}
return writer.toString();
}
}
| epl-1.0 |
RallySoftware/eclipselink.runtime | moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/json/xmlvalue/XMLValuePropDifferentTestCases.java | 1789 | /*******************************************************************************
* Copyright (c) 2011, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Denise Smith - 2.4
******************************************************************************/
package org.eclipse.persistence.testing.jaxb.json.xmlvalue;
import java.util.Map;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
public class XMLValuePropDifferentTestCases extends XMLValuePropTestCases {
private final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/json/xmlvalue/personUnmarshal.json";
private final static String JSON_WRITE_RESOURCE = "org/eclipse/persistence/testing/jaxb/json/xmlvalue/personMarshal.json";
public XMLValuePropDifferentTestCases(String name) throws Exception {
super(name);
setClasses(new Class[]{Person.class});
setControlJSON(JSON_RESOURCE);
setWriteControlJSON(JSON_WRITE_RESOURCE);
}
public void setUp() throws Exception{
super.setUp();
jaxbMarshaller.setProperty(MarshallerProperties.JSON_VALUE_WRAPPER, "marshalWrapper");
jaxbUnmarshaller.setProperty(UnmarshallerProperties.JSON_VALUE_WRAPPER, "unmarshalWrapper");
}
//public Map getProperties(){
// return null;
//}
}
| epl-1.0 |
gameduell/eclipselink.runtime | utils/eclipselink.utils.workbench/mappingsmodel/source/org/eclipse/persistence/tools/workbench/mappingsmodel/mapping/xml/MWEisOneToOneMapping.java | 9822 | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.xml;
import java.util.Iterator;
import java.util.List;
import org.eclipse.persistence.tools.workbench.mappingsmodel.ProblemConstants;
import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.xml.MWEisDescriptor;
import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.MWMapping;
import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.MWProxyIndirectionMapping;
import org.eclipse.persistence.tools.workbench.mappingsmodel.meta.MWClassAttribute;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.xml.MWEisInteraction;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.xml.MWEisQueryManager;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.xml.MWEisInteraction.ArgumentPair;
import org.eclipse.persistence.tools.workbench.mappingsmodel.xml.MWXmlField;
import org.eclipse.persistence.tools.workbench.utility.node.Node;
import org.eclipse.persistence.eis.mappings.EISOneToOneMapping;
import org.eclipse.persistence.internal.indirection.ProxyIndirectionPolicy;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.mappings.XMLDirectMapping;
public final class MWEisOneToOneMapping
extends MWEisReferenceMapping
implements MWProxyIndirectionMapping
{
// **************** Variables *********************************************
private volatile boolean useDescriptorReadObjectInteraction;
public final static String USE_DESCRIPTOR_READ_OBJECT_INTERACTION_PROPERTY = "useDescriptorReadObjectInteraction";
// **************** Constructors ***************
/** Default constructor - for TopLink use only */
private MWEisOneToOneMapping() {
super();
}
public MWEisOneToOneMapping(MWEisDescriptor parent, MWClassAttribute attribute, String name) {
super(parent, attribute, name);
}
// **************** Initialization ****************************************
/** initialize persistent state */
protected void initialize(Node parent) {
super.initialize(parent);
this.useDescriptorReadObjectInteraction = true;
}
protected void initialize(MWClassAttribute attribute, String name) {
super.initialize(attribute, name);
if (!getInstanceVariable().isValueHolder() && getInstanceVariable().getType().isInterface()) {
this.indirectionType = PROXY_INDIRECTION;
}
}
/**
* 1:1 mappings don't have a selection interaction when they
* use the descriptor read object interaction
*/
protected boolean requiresSelectionInteraction() {
return false;
}
// **************** Selection interaction *********************************
public boolean usesDescriptorReadObjectInteraction() {
return this.useDescriptorReadObjectInteraction;
}
public void setUseDescriptorReadObjectInteraction(boolean useDescriptorReadObjectInteraction) {
boolean old = this.useDescriptorReadObjectInteraction;
this.useDescriptorReadObjectInteraction = useDescriptorReadObjectInteraction;
if (old != useDescriptorReadObjectInteraction) {
this.firePropertyChanged(USE_DESCRIPTOR_READ_OBJECT_INTERACTION_PROPERTY, old, useDescriptorReadObjectInteraction);
// clear the selection interaction if the new value is true
this.setSelectionInteraction(useDescriptorReadObjectInteraction ? null : new MWEisInteraction(this));
}
}
// **************** Convenience *******************************************
private MWEisInteraction referenceDescriptorReadInteraction() {
return (this.referenceRootEisDescriptor() == null) ?
null
:
((MWEisQueryManager) this.referenceRootEisDescriptor().getQueryManager()).getReadObjectInteraction();
}
// **************** MWXpathContext contract (for field pairs) *************
/**
* Return true if a source field may use a collection xpath
* @see MWEisReferenceMapping#sourceFieldMayUseCollectionXpath()
*/
public boolean sourceFieldMayUseCollectionXpath() {
return false;
}
// *********** MWProxyIndirectionMapping implementation ***********
public boolean usesProxyIndirection() {
return getIndirectionType() == PROXY_INDIRECTION;
}
public void setUseProxyIndirection() {
setIndirectionType(PROXY_INDIRECTION);
}
// **************** Morphing **********************************************
protected void initializeOn(MWMapping newMapping) {
newMapping.initializeFromMWEisOneToOneMapping(this);
}
// ************** Problem handling ****************************************
protected void addProblemsTo(List newProblems) {
super.addProblemsTo(newProblems);
this.checkFieldPairs(newProblems);
this.checkReferenceDescriptorReadInteraction(newProblems);
this.checkFieldPairsAndReadInteractionArguments(newProblems);
this.addUsesIndirectionWhileMaintainsBiDirectionalRelationship(newProblems);
}
private void checkFieldPairs(List newProblems) {
// the mapping must have field pairs unless
// 1) there is a selection interaction specified -AND-
// 2) the mapping is read only
if ((this.isReadOnly() && this.getSelectionInteraction() == null) || this.xmlFieldPairsSize() == 0) {
newProblems.add(this.buildProblem(ProblemConstants.MAPPING_1_TO_1_FIELD_PAIRS_NOT_SPECIFIED));
}
}
private void checkReferenceDescriptorReadInteraction(List newProblems) {
// if the mapping does not specify a selection interaction, the reference descriptor must
// have a read object interaction specified
if (
this.usesDescriptorReadObjectInteraction()
&& this.referenceRootEisDescriptor() != null
&& this.referenceDescriptorReadInteraction().getFunctionName() == null
) {
newProblems.add(this.buildProblem(ProblemConstants.MAPPING_REFERENCE_DESCRIPTOR_READ_INTERACTION_NOT_SPECIFIED));
}
}
private void checkFieldPairsAndReadInteractionArguments(List newProblems) {
// if the selection interaction is not specified, each argument in the
// reference descriptor's read interaction must correspond to a target key
// in the field pairs.
if (! this.usesDescriptorReadObjectInteraction() || this.referenceDescriptorReadInteraction() == null) {
return;
}
for (Iterator stream = this.referenceDescriptorReadInteraction().inputArguments(); stream.hasNext(); ) {
String argumentFieldName = ((ArgumentPair) stream.next()).getArgumentFieldName();
if (! this.hasCorrespondingTargetKey(argumentFieldName)) {
newProblems.add(this.buildProblem(ProblemConstants.MAPPING_NONCORRESPONDING_TARGET_KEY, argumentFieldName));
}
}
}
private void addUsesIndirectionWhileMaintainsBiDirectionalRelationship(List newProblems) {
if (this.maintainsBidirectionalRelationship() && this.usesNoIndirection()) {
newProblems.add(this.buildProblem(ProblemConstants.MAPPING_REFERENCE_MAINTAINS_BIDI_BUT_NO_INDIRECTION));
}
}
private boolean hasCorrespondingTargetKey(String argumentFieldName) {
for (Iterator stream = this.xmlFieldPairs(); stream.hasNext(); ) {
MWXmlField targetField = ((MWXmlFieldPair) stream.next()).getTargetXmlField();
if (targetField != null && targetField.getXpath().equals(argumentFieldName)) {
return true;
}
}
return false;
}
// **************** Runtime Conversion ***************
protected DatabaseMapping buildRuntimeMapping() {
return new EISOneToOneMapping();
}
public DatabaseMapping runtimeMapping() {
EISOneToOneMapping mapping = (EISOneToOneMapping) super.runtimeMapping();
for (Iterator stream = this.xmlFieldPairs(); stream.hasNext(); ) {
((MWXmlFieldPair) stream.next()).addRuntimeForeignKeyField(mapping);
}
if (usesProxyIndirection()) {
mapping.setIndirectionPolicy(new ProxyIndirectionPolicy());
}
return mapping;
}
// **************** TopLink methods ***************************************
public static XMLDescriptor buildDescriptor() {
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(MWEisOneToOneMapping.class);
descriptor.getInheritancePolicy().setParentClass(MWEisReferenceMapping.class);
XMLDirectMapping useDescriptorReadObjectInteractionMapping = (XMLDirectMapping) descriptor.addDirectMapping("useDescriptorReadObjectInteraction", "use-descriptor-read-object-interaction/text()");
useDescriptorReadObjectInteractionMapping.setNullValue(Boolean.FALSE);
return descriptor;
}
}
| epl-1.0 |
rfdrake/opennms | opennms-provision/opennms-provision-persistence/src/main/java/org/opennms/netmgt/provision/persist/FileProcessor.java | 179 | package org.opennms.netmgt.provision.persist;
import java.io.File;
public interface FileProcessor {
public void processFile(File file, String basename, String extension);
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | development/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.java | 4539 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
//BEGIN_INCLUDE(complete)
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Toast;
/**
* This demonstrates the use of action bar tabs and how they interact
* with other action bar features.
*/
public class FragmentTabs extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
bar.addTab(bar.newTab()
.setText("Simple")
.setTabListener(new TabListener<FragmentStack.CountingFragment>(
this, "simple", FragmentStack.CountingFragment.class)));
bar.addTab(bar.newTab()
.setText("Contacts")
.setTabListener(new TabListener<LoaderCursor.CursorLoaderListFragment>(
this, "contacts", LoaderCursor.CursorLoaderListFragment.class)));
bar.addTab(bar.newTab()
.setText("Apps")
.setTabListener(new TabListener<LoaderCustom.AppListFragment>(
this, "apps", LoaderCustom.AppListFragment.class)));
bar.addTab(bar.newTab()
.setText("Throttle")
.setTabListener(new TabListener<LoaderThrottle.ThrottledLoaderListFragment>(
this, "throttle", LoaderThrottle.ThrottledLoaderListFragment.class)));
if (savedInstanceState != null) {
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Fragment mFragment;
public TabListener(Activity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(Activity activity, String tag, Class<T> clz, Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
ft.detach(mFragment);
ft.commit();
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
ft.add(android.R.id.content, mFragment, mTag);
} else {
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
}
}
}
//END_INCLUDE(complete)
| gpl-2.0 |
justinwm/astor | examples/evo_suite_test/math_70_spooned/src/default/org/apache/commons/math/random/UniformRandomGeneratorTest.java | 868 | package org.apache.commons.math.random;
public class UniformRandomGeneratorTest extends junit.framework.TestCase {
public UniformRandomGeneratorTest(java.lang.String name) {
super(name);
}
public void testMeanAndStandardDeviation() {
org.apache.commons.math.random.RandomGenerator rg = new org.apache.commons.math.random.JDKRandomGenerator();
rg.setSeed(17399225432L);
org.apache.commons.math.random.UniformRandomGenerator generator = new org.apache.commons.math.random.UniformRandomGenerator(rg);
double[] sample = new double[10000];
for (int i = 0 ; i < (sample.length) ; ++i) {
sample[i] = generator.nextNormalizedDouble();
}
junit.framework.Assert.assertEquals(0.0, org.apache.commons.math.stat.StatUtils.mean(sample), 0.07);
junit.framework.Assert.assertEquals(1.0, org.apache.commons.math.stat.StatUtils.variance(sample), 0.02);
}
}
| gpl-2.0 |
hgl888/AcDisplay | project/app/src/main/java/com/achep/base/ui/widgets/DashboardTileView.java | 3535 | /*
* Copyright (C) 2015 AChep@xda <artemchep@gmail.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.achep.base.ui.widgets;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.achep.acdisplay.R;
import com.achep.base.dashboard.DashboardTile;
import com.achep.base.ui.activities.SettingsActivity;
import com.achep.base.utils.RippleUtils;
public class DashboardTileView extends LinearLayout implements View.OnClickListener {
private static final int DEFAULT_COL_SPAN = 1;
private ImageView mImageView;
private TextView mTitleTextView;
private TextView mStatusTextView;
private View mDivider;
private int mColSpan = DEFAULT_COL_SPAN;
private DashboardTile mTile;
public DashboardTileView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mImageView = (ImageView) findViewById(R.id.icon);
mTitleTextView = (TextView) findViewById(R.id.title);
mStatusTextView = (TextView) findViewById(R.id.status);
mDivider = findViewById(R.id.tile_divider);
setOnClickListener(this);
setFocusable(true);
RippleUtils.makeFor(this, true);
}
public void setDashboardTile(@NonNull DashboardTile tile) {
mTile = tile;
Resources res = getResources();
if (tile.iconRes > 0) {
mImageView.setImageResource(tile.iconRes);
} else {
mImageView.setImageDrawable(null);
mImageView.setBackground(null);
}
mTitleTextView.setText(tile.getTitle(res));
CharSequence summary = tile.getSummary(res);
if (!TextUtils.isEmpty(summary)) {
mStatusTextView.setVisibility(View.VISIBLE);
mStatusTextView.setText(summary);
} else {
mStatusTextView.setVisibility(View.GONE);
}
}
public void setDividerVisibility(boolean visible) {
mDivider.setVisibility(visible ? View.VISIBLE : View.GONE);
}
void setColumnSpan(int span) {
mColSpan = span;
}
int getColumnSpan() {
return mColSpan;
}
@Override
public void onClick(View v) {
if (mTile.fragment != null) {
SettingsActivity.Utils.startWithFragment(getContext(),
mTile.fragment, mTile.fragmentArguments, null, 0,
mTile.titleRes, mTile.getTitle(getResources()));
} else if (mTile.intent != null) {
getContext().startActivity(mTile.intent);
}
}
}
| gpl-2.0 |
timrae/Anki-Android | AnkiDroid/src/main/java/com/ichi2/compat/CompatV16.java | 4033 |
package com.ichi2.compat;
import android.annotation.TargetApi;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.util.TypedValue;
import android.widget.RemoteViews;
import com.ichi2.anki.AnkiActivity;
import com.ichi2.anki.R;
import com.ichi2.compat.customtabs.CustomTabActivityHelper;
import com.ichi2.compat.customtabs.CustomTabsFallback;
import com.ichi2.compat.customtabs.CustomTabsHelper;
/** Implementation of {@link Compat} for SDK level 16 */
@TargetApi(16)
public class CompatV16 extends CompatV15 implements Compat {
@Override
public void disableDatabaseWriteAheadLogging(SQLiteDatabase db) {
db.disableWriteAheadLogging();
}
@Override
public String detagged(String txt) {
return Html.escapeHtml(txt);
}
/*
* Update dimensions of widget from V16 on (elder versions do not support widget measuring)
*/
@Override
public void updateWidgetDimensions(Context context, RemoteViews updateViews, Class<?> cls) {
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, cls));
for (int id : ids) {
final float scale = context.getResources().getDisplayMetrics().density;
Bundle options = manager.getAppWidgetOptions(id);
float width, height;
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
width = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
height = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
} else {
width = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
height = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
}
int horizontal, vertical;
float text;
if ((width / height) > 0.8) {
horizontal = (int) (((width - (height * 0.8))/2 + 4) * scale + 0.5f);
vertical = (int) (4 * scale + 0.5f);
text = (float)(Math.sqrt(height * 0.8 / width) * 18);
} else {
vertical = (int) (((height - (width * 1.25))/2 + 4) * scale + 0.5f);
horizontal = (int) (4 * scale + 0.5f);
text = (float)(Math.sqrt(width * 1.25 / height) * 18);
}
updateViews.setTextViewTextSize(R.id.widget_due, TypedValue.COMPLEX_UNIT_SP, text);
updateViews.setTextViewTextSize(R.id.widget_eta, TypedValue.COMPLEX_UNIT_SP, text);
updateViews.setViewPadding(R.id.ankidroid_widget_text_layout, horizontal, vertical, horizontal, vertical);
}
}
@Override
public void openUrl(AnkiActivity activity, Uri uri) {
CustomTabActivityHelper helper = activity.getCustomTabActivityHelper();
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(helper.getSession());
builder.setToolbarColor(ContextCompat.getColor(activity, R.color.material_light_blue_500)).setShowTitle(true);
builder.setStartAnimations(activity, R.anim.slide_right_in, R.anim.slide_left_out);
builder.setExitAnimations(activity, R.anim.slide_left_in, R.anim.slide_right_out);
builder.setCloseButtonIcon(BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_arrow_back_white_24dp));
CustomTabsIntent customTabsIntent = builder.build();
CustomTabsHelper.addKeepAliveExtra(activity, customTabsIntent.intent);
CustomTabActivityHelper.openCustomTab(activity, customTabsIntent, uri, new CustomTabsFallback());
}
} | gpl-3.0 |
gulliverrr/hestia-engine-dev | src/opt/boilercontrol/libs/org.eclipse.paho.client.mqttv3/src/main/java/org/eclipse/paho/client/mqttv3/IMqttAsyncClient.java | 36964 | /*******************************************************************************
* Copyright (c) 2013, 2014 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Dave Locke - initial API and implementation and/or initial documentation
* Ian Craggs - MQTT 3.1.1 support
*/
package org.eclipse.paho.client.mqttv3;
/**
* Enables an application to communicate with an MQTT server using non-blocking methods.
* <p>
* It provides applications a simple programming interface to all features of the MQTT version 3.1
* specification including:
* <ul>
* <li>connect
* <li>publish
* <li>subscribe
* <li>unsubscribe
* <li>disconnect
* </ul>
* </p>
* <p>
* There are two styles of MQTT client, this one and {@link IMqttClient}.
* <ul>
* <li>IMqttAsyncClient provides a set of non-blocking methods that return control to the
* invoking application after initial validation of parameters and state. The main processing is
* performed in the background so as not to block the application program's thread. This non-
* blocking approach is handy when the application needs to carry on processing while the
* MQTT action takes place. For instance connecting to an MQTT server can take time, using
* the non-blocking connect method allows an application to display a busy indicator while the
* connect action takes place in the background. Non blocking methods are particularly useful
* in event oriented programs and graphical programs where invoking methods that take time
* to complete on the the main or GUI thread can cause problems. The non-blocking interface
* can also be used in blocking form.</li>
* <li>IMqttClient provides a set of methods that block and return control to the application
* program once the MQTT action has completed. It is a thin layer that sits on top of the
* IMqttAsyncClient implementation and is provided mainly for compatibility with earlier
* versions of the MQTT client. In most circumstances it is recommended to use IMqttAsyncClient
* based clients which allow an application to mix both non-blocking and blocking calls. </li>
* </ul>
* </p>
* <p>
* An application is not restricted to using one style if an IMqttAsyncClient based client is used
* as both blocking and non-blocking methods can be used in the same application. If an IMqttClient
* based client is used then only blocking methods are available to the application.
* For more details on the blocking client see {@link IMqttClient}</p>
*
* <p>There are two forms of non-blocking method:
* <ol>
* <li>
* <code><pre>
* IMqttToken token = asyncClient.method(parms)
* </pre></code>
* <p>In this form the method returns a token that can be used to track the
* progress of the action (method). The method provides a waitForCompletion()
* method that once invoked will block until the action completes. Once
* completed there are method on the token that can be used to check if the
* action completed successfully or not. For example
* to wait until a connect completes:
* <code><pre>
* IMqttToken conToken;
* conToken = asyncClient.client.connect(conToken);
* ... do some work...
* conToken.waitForCompletion();
* </pre></code>
* </p>
* <p>To turn a method into a blocking invocation the following form can be used:
* <code><pre>
* IMqttToken token;
* token = asyncClient.method(parms).waitForCompletion();
* </pre></code>
* </li>
*
* <li>
* <code><pre>
* IMqttToken token method(parms, Object userContext, IMqttActionListener callback)
* </pre></code>
* <p>In this form a callback is registered with the method. The callback will be
* notified when the action succeeds or fails. The callback is invoked on the thread
* managed by the MQTT client so it is important that processing is minimised in the
* callback. If not the operation of the MQTT client will be inhibited. For example
* to be notified (called back) when a connect completes:
* <code><pre>
* IMqttToken conToken;
* conToken = asyncClient.connect("some context",new new MqttAsyncActionListener() {
* public void onSuccess(IMqttToken asyncActionToken) {
* log("Connected");
* }
*
* public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
* log ("connect failed" +exception);
* }
* });
* </pre></code>
* An optional context object can be passed into the method which will then be made
* available in the callback. The context is stored by the MQTT client) in the token
* which is then returned to the invoker. The token is provided to the callback methods
* where the context can then be accessed.
* </p>
* </li>
* </ol>
* <p>To understand when the delivery of a message is complete either of the two methods above
* can be used to either wait on or be notified when the publish completes. An alternative is to
* use the {@link MqttCallback#deliveryComplete(IMqttDeliveryToken)} method which will
* also be notified when a message has been delivered to the requested quality of service.</p>
*
*/
public interface IMqttAsyncClient {
/**
* Connects to an MQTT server using the default options.
* <p>The default options are specified in {@link MqttConnectOptions} class.
* </p>
*
* @throws MqttSecurityException for security related problems
* @throws MqttException for non security related problems
* @return token used to track and wait for the connect to complete. The token
* will be passed to the callback methods if a callback is set.
* @see #connect(MqttConnectOptions, Object, IMqttActionListener)
*/
public IMqttToken connect() throws MqttException, MqttSecurityException;
/**
* Connects to an MQTT server using the provided connect options.
* <p>The connection will be established using the options specified in the
* {@link MqttConnectOptions} parameter.
* </p>
*
* @param options a set of connection parameters that override the defaults.
* @throws MqttSecurityException for security related problems
* @throws MqttException for non security related problems
* @return token used to track and wait for the connect to complete. The token
* will be passed to any callback that has been set.
* @see #connect(MqttConnectOptions, Object, IMqttActionListener)
*/
public IMqttToken connect(MqttConnectOptions options) throws MqttException, MqttSecurityException ;
/**
* Connects to an MQTT server using the default options.
* <p>The default options are specified in {@link MqttConnectOptions} class.
* </p>
*
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when the connect completes. Use
* null if not required.
* @throws MqttSecurityException for security related problems
* @throws MqttException for non security related problems
* @return token used to track and wait for the connect to complete. The token
* will be passed to any callback that has been set.
* @see #connect(MqttConnectOptions, Object, IMqttActionListener)
*/
public IMqttToken connect(Object userContext, IMqttActionListener callback) throws MqttException, MqttSecurityException;
/**
* Connects to an MQTT server using the specified options.
* <p>The server to connect to is specified on the constructor.
* It is recommended to call {@link #setCallback(MqttCallback)} prior to
* connecting in order that messages destined for the client can be accepted
* as soon as the client is connected.
* </p>
* <p>The method returns control before the connect completes. Completion can
* be tracked by:
* <ul>
* <li>Waiting on the returned token {@link IMqttToken#waitForCompletion()} or</li>
* <li>Passing in a callback {@link IMqttActionListener}</li>
* </ul>
* </p>
*
* @param options a set of connection parameters that override the defaults.
* @param userContext optional object for used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when the connect completes. Use
* null if not required.
* @return token used to track and wait for the connect to complete. The token
* will be passed to any callback that has been set.
* @throws MqttSecurityException for security related problems
* @throws MqttException for non security related problems including communication errors
*/
public IMqttToken connect(MqttConnectOptions options, Object userContext, IMqttActionListener callback) throws MqttException, MqttSecurityException;
/**
* Disconnects from the server.
* <p>An attempt is made to quiesce the client allowing outstanding
* work to complete before disconnecting. It will wait
* for a maximum of 30 seconds for work to quiesce before disconnecting.
* This method must not be called from inside {@link MqttCallback} methods.
* </p>
*
* @return token used to track and wait for disconnect to complete. The token
* will be passed to any callback that has been set.
* @throws MqttException for problems encountered while disconnecting
* @see #disconnect(long, Object, IMqttActionListener)
*/
public IMqttToken disconnect( ) throws MqttException;
/**
* Disconnects from the server.
* <p>An attempt is made to quiesce the client allowing outstanding
* work to complete before disconnecting. It will wait
* for a maximum of the specified quiesce time for work to complete before disconnecting.
* This method must not be called from inside {@link MqttCallback} methods.
* </p>
* @param quiesceTimeout the amount of time in milliseconds to allow for
* existing work to finish before disconnecting. A value of zero or less
* means the client will not quiesce.
* @return token used to track and wait for disconnect to complete. The token
* will be passed to the callback methods if a callback is set.
* @throws MqttException for problems encountered while disconnecting
* @see #disconnect(long, Object, IMqttActionListener)
*/
public IMqttToken disconnect(long quiesceTimeout) throws MqttException;
/**
* Disconnects from the server.
* <p>An attempt is made to quiesce the client allowing outstanding
* work to complete before disconnecting. It will wait
* for a maximum of 30 seconds for work to quiesce before disconnecting.
* This method must not be called from inside {@link MqttCallback} methods.
* </p>
*
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when the disconnect completes. Use
* null if not required.
* @return token used to track and wait for the disconnect to complete. The token
* will be passed to any callback that has been set.
* @throws MqttException for problems encountered while disconnecting
* @see #disconnect(long, Object, IMqttActionListener)
*/
public IMqttToken disconnect( Object userContext, IMqttActionListener callback) throws MqttException;
/**
* Disconnects from the server.
* <p>
* The client will wait for {@link MqttCallback} methods to
* complete. It will then wait for up to the quiesce timeout to allow for
* work which has already been initiated to complete. For instance when a QoS 2
* message has started flowing to the server but the QoS 2 flow has not completed.It
* prevents new messages being accepted and does not send any messages that have
* been accepted but not yet started delivery across the network to the server. When
* work has completed or after the quiesce timeout, the client will disconnect from
* the server. If the cleanSession flag was set to false and is set to false the
* next time a connection is made QoS 1 and 2 messages that
* were not previously delivered will be delivered.</p>
* <p>This method must not be called from inside {@link MqttCallback} methods.</p>
* <p>The method returns control before the disconnect completes. Completion can
* be tracked by:
* <ul>
* <li>Waiting on the returned token {@link IMqttToken#waitForCompletion()} or</li>
* <li>Passing in a callback {@link IMqttActionListener}</li>
* </ul>
* </p>
*
* @param quiesceTimeout the amount of time in milliseconds to allow for
* existing work to finish before disconnecting. A value of zero or less
* means the client will not quiesce.
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when the disconnect completes. Use
* null if not required.
* @return token used to track and wait for the connect to complete. The token
* will be passed to any callback that has been set.
* @throws MqttException for problems encountered while disconnecting
*/
public IMqttToken disconnect(long quiesceTimeout, Object userContext, IMqttActionListener callback) throws MqttException;
/**
* Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
* <p>
* Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to
* send the disconnect packet. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting and
* wait for a maximum of 10 seconds for sending the disconnect packet to server.
*
* @throws MqttException if any unexpected error
* @since 0.4.1
*/
public void disconnectForcibly() throws MqttException;
/**
* Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
* <p>
* Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to
* send the disconnect packet. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting.
*
* @param disconnectTimeout the amount of time in milliseconds to allow send disconnect packet to server.
* @throws MqttException if any unexpected error
* @since 0.4.1
*/
public void disconnectForcibly(long disconnectTimeout) throws MqttException;
/**
* Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
* <p>
* Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to
* send the disconnect packet.
*
* @param quiesceTimeout the amount of time in milliseconds to allow for existing work to finish before
* disconnecting. A value of zero or less means the client will not quiesce.
* @param disconnectTimeout the amount of time in milliseconds to allow send disconnect packet to server.
* @throws MqttException if any unexpected error
* @since 0.4.1
*/
public void disconnectForcibly(long quiesceTimeout, long disconnectTimeout) throws MqttException;
/**
* Determines if this client is currently connected to the server.
*
* @return <code>true</code> if connected, <code>false</code> otherwise.
*/
public boolean isConnected();
/**
* Returns the client ID used by this client.
* <p>All clients connected to the
* same server or server farm must have a unique ID.
* </p>
*
* @return the client ID used by this client.
*/
public String getClientId();
/**
* Returns the address of the server used by this client.
* <p>The format of the returned String is the same as that used on the constructor.
* </p>
*
* @return the server's address, as a URI String.
* @see MqttAsyncClient#MqttAsyncClient(String, String)
*/
public String getServerURI();
/**
* Publishes a message to a topic on the server.
* <p>A convenience method, which will
* create a new {@link MqttMessage} object with a byte array payload and the
* specified QoS, and then publish it.
* </p>
*
* @param topic to deliver the message to, for example "finance/stock/ibm".
* @param payload the byte array to use as the payload
* @param qos the Quality of Service to deliver the message at. Valid values are 0, 1 or 2.
* @param retained whether or not this message should be retained by the server.
* @return token used to track and wait for the publish to complete. The token
* will be passed to any callback that has been set.
* @throws MqttPersistenceException when a problem occurs storing the message
* @throws IllegalArgumentException if value of QoS is not 0, 1 or 2.
* @throws MqttException for other errors encountered while publishing the message.
* For instance if too many messages are being processed.
* @see #publish(String, MqttMessage, Object, IMqttActionListener)
* @see MqttMessage#setQos(int)
* @see MqttMessage#setRetained(boolean)
*/
public IMqttDeliveryToken publish(String topic, byte[] payload, int qos,
boolean retained ) throws MqttException, MqttPersistenceException;
/**
* Publishes a message to a topic on the server.
* <p>A convenience method, which will
* create a new {@link MqttMessage} object with a byte array payload and the
* specified QoS, and then publish it.
* </p>
*
* @param topic to deliver the message to, for example "finance/stock/ibm".
* @param payload the byte array to use as the payload
* @param qos the Quality of Service to deliver the message at. Valid values are 0, 1 or 2.
* @param retained whether or not this message should be retained by the server.
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when message delivery
* hsa completed to the requested quality of service
* @return token used to track and wait for the publish to complete. The token
* will be passed to any callback that has been set.
* @throws MqttPersistenceException when a problem occurs storing the message
* @throws IllegalArgumentException if value of QoS is not 0, 1 or 2.
* @throws MqttException for other errors encountered while publishing the message.
* For instance client not connected.
* @see #publish(String, MqttMessage, Object, IMqttActionListener)
* @see MqttMessage#setQos(int)
* @see MqttMessage#setRetained(boolean)
*/
public IMqttDeliveryToken publish(String topic, byte[] payload, int qos,
boolean retained, Object userContext, IMqttActionListener callback ) throws MqttException, MqttPersistenceException;
/**
* Publishes a message to a topic on the server.
* Takes an {@link MqttMessage} message and delivers it to the server at the
* requested quality of service.
*
* @param topic to deliver the message to, for example "finance/stock/ibm".
* @param message to deliver to the server
* @return token used to track and wait for the publish to complete. The token
* will be passed to any callback that has been set.
* @throws MqttPersistenceException when a problem occurs storing the message
* @throws IllegalArgumentException if value of QoS is not 0, 1 or 2.
* @throws MqttException for other errors encountered while publishing the message.
* For instance client not connected.
* @see #publish(String, MqttMessage, Object, IMqttActionListener)
*/
public IMqttDeliveryToken publish(String topic, MqttMessage message ) throws MqttException, MqttPersistenceException;
/**
* Publishes a message to a topic on the server.
* <p>
* Once this method has returned cleanly, the message has been accepted for publication by the
* client and will be delivered on a background thread.
* In the event the connection fails or the client stops. Messages will be delivered to the
* requested quality of service once the connection is re-established to the server on condition that:
* <ul>
* <li>The connection is re-established with the same clientID
* <li>The original connection was made with (@link MqttConnectOptions#setCleanSession(boolean)}
* set to false
* <li>The connection is re-established with (@link MqttConnectOptions#setCleanSession(boolean)}
* set to false
* <li>Depending when the failure occurs QoS 0 messages may not be delivered.
* </ul>
* </p>
*
* <p>When building an application,
* the design of the topic tree should take into account the following principles
* of topic name syntax and semantics:</p>
*
* <ul>
* <li>A topic must be at least one character long.</li>
* <li>Topic names are case sensitive. For example, <em>ACCOUNTS</em> and <em>Accounts</em> are
* two different topics.</li>
* <li>Topic names can include the space character. For example, <em>Accounts
* payable</em> is a valid topic.</li>
* <li>A leading "/" creates a distinct topic. For example, <em>/finance</em> is
* different from <em>finance</em>. <em>/finance</em> matches "+/+" and "/+", but
* not "+".</li>
* <li>Do not include the null character (Unicode <samp class="codeph">\x0000</samp>) in
* any topic.</li>
* </ul>
*
* <p>The following principles apply to the construction and content of a topic
* tree:</p>
*
* <ul>
* <li>The length is limited to 64k but within that there are no limits to the
* number of levels in a topic tree.</li>
* <li>There can be any number of root nodes; that is, there can be any number
* of topic trees.</li>
* </ul>
* </p>
* <p>The method returns control before the publish completes. Completion can
* be tracked by:
* <ul>
* <li>Setting an {@link IMqttAsyncClient#setCallback(MqttCallback)} where the
* {@link MqttCallback#deliveryComplete(IMqttDeliveryToken)}
* method will be called.</li>
* <li>Waiting on the returned token {@link MqttToken#waitForCompletion()} or</li>
* <li>Passing in a callback {@link IMqttActionListener} to this method</li>
* </ul>
* </p>
*
* @param topic to deliver the message to, for example "finance/stock/ibm".
* @param message to deliver to the server
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when message delivery
* has completed to the requested quality of service
* @return token used to track and wait for the publish to complete. The token
* will be passed to callback methods if set.
* @throws MqttPersistenceException when a problem occurs storing the message
* @throws IllegalArgumentException if value of QoS is not 0, 1 or 2.
* @throws MqttException for other errors encountered while publishing the message.
* For instance client not connected.
* @see MqttMessage
*/
public IMqttDeliveryToken publish(String topic, MqttMessage message,
Object userContext, IMqttActionListener callback) throws MqttException, MqttPersistenceException;
/**
* Subscribe to a topic, which may include wildcards.
*
* @see #subscribe(String[], int[], Object, IMqttActionListener)
*
* @param topicFilter the topic to subscribe to, which can include wildcards.
* @param qos the maximum quality of service at which to subscribe. Messages
* published at a lower quality of service will be received at the published
* QoS. Messages published at a higher quality of service will be received using
* the QoS specified on the subscribe.
* @return token used to track and wait for the subscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error registering the subscription.
*/
public IMqttToken subscribe(String topicFilter, int qos) throws MqttException;
/**
* Subscribe to a topic, which may include wildcards.
*
* @see #subscribe(String[], int[], Object, IMqttActionListener)
*
* @param topicFilter the topic to subscribe to, which can include wildcards.
* @param qos the maximum quality of service at which to subscribe. Messages
* published at a lower quality of service will be received at the published
* QoS. Messages published at a higher quality of service will be received using
* the QoS specified on the subscribe.
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when subscribe
* has completed
* @return token used to track and wait for the subscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error registering the subscription.
*/
public IMqttToken subscribe(String topicFilter, int qos, Object userContext, IMqttActionListener callback)
throws MqttException;
/**
* Subscribe to multiple topics, each of which may include wildcards.
*
* <p>Provides an optimized way to subscribe to multiple topics compared to
* subscribing to each one individually.</p>
*
* @see #subscribe(String[], int[], Object, IMqttActionListener)
*
* @param topicFilters one or more topics to subscribe to, which can include wildcards
* @param qos the maximum quality of service at which to subscribe. Messages
* published at a lower quality of service will be received at the published
* QoS. Messages published at a higher quality of service will be received using
* the QoS specified on the subscribe.
* @return token used to track and wait for the subscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error registering the subscription.
*/
public IMqttToken subscribe(String[] topicFilters, int[] qos) throws MqttException;
/**
* Subscribes to multiple topics, each of which may include wildcards.
* <p>Provides an optimized way to subscribe to multiple topics compared to
* subscribing to each one individually.</p>
* <p>The {@link #setCallback(MqttCallback)} method
* should be called before this method, otherwise any received messages
* will be discarded.
* </p>
* <p>
* If (@link MqttConnectOptions#setCleanSession(boolean)} was set to true
* when when connecting to the server then the subscription remains in place
* until either:
* <ul>
* <li>The client disconnects</li>
* <li>An unsubscribe method is called to un-subscribe the topic</li>
* </li>
* </p>
* <p>
* If (@link MqttConnectOptions#setCleanSession(boolean)} was set to false
* when connecting to the server then the subscription remains in place
* until either:
* <ul>
* <li>An unsubscribe method is called to unsubscribe the topic</li>
* <li>The next time the client connects with cleanSession set to true</ul>
* </li>
* With cleanSession set to false the MQTT server will store messages on
* behalf of the client when the client is not connected. The next time the
* client connects with the <bold>same client ID</bold> the server will
* deliver the stored messages to the client.
* </p>
*
* <p>The "topic filter" string used when subscribing
* may contain special characters, which allow you to subscribe to multiple topics
* at once.</p>
* <p>The topic level separator is used to introduce structure into the topic, and
* can therefore be specified within the topic for that purpose. The multi-level
* wildcard and single-level wildcard can be used for subscriptions, but they
* cannot be used within a topic by the publisher of a message.
* <dl>
* <dt>Topic level separator</dt>
* <dd>The forward slash (/) is used to separate each level within
* a topic tree and provide a hierarchical structure to the topic space. The
* use of the topic level separator is significant when the two wildcard characters
* are encountered in topics specified by subscribers.</dd>
*
* <dt>Multi-level wildcard</dt>
* <dd><p>The number sign (#) is a wildcard character that matches
* any number of levels within a topic. For example, if you subscribe to
* <span><span class="filepath">finance/stock/ibm/#</span></span>, you receive
* messages on these topics:
* <pre> finance/stock/ibm<br /> finance/stock/ibm/closingprice<br /> finance/stock/ibm/currentprice</pre>
* </p>
* <p>The multi-level wildcard
* can represent zero or more levels. Therefore, <em>finance/#</em> can also match
* the singular <em>finance</em>, where <em>#</em> represents zero levels. The topic
* level separator is meaningless in this context, because there are no levels
* to separate.</p>
*
* <p>The <span>multi-level</span> wildcard can
* be specified only on its own or next to the topic level separator character.
* Therefore, <em>#</em> and <em>finance/#</em> are both valid, but <em>finance#</em> is
* not valid. <span>The multi-level wildcard must be the last character
* used within the topic tree. For example, <em>finance/#</em> is valid but
* <em>finance/#/closingprice</em> is not valid.</span></p></dd>
*
* <dt>Single-level wildcard</dt>
* <dd><p>The plus sign (+) is a wildcard character that matches only one topic
* level. For example, <em>finance/stock/+</em> matches
* <em>finance/stock/ibm</em> and <em>finance/stock/xyz</em>,
* but not <em>finance/stock/ibm/closingprice</em>. Also, because the single-level
* wildcard matches only a single level, <em>finance/+</em> does not match <em>finance</em>.</p>
*
* <p>Use
* the single-level wildcard at any level in the topic tree, and in conjunction
* with the multilevel wildcard. Specify the single-level wildcard next to the
* topic level separator, except when it is specified on its own. Therefore,
* <em>+</em> and <em>finance/+</em> are both valid, but <em>finance+</em> is
* not valid. <span>The single-level wildcard can be used at the end of the
* topic tree or within the topic tree.
* For example, <em>finance/+</em> and <em>finance/+/ibm</em> are both valid.</span></p>
* </dd>
* </dl>
* </p>
* <p>The method returns control before the subscribe completes. Completion can
* be tracked by:
* <ul>
* <li>Waiting on the supplied token {@link MqttToken#waitForCompletion()} or</li>
* <li>Passing in a callback {@link IMqttActionListener} to this method</li>
* </ul>
* </p>
*
* @param topicFilters one or more topics to subscribe to, which can include wildcards
* @param qos the maximum quality of service to subscribe each topic at.Messages
* published at a lower quality of service will be received at the published
* QoS. Messages published at a higher quality of service will be received using
* the QoS specified on the subscribe.
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when subscribe
* has completed
* @return token used to track and wait for the subscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error registering the subscription.
* @throws IllegalArgumentException if the two supplied arrays are not the same size.
*/
public IMqttToken subscribe(String[] topicFilters, int[] qos, Object userContext, IMqttActionListener callback)
throws MqttException;
/**
* Requests the server unsubscribe the client from a topic.
*
* @see #unsubscribe(String[], Object, IMqttActionListener)
* @param topicFilter the topic to unsubscribe from. It must match a topicFilter
* specified on an earlier subscribe.
* @return token used to track and wait for the unsubscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error unregistering the subscription.
*/
public IMqttToken unsubscribe(String topicFilter) throws MqttException;
/**
* Requests the server unsubscribe the client from one or more topics.
*
* @see #unsubscribe(String[], Object, IMqttActionListener)
*
* @param topicFilters one or more topics to unsubscribe from. Each topicFilter
* must match one specified on an earlier subscribe. *
* @return token used to track and wait for the unsubscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error unregistering the subscription.
*/
public IMqttToken unsubscribe(String[] topicFilters) throws MqttException;
/**
* Requests the server unsubscribe the client from a topics.
*
* @see #unsubscribe(String[], Object, IMqttActionListener)
*
* @param topicFilter the topic to unsubscribe from. It must match a topicFilter
* specified on an earlier subscribe.
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when unsubscribe
* has completed
* @return token used to track and wait for the unsubscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error unregistering the subscription.
*/
public IMqttToken unsubscribe(String topicFilter, Object userContext, IMqttActionListener callback)
throws MqttException;
/**
* Requests the server unsubscribe the client from one or more topics.
* <p>
* Unsubcribing is the opposite of subscribing. When the server receives the
* unsubscribe request it looks to see if it can find a matching subscription for the
* client and then removes it. After this point the server will send no more
* messages to the client for this subscription.
* </p>
* <p>The topic(s) specified on the unsubscribe must match the topic(s)
* specified in the original subscribe request for the unsubscribe to succeed
* </p>
* <p>The method returns control before the unsubscribe completes. Completion can
* be tracked by:
* <ul>
* <li>Waiting on the returned token {@link MqttToken#waitForCompletion()} or</li>
* <li>Passing in a callback {@link IMqttActionListener} to this method</li>
* </ul>
* </p>
*
* @param topicFilters one or more topics to unsubscribe from. Each topicFilter
* must match one specified on an earlier subscribe.
* @param userContext optional object used to pass context to the callback. Use
* null if not required.
* @param callback optional listener that will be notified when unsubscribe
* has completed
* @return token used to track and wait for the unsubscribe to complete. The token
* will be passed to callback methods if set.
* @throws MqttException if there was an error unregistering the subscription.
*/
public IMqttToken unsubscribe(String[] topicFilters, Object userContext, IMqttActionListener callback)
throws MqttException;
/**
* Sets a callback listener to use for events that happen asynchronously.
* <p>There are a number of events that the listener will be notified about.
* These include:
* <ul>
* <li>A new message has arrived and is ready to be processed</li>
* <li>The connection to the server has been lost</li>
* <li>Delivery of a message to the server has completed</li>
* </ul>
* </p>
* <p>Other events that track the progress of an individual operation such
* as connect and subscribe can be tracked using the {@link MqttToken} returned from
* each non-blocking method or using setting a {@link IMqttActionListener} on the
* non-blocking method.<p>
* @see MqttCallback
* @param callback which will be invoked for certain asynchronous events
*/
public void setCallback(MqttCallback callback);
/**
* Returns the delivery tokens for any outstanding publish operations.
* <p>If a client has been restarted and there are messages that were in the
* process of being delivered when the client stopped this method
* returns a token for each in-flight message enabling the delivery to be tracked
* Alternately the {@link MqttCallback#deliveryComplete(IMqttDeliveryToken)}
* callback can be used to track the delivery of outstanding messages.
* </p>
* <p>If a client connects with cleanSession true then there will be no
* delivery tokens as the cleanSession option deletes all earlier state.
* For state to be remembered the client must connect with cleanSession
* set to false</P>
* @return zero or more delivery tokens
*/
public IMqttDeliveryToken[] getPendingDeliveryTokens();
/**
* Close the client
* Releases all resource associated with the client. After the client has
* been closed it cannot be reused. For instance attempts to connect will fail.
* @throws MqttException if the client is not disconnected.
*/
public void close() throws MqttException;
}
| gpl-3.0 |
danifelipe/freedots | src/freedots/music/ClefChange.java | 3135 | /* -*- c-basic-offset: 2; indent-tabs-mode: nil; -*- */
/*
* FreeDots -- MusicXML to braille music transcription
*
* Copyright 2008-2010 Mario Lang All Rights Reserved.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 3, as
* published by the Free Software Foundation.
*
* 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
* for more details (a copy is included in the LICENSE.txt file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License
* along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This file is maintained by Mario Lang <mlang@delysid.org>.
*/
package freedots.music;
import freedots.Braille;
import freedots.math.Fraction;
/** Indicates a change of a clef at a certain musical duration and staff.
*/
public final class ClefChange implements StaffElement {
private final Fraction moment;
private Clef clef;
private int staffNumber;
private Staff staff;
public ClefChange(final Fraction moment,
final Clef clef, final int staffNumber) {
this.moment = moment;
this.clef = clef;
this.staffNumber = staffNumber;
}
public Clef getClef() { return clef; }
public int getStaffNumber() { return staffNumber; }
public Fraction getMoment() { return moment; }
public Staff getStaff() { return staff; }
public void setStaff(Staff staff) { this.staff = staff; }
public boolean isRest() { return false; }
@Deprecated
public String toBrailleString() {
if (moment.compareTo(Fraction.ZERO) > 0) {
Clef initialClef = staff.getClef();
if (initialClef.isBass())
if (clef.isTreble()) {
return String.valueOf(Braille.unicodeBraille(Braille.dotsToBits(345)))
+ Braille.unicodeBraille(Braille.dotsToBits(34))
+ Braille.unicodeBraille(Braille.dotsToBits(13));
}
else if (initialClef.isTreble())
if (clef.isBass()) {
return "" + Braille.unicodeBraille(Braille.dotsToBits(345)) +
Braille.unicodeBraille(Braille.dotsToBits(3456)) +
Braille.unicodeBraille(Braille.dotsToBits(13));
}
}
if (clef.isTreble())
return "" + Braille.unicodeBraille(Braille.dotsToBits(345)) +
Braille.unicodeBraille(Braille.dotsToBits(34)) +
Braille.unicodeBraille(Braille.dotsToBits(123));
else if (clef.isBass())
return "" + Braille.unicodeBraille(Braille.dotsToBits(345)) +
Braille.unicodeBraille(Braille.dotsToBits(3456)) +
Braille.unicodeBraille(Braille.dotsToBits(123));
return "UNHANDLED CLEF";
}
public boolean equalsIgnoreOffset(Event other) {
if (other instanceof ClefChange) {
return clef.equals(((ClefChange)other).getClef());
}
return false;
}
}
| gpl-3.0 |
norbim1/axoloti | src/main/java/components/displays/VLineComponentDB.java | 2867 | /**
* Copyright (C) 2013, 2014 Johannes Taelman
*
* This file is part of Axoloti.
*
* Axoloti is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* Axoloti 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
* Axoloti. If not, see <http://www.gnu.org/licenses/>.
*/
package components.displays;
import axoloti.Theme;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
/**
*
* @author Johannes Taelman
*/
public class VLineComponentDB extends ADispComponent {
private double value;
private double max;
private double min;
int height = 128;
int width = 1;
public VLineComponentDB(double value, double min, double max) {
this.max = max;
this.min = min;
this.value = value;
Dimension d = new Dimension(width, height);
setPreferredSize(d);
setMaximumSize(d);
setMinimumSize(d);
}
int px;
final int margin = 0;
int ValToPos(double v) {
double dB = -1000;
if (v != 0) {
dB = 20 * Math.log10(Math.abs(v) / 64.0);
}
if (dB > max) {
dB = max;
}
if (dB < min) {
dB = min;
}
return (int) (margin + ((max - dB) * (height - 2 * margin)) / (max - min));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setPaint(Theme.getCurrentTheme().Component_Secondary);
g2.fillRect(0, 0, getWidth(), height);
int p = ValToPos(value);
int p1 = ValToPos(0);
g2.setPaint(Theme.getCurrentTheme().Component_Mid);
g2.drawLine(0, p, 0, p1);
}
@Override
public void setValue(double value) {
this.value = value;
if (this.value != value) {
this.value = value;
repaint();
}
}
public void setMinimum(double min) {
this.min = min;
}
public double getMinimum() {
return min;
}
public void setMaximum(double max) {
this.max = max;
}
public double getMaximum() {
return max;
}
}
| gpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/forms/patientproblemlist/BaseAccessLogic.java | 3520 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.spinalinjuries.forms.patientproblemlist;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
if(!form.getGlobalContext().Core.getCurrentCareContextIsNotNull())
return false;
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
}
}
}
| agpl-3.0 |
open-health-hub/openMAXIMS | openmaxims_workspace/Clinical/src/ims/clinical/forms/obspatientassessmentcc/BaseAccessLogic.java | 3776 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# 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 Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.forms.obspatientassessmentcc;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
Assessment = new AssessmentForms();
}
public final class AssessmentForms implements Serializable
{
private static final long serialVersionUID = 1L;
private AssessmentForms()
{
AssessmentsForSpecialty = new LocalFormName(127123);
}
public final FormName AssessmentsForSpecialty;
}
public AssessmentForms Assessment;
}
}
| agpl-3.0 |
victos/opencms-core | src/org/opencms/gwt/shared/alias/CmsAliasInitialFetchResult.java | 3660 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (C) Alkacon Software (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.gwt.shared.alias;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* The class used to transmit the original alias list when the alias editor dialog is first loaded.<p>
*/
public class CmsAliasInitialFetchResult implements IsSerializable {
/** The alias lock owner name (null if the current user is lock owner). */
private String m_aliasLockOwner;
/** The list of aliases. */
private List<CmsAliasTableRow> m_aliasRows;
/** The alias download URL. */
private String m_downloadUrl;
/** The initial list of rewrite aliases. */
private List<CmsRewriteAliasTableRow> m_rewriteAliases = new ArrayList<CmsRewriteAliasTableRow>();
/**
* Gets the alias lock owner.<p>
*
* This will return null if the current user is the lock owner.<p>
*
* @return the alias lock owner
*/
public String getAliasTableLockOwner() {
return m_aliasLockOwner;
}
/**
* Gets the alias download URL.<p>
*
* @return the alias download URL
*/
public String getDownloadUrl() {
return m_downloadUrl;
}
/**
* Gets the list of rewrite aliases.<p>
*
* @return the list of rewrite aliases
*/
public List<CmsRewriteAliasTableRow> getRewriteAliases() {
return m_rewriteAliases;
}
/**
* Gets the alias table rows.<p>
*
* @return the alias table rows
*/
public List<CmsAliasTableRow> getRows() {
return m_aliasRows;
}
/**
* Sets the alias lock owner name.<p>
*
* @param name the alias lock owner name
*/
public void setAliasLockOwner(String name) {
m_aliasLockOwner = name;
}
/**
* Sets the download URL for aliases.<p>
*
* @param downloadUrl the download URL for aliases
*/
public void setDownloadUrl(String downloadUrl) {
m_downloadUrl = downloadUrl;
}
/**
* Sets the initial list of rewrite aliases.<p>
*
* @param rows the list of rewrite aliases
*/
public void setRewriteRows(List<CmsRewriteAliasTableRow> rows) {
m_rewriteAliases = rows;
}
/**
* Sets the alias table rows.<p>
*
* @param rows the alias table rows
*/
public void setRows(List<CmsAliasTableRow> rows) {
m_aliasRows = rows;
}
}
| lgpl-2.1 |
paulklinkenberg/Lucee4 | lucee-java/lucee-core/src/lucee/runtime/functions/struct/StructIsEmpty.java | 1377 | /**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
/**
* Implements the CFML Function structisempty
*/
package lucee.runtime.functions.struct;
import lucee.runtime.PageContext;
import lucee.runtime.exp.PageException;
import lucee.runtime.functions.BIF;
import lucee.runtime.op.Caster;
import lucee.runtime.type.Struct;
public final class StructIsEmpty extends BIF {
private static final long serialVersionUID = 6804878535578055394L;
public static boolean call(PageContext pc , Struct struct) {
return struct.size()==0;
}
@Override
public Object invoke(PageContext pc, Object[] args) throws PageException {
return call(pc,Caster.toStruct(args[0]));
}
} | lgpl-2.1 |
paulklinkenberg/Lucee4 | lucee-java/lucee-core/src/lucee/runtime/functions/rest/RestInitApplication.java | 3655 | /**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.functions.rest;
import lucee.commons.io.res.Resource;
import lucee.commons.lang.StringUtil;
import lucee.runtime.PageContext;
import lucee.runtime.config.ConfigWebAdmin;
import lucee.runtime.config.ConfigWebImpl;
import lucee.runtime.exp.PageException;
import lucee.runtime.op.Caster;
import lucee.runtime.rest.Mapping;
import lucee.runtime.rest.RestUtil;
public class RestInitApplication {
public static String call(PageContext pc , String dirPath) throws PageException {
return _call(pc, dirPath, null,null,null);
}
public static String call(PageContext pc , String dirPath, String serviceMapping) throws PageException {
return _call(pc, dirPath, serviceMapping, null,null);
}
public static String call(PageContext pc , String dirPath, String serviceMapping, boolean defaultMapping) throws PageException {
return _call(pc, dirPath, serviceMapping, defaultMapping, null);
}
public static String call(PageContext pc , String dirPath, String serviceMapping, boolean defaultMapping, String webAdminPassword) throws PageException {
return _call(pc, dirPath, serviceMapping, defaultMapping, webAdminPassword);
}
public static String _call(PageContext pc , String dirPath, String serviceMapping, Boolean defaultMapping, String webAdminPassword) throws PageException {
if(StringUtil.isEmpty(serviceMapping,true)){
serviceMapping=pc.getApplicationContext().getName();
}
Resource dir=RestDeleteApplication.toResource(pc,dirPath);
ConfigWebImpl config=(ConfigWebImpl) pc.getConfig();
Mapping[] mappings = config.getRestMappings();
Mapping mapping;
// id is mapping name
String virtual=serviceMapping.trim();
if(!virtual.startsWith("/")) virtual="/"+virtual;
if(!virtual.endsWith("/")) virtual+="/";
boolean hasResetted=false;
for(int i=0;i<mappings.length;i++){
mapping=mappings[i];
if(mapping.getVirtualWithSlash().equals(virtual)){
// directory has changed
if(!RestUtil.isMatch(pc, mapping, dir) || (defaultMapping!=null && mapping.isDefault()!=defaultMapping.booleanValue())) {
update(pc,dir,virtual,RestDeleteApplication.getPassword(pc,webAdminPassword),defaultMapping==null?mapping.isDefault():defaultMapping.booleanValue());
}
mapping.reset(pc);
hasResetted=true;
}
}
if(!hasResetted) {
update(pc,dir,virtual,RestDeleteApplication.getPassword(pc,webAdminPassword),defaultMapping==null?false:defaultMapping.booleanValue());
}
return null;
}
private static void update(PageContext pc,Resource dir, String virtual, String webAdminPassword, boolean defaultMapping) throws PageException {
try {
ConfigWebAdmin admin = ConfigWebAdmin.newInstance((ConfigWebImpl)pc.getConfig(),webAdminPassword);
admin.updateRestMapping(virtual, dir.getAbsolutePath(), defaultMapping);
admin.store();
}
catch (Exception e) {
throw Caster.toPageException(e);
}
}
}
| lgpl-2.1 |
wolfgangmm/exist | exist-core/src/main/java/org/exist/security/realm/AuthenticatingRealm.java | 1234 | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* info@exist-db.org
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.security.realm;
import org.exist.security.AuthenticationException;
import org.exist.security.Subject;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public interface AuthenticatingRealm {
Subject authenticate(final String accountName, Object credentials) throws AuthenticationException;
}
| lgpl-2.1 |
wseyler/pentaho-kettle | engine/src/main/java/org/pentaho/di/trans/steps/excelinput/staxpoi/StaxPoiSheet.java | 16717 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2020 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/**
* Author = Shailesh Ahuja
*/
package org.pentaho.di.trans.steps.excelinput.staxpoi;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTXf;
import org.pentaho.di.core.spreadsheet.KCell;
import org.pentaho.di.core.spreadsheet.KCellType;
import org.pentaho.di.core.spreadsheet.KSheet;
import org.pentaho.di.core.xml.XMLParserFactoryProducer;
/**
* Streaming reader for XLSX sheets.<br>
* Rows should only be accessed sequentially: random access will severely impact performance.<br>
*/
public class StaxPoiSheet implements KSheet {
// set to UTC for coherence with PoiSheet
private static final TimeZone DATE_TZ = TimeZone.getTimeZone( "UTC" );
private static final String ATTRIBUTE_T = "t";
private static final String TAG_C = "c";
private static final String TAG_IS = "is";
private static final String TAG_ROW = "row";
private static final String TAG_SHEET_DATA = "sheetData";
private static final String TAG_T = "t";
private static final String TAG_V = "v";
private final String sheetName;
private final String sheetId;
private final XSSFReader xssfReader;
private InputStream sheetStream;
private XMLStreamReader sheetReader;
// hold the pointer to the current row so that access to the next row in the stream is quick and easy
private int currentRow;
private List<String> headerRow;
private int numRows;
private int numCols;
private boolean maxColsNumberDefined = true;
// 1-based first non-empty row
private int firstRow;
private KCell[] currentRowCells;
// full shared strings table
private SharedStringsTable sst;
// custom styles
private StylesTable styles;
public StaxPoiSheet( XSSFReader reader, String sheetName, String sheetID )
throws InvalidFormatException, IOException, XMLStreamException {
this.sheetName = sheetName;
xssfReader = reader;
sheetId = sheetID;
sst = reader.getSharedStringsTable();
styles = reader.getStylesTable();
sheetStream = reader.getSheet( sheetID );
XMLInputFactory factory = XMLParserFactoryProducer.createSecureXMLInputFactory();
sheetReader = factory.createXMLStreamReader( sheetStream );
headerRow = new ArrayList<>();
while ( sheetReader.hasNext() ) {
int event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT ) {
if ( sheetReader.getLocalName().equals( "dimension" ) ) {
String dim = sheetReader.getAttributeValue( null, "ref" );
// empty sheets have dimension with no range
if ( StringUtils.contains( dim, ':' ) ) {
dim = dim.split( ":" )[ 1 ];
numRows = StaxUtil.extractRowNumber( dim );
numCols = StaxUtil.extractColumnNumber( dim );
} else {
maxColsNumberDefined = false;
numCols = StaxUtil.MAX_COLUMNS;
numRows = StaxUtil.MAX_ROWS;
}
} else if ( sheetReader.getLocalName().equals( TAG_ROW ) ) {
currentRow = Integer.parseInt( sheetReader.getAttributeValue( null, "r" ) );
firstRow = currentRow;
// calculate the number of columns in the header row
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( TAG_ROW ) ) {
// if the row has ended, break the inner while loop
break;
}
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( TAG_C ) ) {
String attributeValue = sheetReader.getAttributeValue( null, ATTRIBUTE_T );
if ( attributeValue != null ) {
if ( attributeValue.equals( "s" ) ) {
// if the type of the cell is string, we continue
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( TAG_V ) ) {
int idx = Integer.parseInt( sheetReader.getElementText() );
String content = new XSSFRichTextString( sst.getEntryAt( idx ) ).toString();
headerRow.add( content );
break;
}
}
} else if ( attributeValue.equals( "inlineStr" ) ) {
// if the type of the cell is string, we continue
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( TAG_IS ) ) {
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.CHARACTERS ) {
String content = new XSSFRichTextString( sheetReader.getText() ).toString();
headerRow.add( content );
break;
}
if ( event == XMLStreamConstants.END_ELEMENT ) {
if ( sheetReader.getLocalName().equals( TAG_T ) ) {
// If "t" ended, this is a 'blank' cell
headerRow.add( "" );
break;
} else if ( sheetReader.getLocalName().equals( TAG_IS ) ) {
// If "is" ended, this is a 'null' cell
headerRow.add( null );
break;
}
}
}
break;
}
}
}
} else {
// Most probably a 'null' cell, but let's make sure...
if ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( TAG_C ) ) {
// Yes, it is a 'null' cell!
headerRow.add( null );
continue;
}
}
break;
}
}
}
// we have parsed the header row
break;
}
}
}
}
boolean isMaxColsNumberDefined() {
return maxColsNumberDefined;
}
@Override
public KCell[] getRow( int rownr ) {
// xlsx raw row numbers are 1-based index, KSheet is 0-based
// Don't check the upper limit as not all rows may have been read!
// If it's found that the row does not exist, the exception will be thrown at the end of this method.
if ( rownr < 0 ) {
// KSheet requires out of bounds here
throw new ArrayIndexOutOfBoundsException( rownr );
}
if ( rownr + 1 < firstRow ) {
// before first non-empty row
return new KCell[0];
}
if ( rownr > 0 && currentRow == rownr + 1 ) {
if ( currentRowCells != null ) {
return currentRowCells;
}
// The case when the table contains the empty row(s) before the header
// but at the same time user wants to read starting from 0 row
return new KCell[0];
}
try {
if ( currentRow >= rownr + 1 ) {
// allow random access per api despite performance hit
resetSheetReader();
}
while ( sheetReader.hasNext() ) {
int event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( TAG_ROW ) ) {
String rowIndicator = sheetReader.getAttributeValue( null, "r" );
currentRow = Integer.parseInt( rowIndicator );
if ( currentRow < rownr + 1 ) {
continue;
}
currentRowCells = parseRow();
return currentRowCells;
}
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( TAG_SHEET_DATA ) ) {
// There're no more columns, no need to continue to read
break;
}
}
} catch ( Exception e ) {
throw new RuntimeException( e );
}
// We've read all document rows, let's update the final count.
numRows = currentRow;
// And, as this was an invalid row to ask for, throw the proper exception!
throw new ArrayIndexOutOfBoundsException( rownr );
}
private KCell[] parseRow() throws XMLStreamException {
List<StaxPoiCell> cells;
if ( isMaxColsNumberDefined() ) {
cells = new ArrayList<>( numCols );
} else {
cells = new ArrayList<>();
}
int undefinedColIndex = 0;
for ( int i = 0; i < numCols; i++ ) {
// go to the "c" cell tag
while ( sheetReader.hasNext() ) {
int event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( TAG_C ) ) {
break;
}
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( TAG_ROW ) ) {
// premature end of row, returning what we have
return cells.toArray( new StaxPoiCell[cells.size()] );
}
}
// We're on the "c" cell tag
String cellLocation = sheetReader.getAttributeValue( null, "r" );
int columnIndex = StaxUtil.extractColumnNumber( cellLocation ) - 1;
String cellType = sheetReader.getAttributeValue( null, ATTRIBUTE_T );
String cellStyle = sheetReader.getAttributeValue( null, "s" );
boolean isFormula = false;
String content = null;
// get value tag
while ( sheetReader.hasNext() ) {
int event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT ) {
if ( sheetReader.getLocalName().equals( TAG_V ) ) {
// read content as string
if ( cellType != null && cellType.equals( "s" ) ) {
int idx = Integer.parseInt( sheetReader.getElementText() );
content = new XSSFRichTextString( sst.getEntryAt( idx ) ).toString();
} else {
content = sheetReader.getElementText();
}
} else if ( sheetReader.getLocalName().equals( TAG_IS ) ) {
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.CHARACTERS ) {
content = new XSSFRichTextString( sheetReader.getText() ).toString();
break;
}
if ( event == XMLStreamConstants.END_ELEMENT ) {
if ( sheetReader.getLocalName().equals( TAG_T ) ) {
// If "t" ended, this is a 'blank' cell
content = "";
break;
} else if ( sheetReader.getLocalName().equals( TAG_IS ) ) {
// If "is" ended, this is a 'null' cell
content = null;
break;
}
}
}
} else if ( sheetReader.getLocalName().equals( "f" ) ) {
isFormula = true;
}
}
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( TAG_C ) ) {
break;
}
}
if ( content != null ) {
KCellType kcType = getCellType( cellType, cellStyle, isFormula );
setCells( cells, undefinedColIndex, columnIndex, new StaxPoiCell( parseValue( kcType, content ), kcType, currentRow ) );
} else {
// else let cell be null
setCells( cells, undefinedColIndex, columnIndex, null );
}
undefinedColIndex = columnIndex + 1;
}
return cells.toArray( new StaxPoiCell[cells.size()] );
}
private static void setCells( List<StaxPoiCell> cellsArray, int firstUndefinedColIndex, int foundColIndex, StaxPoiCell cell ) {
// fill all cells before found with Null
for ( int index = firstUndefinedColIndex; index < foundColIndex; index++ ) {
cellsArray.add( null );
}
// add the found Cell
cellsArray.add( cell );
}
@Override
public String getName() {
return sheetName;
}
@Override
public int getRows() {
return numRows;
}
@Override
public KCell getCell( int colnr, int rownr ) {
if ( rownr == 0 && colnr < headerRow.size() ) {
// only possible to return header
return new StaxPoiCell( headerRow.get( colnr ), rownr );
}
// if random access this will be very expensive
KCell[] row = getRow( rownr );
if ( row != null && rownr < row.length ) {
return row[colnr];
}
return null;
}
private KCellType getCellType( String cellType, String cellStyle, boolean isFormula ) {
// numeric type can be implicit or 'n'
if ( cellType == null || cellType.equals( "n" ) ) {
// the only difference between date and numeric is the cell format
if ( isDateCell( cellStyle ) ) {
return isFormula ? KCellType.DATE_FORMULA : KCellType.DATE;
}
return isFormula ? KCellType.NUMBER_FORMULA : KCellType.NUMBER;
}
switch ( cellType ) {
case "s":
return KCellType.LABEL;
case "b":
return isFormula ? KCellType.BOOLEAN_FORMULA : KCellType.BOOLEAN;
case "e":
// error
return KCellType.EMPTY;
case "str":
default:
return KCellType.STRING_FORMULA;
}
}
@VisibleForTesting
protected boolean isDateCell( String cellStyle ) {
if ( cellStyle != null ) {
int styleIdx = Integer.parseInt( cellStyle );
CTXf cellXf = styles.getCellXfAt( styleIdx );
if ( cellXf != null ) {
// need id for builtin types, format if custom
short formatId = (short) cellXf.getNumFmtId();
String format = styles.getNumberFormatAt( formatId );
return DateUtil.isADateFormat( formatId, format );
}
}
return false;
}
private Object parseValue( KCellType type, String vContent ) {
if ( vContent == null ) {
return null;
}
try {
switch ( type ) {
case NUMBER:
case NUMBER_FORMULA:
return Double.parseDouble( vContent );
case BOOLEAN:
case BOOLEAN_FORMULA:
return vContent.equals( "1" );
case DATE:
case DATE_FORMULA:
Double xlDate = Double.parseDouble( vContent );
return DateUtil.getJavaDate( xlDate, DATE_TZ );
case LABEL:
case STRING_FORMULA:
case EMPTY:
default:
return vContent;
}
} catch ( Exception e ) {
return vContent;
}
}
private void resetSheetReader() throws IOException, XMLStreamException, InvalidFormatException {
sheetReader.close();
sheetStream.close();
sheetStream = xssfReader.getSheet( sheetId );
XMLInputFactory factory = XMLParserFactoryProducer.createSecureXMLInputFactory();
sheetReader = factory.createXMLStreamReader( sheetStream );
}
public void close() throws IOException, XMLStreamException {
sheetReader.close();
sheetStream.close();
}
}
| apache-2.0 |
MikeThomsen/nifi | nifi-registry/nifi-registry-core/nifi-registry-test/src/main/java/org/apache/nifi/registry/db/MySql7DataSourceFactory.java | 1381 | /*
* 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.nifi.registry.db;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.testcontainers.containers.MySQLContainer;
@Configuration
@Profile({"mysql", "mysql-57"})
public class MySql7DataSourceFactory extends MySqlDataSourceFactory {
private static final MySQLContainer MYSQL_CONTAINER = new MySqlCustomContainer("mysql:5.7");
static {
MYSQL_CONTAINER.start();
}
@Override
protected MySQLContainer mysqlContainer() {
return MYSQL_CONTAINER;
}
}
| apache-2.0 |
spring-projects/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBean.java | 3988 | /*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.condition;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.Conditional;
/**
* {@link Conditional @Conditional} that only matches when beans meeting all the specified
* requirements are already contained in the {@link BeanFactory}. All the requirements
* must be met for the condition to match, but they do not have to be met by the same
* bean.
* <p>
* When placed on a {@code @Bean} method, the bean class defaults to the return type of
* the factory method:
*
* <pre class="code">
* @Configuration
* public class MyAutoConfiguration {
*
* @ConditionalOnBean
* @Bean
* public MyService myService() {
* ...
* }
*
* }</pre>
* <p>
* In the sample above the condition will match if a bean of type {@code MyService} is
* already contained in the {@link BeanFactory}.
* <p>
* The condition can only match the bean definitions that have been processed by the
* application context so far and, as such, it is strongly recommended to use this
* condition on auto-configuration classes only. If a candidate bean may be created by
* another auto-configuration, make sure that the one using this condition runs after.
*
* @author Phillip Webb
* @since 1.0.0
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnBean {
/**
* The class types of beans that should be checked. The condition matches when beans
* of all classes specified are contained in the {@link BeanFactory}.
* @return the class types of beans to check
*/
Class<?>[] value() default {};
/**
* The class type names of beans that should be checked. The condition matches when
* beans of all classes specified are contained in the {@link BeanFactory}.
* @return the class type names of beans to check
*/
String[] type() default {};
/**
* The annotation type decorating a bean that should be checked. The condition matches
* when all of the annotations specified are defined on beans in the
* {@link BeanFactory}.
* @return the class-level annotation types to check
*/
Class<? extends Annotation>[] annotation() default {};
/**
* The names of beans to check. The condition matches when all of the bean names
* specified are contained in the {@link BeanFactory}.
* @return the names of beans to check
*/
String[] name() default {};
/**
* Strategy to decide if the application context hierarchy (parent contexts) should be
* considered.
* @return the search strategy
*/
SearchStrategy search() default SearchStrategy.ALL;
/**
* Additional classes that may contain the specified bean types within their generic
* parameters. For example, an annotation declaring {@code value=Name.class} and
* {@code parameterizedContainer=NameRegistration.class} would detect both
* {@code Name} and {@code NameRegistration<Name>}.
* @return the container types
* @since 2.1.0
*/
Class<?>[] parameterizedContainer() default {};
}
| apache-2.0 |
wanhao/IRIndex | src/test/java/org/apache/hadoop/hbase/mttr/IntegrationTestMTTR.java | 16615 | /**
* 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.hadoop.hbase.mttr;
import com.google.common.base.Objects;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.apache.hadoop.hbase.ClusterStatus;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.IntegrationTestingUtility;
import org.apache.hadoop.hbase.IntegrationTests;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.KeyOnlyFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ChaosMonkey;
import org.apache.hadoop.hbase.util.LoadTestTool;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static junit.framework.Assert.assertEquals;
/**
* Integration test that should benchmark how fast HBase can recover from failures. This test starts
* different threads:
* <ol>
* <li>
* Load Test Tool.<br/>
* This runs so that all RegionServers will have some load and HLogs will be full.
* </li>
* <li>
* Scan thread.<br/>
* This thread runs a very short scan over and over again recording how log it takes to respond.
* The longest response is assumed to be the time it took to recover.
* </li>
* <li>
* Put thread.<br/>
* This thread just like the scan thread except it does a very small put.
* </li>
* <li>
* Admin thread. <br/>
* This thread will continually go to the master to try and get the cluster status. Just like the
* put and scan threads, the time to respond is recorded.
* </li>
* <li>
* Chaos Monkey thread.<br/>
* This thread runs a ChaosMonkey.Action.
* </li>
* </ol>
* <p/>
* The ChaosMonkey actions currently run are:
* <ul>
* <li>Restart the RegionServer holding meta.</li>
* <li>Restart the RegionServer holding the table the scan and put threads are targeting.</li>
* <li>Move the Regions of the table used by the scan and put threads.</li>
* <li>Restart the master.</li>
* </ul>
* <p/>
* At the end of the test a log line is output on the INFO level containing the timing data that was
* collected.
*/
@Category(IntegrationTests.class)
public class IntegrationTestMTTR {
/**
* Constants.
*/
private static final byte[] FAMILY = Bytes.toBytes("d");
private static final Log LOG = LogFactory.getLog(IntegrationTestMTTR.class);
private static final long SLEEP_TIME = 60 * 1000l;
/**
* Configurable table names.
*/
private static String tableName;
private static byte[] tableNameBytes;
private static String loadTableName;
private static byte[] loadTableNameBytes;
/**
* Util to get at the cluster.
*/
private static IntegrationTestingUtility util;
/**
* Executor for test threads.
*/
private static ExecutorService executorService;
/**
* All of the chaos monkey actions used.
*/
private static ChaosMonkey.Action restartRSAction;
private static ChaosMonkey.Action restartMetaAction;
private static ChaosMonkey.Action moveRegionAction;
private static ChaosMonkey.Action restartMasterAction;
/**
* The load test tool used to create load and make sure that HLogs aren't empty.
*/
private static LoadTestTool loadTool;
@BeforeClass
public static void setUp() throws Exception {
// Set up the integration test util
if (util == null) {
util = new IntegrationTestingUtility();
}
// Make sure there are three servers.
util.initializeCluster(3);
// Set up the load test tool.
loadTool = new LoadTestTool();
loadTool.setConf(util.getConfiguration());
// Create executor with enough threads to restart rs's,
// run scans, puts, admin ops and load test tool.
executorService = Executors.newFixedThreadPool(8);
// Set up the tables needed.
setupTables();
// Set up the actions.
setupActions();
}
private static void setupActions() throws IOException {
// Set up the action that will restart a region server holding a region from our table
// because this table should only have one region we should be good.
restartRSAction = new ChaosMonkey.RestartRsHoldingTable(SLEEP_TIME, tableName);
// Set up the action that will kill the region holding meta.
restartMetaAction = new ChaosMonkey.RestartRsHoldingMeta(SLEEP_TIME);
// Set up the action that will move the regions of our table.
moveRegionAction = new ChaosMonkey.MoveRegionsOfTable(SLEEP_TIME, tableName);
// Kill the master
restartMasterAction = new ChaosMonkey.RestartActiveMaster(1000);
// Give the action the access to the cluster.
ChaosMonkey.ActionContext actionContext = new ChaosMonkey.ActionContext(util);
restartRSAction.init(actionContext);
restartMetaAction.init(actionContext);
moveRegionAction.init(actionContext);
restartMasterAction.init(actionContext);
}
private static void setupTables() throws IOException {
// Get the table name.
tableName = util.getConfiguration()
.get("hbase.IntegrationTestMTTR.tableName", "IntegrationTestMTTR");
tableNameBytes = Bytes.toBytes(tableName);
loadTableName = util.getConfiguration()
.get("hbase.IntegrationTestMTTR.loadTableName", "IntegrationTestMTTRLoadTestTool");
loadTableNameBytes = Bytes.toBytes(loadTableName);
if (util.getHBaseAdmin().tableExists(tableNameBytes)) {
util.deleteTable(tableNameBytes);
}
if (util.getHBaseAdmin().tableExists(loadTableName)) {
util.deleteTable(loadTableNameBytes);
}
// Create the table. If this fails then fail everything.
HTableDescriptor tableDescriptor = new HTableDescriptor(tableNameBytes);
// Make the max file size huge so that splits don't happen during the test.
tableDescriptor.setMaxFileSize(Long.MAX_VALUE);
HColumnDescriptor descriptor = new HColumnDescriptor(FAMILY);
descriptor.setMaxVersions(1);
tableDescriptor.addFamily(descriptor);
util.getHBaseAdmin().createTable(tableDescriptor);
// Setup the table for LoadTestTool
int ret = loadTool.run(new String[]{"-tn", loadTableName, "-init_only"});
assertEquals("Failed to initialize LoadTestTool", 0, ret);
}
@AfterClass
public static void after() throws IOException {
// Clean everything up.
util.restoreCluster();
util = null;
// Stop the threads so that we know everything is complete.
executorService.shutdown();
executorService = null;
// Clean up the actions.
moveRegionAction = null;
restartMetaAction = null;
restartRSAction = null;
restartMasterAction = null;
loadTool = null;
}
@Test
public void testRestartRsHoldingTable() throws Exception {
run(new ActionCallable(restartRSAction), "RestartRsHoldingTable");
}
@Test
public void testKillRsHoldingMeta() throws Exception {
run(new ActionCallable(restartMetaAction), "KillRsHoldingMeta");
}
@Test
public void testMoveRegion() throws Exception {
run(new ActionCallable(moveRegionAction), "MoveRegion");
}
@Test
public void testRestartMaster() throws Exception {
run(new ActionCallable(restartMasterAction), "RestartMaster");
}
public void run(Callable<Boolean> monkeyCallable, String testName) throws Exception {
int maxIters = util.getHBaseClusterInterface().isDistributedCluster() ? 10 : 3;
// Array to keep track of times.
ArrayList<TimingResult> resultPuts = new ArrayList<TimingResult>(maxIters);
ArrayList<TimingResult> resultScan = new ArrayList<TimingResult>(maxIters);
ArrayList<TimingResult> resultAdmin = new ArrayList<TimingResult>(maxIters);
long start = System.nanoTime();
// We're going to try this multiple times
for (int fullIterations = 0; fullIterations < maxIters; fullIterations++) {
// Create and start executing a callable that will kill the servers
Future<Boolean> monkeyFuture = executorService.submit(monkeyCallable);
// Pass that future to the timing Callables.
Future<TimingResult> putFuture = executorService.submit(new PutCallable(monkeyFuture));
Future<TimingResult> scanFuture = executorService.submit(new ScanCallable(monkeyFuture));
Future<TimingResult> adminFuture = executorService.submit(new AdminCallable(monkeyFuture));
Future<Boolean> loadFuture = executorService.submit(new LoadCallable(monkeyFuture));
monkeyFuture.get();
loadFuture.get();
// Get the values from the futures.
TimingResult putTime = putFuture.get();
TimingResult scanTime = scanFuture.get();
TimingResult adminTime = adminFuture.get();
// Store the times to display later.
resultPuts.add(putTime);
resultScan.add(scanTime);
resultAdmin.add(adminTime);
// Wait some time for everything to settle down.
Thread.sleep(5000l);
}
long runtimeMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
Objects.ToStringHelper helper = Objects.toStringHelper("MTTRResults")
.add("putResults", resultPuts)
.add("scanResults", resultScan)
.add("adminResults", resultAdmin)
.add("totalRuntimeMs", runtimeMs)
.add("name", testName);
// Log the info
LOG.info(helper.toString());
}
/**
* Class to store results of TimingCallable.
*
* Stores times and trace id.
*/
private class TimingResult {
DescriptiveStatistics stats = new DescriptiveStatistics();
/**
* Add a result to this aggregate result.
* @param time Time in nanoseconds
* @param span Span. To be kept if the time taken was over 1 second
*/
public void addResult(long time) {
stats.addValue(TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS));
}
public String toString() {
Objects.ToStringHelper helper = Objects.toStringHelper(this)
.add("numResults", stats.getN())
.add("minTime", stats.getMin())
.add("meanTime", stats.getMean())
.add("maxTime", stats.getMax())
.add("25th", stats.getPercentile(25))
.add("50th", stats.getPercentile(50))
.add("75th", stats.getPercentile(75))
.add("90th", stats.getPercentile(90))
.add("95th", stats.getPercentile(95))
.add("99th", stats.getPercentile(99))
.add("99.9th", stats.getPercentile(99.9))
.add("99.99th", stats.getPercentile(99.99));
return helper.toString();
}
}
/**
* Base class for actions that need to record the time needed to recover from a failure.
*/
public abstract class TimingCallable implements Callable<TimingResult> {
protected final Future future;
public TimingCallable(Future f) {
future = f;
}
@Override
public TimingResult call() throws Exception {
TimingResult result = new TimingResult();
int numAfterDone = 0;
// Keep trying until the rs is back up and we've gotten a put through
while (numAfterDone < 10) {
long start = System.nanoTime();
try {
boolean actionResult = doAction();
if (actionResult && future.isDone()) {
numAfterDone ++;
}
} catch (Exception e) {
numAfterDone = 0;
}
result.addResult(System.nanoTime() - start);
}
return result;
}
protected abstract boolean doAction() throws Exception;
protected String getSpanName() {
return this.getClass().getSimpleName();
}
}
/**
* Callable that will keep putting small amounts of data into a table
* until the future supplied returns. It keeps track of the max time.
*/
public class PutCallable extends TimingCallable {
private final HTable table;
public PutCallable(Future f) throws IOException {
super(f);
this.table = new HTable(util.getConfiguration(), tableNameBytes);
}
@Override
protected boolean doAction() throws Exception {
Put p = new Put(Bytes.toBytes(RandomStringUtils.randomAlphanumeric(5)));
p.add(FAMILY, Bytes.toBytes("\0"), Bytes.toBytes(RandomStringUtils.randomAscii(5)));
table.put(p);
table.flushCommits();
return true;
}
@Override
protected String getSpanName() {
return "MTTR Put Test";
}
}
/**
* Callable that will keep scanning for small amounts of data until the
* supplied future returns. Returns the max time taken to scan.
*/
public class ScanCallable extends TimingCallable {
private final HTable table;
public ScanCallable(Future f) throws IOException {
super(f);
this.table = new HTable(util.getConfiguration(), tableNameBytes);
}
@Override
protected boolean doAction() throws Exception {
ResultScanner rs = null;
try {
Scan s = new Scan();
s.setBatch(2);
s.addFamily(FAMILY);
s.setFilter(new KeyOnlyFilter());
s.setMaxVersions(1);
rs = table.getScanner(s);
Result result = rs.next();
return rs != null && result != null && result.size() > 0;
} finally {
if (rs != null) {
rs.close();
}
}
}
@Override
protected String getSpanName() {
return "MTTR Scan Test";
}
}
/**
* Callable that will keep going to the master for cluster status. Returns the max time taken.
*/
public class AdminCallable extends TimingCallable {
public AdminCallable(Future f) throws IOException {
super(f);
}
@Override
protected boolean doAction() throws Exception {
HBaseAdmin admin = new HBaseAdmin(util.getConfiguration());
ClusterStatus status = admin.getClusterStatus();
return status != null;
}
@Override
protected String getSpanName() {
return "MTTR Admin Test";
}
}
public class ActionCallable implements Callable<Boolean> {
private final ChaosMonkey.Action action;
public ActionCallable(ChaosMonkey.Action action) {
this.action = action;
}
@Override
public Boolean call() throws Exception {
this.action.perform();
return true;
}
}
/**
* Callable used to make sure the cluster has some load on it.
* This callable uses LoadTest tool to
*/
public class LoadCallable implements Callable<Boolean> {
private final Future future;
public LoadCallable(Future f) {
future = f;
}
@Override
public Boolean call() throws Exception {
int colsPerKey = 10;
int recordSize = 500;
int numServers = util.getHBaseClusterInterface().getInitialClusterStatus().getServersSize();
int numKeys = numServers * 5000;
int writeThreads = 10;
// Loop until the chaos monkey future is done.
// But always go in just in case some action completes quickly
do {
int ret = loadTool.run(new String[]{
"-tn", loadTableName,
"-write", String.format("%d:%d:%d", colsPerKey, recordSize, writeThreads),
"-num_keys", String.valueOf(numKeys),
"-skip_init"
});
assertEquals("Load failed", 0, ret);
} while (!future.isDone());
return true;
}
}
}
| apache-2.0 |