repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
harfalm/Sakai-10.1 | gradebook/app/standalone-app/src/test/org/sakaiproject/tool/gradebook/test/TestServiceAgainstLoadedData.java | 7767 | /**********************************************************************************
*
* $Id: TestServiceAgainstLoadedData.java 105079 2012-02-24 23:08:11Z ottenhoff@longsight.com $
*
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-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.sakaiproject.tool.gradebook.test;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.section.api.coursemanagement.EnrollmentRecord;
import org.sakaiproject.section.api.facade.Role;
import org.sakaiproject.tool.gradebook.Assignment;
import org.sakaiproject.tool.gradebook.Gradebook;
/**
* This odd-looking JUnit class provides a very primitive test for data
* contention when using the external service API. You'll see what look like
* the same "tests" several times in a row. The idea is to run the test from
* multiple windows simultaneously and try for locking exceptions.
*
* Pretty cheap stuff, but it took less time to get going than trying to
* coordinate one of the JUnit multi-threading add-on projects with
* Spring and Hivernate....
*
* Sample usage:
*
* # Build standalone and load up the test database.
* cd ../sections/
* maven -Dmode=standalone -Dhibernate.properties.dir=C:/java/sakaisettings/mysql-standalone cln bld
* cd ../gradebook
* maven -Dhibernate.properties.dir=C:/java/sakaisettings/mysql-standalone cln bld
* maven -Dhibernate.properties.dir=C:/java/sakaisettings/mysql-standalone load-full-standalone
*
* # Then do this from as many windows as you feel up to.
* cd app/standalone-app/
* maven -Dhibernate.properties.dir=C:/java/sakaisettings/mysql-standalone test-against-loaded-data
*/
public class TestServiceAgainstLoadedData extends GradebookLoaderBase {
private static final Log log = LogFactory.getLog(TestServiceAgainstLoadedData.class);
public TestServiceAgainstLoadedData() {
// Don't roll these tests back, since they are intended to act like real-world users.
setDefaultRollback(false);
}
private Assignment getAssignment(Gradebook gradebook, String assignmentName) {
List assignments = gradebookManager.getAssignments(gradebook.getId());
for (Iterator iter = assignments.iterator(); iter.hasNext();) {
Assignment asn = (Assignment)iter.next();
if (asn.getName().equals(assignmentName)) {
return asn;
}
}
return null;
}
public void testUpdateExternalScores() throws Exception {
Gradebook gradebook = gradebookManager.getGradebook(TestGradebookLoader.GRADEBOOK_WITH_GRADES);
List enrollments = sectionAwareness.getSiteMembersInRole(gradebook.getUid(), Role.STUDENT);
Assignment asn = getAssignment(gradebook, TestGradebookLoader.EXTERNAL_ASN_NAME1);
Map studentUidsToScores = new HashMap();
int scoreGoRound = -1;
for (Iterator iter = enrollments.iterator(); iter.hasNext(); ) {
EnrollmentRecord enr = (EnrollmentRecord)iter.next();
String score = (scoreGoRound == -1) ? null : new Integer(scoreGoRound).toString();
scoreGoRound = (scoreGoRound < 11) ? (scoreGoRound + 1) : -1;
studentUidsToScores.put(enr.getUser().getUserUid(), score);
}
log.warn("about to updateExternalAssessmentScores with " + enrollments.size() + " scores for " + asn.getExternalId());
gradebookExternalAssessmentService.updateExternalAssessmentScoresString(gradebook.getUid(), asn.getExternalId(), studentUidsToScores);
}
public void testUpdateExternalScore() throws Exception {
Gradebook gradebook = gradebookManager.getGradebook(TestGradebookLoader.GRADEBOOK_WITH_GRADES);
List enrollments = sectionAwareness.getSiteMembersInRole(gradebook.getUid(), Role.STUDENT);
Assignment asn = getAssignment(gradebook, TestGradebookLoader.EXTERNAL_ASN_NAME2);
int scoreGoRound = 2;
for (Iterator iter = enrollments.iterator(); iter.hasNext(); ) {
EnrollmentRecord enr = (EnrollmentRecord)iter.next();
Double score = (scoreGoRound == -1) ? null : new Double(scoreGoRound);
scoreGoRound = (scoreGoRound < 11) ? (scoreGoRound + 1) : -1;
gradebookExternalAssessmentService.updateExternalAssessmentScore(gradebook.getUid(), asn.getExternalId(), enr.getUser().getUserUid(), score.toString());
}
}
public void testUpdateExternalScores2() throws Exception {
Gradebook gradebook = gradebookManager.getGradebook(TestGradebookLoader.GRADEBOOK_WITH_GRADES);
List enrollments = sectionAwareness.getSiteMembersInRole(gradebook.getUid(), Role.STUDENT);
Assignment asn = getAssignment(gradebook, TestGradebookLoader.EXTERNAL_ASN_NAME2);
Map studentUidsToScores = new HashMap();
int scoreGoRound = -1;
for (Iterator iter = enrollments.iterator(); iter.hasNext(); ) {
EnrollmentRecord enr = (EnrollmentRecord)iter.next();
String score = (scoreGoRound == -1) ? null : new Double(scoreGoRound).toString();
scoreGoRound = (scoreGoRound < 11) ? (scoreGoRound + 1) : -1;
studentUidsToScores.put(enr.getUser().getUserUid(), score);
}
log.warn("about to updateExternalAssessmentScores with " + enrollments.size() + " scores for " + asn.getExternalId());
gradebookExternalAssessmentService.updateExternalAssessmentScoresString(gradebook.getUid(), asn.getExternalId(), studentUidsToScores);
}
public void testUpdateExternalScore2() throws Exception {
Gradebook gradebook = gradebookManager.getGradebook(TestGradebookLoader.GRADEBOOK_WITH_GRADES);
List enrollments = sectionAwareness.getSiteMembersInRole(gradebook.getUid(), Role.STUDENT);
Assignment asn = getAssignment(gradebook, TestGradebookLoader.EXTERNAL_ASN_NAME1);
int scoreGoRound = 2;
for (Iterator iter = enrollments.iterator(); iter.hasNext(); ) {
EnrollmentRecord enr = (EnrollmentRecord)iter.next();
Double score = (scoreGoRound == -1) ? null : new Double(scoreGoRound);
scoreGoRound = (scoreGoRound < 11) ? (scoreGoRound + 1) : -1;
gradebookExternalAssessmentService.updateExternalAssessmentScore(gradebook.getUid(), asn.getExternalId(), enr.getUser().getUserUid(), score.toString());
}
}
public void testUpdateExternalScores2Same() throws Exception {
Gradebook gradebook = gradebookManager.getGradebook(TestGradebookLoader.GRADEBOOK_WITH_GRADES);
List enrollments = sectionAwareness.getSiteMembersInRole(gradebook.getUid(), Role.STUDENT);
Assignment asn = getAssignment(gradebook, TestGradebookLoader.EXTERNAL_ASN_NAME2);
Map studentUidsToScores = new HashMap();
int scoreGoRound = -1;
for (Iterator iter = enrollments.iterator(); iter.hasNext(); ) {
EnrollmentRecord enr = (EnrollmentRecord)iter.next();
String score = (scoreGoRound == -1) ? null : new Double(scoreGoRound).toString();
scoreGoRound = (scoreGoRound < 11) ? (scoreGoRound + 1) : -1;
studentUidsToScores.put(enr.getUser().getUserUid(), score);
}
log.warn("about to updateExternalAssessmentScores with " + enrollments.size() + " scores for " + asn.getExternalId());
gradebookExternalAssessmentService.updateExternalAssessmentScoresString(gradebook.getUid(), asn.getExternalId(), studentUidsToScores);
}
}
| apache-2.0 |
liquibase/liquibase | liquibase-core/src/main/java/liquibase/logging/core/CompositeLogService.java | 1060 | package liquibase.logging.core;
import liquibase.Scope;
import liquibase.logging.LogService;
import liquibase.logging.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CompositeLogService extends AbstractLogService {
private List<LogService> services = new ArrayList<>();
public CompositeLogService() {
}
public CompositeLogService(boolean includeCurrentScopeLogService, LogService... logService) {
this.services = new ArrayList<>(Arrays.asList(logService));
if (includeCurrentScopeLogService) {
services.add(Scope.getCurrentScope().get(Scope.Attr.logService, LogService.class));
}
}
@Override
public int getPriority() {
return PRIORITY_NOT_APPLICABLE;
}
@Override
public Logger getLog(Class clazz) {
List<Logger> loggers = new ArrayList<>();
for (LogService service : services) {
loggers.add(service.getLog(clazz));
}
return new CompositeLogger(loggers, this.filter);
}
}
| apache-2.0 |
alibaba/fastjson | src/test/java/com/alibaba/json/bvt/bug/Bug_for_stv_liu.java | 1573 | package com.alibaba.json.bvt.bug;
import java.io.Serializable;
import org.junit.Assert;
import junit.framework.TestCase;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class Bug_for_stv_liu extends TestCase {
protected void setUp() throws Exception {
com.alibaba.fastjson.parser.ParserConfig.global.addAccept("com.alibaba.json.bvt.bug.Bug_for_stv_liu.");
}
public void test() {
User user = new User();
user.setId("1");
user.setUsername("test");
String json = JSON.toJSONString(user, SerializerFeature.WriteClassName);
user = (User) JSON.parse(json);// 此处抛异常
Assert.assertNotNull(user);
}
public static interface IdEntity<T extends Serializable> extends Serializable {
T getId();
void setId(T id);
}
public static class BaseEntity implements IdEntity<String> {
private static final long serialVersionUID = 1L;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public static class User extends BaseEntity {
private String username;
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
}
}
| apache-2.0 |
intrigus/jtransc | jtransc-rt/src/java/lang/annotation/ElementType.java | 755 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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 java.lang.annotation;
public enum ElementType {TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE}
| apache-2.0 |
rritoch/gemini.blueprint | integration-tests/bundles/reference.test.bundle/src/main/java/org/eclipse/gemini/blueprint/iandt/reference/proxy/ServiceReferer.java | 1168 | /******************************************************************************
* Copyright (c) 2006, 2010 VMware Inc., Oracle Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html and the Apache License v2.0
* is available at http://www.opensource.org/licenses/apache2.0.php.
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
* VMware Inc.
* Oracle Inc.
*****************************************************************************/
package org.eclipse.gemini.blueprint.iandt.reference.proxy;
import org.eclipse.gemini.blueprint.iandt.simpleservice.MyService;
/**
* @author Hal Hildebrand
* Date: Nov 25, 2006
* Time: 12:50:20 PM
*/
public class ServiceReferer {
public static MyService serviceReference;
public void setReference(MyService reference) {
serviceReference = reference;
}
}
| apache-2.0 |
apiman/apiman-test | apiman-it-ui/src/test/java/io/apiman/test/integration/ui/support/selenide/pages/plans/CreatePlanVersionPage.java | 1518 | /*
* Copyright 2016 Red Hat 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 io.apiman.test.integration.ui.support.selenide.pages.plans;
import io.apiman.test.integration.ui.support.selenide.PageLocation;
import io.apiman.test.integration.ui.support.selenide.components.CreateEntityVersionForm;
import io.apiman.test.integration.ui.support.selenide.layouts.AbstractPage;
import io.apiman.test.integration.ui.support.selenide.pages.plans.detail.AbstractPlanDetailPage;
import io.apiman.test.integration.ui.support.selenide.pages.plans.detail.PlanDetailPage;
/**
* Created by Jarek Kaspar
*/
@PageLocation("/api-manager/orgs/{0}/plans/{1}/{2}/new-version")
public class CreatePlanVersionPage extends AbstractPage<CreatePlanVersionPage>
implements CreateEntityVersionForm<CreatePlanVersionPage> {
/**
* Click the create button
* @return PlanDetailPage page object
*/
public AbstractPlanDetailPage create() {
return create(PlanDetailPage.class);
}
}
| apache-2.0 |
AndroidX/constraintlayout | desktop/CycleEditor/src/main/java/androidx/motionlayout/cycleEditor/AnimationPanel.java | 8958 | /*
* Copyright (C) 2019 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 androidx.motionlayout.cycleEditor;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.geom.AffineTransform;
/**
* This panel simulates and Android view parameter for controlling a button
*/
class AnimationPanel extends JPanel {
public static final String[] EASING_OPTIONS = Easing.NAMED_EASING;
private static final boolean RENDERING_STATS = Boolean.parseBoolean(System.getProperty("stats"));
private float mDuration = 20000; // duration in milliseconds
private float myAnimationPercent;
private long myLastTime;
private static final int BUTTON_WIDTH = 123;
private static final int BUTTON_HEIGHT = 40;
private String myTitle = "button";
private JButton myPlayButton;
private boolean myIsPlaying = false;
private Timer myPlayTimer = new Timer(14, e -> step());
private CycleSetModel myCycleModel;
private int myAttributeMask;
private Easing myEasing = Easing.getInterpolator(Easing.STANDARD_NAME);
private float myEasedPercent;
static final Stroke DASH_STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
1, new float[]{10, 10}, 0);
AnimationPanel(CycleSetModel cycleModel, JButton play) {
super(new FlowLayout(FlowLayout.LEFT));
setBackground(new Color(0xF8F8F4));
setBorder(new LineBorder(new Color(0x888888), 1));
myCycleModel = cycleModel;
myPlayButton = play;
myPlayButton.addActionListener(e -> play());
}
public void setEasing(String easing) {
myEasing = Easing.getInterpolator(easing);
}
public void setModel(CycleSetModel cycleModel) {
myCycleModel = cycleModel;
}
public void setMode() {
myAttributeMask = myCycleModel.getAttributeMask();
}
public void play() {
if (myIsPlaying) {
myCycleModel.setDot(Float.NaN);
pause();
myIsPlaying = false;
return;
}
myPlayButton.setText("pause");
myIsPlaying = true;
myAttributeMask = myCycleModel.getAttributeMask();
myPlayTimer.start();
}
int call_count = 0;
int paint_count = 0;
long last_update;
public void step() {
long time = System.currentTimeMillis();
myAnimationPercent += (time - myLastTime) / mDuration;
if (myAnimationPercent > 1.0f) {
myAnimationPercent = 0;
}
myEasedPercent = (float) myEasing.get(myAnimationPercent);
myCycleModel.setDot(myEasedPercent);
call_count++;
repaint();
myLastTime = time;
}
public void pause() {
myPlayButton.setText("play");
myPlayTimer.stop();
}
@Override
public void paint(Graphics g) {
super.paint(g);
paint_count++;
long time = System.currentTimeMillis();
int w = getWidth();
int h = getHeight();
float buttonCX = w / 2.0f;
float buttonCY = h / 2.0f;
float startX = buttonCX;
float startY = buttonCY;
float endX = buttonCX;
float endY = buttonCY;
if (myMoveObject != 0) {
float dx = movement[myMoveObject][0];
float dy = movement[myMoveObject][1];
startX = buttonCX - (dx * w) / 3.0f;
startY = buttonCY - (dy * h) / 3.0f;
endX = buttonCX + (dx * w) / 3.0f;
endY = buttonCY + (dy * h) / 3.0f;
buttonCX = startX + myEasedPercent * (endX - startX);
buttonCY = startY + myEasedPercent * (endY - startY);
}
Graphics2D g2d = (Graphics2D) g.create();
AffineTransform at;
Stroke old = g2d.getStroke();
g2d.setColor(Color.RED);
g2d.setStroke(DASH_STROKE);
g2d.drawLine((int) startX, (int) startY, (int) endX, (int) endY);
g2d.setStroke(old);
Color background = Color.LIGHT_GRAY;
Color border = Color.DARK_GRAY;
Color text = Color.BLACK;
if (myAttributeMask != 0) {
if ((myAttributeMask & (1 << CycleView.Prop.PATH_ROTATE.ordinal())) != 0) {
at = new AffineTransform();
at.rotate(Math.toRadians(myCycleModel.getValue(CycleView.Prop.PATH_ROTATE, myEasedPercent)), buttonCX,
buttonCY);
g2d.transform(at);
}
if ((myAttributeMask & (1 << CycleView.Prop.ALPHA.ordinal())) != 0) {
int alpha = Math
.max(0, Math.min(255, (int) (myCycleModel.getValue(CycleView.Prop.ALPHA, myEasedPercent) * 255)));
background = new Color(background.getRed(), background.getGreen(), background.getBlue(),
alpha);
border = new Color(border.getRed(), border.getGreen(), border.getBlue(), alpha);
text = new Color(text.getRed(), text.getGreen(), text.getBlue(), alpha);
}
if ((myAttributeMask & (1 << CycleView.Prop.SCALE_X.ordinal())) != 0) {
at = new AffineTransform();
at.translate(w / 2.0, buttonCY);
at.scale(myCycleModel.getValue(CycleView.Prop.SCALE_X, myEasedPercent), 1);
at.translate(-w / 2.0, -buttonCY);
g2d.transform(at);
}
if ((myAttributeMask & (1 << CycleView.Prop.SCALE_Y.ordinal())) != 0) {
at = new AffineTransform();
at.translate(buttonCX, buttonCY);
at.scale(1, myCycleModel.getValue(CycleView.Prop.SCALE_Y, myEasedPercent));
at.translate(-buttonCX, -buttonCY);
g2d.transform(at);
}
if ((myAttributeMask & (1 << CycleView.Prop.TRANSLATION_X.ordinal())) != 0) {
at = new AffineTransform();
at.translate(myCycleModel.getValue(CycleView.Prop.TRANSLATION_X, myEasedPercent), 0);
g2d.transform(at);
}
if ((myAttributeMask & (1 << CycleView.Prop.TRANSLATION_Y.ordinal())) != 0) {
at = new AffineTransform();
at.translate(0, myCycleModel.getValue(CycleView.Prop.TRANSLATION_Y, myEasedPercent));
g2d.transform(at);
}
if ((myAttributeMask & (1 << CycleView.Prop.ROTATION.ordinal())) != 0) {
at = new AffineTransform();
at.rotate(Math.toRadians(myCycleModel.getValue(CycleView.Prop.ROTATION, myEasedPercent)), buttonCX,
buttonCY);
g2d.transform(at);
}
}
int px = (int) (0.5 + buttonCX - BUTTON_WIDTH / 2.0f);
int py = (int) (0.5 + buttonCY - BUTTON_HEIGHT / 2.0f);
g2d.setColor(background);
g2d.fillRoundRect(px, py, BUTTON_WIDTH, BUTTON_HEIGHT, 5, 5);
g2d.setColor(border);
g2d.drawRoundRect(px, py, BUTTON_WIDTH, BUTTON_HEIGHT, 5, 5);
int sw = g.getFontMetrics().stringWidth(myTitle);
int fh = g.getFontMetrics().getHeight();
int fa = g.getFontMetrics().getAscent();
g2d.setColor(text);
g2d.drawString(myTitle, px + BUTTON_WIDTH / 2 - sw / 2, py + BUTTON_HEIGHT / 2 + fa - fh / 2);
if (time - last_update > 1000) {
if (RENDERING_STATS) {
System.out.println("render" + 1000 * call_count / (time - last_update) + "fps paint "
+ 1000 * paint_count / (time - last_update) + "fps");
}
last_update = time;
paint_count = 0;
call_count = 0;
}
}
static String[] MOVE_NAMES = {"Stationary", "South to North", "West to East", "SW to NE",
"NW to SE", "SE to NW", "NE to SW"};
static String[] DURATION = {"0.1s", "0.5s", "1.0s", "2.0s", "5s", "10s", "20s"};
static int[] DURATION_VAL = {100, 500, 1000, 2000, 5000, 10000, 20000};
static int[][] movement = {
{0, 0},
{0, -1},
{1, 0},
{1, -1},
{1, 1},
{-1, -1},
{-1, 1},
};
int myMoveObject = 0;
public void setMovement(int move) {
myMoveObject = move;
repaint();
}
public void setDurationIndex(int selectedIndex) {
mDuration = DURATION_VAL[selectedIndex];
}
}
| apache-2.0 |
commoncrawl/nutch | src/plugin/publish-rabbitmq/src/java/org/apache/nutch/publisher/rabbitmq/RabbitMQConstants.java | 1448 | /*
* 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.nutch.publisher.rabbitmq;
interface RabbitMQConstants {
String RABBIT_PREFIX = "rabbitmq.publisher.";
String SERVER_URI = RABBIT_PREFIX + "server.uri";
String EXCHANGE_NAME = RABBIT_PREFIX + "exchange.name";
String EXCHANGE_OPTIONS = RABBIT_PREFIX + "exchange.options";
String QUEUE_NAME = RABBIT_PREFIX + "queue.name";
String QUEUE_OPTIONS = RABBIT_PREFIX + "queue.options";
String ROUTING_KEY = RABBIT_PREFIX + "routingkey";
String BINDING = RABBIT_PREFIX + "binding";
String BINDING_ARGUMENTS = RABBIT_PREFIX + "binding.arguments";
String HEADERS_STATIC = RABBIT_PREFIX + "headers.static";
}
| apache-2.0 |
nevenr/jolokia | agent/core/src/test/java/org/jolokia/detector/JBossDetectorTest.java | 8976 | package org.jolokia.detector;
/*
* Copyright 2009-2011 Roland Huss
*
* 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.
*/
import java.lang.instrument.Instrumentation;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import javax.management.*;
import org.jolokia.backend.executor.MBeanServerExecutor;
import org.jolokia.request.JmxRequest;
import org.jolokia.request.JmxRequestBuilder;
import org.jolokia.util.RequestType;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*;
/**
* @author roland
* @since 02.09.11
*/
public class JBossDetectorTest extends BaseDetectorTest {
private JBossDetector detector;
private MBeanServer server;
private MBeanServerExecutor servers;
@BeforeMethod
public void setup() {
detector = new JBossDetector();
server = createMock(MBeanServer.class);
servers = getMBeanServerManager(server);
}
@Test
public void simpleNotFound() throws MalformedObjectNameException {
for (String name : new String[]{
"jboss.system:type=Server",
"jboss.as:*",
"jboss.modules:*"
}) {
expect(server.queryNames(new ObjectName(name), null)).andReturn(Collections.<ObjectName>emptySet()).anyTimes();
}
replay(server);
assertNull(detector.detect(servers));
verify(server);
}
@Test
public void simpleFound() throws MalformedObjectNameException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException, IntrospectionException {
expect(server.queryNames(new ObjectName("jboss.as:management-root=server"),null)).andReturn(Collections.EMPTY_SET);
ObjectName oName = prepareQuery("jboss.system:type=Server");
expect(server.isRegistered(oName)).andStubReturn(true);
expect(server.getAttribute(oName, "Version")).andReturn("5.1.0");
replay(server);
ServerHandle handle = detector.detect(servers);
assertEquals(handle.getVersion(),"5.1.0");
assertEquals(handle.getVendor(),"RedHat");
assertEquals(handle.getProduct(),"jboss");
// Verify workaround
reset(server);
ObjectName memoryBean = new ObjectName("java.lang:type=Memory");
expect(server.isRegistered(memoryBean)).andStubReturn(true);
replay(server);
handle.preDispatch(servers, new JmxRequestBuilder(RequestType.READ, memoryBean).attribute("HeapMemoryUsage").<JmxRequest>build());
verify(server);
}
@Test
public void version71() throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException {
expect(server.queryNames(new ObjectName("jboss.system:type=Server"),null)).andReturn(Collections.<ObjectName>emptySet());
prepareQuery("jboss.as:*");
ObjectName oName = new ObjectName("jboss.as:management-root=server");
expect(server.getAttribute(oName,"productVersion")).andReturn(null);
expect(server.getAttribute(oName,"releaseVersion")).andReturn("7.1.1.Final");
expect(server.getAttribute(oName,"productName")).andReturn(null);
replay(server);
ServerHandle handle = detector.detect(servers);
assertEquals(handle.getVersion(),"7.1.1.Final");
assertEquals(handle.getVendor(),"RedHat");
assertEquals(handle.getProduct(),"jboss");
verifyNoWorkaround(handle);
}
@Test
public void version101() throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, ReflectionException, AttributeNotFoundException, MBeanException {
expect(server.queryNames(new ObjectName("jboss.system:type=Server"),null)).andReturn(Collections.<ObjectName>emptySet());
prepareQuery("jboss.as:*");
ObjectName oName = new ObjectName("jboss.as:management-root=server");
expect(server.getAttribute(oName,"productVersion")).andReturn("10.1.0.Final");
expect(server.getAttribute(oName,"productName")).andReturn("WildFly Full");
replay(server);
ServerHandle handle = detector.detect(servers);
assertEquals(handle.getVersion(),"10.1.0.Final");
assertEquals(handle.getVendor(),"RedHat");
assertEquals(handle.getProduct(),"WildFly Full");
verifyNoWorkaround(handle);
}
private void verifyNoWorkaround(ServerHandle pHandle) throws MalformedObjectNameException {
// Verify that no workaround is active
reset(server);
ObjectName memoryBean = new ObjectName("java.lang:type=Memory");
replay(server);
pHandle.preDispatch(servers, new JmxRequestBuilder(RequestType.READ, memoryBean).attribute("HeapMemoryUsage").<JmxRequest>build());
verify(server);
}
@Test
public void version7() throws MalformedObjectNameException, IntrospectionException, InstanceNotFoundException, ReflectionException {
expect(server.queryNames(new ObjectName("jboss.system:type=Server"),null)).andReturn(Collections.<ObjectName>emptySet());
expect(server.queryNames(new ObjectName("jboss.as:*"),null)).andReturn(Collections.<ObjectName>emptySet());
prepareQuery("jboss.modules:*");
replay(server);
ServerHandle handle = detector.detect(servers);
assertEquals(handle.getVersion(),"7");
assertEquals(handle.getVendor(),"RedHat");
assertEquals(handle.getProduct(),"jboss");
// Verify that no workaround is active
verifyNoWorkaround(handle);
}
private ObjectName prepareQuery(String pName) throws MalformedObjectNameException {
ObjectName oName = new ObjectName(pName);
Set<ObjectName> oNames = new HashSet<ObjectName>(Arrays.asList(oName));
expect(server.queryNames(oName,null)).andReturn(oNames);
return oName;
}
@Test
public void addMBeanServers() {
replay(server);
detector.addMBeanServers(new HashSet<MBeanServerConnection>());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void verifyIsClassLoadedArgumentChecksNullInstrumentation() {
detector.isClassLoaded("xx", null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void verifyIsClassLoadedArgumentChecks2NullClassname() {
detector.isClassLoaded(null, createMock(Instrumentation.class));
}
@Test
public void verifyIsClassLoadedNotLoaded() {
Instrumentation inst = createMock(Instrumentation.class);
expect(inst.getAllLoadedClasses()).andReturn(new Class[] {}).once();
replay(inst);
assertFalse(detector.isClassLoaded("org.Dummy", inst));
verify(inst);
}
@Test
public void verifyIsClassLoadedLoaded() {
Instrumentation inst = createMock(Instrumentation.class);
expect(inst.getAllLoadedClasses()).andReturn(new Class[] {JBossDetectorTest.class}).once();
replay(inst);
assertTrue(detector.isClassLoaded(JBossDetectorTest.class.getName(), inst));
verify(inst);
}
@Test
public void verifyJvmAgentStartup() throws MalformedURLException {
Instrumentation inst = createMock(Instrumentation.class);
expect(inst.getAllLoadedClasses()).andReturn(new Class[] {}).times(3);
expect(inst.getAllLoadedClasses()).andReturn(new Class[] {JBossDetectorTest.class}).atLeastOnce();
ClassLoader cl = createMock(ClassLoader.class);
expect(cl.getResource("org/jboss/modules/Main.class")).andReturn(new URL("http", "dummy", "")).anyTimes();
String prevPkgValue = System.setProperty("jboss.modules.system.pkgs", "blah");
String prevLogValue = System.setProperty("java.util.logging.manager", JBossDetectorTest.class.getName());
replay(inst,cl);
try {
detector.jvmAgentStartup(inst, cl);
} finally {
resetSysProp(prevLogValue, "java.util.logging.manager");
resetSysProp(prevPkgValue, "jboss.modules.system.pkgs");
}
verify(inst);
}
protected void resetSysProp(String prevValue, String key) {
if (prevValue == null) {
System.getProperties().remove(key);
} else {
System.setProperty(key, prevValue);
}
}
}
| apache-2.0 |
CrazyTaro/freeCalendar | calendarlib/src/main/java/com/taro/calendar/lib/ColorSetting.java | 8008 | package com.taro.calendar.lib;
import android.graphics.Color;
import android.support.annotation.ColorInt;
/**
* Created by taro on 2017/6/4.
*/
public class ColorSetting {
/**
* 默认的黄色
*/
public static final int DEFAULT_COLOR_YELLOW = Color.parseColor("#fdc183");
/**
* 默认的绿色
*/
public static final int DEFAULT_COLOR_GREEN = Color.parseColor("#90c41f");
/**
* 默认的蓝色
*/
public static final int DEFAULT_COLOR_BLUE = Color.parseColor("#04A3E3");
/**
* 默认的红色
*/
public static final int DEFAULT_COLOR_RED = Color.parseColor("#F06F28");
/**
* 默认次要字体颜色
*/
public static final int DEFAULT_TEXT_COLOR_MINOR = Color.parseColor("#33000000");
/**
* 默认农历字体颜色
*/
public static final int DEFAULT_TEXT_COLOR_LUNAR = Color.parseColor("#717171");
/**
* 默认周末字体颜色
*/
public static final int DEFAULT_TEXT_COLOR_WEEKEND = Color.parseColor("#F06F28");
/**
* 默认节日字体颜色
*/
public static final int DEFAULT_TEXT_COLOR_FESTIVAL = DEFAULT_TEXT_COLOR_WEEKEND;
/**
* 默认普通字体颜色
*/
public static final int DEFAULT_TEXT_COLOR_NORMAL = Color.BLACK;
/**
* 默认选中字体颜色
*/
public static final int DEFAULT_TEXT_COLOR_SELECTED_DAY = Color.WHITE;
/**
* 默认选中当天背景色
*/
public static final int DEFAULT_BACKGROUND_SELECTED_DAY = DEFAULT_COLOR_BLUE;
/**
* 默认日历控件的背景色
*/
public static final int DEFAULT_BACKGROUND_CALENDAR = Color.WHITE;
/**
* 星期说明标题栏的字体颜色
*/
public int mWeekTitleTextColor;
/**
* 星期说明标题栏的背景色
*/
public int mWeekTitleBackgroundColor;
/**
* 周末字体颜色
*/
public int mWeekendTextColor;
/**
* 节日字体颜色
*/
public int mFestivalTextColor;
/**
* 农历字体颜色
*/
public int mLunarTextColor;
/**
* 默认普通字体颜色
*/
public int mNormalDateTextColor;
/**
* 次要文字颜色(次要月份等中使用)
*/
public int mMinorDateTextColor;
/**
* 选中日期的字体色
*/
public int mSelectDateTextColor;
/**
* 今天字体颜色
*/
public int mTodayDateTextColor;
/**
* 控件背景
*/
public int mBackgroundColor;
/**
* 每一个日期的背景色
*/
public int mDateBackgroundColor;
/**
* 选中日期的背景色
*/
public int mSelectDateBackgroundColor;
/**
* 今天日期的背景色
*/
public int mTodayBackgroundColor;
public ColorSetting() {
reset();
}
public ColorSetting(@ColorInt int festival, @ColorInt int lunar, @ColorInt int selected, @ColorInt int selectedBackground) {
this();
mFestivalTextColor = festival;
mLunarTextColor = lunar;
mSelectDateTextColor = selected;
mSelectDateBackgroundColor = selectedBackground;
}
public ColorSetting(@ColorInt int normal, @ColorInt int minor, @ColorInt int weekend, @ColorInt int festival, @ColorInt int lunar, @ColorInt int selected) {
this();
mNormalDateTextColor = normal;
mMinorDateTextColor = minor;
mWeekendTextColor = weekend;
mFestivalTextColor = festival;
mLunarTextColor = lunar;
mSelectDateTextColor = selected;
}
private void init(int normal, int minor, int weekTitle,
int weekTitleBackground, int weekend,
int festival, int lunar, int selected, int today,
int todayBackground, int selectedBackground,
int background, int dateBackground) {
mWeekTitleTextColor = weekTitle;
mWeekTitleBackgroundColor = weekTitleBackground;
mWeekendTextColor = weekend;
mFestivalTextColor = festival;
mLunarTextColor = lunar;
mNormalDateTextColor = normal;
mMinorDateTextColor = minor;
mSelectDateTextColor = selected;
mTodayDateTextColor = today;
mBackgroundColor = background;
mDateBackgroundColor = dateBackground;
mSelectDateBackgroundColor = selectedBackground;
mTodayBackgroundColor = todayBackground;
}
public ColorSetting reset() {
//周末标题/周末背景色/周末文本颜色
init(DEFAULT_TEXT_COLOR_NORMAL, DEFAULT_TEXT_COLOR_MINOR, DEFAULT_TEXT_COLOR_LUNAR,
//周末背景色/周末文本颜色
Color.TRANSPARENT, DEFAULT_TEXT_COLOR_WEEKEND,
//节日文本颜色/农历日历文本颜色
DEFAULT_TEXT_COLOR_FESTIVAL, DEFAULT_TEXT_COLOR_LUNAR,
//选中文本颜色/今日文本颜色
DEFAULT_TEXT_COLOR_SELECTED_DAY, DEFAULT_TEXT_COLOR_NORMAL,
//今日背景颜色/选中背景颜色
DEFAULT_BACKGROUND_SELECTED_DAY, DEFAULT_BACKGROUND_SELECTED_DAY,
//控件背景色/日期背景色
DEFAULT_BACKGROUND_CALENDAR, Color.TRANSPARENT);
return this;
}
/**
* 设置默认的文本颜色
*
* @param color
* @return
*/
public ColorSetting setNormalDateTextColor(@ColorInt int color) {
mNormalDateTextColor = color;
return this;
}
/**
* 设置次要的文本颜色
*
* @param color
* @return
*/
public ColorSetting setMinorDateTextColor(@ColorInt int color) {
mMinorDateTextColor = color;
return this;
}
/**
* 设置周末标题文本颜色
*
* @param color
* @return
*/
public ColorSetting setWeekTitleTextColor(@ColorInt int color) {
mWeekTitleTextColor = color;
return this;
}
/**
* 设置周末文本颜色
*
* @param color
* @return
*/
public ColorSetting setWeekendTextColor(@ColorInt int color) {
mWeekendTextColor = color;
return this;
}
/**
* 设置节日文本颜色
*
* @param color
* @return
*/
public ColorSetting setFestivalTextColor(@ColorInt int color) {
mFestivalTextColor = color;
return this;
}
/**
* 设置农历文本颜色
*
* @param color
* @return
*/
public ColorSetting setLunarTextColor(@ColorInt int color) {
mLunarTextColor = color;
return this;
}
/**
* 设置选中日期文本颜色
*
* @param color
* @return
*/
public ColorSetting setSelectedDateTextColor(@ColorInt int color) {
mSelectDateTextColor = color;
return this;
}
/**
* 设置今日文本颜色
*
* @param color
* @return
*/
public ColorSetting setTodayDateTextColor(@ColorInt int color) {
mTodayDateTextColor = color;
return this;
}
/**
* 设置选中日期背景色
*
* @param color
* @return
*/
public ColorSetting setSelectedDateBackgroundColor(@ColorInt int color) {
mSelectDateBackgroundColor = color;
return this;
}
/**
* 设置今日背景色
*
* @param color
* @return
*/
public ColorSetting setTodayBackgroundColor(@ColorInt int color) {
mTodayBackgroundColor = color;
return this;
}
/**
* 设置控件背景色
*
* @param color
* @return
*/
public ColorSetting setBackgroundColor(@ColorInt int color) {
mBackgroundColor = color;
return this;
}
/**
* 设置日期背景色
*
* @param color
* @return
*/
public ColorSetting setDateBackgroundColor(@ColorInt int color) {
mDateBackgroundColor = color;
return this;
}
}
| apache-2.0 |
ullgren/camel | components/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2ComponentVerifierExtension.java | 4031 | /*
* 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.camel.component.aws2.kinesis;
import java.util.Map;
import org.apache.camel.component.extension.verifier.DefaultComponentVerifierExtension;
import org.apache.camel.component.extension.verifier.ResultBuilder;
import org.apache.camel.component.extension.verifier.ResultErrorBuilder;
import org.apache.camel.component.extension.verifier.ResultErrorHelper;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisClient;
import software.amazon.awssdk.services.kinesis.KinesisClientBuilder;
public class Kinesis2ComponentVerifierExtension extends DefaultComponentVerifierExtension {
public Kinesis2ComponentVerifierExtension() {
this("aws2-kinesis");
}
public Kinesis2ComponentVerifierExtension(String scheme) {
super(scheme);
}
// *********************************
// Parameters validation
// *********************************
@Override
protected Result verifyParameters(Map<String, Object> parameters) {
ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS).error(ResultErrorHelper.requiresOption("accessKey", parameters))
.error(ResultErrorHelper.requiresOption("secretKey", parameters)).error(ResultErrorHelper.requiresOption("region", parameters))
.error(ResultErrorHelper.requiresOption("streamName", parameters));
// Validate using the catalog
super.verifyParametersAgainstCatalog(builder, parameters);
return builder.build();
}
// *********************************
// Connectivity validation
// *********************************
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);
try {
Kinesis2Configuration configuration = setProperties(new Kinesis2Configuration(), parameters);
AwsBasicCredentials cred = AwsBasicCredentials.create(configuration.getAccessKey(), configuration.getSecretKey());
KinesisClientBuilder clientBuilder = KinesisClient.builder();
KinesisClient client = clientBuilder.credentialsProvider(StaticCredentialsProvider.create(cred)).region(Region.of(configuration.getRegion())).build();
client.listStreams();
} catch (SdkClientException e) {
ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
.detail("aws_kinesis_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
.detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);
builder.error(errorBuilder.build());
} catch (Exception e) {
builder.error(ResultErrorBuilder.withException(e).build());
}
return builder.build();
}
}
| apache-2.0 |
monetate/closure-compiler | test/com/google/javascript/jscomp/Es6RewriteModulesTest.java | 46129 | /*
* Copyright 2014 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.CompilerOptions.ChunkOutputType;
import com.google.javascript.jscomp.deps.ModuleLoader;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.SemanticReverseAbstractInterpreter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link Es6RewriteModules}
*
* <p>See also Es6RewriteModulesBeforeTypeCheckingTest. This file tests only behavior when run after
* type checking.
*
* <p>TODO(b/144593112): Remove the other test class when the pass is permanently moved after type
* checking.
*/
@RunWith(JUnit4.class)
public final class Es6RewriteModulesTest extends CompilerTestCase {
private ImmutableList<String> moduleRoots = null;
private ChunkOutputType chunkOutputType = ChunkOutputType.GLOBAL_NAMESPACE;
private static final SourceFile other =
SourceFile.fromCode(
"other.js",
lines(
"export default 0;", //
"export let name, x, a, b, c;",
"export {x as class};",
"export class Parent {}"));
private static final SourceFile otherExpected =
SourceFile.fromCode(
"other.js",
lines(
"var $jscompDefaultExport$$module$other = 0;", //
"let name$$module$other, x$$module$other, a$$module$other, b$$module$other, ",
" c$$module$other;",
"class Parent$$module$other {}",
"/** @const */ var module$other = {};",
"/** @const */ module$other.Parent = Parent$$module$other;",
"/** @const */ module$other.a = a$$module$other;",
"/** @const */ module$other.b = b$$module$other;",
"/** @const */ module$other.c = c$$module$other;",
"/** @const */ module$other.class = x$$module$other;",
"/** @const */ module$other.default = $jscompDefaultExport$$module$other;",
"/** @const */ module$other.name = name$$module$other;",
"/** @const */ module$other.x = x$$module$other;"));
@Override
@Before
public void setUp() throws Exception {
super.setUp();
// ECMASCRIPT5 to trigger module processing after parsing.
enableCreateModuleMap();
enableTypeInfoValidation();
disableScriptFeatureValidation();
}
@Override
protected CompilerOptions getOptions() {
CompilerOptions options = super.getOptions();
// ECMASCRIPT5 to Trigger module processing after parsing.
options.setWarningLevel(DiagnosticGroups.LINT_CHECKS, CheckLevel.ERROR);
options.setPrettyPrint(true);
if (moduleRoots != null) {
options.setModuleRoots(moduleRoots);
}
return options;
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return (externs, root) -> {
ReverseAbstractInterpreter rai =
new SemanticReverseAbstractInterpreter(compiler.getTypeRegistry());
TypedScope globalTypedScope =
checkNotNull(
new TypeCheck(compiler, rai, compiler.getTypeRegistry())
.processForTesting(externs, root));
compiler.setTypeCheckingHasRun(true);
new Es6RewriteModules(
compiler,
compiler.getModuleMetadataMap(),
compiler.getModuleMap(),
/* preprocessorSymbolTable= */ null,
globalTypedScope,
chunkOutputType)
.process(externs, root);
if (chunkOutputType == ChunkOutputType.ES_MODULES) {
new ConvertChunksToESModules(compiler).process(externs, root);
}
};
}
void testModules(String input, String expected) {
test(
srcs(other, SourceFile.fromCode("testcode", input)),
expected(otherExpected, SourceFile.fromCode("testcode", expected)));
}
@Test
public void testImport() {
testModules(
lines(
"import name from './other.js';", //
"use(name);"),
"use($jscompDefaultExport$$module$other); /** @const */ var module$testcode = {};");
testModules("import {a as name} from './other.js';", "/** @const */ var module$testcode = {};");
testModules(
lines(
"import x, {a as foo, b as bar} from './other.js';", //
"use(x);"),
"use($jscompDefaultExport$$module$other); /** @const */ var module$testcode = {};");
testModules(
lines(
"import {default as name} from './other.js';", //
"use(name);"),
"use($jscompDefaultExport$$module$other); /** @const */ var module$testcode = {};");
testModules(
lines(
"import {class as name} from './other.js';", //
"use(name);"),
"use(x$$module$other); /** @const */ var module$testcode = {};");
}
@Test
public void testImport_missing() {
ModulesTestUtils.testModulesError(
this, "import name from './does_not_exist';\n use(name);", ModuleLoader.LOAD_WARNING);
ignoreWarnings(ModuleLoader.LOAD_WARNING);
// These are different as a side effect of the way that the fake bindings are made. The first
// makes a binding for a fake variable in the fake module. The second creates a fake binding
// for the fake module. When "dne.name" is resolved, the module does not have key "name", so
// it chooses to rewrite to "module$does_not_exist.name", thinking that this could've been a
// reference to an export that doesn't exist.
testModules(
lines(
"import {name} from './does_not_exist';", //
"use(name);"),
lines(
"use(name$$module$does_not_exist);", //
"/** @const */ var module$testcode = {};"));
testModules(
lines(
"import * as dne from './does_not_exist';", //
"use(dne.name);"),
lines(
"use(module$does_not_exist.name);", //
"/** @const */ var module$testcode = {};"));
}
@Test
public void testImportStar() {
testModules(
lines(
"import * as name from './other.js';", //
"use(name.a);"),
"use(a$$module$other); /** @const */ var module$testcode = {};");
}
@Test
public void testTypeNodeRewriting() {
test(
srcs(
SourceFile.fromCode(
"other.js",
lines(
"export default 0;", //
"export let name = 'George';",
"export let a = class {};")),
SourceFile.fromCode(
"testcode",
lines(
"import * as name from './other.js';", //
"/** @type {name.a} */ var x;"))),
expected(
SourceFile.fromCode(
"other.js",
lines(
"var $jscompDefaultExport$$module$other = 0;", //
"let name$$module$other = 'George';",
"let a$$module$other = class {};",
"/** @const */ var module$other = {};",
"/** @const */ module$other.a = a$$module$other;",
"/** @const */ module$other.default = $jscompDefaultExport$$module$other;",
"/** @const */ module$other.name = name$$module$other;",
"")),
SourceFile.fromCode(
"testcode",
lines(
"/** @type {a$$module$other} */ var x$$module$testcode;",
"/** @const */ var module$testcode = {};"))));
}
@Test
public void testExport() {
testModules(
"export var a = 1, b = 2;",
lines(
"var a$$module$testcode = 1, b$$module$testcode = 2;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.a = a$$module$testcode;",
"/** @const */ module$testcode.b = b$$module$testcode;"));
testModules(
"export var a;\nexport var b;",
lines(
"var a$$module$testcode; var b$$module$testcode;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.a = a$$module$testcode;",
"/** @const */ module$testcode.b = b$$module$testcode;"));
testModules(
"export function f() {};",
lines(
"function f$$module$testcode() {}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.f = f$$module$testcode;"));
testModules(
"export function f() {};\nfunction g() { f(); }",
lines(
"function f$$module$testcode() {}",
"function g$$module$testcode() { f$$module$testcode(); }",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.f = f$$module$testcode;"));
testModules(
lines("export function MyClass() {};", "MyClass.prototype.foo = function() {};"),
lines(
"function MyClass$$module$testcode() {}",
"MyClass$$module$testcode.prototype.foo = function() {};",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.MyClass = MyClass$$module$testcode;"));
testModules(
"var f = 1;\nvar b = 2;\nexport {f as foo, b as bar};",
lines(
"var f$$module$testcode = 1;",
"var b$$module$testcode = 2;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.bar = b$$module$testcode;",
"/** @const */ module$testcode.foo = f$$module$testcode;"));
testModules(
"var f = 1;\nexport {f as default};",
lines(
"var f$$module$testcode = 1;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = f$$module$testcode;"));
testModules(
"var f = 1;\nexport {f as class};",
lines(
"var f$$module$testcode = 1;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.class = f$$module$testcode;"));
}
@Test
public void testModulesInExterns() {
testError(
srcs(
SourceFile.fromCode(
"externsMod.js",
lines(
"/** @fileoverview @externs */",
"export let /** !number */ externalName;",
""))),
error(Es6ToEs3Util.CANNOT_CONVERT_YET));
}
@Test
public void testModulesInTypeSummary() {
allowExternsChanges();
test(
srcs(
SourceFile.fromCode(
"mod1.js",
lines(
"/** @fileoverview @typeSummary */",
"export let /** !number */ externalName;",
"")),
SourceFile.fromCode(
"mod2.js",
lines(
"import {externalName as localName} from './mod1.js'",
"alert(localName);",
""))),
expected(
SourceFile.fromCode(
"mod2.js",
lines(
"alert(externalName$$module$mod1);",
"/** @const */ var module$mod2 = {};",
""))));
}
@Test
public void testMutableExport() {
testModules(
lines(
"export var a = 1, b = 2;", //
"function f() {",
" a++;",
" b++",
"}"),
lines(
"var a$$module$testcode = 1, b$$module$testcode = 2;",
"function f$$module$testcode() {",
" a$$module$testcode++;",
" b$$module$testcode++",
"}",
"/** @const */ var module$testcode = {",
" get a() { return a$$module$testcode; },",
" get b() { return b$$module$testcode; },",
"};"));
testModules(
lines(
"var a = 1, b = 2; export {a as A, b as B};",
"const f = () => {",
" a++;",
" b++",
"};"),
lines(
"var a$$module$testcode = 1, b$$module$testcode = 2;",
"const f$$module$testcode = () => {",
" a$$module$testcode++;",
" b$$module$testcode++",
"};",
"/** @const */ var module$testcode = {",
" get A() { return a$$module$testcode; },",
" get B() { return b$$module$testcode; },",
"};"));
testModules(
lines(
"export function f() {};", //
"function g() {",
" f = function() {};",
"}"),
lines(
"function f$$module$testcode() {}",
"function g$$module$testcode() {",
" f$$module$testcode = function() {};",
"}",
"/** @const */ var module$testcode = {",
" get f() { return f$$module$testcode; },",
"};"));
testModules(
lines(
"export default function f() {};", //
"function g() {",
" f = function() {};",
"}"),
lines(
"function f$$module$testcode() {}",
"function g$$module$testcode() {",
" f$$module$testcode = function() {};",
"}",
"/** @const */ var module$testcode = {",
" get default() { return f$$module$testcode; },",
"};"));
testModules(
lines(
"export class C {};", //
"function g() {",
" C = class {};",
"}"),
lines(
"class C$$module$testcode {}",
"function g$$module$testcode() {",
" C$$module$testcode = class {};",
"}",
"/** @const */ var module$testcode = {",
" get C() { return C$$module$testcode; },",
"};"));
testModules(
lines(
"export default class C {};", //
"function g() {",
" C = class {};",
"}"),
lines(
"class C$$module$testcode {}",
"function g$$module$testcode() {",
" C$$module$testcode = class {};",
"}",
"/** @const */ var module$testcode = {",
" get default() { return C$$module$testcode; },",
"};"));
testModules(
lines(
"export var IN, OF;", //
"function f() {",
" for (IN in {});",
" for (OF of []);",
"}"),
lines(
"var IN$$module$testcode, OF$$module$testcode;",
"function f$$module$testcode() {",
" for (IN$$module$testcode in {});",
" for (OF$$module$testcode of []);",
"}",
"/** @const */ var module$testcode = {",
" get IN() { return IN$$module$testcode; },",
" get OF() { return OF$$module$testcode; },",
"};"));
testModules(
lines(
"export var ARRAY, OBJ, UNCHANGED;",
"function f() {",
" ({OBJ} = {OBJ: {}});",
" [ARRAY] = [];",
" var x = {UNCHANGED: 0};",
"}"),
lines(
"var ARRAY$$module$testcode, OBJ$$module$testcode, UNCHANGED$$module$testcode;",
"function f$$module$testcode() {",
" ({OBJ:OBJ$$module$testcode} = {OBJ: {}});",
" [ARRAY$$module$testcode] = [];",
" var x = {UNCHANGED: 0};",
"}",
"/** @const */ var module$testcode = {",
" get ARRAY() { return ARRAY$$module$testcode; },",
" get OBJ() { return OBJ$$module$testcode; },",
"};",
"/** @const */ module$testcode.UNCHANGED = UNCHANGED$$module$testcode"));
}
@Test
public void testConstClassExportIsConstant() {
testModules(
"export const Class = class {}",
lines(
"const Class$$module$testcode = class {}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Class = Class$$module$testcode;"));
}
@Test
public void testTopLevelMutationIsNotMutable() {
testModules(
lines(
"export var a = 1, b = 2;", //
"a++;",
"b++"),
lines(
"var a$$module$testcode = 1, b$$module$testcode = 2;",
"a$$module$testcode++;",
"b$$module$testcode++",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.a = a$$module$testcode;",
"/** @const */ module$testcode.b = b$$module$testcode;"));
testModules(
lines(
"var a = 1, b = 2; export {a as A, b as B};", //
"if (change) {",
" a++;",
" b++",
"}"),
lines(
"var a$$module$testcode = 1, b$$module$testcode = 2;",
"if (change) {",
" a$$module$testcode++;",
" b$$module$testcode++",
"}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.A = a$$module$testcode;",
"/** @const */ module$testcode.B = b$$module$testcode;"));
testModules(
lines(
"export function f() {};", //
"if (change) {",
" f = function() {};",
"}"),
lines(
"function f$$module$testcode() {}",
"if (change) {",
" f$$module$testcode = function() {};",
"}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.f = f$$module$testcode;"));
testModules(
lines(
"export default function f() {};",
"try { f = function() {}; } catch (e) { f = function() {}; }"),
lines(
"function f$$module$testcode() {}",
"try { f$$module$testcode = function() {}; }",
"catch (e) { f$$module$testcode = function() {}; }",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = f$$module$testcode;"));
testModules(
lines(
"export class C {};", //
"if (change) {",
" C = class {};",
"}"),
lines(
"class C$$module$testcode {}",
"if (change) {",
" C$$module$testcode = class {};",
"}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.C = C$$module$testcode;"));
testModules(
lines(
"export default class C {};", //
"{",
" C = class {};",
"}"),
lines(
"class C$$module$testcode {}",
"{",
" C$$module$testcode = class {};",
"}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = C$$module$testcode;"));
}
@Test
public void testExportWithJsDoc() {
testModules(
"/** @constructor */\nexport function F() { return '';}",
lines(
"/** @constructor */",
"function F$$module$testcode() { return ''; }",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.F = F$$module$testcode;"));
testModules(
"/** @return {string} */\nexport function f() { return '';}",
lines(
"/** @return {string} */",
"function f$$module$testcode() { return ''; }",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.f = f$$module$testcode;"));
testModules(
"/** @return {string} */\nexport var f = function() { return '';}",
lines(
"/** @return {string} */",
"var f$$module$testcode = function() { return ''; }",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.f = f$$module$testcode;"));
testModules(
"/** @type {number} */\nexport var x = 3",
lines(
"/** @type {number} */",
"var x$$module$testcode = 3;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.x = x$$module$testcode;"));
}
@Test
public void testImportAndExport() {
testModules(
lines(
"import {name as n} from './other.js';", //
"use(n);",
"export {n as name};"),
lines(
"use(name$$module$other);",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.name = name$$module$other;"));
}
@Test
public void testExportFrom() {
test(
srcs(
other,
SourceFile.fromCode(
"testcode",
lines(
"export {name} from './other.js';",
"export {default} from './other.js';",
"export {class} from './other.js';"))),
expected(
otherExpected,
SourceFile.fromCode(
"testcode",
lines(
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.class = x$$module$other;",
"/** @const */ module$testcode.default = $jscompDefaultExport$$module$other;",
"/** @const */ module$testcode.name = name$$module$other;"))));
test(
srcs(other, SourceFile.fromCode("testcode", "export {a, b as c, x} from './other.js';")),
expected(
otherExpected,
SourceFile.fromCode(
"testcode",
lines(
"/** @const */ var module$testcode = {}",
"/** @const */ module$testcode.a = a$$module$other;",
"/** @const */ module$testcode.c = b$$module$other;",
"/** @const */ module$testcode.x = x$$module$other;"))));
test(
srcs(other, SourceFile.fromCode("testcode", "export {a as b, b as a} from './other.js';")),
expected(
otherExpected,
SourceFile.fromCode(
"testcode",
lines(
"/** @const */ var module$testcode = {}",
"/** @const */ module$testcode.a = b$$module$other;",
"/** @const */ module$testcode.b = a$$module$other;"))));
test(
srcs(
other,
SourceFile.fromCode(
"testcode",
lines(
"export {default as a} from './other.js';",
"export {a as a2, default as b} from './other.js';",
"export {class as switch} from './other.js';"))),
expected(
otherExpected,
SourceFile.fromCode(
"testcode",
lines(
"/** @const */ var module$testcode = {}",
"/** @const */ module$testcode.a = $jscompDefaultExport$$module$other;",
"/** @const */ module$testcode.a2 = a$$module$other;",
"/** @const */ module$testcode.b = $jscompDefaultExport$$module$other;",
"/** @const */ module$testcode.switch = x$$module$other;"))));
}
@Test
public void testExportDefault() {
testModules(
"export default 'someString';",
lines(
"var $jscompDefaultExport$$module$testcode = 'someString';",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = $jscompDefaultExport$$module$testcode;"));
testModules(
"var x = 5;\nexport default x;",
lines(
"var x$$module$testcode = 5;",
"var $jscompDefaultExport$$module$testcode = x$$module$testcode;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = $jscompDefaultExport$$module$testcode;"));
testModules(
"export default function f(){};\n var x = f();",
lines(
"function f$$module$testcode() {}",
"var x$$module$testcode = f$$module$testcode();",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = f$$module$testcode;"));
testModules(
"export default class Foo {};\n var x = new Foo;",
lines(
"class Foo$$module$testcode {}",
"var x$$module$testcode = new Foo$$module$testcode;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = Foo$$module$testcode;"));
}
@Test
public void testExportDefault_anonymous() {
testModules(
"export default class {};",
lines(
"var $jscompDefaultExport$$module$testcode = class {};",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = $jscompDefaultExport$$module$testcode;"));
testModules(
"export default function() {}",
lines(
"var $jscompDefaultExport$$module$testcode = function() {}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.default = $jscompDefaultExport$$module$testcode;"));
}
@Test
public void testExportDestructureDeclaration() {
testModules(
"export let {a, c:b} = obj;",
lines(
"let {a:a$$module$testcode, c:b$$module$testcode} = obj;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.a = a$$module$testcode;",
"/** @const */ module$testcode.b = b$$module$testcode;"));
testModules(
"export let [a, b] = obj;",
lines(
"let [a$$module$testcode, b$$module$testcode] = obj;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.a = a$$module$testcode;",
"/** @const */ module$testcode.b = b$$module$testcode;"));
testModules(
"export let {a, b:[c,d]} = obj;",
lines(
"let {a:a$$module$testcode, b:[c$$module$testcode, d$$module$testcode]} = obj;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.a = a$$module$testcode;",
"/** @const */ module$testcode.c = c$$module$testcode;",
"/** @const */ module$testcode.d = d$$module$testcode;"));
}
@Test
public void testExtendImportedClass() {
testModules(
lines(
"import {Parent} from './other.js';",
"class Child extends Parent {",
" /** @param {Parent} parent */",
" useParent(parent) {}",
"}"),
lines(
"class Child$$module$testcode extends Parent$$module$other {",
" /** @param {Parent$$module$other} parent */",
" useParent(parent) {}",
"}",
"/** @const */ var module$testcode = {};"));
testModules(
lines(
"import {Parent} from './other.js';",
"export class Child extends Parent {",
" /** @param {Parent} parent */",
" useParent(parent) {}",
"}"),
lines(
"class Child$$module$testcode extends Parent$$module$other {",
" /** @param {Parent$$module$other} parent */",
" useParent(parent) {}",
"}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Child = Child$$module$testcode;"));
}
@Test
public void testFixTypeNode() {
testModules(
lines(
"export class Child {", //
" /** @param {Child} child */",
" useChild(child) {}",
"}"),
lines(
"class Child$$module$testcode {",
" /** @param {Child$$module$testcode} child */",
" useChild(child) {}",
"}",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Child = Child$$module$testcode;"));
testModules(
lines(
"export class Child {",
" /** @param {Child.Foo.Bar.Baz} baz */",
" useBaz(baz) {}",
"}",
"",
"Child.Foo = class {};",
"",
"Child.Foo.Bar = class {};",
"",
"Child.Foo.Bar.Baz = class {};",
""),
lines(
"class Child$$module$testcode {",
" /** @param {Child$$module$testcode.Foo.Bar.Baz} baz */",
" useBaz(baz) {}",
"}",
"Child$$module$testcode.Foo=class{};",
"Child$$module$testcode.Foo.Bar=class{};",
"Child$$module$testcode.Foo.Bar.Baz=class{};",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Child = Child$$module$testcode;"));
}
@Test
public void testRenameTypedef() {
testModules(
lines(
"import './other.js';", //
"/** @typedef {string|!Object} */",
"export var UnionType;"),
lines(
"/** @typedef {string|!Object} */",
"var UnionType$$module$testcode;",
"/** @const */ var module$testcode = {};",
"/** @typedef {UnionType$$module$testcode} */",
"module$testcode.UnionType;"));
}
@Test
public void testNoInnerChange() {
testModules(
lines(
"var Foo = (function () {",
" /** @param bar */",
" function Foo(bar) {}",
" return Foo;",
"}());",
"export { Foo };"),
lines(
"var Foo$$module$testcode = function() {",
" /** @param bar */",
" function Foo(bar) {}",
" return Foo;",
"}();",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Foo = Foo$$module$testcode;"));
}
@Test
public void testRenameImportedReference() {
testModules(
lines(
"import {a} from './other.js';",
"import {b as bar} from './other.js';",
"a();",
"function g() {",
" a();",
" bar++;",
" function h() {",
" var a = 3;",
" { let a = 4; }",
" }",
"}"),
lines(
"a$$module$other();",
"function g$$module$testcode() {",
" a$$module$other();",
" b$$module$other++;",
" function h() {",
" var a = 3;",
" { let a = 4; }",
" }",
"}",
"/** @const */ var module$testcode = {};"));
}
@Test
public void testObjectDestructuringAndObjLitShorthand() {
testModules(
lines(
"import {c} from './other.js';",
"const foo = 1;",
"const {a, b} = c({foo});",
"use(a, b);"),
lines(
"const foo$$module$testcode = 1;",
"const {",
" a: a$$module$testcode,",
" b: b$$module$testcode,",
"} = c$$module$other({foo: foo$$module$testcode});",
"use(a$$module$testcode, b$$module$testcode);",
"/** @const */ var module$testcode = {};"));
}
@Test
public void testObjectDestructuringAndObjLitShorthandWithDefaultValue() {
testModules(
lines(
"import {c} from './other.js';",
"const foo = 1;",
"const {a = 'A', b = 'B'} = c({foo});",
"use(a, b);"),
lines(
"const foo$$module$testcode = 1;",
"const {",
" a: a$$module$testcode = 'A',",
" b: b$$module$testcode = 'B',",
"} = c$$module$other({foo: foo$$module$testcode});",
"use(a$$module$testcode, b$$module$testcode);",
"/** @const */ var module$testcode = {};"));
}
@Test
public void testImportWithoutReferences() {
testModules(
"import './other.js';", //
"/** @const */ var module$testcode = {};");
}
@Test
public void testUselessUseStrict() {
ModulesTestUtils.testModulesError(
this,
lines(
"'use strict';", //
"export default undefined;"),
ClosureRewriteModule.USELESS_USE_STRICT_DIRECTIVE);
}
@Test
public void testUseStrict_noWarning() {
testSame(
lines(
"'use strict';", //
"var x;"));
}
@Test
public void testAbsoluteImportsWithModuleRoots() {
moduleRoots = ImmutableList.of("/base");
test(
srcs(
SourceFile.fromCode(Compiler.joinPathParts("base", "mod", "name.js"), ""),
SourceFile.fromCode(
Compiler.joinPathParts("base", "test", "sub.js"),
"import * as foo from '/mod/name.js';")),
expected(
SourceFile.fromCode(Compiler.joinPathParts("base", "mod", "name.js"), ""),
SourceFile.fromCode(
Compiler.joinPathParts("base", "test", "sub.js"),
"/** @const */ var module$test$sub = {};")));
}
@Test
public void testUseImportInEs6ObjectLiteralShorthand() {
testModules(
lines(
"import {b} from './other.js';", //
"var bar = {a: 1, b};"),
lines(
"var bar$$module$testcode={a: 1, b: b$$module$other};",
"/** @const */ var module$testcode = {};"));
testModules(
lines(
"import {a as foo} from './other.js';", //
"var bar = {a: 1, foo};"),
lines(
"var bar$$module$testcode={a: 1, foo: a$$module$other};",
"/** @const */ var module$testcode = {};"));
testModules(
lines(
"import f from './other.js';", //
"var bar = {a: 1, f};"),
lines(
"var bar$$module$testcode={a: 1, f: $jscompDefaultExport$$module$other};",
"/** @const */ var module$testcode = {};"));
testModules(
"import * as f from './other.js';\nvar bar = {a: 1, f};",
lines(
"var bar$$module$testcode={a: 1, f: module$other};",
"/** @const */ var module$testcode = {};"));
}
@Test
public void testImportAliasInTypeNode() {
test(
srcs(
SourceFile.fromCode("a.js", "export class A {}"),
SourceFile.fromCode(
"b.js",
lines(
"import {A as B} from './a.js';", //
"const /** !B */ b = new B();"))),
expected(
SourceFile.fromCode(
"a.js",
lines(
"class A$$module$a {}",
"/** @const */ var module$a = {};",
"/** @const */ module$a.A = A$$module$a;")),
SourceFile.fromCode(
"b.js",
lines(
"const /** !A$$module$a*/ b$$module$b = new A$$module$a();",
"/** @const */ var module$b = {};"))));
}
@Test
public void testExportStar() {
testModules(
"export * from './other.js';",
lines(
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Parent = Parent$$module$other;",
"/** @const */ module$testcode.a = a$$module$other;",
"/** @const */ module$testcode.b = b$$module$other;",
"/** @const */ module$testcode.c = c$$module$other;",
"/** @const */ module$testcode.class = x$$module$other;",
// no default
"/** @const */ module$testcode.name = name$$module$other;",
"/** @const */ module$testcode.x = x$$module$other;"));
}
@Test
public void testExportStarWithLocalExport() {
testModules(
lines(
"export * from './other.js';", //
"export let baz, zed;"),
lines(
"let baz$$module$testcode, zed$$module$testcode;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Parent = Parent$$module$other;",
"/** @const */ module$testcode.a = a$$module$other;",
"/** @const */ module$testcode.b = b$$module$other;",
"/** @const */ module$testcode.baz = baz$$module$testcode;",
"/** @const */ module$testcode.c = c$$module$other;",
"/** @const */ module$testcode.class = x$$module$other;",
"/** @const */ module$testcode.name = name$$module$other;",
"/** @const */ module$testcode.x = x$$module$other;",
"/** @const */ module$testcode.zed = zed$$module$testcode;"));
}
@Test
public void testExportStarWithLocalExportOverride() {
testModules(
lines(
"export * from './other.js';", //
"export let a, zed;"),
lines(
"let a$$module$testcode, zed$$module$testcode;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.Parent = Parent$$module$other;",
"/** @const */ module$testcode.a = a$$module$testcode;",
"/** @const */ module$testcode.b = b$$module$other;",
"/** @const */ module$testcode.c = c$$module$other;",
"/** @const */ module$testcode.class = x$$module$other;",
"/** @const */ module$testcode.name = name$$module$other;",
"/** @const */ module$testcode.x = x$$module$other;",
"/** @const */ module$testcode.zed = zed$$module$testcode;"));
}
@Test
public void testTransitiveImport() {
test(
srcs(
SourceFile.fromCode("a.js", "export class A {}"),
SourceFile.fromCode("b.js", "export {A} from './a.js';"),
SourceFile.fromCode(
"c.js",
lines(
"import {A} from './b.js';", //
"let /** !A */ a = new A();"))),
expected(
SourceFile.fromCode(
"a.js",
lines(
"class A$$module$a {}",
"/** @const */ var module$a = {};",
"/** @const */ module$a.A = A$$module$a;")),
SourceFile.fromCode(
"b.js",
lines(
"/** @const */ var module$b = {};", //
"/** @const */ module$b.A = A$$module$a;")),
SourceFile.fromCode(
"c.js",
lines(
"let /** !A$$module$a*/ a$$module$c = new A$$module$a();",
"/** @const */ var module$c = {};"))));
test(
srcs(
SourceFile.fromCode("a.js", "export class A {}"),
SourceFile.fromCode("b.js", "export {A as B} from './a.js';"),
SourceFile.fromCode(
"c.js",
lines(
"import {B as C} from './b.js';", //
"let /** !C */ a = new C();"))),
expected(
SourceFile.fromCode(
"a.js",
lines(
"class A$$module$a {}",
"/** @const */ var module$a = {};",
"/** @const */ module$a.A = A$$module$a;")),
SourceFile.fromCode(
"b.js",
lines(
"/** @const */ var module$b = {};", //
"/** @const */ module$b.B = A$$module$a;")),
SourceFile.fromCode(
"c.js",
lines(
"let /** !A$$module$a*/ a$$module$c = new A$$module$a();",
"/** @const */ var module$c = {};"))));
}
@Test
public void testMutableTransitiveImport() {
test(
srcs(
SourceFile.fromCode("a.js", "export let A = class {}; () => (A = class {});"),
SourceFile.fromCode("b.js", "export {A} from './a.js';"),
SourceFile.fromCode(
"c.js",
lines(
"import {A} from './b.js';", //
"let /** !A */ a = new A();"))),
expected(
SourceFile.fromCode(
"a.js",
lines(
"let A$$module$a = class {};",
"()=>A$$module$a = class {};",
"/** @const */ var module$a = {",
" get A() { return A$$module$a; },",
"};")),
SourceFile.fromCode(
"b.js",
lines(
"/** @const */ var module$b = {", " get A() { return A$$module$a; },", "};")),
SourceFile.fromCode(
"c.js",
lines(
"let /** !A$$module$a*/ a$$module$c = new A$$module$a();",
"/** @const */ var module$c = {};"))));
test(
srcs(
SourceFile.fromCode("a.js", "export let A = class {}; () => (A = class {});"),
SourceFile.fromCode("b.js", "export {A as B} from './a.js';"),
SourceFile.fromCode(
"c.js",
lines(
"import {B as C} from './b.js';", //
"let /** !C */ a = new C();"))),
expected(
SourceFile.fromCode(
"a.js",
lines(
"let A$$module$a = class {};",
"()=>A$$module$a = class {};",
"/** @const */ var module$a = {",
" get A() { return A$$module$a; },",
"};")),
SourceFile.fromCode(
"b.js",
lines(
"/** @const */ var module$b = {", " get B() { return A$$module$a; },", "};")),
SourceFile.fromCode(
"c.js",
lines(
"let /** !A$$module$a*/ a$$module$c = new A$$module$a();",
"/** @const */ var module$c = {};"))));
}
@Test
public void testRewriteGetPropsWhileModuleReference() {
test(
srcs(
SourceFile.fromCode("a.js", "export class A {}"),
SourceFile.fromCode(
"b.js",
lines(
"import * as a from './a.js';", //
"export {a};")),
SourceFile.fromCode(
"c.js",
lines(
"import * as b from './b.js';", //
"let /** !b.a.A */ a = new b.a.A();"))),
expected(
SourceFile.fromCode(
"a.js",
lines(
"class A$$module$a {}",
"/** @const */ var module$a = {};",
"/** @const */ module$a.A = A$$module$a;")),
SourceFile.fromCode(
"b.js",
lines(
"/** @const */ var module$b = {};", //
"/** @const */ module$b.a = module$a;")),
SourceFile.fromCode(
"c.js",
lines(
"let /** !A$$module$a*/ a$$module$c = new A$$module$a();",
"/** @const */ var module$c = {};"))));
}
@Test
public void testRewritePropsWhenNotModuleReference() {
test(
srcs(
SourceFile.fromCode(
"other.js", lines("export const name = {}, a = { Type: class {} };")),
SourceFile.fromCode(
"testcode",
lines(
"import * as name from './other.js';", //
"let /** !name.a.Type */ t = new name.a.Type();"))),
expected(
SourceFile.fromCode(
"other.js",
lines(
"const name$$module$other = {}, a$$module$other = { Type: class {} };",
"/** @const */ var module$other = {};",
"/** @const */ module$other.a = a$$module$other;",
"/** @const */ module$other.name = name$$module$other;")),
SourceFile.fromCode(
"testcode",
lines(
"let /** !a$$module$other.Type */ t$$module$testcode =",
" new a$$module$other.Type();",
"/** @const */ var module$testcode = {};"))));
}
@Test
public void testExportsNotImplicitlyLocallyDeclared() {
test(
externs("var exports;"),
srcs("typeof exports; export {};"),
// Regression test; compiler used to rewrite `exports` to `exports$$module$testcode`.
expected("typeof exports; /** @const */ var module$testcode = {};"));
}
@Test
public void testImportMeta() {
testError("import.meta", Es6ToEs3Util.CANNOT_CONVERT);
}
@Test
public void testImportMetaESModuleOutput() {
chunkOutputType = ChunkOutputType.ES_MODULES;
test(
lines("const url = import.meta.url;", "export {url};"),
lines(
"const url$$module$testcode = import.meta.url;",
"/** @const */ var module$testcode = {};",
"/** @const */ module$testcode.url = url$$module$testcode;",
"export {};"));
}
}
| apache-2.0 |
renesugar/arrow | java/plasma/src/main/java/org/apache/arrow/plasma/ObjectStoreLink.java | 4638 | /*
* 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.arrow.plasma;
import java.util.List;
import org.apache.arrow.plasma.exceptions.DuplicateObjectException;
import org.apache.arrow.plasma.exceptions.PlasmaOutOfMemoryException;
/**
* Object store interface, which provides the capabilities to put and get raw byte array, and serves.
*/
public interface ObjectStoreLink {
/**
* Tuple for data and metadata stored in Plasma.
*/
class ObjectStoreData {
public ObjectStoreData(byte[] metadata, byte[] data) {
this.data = data;
this.metadata = metadata;
}
public final byte[] metadata;
public final byte[] data;
}
/**
* Put value in the local plasma store with object ID <tt>objectId</tt>.
*
* @param objectId The object ID of the value to be put.
* @param value The value to put in the object store.
* @param metadata encodes whatever metadata the user wishes to encode.
*/
void put(byte[] objectId, byte[] value, byte[] metadata)
throws DuplicateObjectException, PlasmaOutOfMemoryException;
/**
* Get a buffer from the PlasmaStore based on the <tt>objectId</tt>.
*
* @param objectId The object ID used to identify the object.
* @param timeoutMs The number of milliseconds that the get call should block before timing out
* and returning. Pass -1 if the call should block and 0 if the call should return immediately.
* @param isMetadata false if get data, otherwise get metadata.
* @return A PlasmaBuffer wrapping the object.
*/
default byte[] get(byte[] objectId, int timeoutMs, boolean isMetadata) {
byte[][] objectIds = {objectId};
return get(objectIds, timeoutMs, isMetadata).get(0);
}
/**
* Get buffers from the PlasmaStore based on <tt>objectIds</tt>.
*
* @param objectIds List of object IDs used to identify some objects.
* @param timeoutMs The number of milliseconds that the get call should block before timing out
* and returning. Pass -1 if the call should block and 0 if the call should return immediately.
* @param isMetadata false if get data, otherwise get metadata.
* @return List of PlasmaBuffers wrapping objects.
*/
List<byte[]> get(byte[][] objectIds, int timeoutMs, boolean isMetadata);
/**
* Get buffer pairs (data & metadata) from the PlasmaStore based on <tt>objectIds</tt>.
*
* @param objectIds List of object IDs used to identify some objects.
* @param timeoutMs The number of milliseconds that the get call should block before timing out
* and returning. Pass -1 if the call should block and 0 if the call should return immediately.
* @return List of Pairs of PlasmaBuffer wrapping objects and its metadata.
*/
List<ObjectStoreData> get(byte[][] objectIds, int timeoutMs);
/**
* Compute the hash of an object in the object store.
*
* @param objectId The object ID used to identify the object.
* @return A digest byte array contains object's SHA256 hash. <tt>null</tt> means that the object
* isn't in the object store.
*/
byte[] hash(byte[] objectId);
/**
* Evict some objects to recover given count of bytes.
*
* @param numBytes The number of bytes to attempt to recover.
* @return The number of bytes that have been evicted.
*/
long evict(long numBytes);
/**
* Release the reference of the object.
*
* @param objectId The object ID used to release the reference of the object.
*/
void release(byte[] objectId);
/**
* Removes object with given objectId from plasma store.
*
* @param objectId used to identify an object.
*/
void delete(byte[] objectId);
/**
* Check if the object is present and has been sealed in the PlasmaStore.
*
* @param objectId used to identify an object.
*/
boolean contains(byte[] objectId);
}
| apache-2.0 |
byu-oit/android-byu-suite-v2 | app/src/main/java/edu/byu/suite/features/addDrop/model/addDropMetas/CreditHoursResponseWrapper.java | 885 | package edu.byu.suite.features.addDrop.model.addDropMetas;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import edu.byu.suite.features.addDrop.model.AddDropGenericValue;
/**
* Created by poolguy on 3/17/17
*/
public class CreditHoursResponseWrapper {
@SerializedName("values")
private List<CreditHourWrapper> creditHourWrappers;
public List<CreditHourWrapper> getCreditHourWrappers() {
return creditHourWrappers;
}
private class CreditHourWrapper extends AddDropMeta {
private AddDropGenericValue<String> creditHours;
@Override
public String getText() {
return creditHours.getValue();
}
@Override
public String getDetailText() {
return null;
}
@Override
public String getShortTitle() {
return creditHours.getValue();
}
@Override
public String getQueryParam() {
return creditHours.getValue();
}
}
}
| apache-2.0 |
aledsage/legacy-brooklyn | software/nosql/src/main/java/brooklyn/entity/nosql/couchbase/CouchbaseCluster.java | 5720 | package brooklyn.entity.nosql.couchbase;
import java.util.List;
import java.util.Set;
import com.google.common.reflect.TypeToken;
import brooklyn.config.ConfigKey;
import brooklyn.entity.Entity;
import brooklyn.entity.basic.ConfigKeys;
import brooklyn.entity.group.DynamicCluster;
import brooklyn.entity.proxying.ImplementedBy;
import brooklyn.event.AttributeSensor;
import brooklyn.event.basic.Sensors;
import brooklyn.util.flags.SetFromFlag;
import brooklyn.util.time.Duration;
@ImplementedBy(CouchbaseClusterImpl.class)
public interface CouchbaseCluster extends DynamicCluster {
AttributeSensor<Integer> ACTUAL_CLUSTER_SIZE = Sensors.newIntegerSensor("coucbase.cluster.actualClusterSize", "returns the actual number of nodes in the cluster");
@SuppressWarnings("serial")
AttributeSensor<Set<Entity>> COUCHBASE_CLUSTER_UP_NODES = Sensors.newSensor(new TypeToken<Set<Entity>>() {
}, "couchbase.cluster.clusterEntities", "the set of service up nodes");
@SuppressWarnings("serial")
AttributeSensor<List<String>> COUCHBASE_CLUSTER_BUCKETS = Sensors.newSensor(new TypeToken<List<String>>() {
}, "couchbase.cluster.buckets", "Names of all the buckets the couchbase cluster");
AttributeSensor<Entity> COUCHBASE_PRIMARY_NODE = Sensors.newSensor(Entity.class, "couchbase.cluster.primaryNode", "The primary couchbase node to query and issue add-server and rebalance on");
AttributeSensor<Boolean> IS_CLUSTER_INITIALIZED = Sensors.newBooleanSensor("couchbase.cluster.isClusterInitialized", "flag to emit if the couchbase cluster was intialized");
@SetFromFlag("intialQuorumSize")
ConfigKey<Integer> INITIAL_QUORUM_SIZE = ConfigKeys.newIntegerConfigKey("couchbase.cluster.intialQuorumSize", "Initial cluster quorum size - number of initial nodes that must have been successfully started to report success (if < 0, then use value of INITIAL_SIZE)",
-1);
@SetFromFlag("delayBeforeAdvertisingCluster")
ConfigKey<Duration> DELAY_BEFORE_ADVERTISING_CLUSTER = ConfigKeys.newConfigKey(Duration.class, "couchbase.cluster.delayBeforeAdvertisingCluster", "Delay after cluster is started before checking and advertising its availability", Duration.THIRTY_SECONDS);
@SetFromFlag("serviceUpTimeOut")
ConfigKey<Duration> SERVICE_UP_TIME_OUT = ConfigKeys.newConfigKey(Duration.class, "couchbase.cluster.serviceUpTimeOut", "Service up time out duration for all the couchbase nodes", Duration.seconds(3 * 60));
@SuppressWarnings("serial")
AttributeSensor<List<String>> COUCHBASE_CLUSTER_UP_NODE_ADDRESSES = Sensors.newSensor(new TypeToken<List<String>>() {},
"couchbase.cluster.node.addresses", "List of host:port of all active nodes in the cluster (http admin port, and public hostname/IP)");
// Interesting stats
AttributeSensor<Double> OPS_PER_NODE = Sensors.newDoubleSensor("couchbase.stats.cluster.per.node.ops",
"Average across cluster for pools/nodes/<current node>/interestingStats/ops");
AttributeSensor<Double> EP_BG_FETCHED_PER_NODE = Sensors.newDoubleSensor("couchbase.stats.cluster.per.node.ep.bg.fetched",
"Average across cluster for pools/nodes/<current node>/interestingStats/ep_bg_fetched");
AttributeSensor<Double> CURR_ITEMS_PER_NODE = Sensors.newDoubleSensor("couchbase.stats.cluster.per.node.curr.items",
"Average across cluster for pools/nodes/<current node>/interestingStats/curr_items");
AttributeSensor<Double> VB_REPLICA_CURR_ITEMS_PER_NODE = Sensors.newDoubleSensor("couchbase.stats.cluster.per.node.vb.replica.curr.items",
"Average across cluster for pools/nodes/<current node>/interestingStats/vb_replica_curr_items");
AttributeSensor<Double> GET_HITS_PER_NODE = Sensors.newDoubleSensor("couchbase.stats.cluster.per.node.get.hits",
"Average across cluster for pools/nodes/<current node>/interestingStats/get_hits");
AttributeSensor<Double> CMD_GET_PER_NODE = Sensors.newDoubleSensor("couchbase.stats.cluster.per.node.cmd.get",
"Average across cluster for pools/nodes/<current node>/interestingStats/cmd_get");
AttributeSensor<Double> CURR_ITEMS_TOT_PER_NODE = Sensors.newDoubleSensor("couchbase.stats.cluster.per.node.curr.items.tot",
"Average across cluster for pools/nodes/<current node>/interestingStats/curr_items_tot");
// Although these are Double (after aggregation), they need to be coerced to Long for ByteSizeStrings rendering
AttributeSensor<Long> COUCH_DOCS_DATA_SIZE_PER_NODE = Sensors.newLongSensor("couchbase.stats.cluster.per.node.couch.docs.data.size",
"Average across cluster for pools/nodes/<current node>/interestingStats/couch_docs_data_size");
AttributeSensor<Long> MEM_USED_PER_NODE = Sensors.newLongSensor("couchbase.stats.cluster.per.node.mem.used",
"Average across cluster for pools/nodes/<current node>/interestingStats/mem_used");
AttributeSensor<Long> COUCH_VIEWS_ACTUAL_DISK_SIZE_PER_NODE = Sensors.newLongSensor("couchbase.stats.cluster.per.node.couch.views.actual.disk.size",
"Average across cluster for pools/nodes/<current node>/interestingStats/couch_views_actual_disk_size");
AttributeSensor<Long> COUCH_DOCS_ACTUAL_DISK_SIZE_PER_NODE = Sensors.newLongSensor("couchbase.stats.cluster.per.node.couch.docs.actual.disk.size",
"Average across cluster for pools/nodes/<current node>/interestingStats/couch_docs_actual_disk_size");
AttributeSensor<Long> COUCH_VIEWS_DATA_SIZE_PER_NODE = Sensors.newLongSensor("couchbase.stats.cluster.per.node.couch.views.data.size",
"Average across cluster for pools/nodes/<current node>/interestingStats/couch_views_data_size");
}
| apache-2.0 |
fastconnect/tibco-bwmaven | bw-maven-plugin/src/main/java/fr/fastconnect/factory/tibco/bw/maven/hawk/AdvancedSubscriptionHandler.java | 1378 | /**
* (C) Copyright 2011-2015 FastConnect SAS
* (http://www.fastconnect.fr/) and others.
*
* 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 fr.fastconnect.factory.tibco.bw.maven.hawk;
import COM.TIBCO.hawk.console.hawkeye.AgentManager;
import COM.TIBCO.hawk.talon.MethodSubscription;
import COM.TIBCO.hawk.talon.MicroAgentException;
import COM.TIBCO.hawk.talon.MicroAgentID;
import COM.TIBCO.hawk.talon.SubscriptionHandler;
public interface AdvancedSubscriptionHandler extends SubscriptionHandler {
public void onSubscribe();
public Object getResult();
public String formatData(Object data);
void subscribe(AgentManager agentManager, MicroAgentID microAgentID, MethodSubscription methodSubscription, Integer numberOfRetry, boolean displayOuptutData) throws MicroAgentException;
void decreaseReferenceCount();
void increaseReferenceCount();
}
| apache-2.0 |
cityzendata/warp10-platform | warp10/src/main/java/io/warp10/continuum/KafkaSynchronizedConsumerPool.java | 12497 | //
// Copyright 2018 SenX S.A.S.
//
// 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.warp10.continuum;
import io.warp10.continuum.store.Directory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
/**
* Generic class handling Kafka topic consumption and handling
* by multiple threads.
*
* One thread called the spawner will create consuming threads
* at launch time and when an abort situation is encountered.
*
* One thread called the synchronizer will periodically synchronize
* the consuming threads via a cyclic barrier and commit the offsets.
*
* The consuming threads consume the Kafka messages and act upon them.
*/
public class KafkaSynchronizedConsumerPool {
private static final Logger LOG = LoggerFactory.getLogger(KafkaSynchronizedConsumerPool.class);
private CyclicBarrier barrier;
private final AtomicBoolean abort;
private final AtomicBoolean initialized;
private final Synchronizer synchronizer;
private final Spawner spawner;
private final KafkaOffsetCounters counters;
private final AtomicBoolean shutdown = new AtomicBoolean(false);
private final AtomicBoolean stopped = new AtomicBoolean(false);
public static interface ConsumerFactory {
public Runnable getConsumer(KafkaSynchronizedConsumerPool pool, KafkaStream<byte[], byte[]> stream);
}
public static interface Hook {
public void call();
}
private static class Synchronizer extends Thread {
private final KafkaSynchronizedConsumerPool pool;
private final long commitPeriod;
private Hook syncHook = null;
public Synchronizer(KafkaSynchronizedConsumerPool pool, long commitPeriod) {
this.pool = pool;
this.commitPeriod = commitPeriod;
}
@Override
public void run() {
long lastsync = System.currentTimeMillis();
//
// Check for how long we've been storing readings, if we've reached the commitperiod,
// flush any pending commits and synchronize with the other threads so offsets can be committed
//
while(true) {
long now = System.currentTimeMillis();
//
// Only do something is the pool has been initialized (or re-initialized)
//
if (pool.getInitialized().get() && !pool.getAbort().get() && (now - lastsync > commitPeriod)) {
//
// Now join the cyclic barrier which will trigger the
// commit of offsets
//
try {
pool.getBarrier().await();
if (null != syncHook) {
syncHook.call();
}
// MOVE into sync hook - Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STORE_BARRIER_SYNCS, Sensision.EMPTY_LABELS, 1);
} catch (Exception e) {
pool.getAbort().set(true);
} finally {
lastsync = System.currentTimeMillis();
}
}
try {
Thread.sleep(100L);
} catch (InterruptedException ie) {
}
}
}
}
private static class Spawner extends Thread {
private final KafkaSynchronizedConsumerPool pool;
private final String zkconnect;
private final String topic;
private final String groupid;
private final String clientid;
private final String strategy;
private final String autoOffsetReset;
private final int nthreads;
private final ConsumerFactory factory;
private Hook abortHook = null;
private Hook preCommitOffsetHook = null;
private Hook commitOffsetHook = null;
public Spawner(KafkaSynchronizedConsumerPool pool, String zkconnect, String topic, String clientid, String groupid, String strategy, String autoOffsetReset, int nthreads, ConsumerFactory factory) {
this.pool = pool;
this.zkconnect = zkconnect;
this.topic = topic;
this.groupid = groupid;
this.strategy = strategy;
this.autoOffsetReset = autoOffsetReset;
this.clientid = clientid;
this.nthreads = nthreads;
this.factory = factory;
}
public void run() {
ExecutorService executor = null;
ConsumerConnector connector = null;
while(!pool.shutdown.get()) {
try {
//
// Enter an endless loop which will spawn 'nthreads' threads
// each time the Kafka consumer is shut down (which will happen if an error
// happens while talking to HBase for example, to get a chance to re-read data from the
// previous snapshot).
//
Map<String,Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(topic, nthreads);
Properties props = new Properties();
props.setProperty("zookeeper.connect", this.zkconnect);
props.setProperty("group.id",this.groupid);
if (null != this.clientid) {
props.setProperty("client.id", this.clientid);
}
if (null != this.strategy) {
props.setProperty("partition.assignment.strategy", this.strategy);
}
props.setProperty("auto.commit.enable", "false");
if (null != this.autoOffsetReset) {
props.setProperty("auto.offset.reset", this.autoOffsetReset);
}
ConsumerConfig config = new ConsumerConfig(props);
connector = Consumer.createJavaConsumerConnector(config);
Map<String,List<KafkaStream<byte[], byte[]>>> consumerMap = connector.createMessageStreams(topicCountMap);
// Reset counters so we only export metrics for partitions we really consume
pool.getCounters().reset();
List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);
// 1 for the Synchronizer, 1 for the Spawner
pool.setBarrier(new CyclicBarrier(1 + 1));
executor = Executors.newFixedThreadPool(nthreads);
//
// now create runnables which will consume messages
//
for (final KafkaStream<byte[],byte[]> stream : streams) {
executor.submit(factory.getConsumer(pool,stream));
}
pool.getInitialized().set(true);
while(!pool.getAbort().get() && !Thread.currentThread().isInterrupted()) {
try {
if (1 == pool.getBarrier().getNumberWaiting()) {
//
// Check if we should abort, which could happen when
// an exception was thrown when flushing the commits just before
// entering the barrier
//
if (pool.getAbort().get()) {
break;
}
//
// All processing threads are waiting on the barrier, this means we can flush the offsets because
// they have all processed data successfully for the given activity period
//
if (null != preCommitOffsetHook) {
preCommitOffsetHook.call();
}
// Commit offsets
connector.commitOffsets();
pool.getCounters().commit();
pool.getCounters().sensisionPublish();
if (null != commitOffsetHook) {
commitOffsetHook.call();
}
// MOVE in COMMIT HOOK - Sensision.update(SensisionConstants.SENSISION_CLASS_WEBCALL_KAFKA_IN_COMMITS, Sensision.EMPTY_LABELS, 1);
// Release the waiting threads
try {
pool.getBarrier().await();
} catch (Exception e) {
break;
}
}
} catch (Throwable t) {
pool.getAbort().set(true);
}
LockSupport.parkNanos(100000000L);
}
} catch (Throwable t) {
LOG.error("", t);
} finally {
//
// We exited the loop, this means one of the threads triggered an abort,
// we will shut down the executor and shut down the connector to start over.
//
if (null != executor) {
try {
executor.shutdownNow();
} catch (Exception e) {
}
}
if (null != connector) {
try {
connector.shutdown();
} catch (Exception e) {
}
}
if (null != abortHook) {
abortHook.call();
}
// MOVE in ABORT HOOK - Sensision.update(SensisionConstants.SENSISION_CLASS_WEBCALL_IN_ABORTS, Sensision.EMPTY_LABELS, 1);
// Set initialized to false first as this is what is checked by the Synchronizer
pool.getInitialized().set(false);
pool.getAbort().set(false);
LockSupport.parkNanos(1000000000L);
}
}
pool.stopped.set(true);
}
}
public KafkaSynchronizedConsumerPool(String zkconnect, String topic, String clientid, String groupid, String strategy, int nthreads, long commitPeriod, ConsumerFactory factory) {
this(zkconnect, topic, clientid, groupid, strategy, null, nthreads, commitPeriod, factory);
}
public KafkaSynchronizedConsumerPool(String zkconnect, String topic, String clientid, String groupid, String strategy, String autoOffsetReset, int nthreads, long commitPeriod, ConsumerFactory factory) {
this.abort = new AtomicBoolean(false);
this.initialized = new AtomicBoolean(false);
this.synchronizer = new Synchronizer(this, commitPeriod);
this.spawner = new Spawner(this, zkconnect, topic, clientid, groupid, strategy, autoOffsetReset, nthreads, factory);
this.counters = new KafkaOffsetCounters(topic, groupid, commitPeriod * 2);
synchronizer.setName("[Synchronizer '" + topic + "' (" + groupid + ") nthr=" + nthreads + " every " + commitPeriod + " ms]");
synchronizer.setDaemon(true);
synchronizer.start();
spawner.setName("[Spawner '" + topic + "' (" + groupid + ") nthr=" + nthreads + " every " + commitPeriod + " ms]");
spawner.setDaemon(true);
spawner.start();
}
private void setBarrier(CyclicBarrier barrier) {
this.barrier = barrier;
}
private CyclicBarrier getBarrier() {
return this.barrier;
}
public AtomicBoolean getAbort() {
return this.abort;
}
public AtomicBoolean getInitialized() {
return this.initialized;
}
public void setAbortHook(Hook hook) {
this.spawner.abortHook = hook;
}
public void setPreCommitOffsetHook(Hook hook) {
this.spawner.preCommitOffsetHook = hook;
}
public void setCommitOffsetHook(Hook hook) {
this.spawner.commitOffsetHook = hook;
}
public void setSyncHook(Hook hook) {
this.synchronizer.syncHook = hook;
}
public KafkaOffsetCounters getCounters() {
return this.counters;
}
public void shutdown() {
// Set shutdown to true first
this.shutdown.set(true);
this.abort.set(true);
}
public boolean isStopped() {
return this.stopped.get();
}
}
| apache-2.0 |
raksha-rao/gluster-ovirt | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/template/SubTabTemplateStoragePresenter.java | 2980 | package org.ovirt.engine.ui.webadmin.section.main.presenter.tab.template;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateListModel;
import org.ovirt.engine.ui.uicommonweb.models.templates.TemplateStorageListModel;
import org.ovirt.engine.ui.webadmin.gin.ClientGinjector;
import org.ovirt.engine.ui.webadmin.place.ApplicationPlaces;
import org.ovirt.engine.ui.webadmin.section.main.presenter.AbstractSubTabPresenter;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.TemplateSelectionChangeEvent;
import org.ovirt.engine.ui.webadmin.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.webadmin.widget.tab.ModelBoundTabData;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.TabData;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.ProxyEvent;
import com.gwtplatform.mvp.client.annotations.TabInfo;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;
import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace;
public class SubTabTemplateStoragePresenter extends AbstractSubTabPresenter<VmTemplate, TemplateListModel, TemplateStorageListModel, SubTabTemplateStoragePresenter.ViewDef, SubTabTemplateStoragePresenter.ProxyDef> {
@ProxyCodeSplit
@NameToken(ApplicationPlaces.templateStorageSubTabPlace)
public interface ProxyDef extends TabContentProxyPlace<SubTabTemplateStoragePresenter> {
}
public interface ViewDef extends AbstractSubTabPresenter.ViewDef<VmTemplate> {
}
@TabInfo(container = TemplateSubTabPanelPresenter.class)
static TabData getTabData(ClientGinjector ginjector) {
return new ModelBoundTabData(ginjector.getApplicationConstants().templateStorageSubTabLabel(), 4,
ginjector.getSubTabTemplateStorageModelProvider());
}
@Inject
public SubTabTemplateStoragePresenter(EventBus eventBus, ViewDef view, ProxyDef proxy,
PlaceManager placeManager,
SearchableDetailModelProvider<storage_domains, TemplateListModel, TemplateStorageListModel> modelProvider) {
super(eventBus, view, proxy, placeManager, modelProvider);
}
@Override
protected void revealInParent() {
RevealContentEvent.fire(this, TemplateSubTabPanelPresenter.TYPE_SetTabContent, this);
}
@Override
protected PlaceRequest getMainTabRequest() {
return new PlaceRequest(ApplicationPlaces.templateMainTabPlace);
}
@ProxyEvent
public void onTemplateSelectionChange(TemplateSelectionChangeEvent event) {
updateMainTabSelection(event.getSelectedItems());
}
}
| apache-2.0 |
andrewvc/elasticsearch | src/main/java/org/elasticsearch/cluster/routing/allocation/decider/AwarenessAllocationDecider.java | 11584 | /*
* Licensed to ElasticSearch and Shay Banon 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.cluster.routing.allocation.decider;
import com.carrotsearch.hppc.ObjectIntOpenHashMap;
import com.google.common.collect.Maps;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.routing.MutableShardRouting;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.settings.NodeSettingsService;
import java.util.HashMap;
import java.util.Map;
/**
* This {@link AllocationDecider} controls shard allocation based on
* <tt>awareness</tt> key-value pairs defined in the node configuration.
* Awareness explicitly controls where replicas should be allocated based on
* attributes like node or physical rack locations. Awareness attributes accept
* arbitrary configuration keys like a rack data-center identifier. For example
* the setting:
* <p/>
* <pre>
* cluster.routing.allocation.awareness.attributes: rack_id
* </pre>
* <p/>
* will cause allocations to be distributed over different racks such that
* ideally at least one replicas of the all shard is available on the same rack.
* To enable allocation awareness in this example nodes should contain a value
* for the <tt>rack_id</tt> key like:
* <p/>
* <pre>
* node.rack_id:1
* </pre>
* <p/>
* Awareness can also be used to prevent over-allocation in the case of node or
* even "zone" failure. For example in cloud-computing infrastructures like
* Amazone AWS a cluster might span over multiple "zones". Awareness can be used
* to distribute replicas to individual zones by setting:
* <p/>
* <pre>
* cluster.routing.allocation.awareness.attributes: zone
* </pre>
* <p/>
* and forcing allocation to be aware of the following zone the data resides in:
* <p/>
* <pre>
* cluster.routing.allocation.awareness.force.zone.values: zone1,zone2
* </pre>
* <p/>
* In contrast to regular awareness this setting will prevent over-allocation on
* <tt>zone1</tt> even if <tt>zone2</tt> fails partially or becomes entirely
* unavailable. Nodes that belong to a certain zone / group should be started
* with the zone id configured on the node-level settings like:
* <p/>
* <pre>
* node.zone: zone1
* </pre>
*/
public class AwarenessAllocationDecider extends AllocationDecider {
public static final String CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTES = "cluster.routing.allocation.awareness.attributes";
public static final String CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP = "cluster.routing.allocation.awareness.force.";
class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
String[] awarenessAttributes = settings.getAsArray(CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTES, null);
if (awarenessAttributes == null && "".equals(settings.get(CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTES, null))) {
awarenessAttributes = Strings.EMPTY_ARRAY; // the empty string resets this
}
if (awarenessAttributes != null) {
logger.info("updating [cluster.routing.allocation.awareness.attributes] from [{}] to [{}]", AwarenessAllocationDecider.this.awarenessAttributes, awarenessAttributes);
AwarenessAllocationDecider.this.awarenessAttributes = awarenessAttributes;
}
Map<String, String[]> forcedAwarenessAttributes = new HashMap<String, String[]>(AwarenessAllocationDecider.this.forcedAwarenessAttributes);
Map<String, Settings> forceGroups = settings.getGroups(CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP);
if (!forceGroups.isEmpty()) {
for (Map.Entry<String, Settings> entry : forceGroups.entrySet()) {
String[] aValues = entry.getValue().getAsArray("values");
if (aValues.length > 0) {
forcedAwarenessAttributes.put(entry.getKey(), aValues);
}
}
}
AwarenessAllocationDecider.this.forcedAwarenessAttributes = forcedAwarenessAttributes;
}
}
private String[] awarenessAttributes;
private Map<String, String[]> forcedAwarenessAttributes;
/**
* Creates a new {@link AwarenessAllocationDecider} instance
*/
public AwarenessAllocationDecider() {
this(ImmutableSettings.Builder.EMPTY_SETTINGS);
}
/**
* Creates a new {@link AwarenessAllocationDecider} instance from given settings
*
* @param settings {@link Settings} to use
*/
public AwarenessAllocationDecider(Settings settings) {
this(settings, new NodeSettingsService(settings));
}
@Inject
public AwarenessAllocationDecider(Settings settings, NodeSettingsService nodeSettingsService) {
super(settings);
this.awarenessAttributes = settings.getAsArray(CLUSTER_ROUTING_ALLOCATION_AWARENESS_ATTRIBUTES);
forcedAwarenessAttributes = Maps.newHashMap();
Map<String, Settings> forceGroups = settings.getGroups(CLUSTER_ROUTING_ALLOCATION_AWARENESS_FORCE_GROUP);
for (Map.Entry<String, Settings> entry : forceGroups.entrySet()) {
String[] aValues = entry.getValue().getAsArray("values");
if (aValues.length > 0) {
forcedAwarenessAttributes.put(entry.getKey(), aValues);
}
}
nodeSettingsService.addListener(new ApplySettings());
}
/**
* Get the attributes defined by this instance
*
* @return attributes defined by this instance
*/
public String[] awarenessAttributes() {
return this.awarenessAttributes;
}
@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
return underCapacity(shardRouting, node, allocation, true) ? Decision.YES : Decision.NO;
}
@Override
public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
return underCapacity(shardRouting, node, allocation, false) ? Decision.YES : Decision.NO;
}
private boolean underCapacity(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation, boolean moveToNode) {
if (awarenessAttributes.length == 0) {
return true;
}
IndexMetaData indexMetaData = allocation.metaData().index(shardRouting.index());
int shardCount = indexMetaData.numberOfReplicas() + 1; // 1 for primary
for (String awarenessAttribute : awarenessAttributes) {
// the node the shard exists on must be associated with an awareness attribute
if (!node.node().attributes().containsKey(awarenessAttribute)) {
return false;
}
// build attr_value -> nodes map
ObjectIntOpenHashMap<String> nodesPerAttribute = allocation.routingNodes().nodesPerAttributesCounts(awarenessAttribute);
// build the count of shards per attribute value
ObjectIntOpenHashMap<String> shardPerAttribute = new ObjectIntOpenHashMap<String>();
for (RoutingNode routingNode : allocation.routingNodes()) {
for (int i = 0; i < routingNode.shards().size(); i++) {
MutableShardRouting nodeShardRouting = routingNode.shards().get(i);
if (nodeShardRouting.shardId().equals(shardRouting.shardId())) {
// if the shard is relocating, then make sure we count it as part of the node it is relocating to
if (nodeShardRouting.relocating()) {
RoutingNode relocationNode = allocation.routingNodes().node(nodeShardRouting.relocatingNodeId());
shardPerAttribute.addTo(relocationNode.node().attributes().get(awarenessAttribute), 1);
} else if (nodeShardRouting.started()) {
shardPerAttribute.addTo(routingNode.node().attributes().get(awarenessAttribute), 1);
}
}
}
}
if (moveToNode) {
if (shardRouting.assignedToNode()) {
String nodeId = shardRouting.relocating() ? shardRouting.relocatingNodeId() : shardRouting.currentNodeId();
if (!node.nodeId().equals(nodeId)) {
// we work on different nodes, move counts around
shardPerAttribute.putOrAdd(allocation.routingNodes().node(nodeId).node().attributes().get(awarenessAttribute), 0, -1);
shardPerAttribute.addTo(node.node().attributes().get(awarenessAttribute), 1);
}
} else {
shardPerAttribute.addTo(node.node().attributes().get(awarenessAttribute), 1);
}
}
int numberOfAttributes = nodesPerAttribute.size();
String[] fullValues = forcedAwarenessAttributes.get(awarenessAttribute);
if (fullValues != null) {
for (String fullValue : fullValues) {
if (!shardPerAttribute.containsKey(fullValue)) {
numberOfAttributes++;
}
}
}
// TODO should we remove ones that are not part of full list?
int averagePerAttribute = shardCount / numberOfAttributes;
int totalLeftover = shardCount % numberOfAttributes;
int requiredCountPerAttribute;
if (averagePerAttribute == 0) {
// if we have more attributes values than shard count, no leftover
totalLeftover = 0;
requiredCountPerAttribute = 1;
} else {
requiredCountPerAttribute = averagePerAttribute;
}
int leftoverPerAttribute = totalLeftover == 0 ? 0 : 1;
int currentNodeCount = shardPerAttribute.get(node.node().attributes().get(awarenessAttribute));
// if we are above with leftover, then we know we are not good, even with mod
if (currentNodeCount > (requiredCountPerAttribute + leftoverPerAttribute)) {
return false;
}
// all is well, we are below or same as average
if (currentNodeCount <= requiredCountPerAttribute) {
continue;
}
}
return true;
}
}
| apache-2.0 |
p3et/gradoop | gradoop-flink/src/main/java/org/gradoop/flink/algorithms/fsm/dimspan/model/DFSCodeUtils.java | 2333 | /**
* Copyright © 2014 - 2017 Leipzig University (Database Research Group)
*
* 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.gradoop.flink.algorithms.fsm.dimspan.model;
import org.apache.commons.lang3.ArrayUtils;
/**
* Util methods to interpret and manipulate int-array encoded patterns represented by DFS codes.
*/
public class DFSCodeUtils extends GraphUtilsBase {
/**
* Extracts the branch of a give DFS code multiplex.
*
* @param mux DFS code multiplex
*
* @return mux of its first extension (branch)
*/
public int[] getBranch(int[] mux) {
return ArrayUtils.subarray(mux, 0, EDGE_LENGTH);
}
/**
* Extends a parent DFS code's multiplex
*
* @param parentMux multiplex
* @param fromTime from time
* @param fromLabel from label
* @param outgoing outgoing traversal
* @param edgeLabel traversed edge label
* @param toTime to time
* @param toLabel to label
*
* @return child DFS code's multiplex
*/
public int[] addExtension(int[] parentMux,
int fromTime, int fromLabel, boolean outgoing, int edgeLabel, int toTime, int toLabel) {
return ArrayUtils.addAll(
parentMux, multiplex(fromTime, fromLabel, outgoing, edgeLabel, toTime, toLabel));
}
/**
* Checks if a DFS code is child of another one.
*
* @param childMux multiplex of the child's DFS code
* @param parentMux mulitplex of the parent't DFS code
*
* @return true, if child is actually a child of the parent
*/
public boolean isChildOf(int[] childMux, int[] parentMux) {
boolean isChild = parentMux.length >= childMux.length;
if (isChild) {
for (int i = 0; i < childMux.length; i++) {
if (childMux[i] != parentMux[i]) {
isChild = false;
break;
}
}
}
return isChild;
}
}
| apache-2.0 |
shuliangtao/struts-1.3.10 | src/el/src/main/java/org/apache/strutsel/taglib/tiles/ELImportAttributeTag.java | 4590 | /*
* $Id: ELImportAttributeTag.java 471754 2006-11-06 14:55:09Z husted $
*
* 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.strutsel.taglib.tiles;
import org.apache.struts.tiles.taglib.ImportAttributeTag;
import org.apache.strutsel.taglib.utils.EvalHelper;
import javax.servlet.jsp.JspException;
/**
* Import attribute from component to requested scope. Attribute name and
* scope are optional. If not specified, all component attributes are imported
* in page scope. <p> This class is a subclass of the class
* <code>org.apache.struts.taglib.tiles.ImportAttributeTag</code> which
* provides most of the described functionality. This subclass allows all
* attribute values to be specified as expressions utilizing the JavaServer
* Pages Standard Library expression language.
*
* @version $Rev: 471754 $
*/
public class ELImportAttributeTag extends ImportAttributeTag {
/**
* Instance variable mapped to "scope" tag attribute. (Mapping set in
* associated BeanInfo class.)
*/
private String scopeExpr;
/**
* Instance variable mapped to "name" tag attribute. (Mapping set in
* associated BeanInfo class.)
*/
private String nameExpr;
/**
* Instance variable mapped to "ignore" tag attribute. (Mapping set in
* associated BeanInfo class.)
*/
private String ignoreExpr;
/**
* Getter method for "scope" tag attribute. (Mapping set in associated
* BeanInfo class.)
*/
public String getScopeExpr() {
return (scopeExpr);
}
/**
* Getter method for "name" tag attribute. (Mapping set in associated
* BeanInfo class.)
*/
public String getNameExpr() {
return (nameExpr);
}
/**
* Getter method for "ignore" tag attribute. (Mapping set in associated
* BeanInfo class.)
*/
public String getIgnoreExpr() {
return (ignoreExpr);
}
/**
* Setter method for "scope" tag attribute. (Mapping set in associated
* BeanInfo class.)
*/
public void setScopeExpr(String scopeExpr) {
this.scopeExpr = scopeExpr;
}
/**
* Setter method for "name" tag attribute. (Mapping set in associated
* BeanInfo class.)
*/
public void setNameExpr(String nameExpr) {
this.nameExpr = nameExpr;
}
/**
* Setter method for "ignore" tag attribute. (Mapping set in associated
* BeanInfo class.)
*/
public void setIgnoreExpr(String ignoreExpr) {
this.ignoreExpr = ignoreExpr;
}
/**
* Resets attribute values for tag reuse.
*/
public void release() {
super.release();
setScopeExpr(null);
setNameExpr(null);
setIgnoreExpr(null);
}
/**
* Process the start tag.
*
* @throws JspException if a JSP exception has occurred
*/
public int doStartTag() throws JspException {
evaluateExpressions();
return (super.doStartTag());
}
/**
* Processes all attribute values which use the JSTL expression evaluation
* engine to determine their values.
*
* @throws JspException if a JSP exception has occurred
*/
private void evaluateExpressions()
throws JspException {
String string = null;
Boolean bool = null;
if ((string =
EvalHelper.evalString("scope", getScopeExpr(), this, pageContext)) != null) {
setScope(string);
}
if ((string =
EvalHelper.evalString("name", getNameExpr(), this, pageContext)) != null) {
setName(string);
}
if ((bool =
EvalHelper.evalBoolean("ignore", getIgnoreExpr(), this,
pageContext)) != null) {
setIgnore(bool.booleanValue());
}
}
}
| apache-2.0 |
christian-posta/spring-boot | spring-boot/src/test/java/org/springframework/boot/web/servlet/WebServletHandlerTests.java | 6438 | /*
* Copyright 2012-2015 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.springframework.boot.web.servlet;
import java.io.IOException;
import java.util.Map;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.springframework.context.annotation.ScannedGenericBeanDefinition;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link WebServletHandler}.
*
* @author Andy Wilkinson
*/
public class WebServletHandlerTests {
private final WebServletHandler handler = new WebServletHandler();
private final SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
@Rule
public ExpectedException thrown = ExpectedException.none();
@SuppressWarnings("unchecked")
@Test
public void defaultServletConfiguration() throws IOException {
ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition(
new SimpleMetadataReaderFactory()
.getMetadataReader(DefaultConfigurationServlet.class.getName()));
this.handler.handle(scanned, this.registry);
BeanDefinition servletRegistrationBean = this.registry
.getBeanDefinition(DefaultConfigurationServlet.class.getName());
MutablePropertyValues propertyValues = servletRegistrationBean
.getPropertyValues();
assertThat(propertyValues.get("asyncSupported"), is((Object) false));
assertThat(((Map<String, String>) propertyValues.get("initParameters")).size(),
is(0));
assertThat((Integer) propertyValues.get("loadOnStartup"), is(-1));
assertThat(propertyValues.get("name"),
is((Object) DefaultConfigurationServlet.class.getName()));
assertThat((String[]) propertyValues.get("urlMappings"), is(arrayWithSize(0)));
assertThat(propertyValues.get("servlet"), is(equalTo((Object) scanned)));
}
@Test
public void servletWithCustomName() throws IOException {
ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition(
new SimpleMetadataReaderFactory()
.getMetadataReader(CustomNameServlet.class.getName()));
this.handler.handle(scanned, this.registry);
BeanDefinition servletRegistrationBean = this.registry
.getBeanDefinition("custom");
MutablePropertyValues propertyValues = servletRegistrationBean
.getPropertyValues();
assertThat(propertyValues.get("name"), is((Object) "custom"));
}
@Test
public void asyncSupported() throws IOException {
BeanDefinition servletRegistrationBean = getBeanDefinition(
AsyncSupportedServlet.class);
MutablePropertyValues propertyValues = servletRegistrationBean
.getPropertyValues();
assertThat(propertyValues.get("asyncSupported"), is((Object) true));
}
@SuppressWarnings("unchecked")
@Test
public void initParameters() throws IOException {
BeanDefinition servletRegistrationBean = getBeanDefinition(
InitParametersServlet.class);
MutablePropertyValues propertyValues = servletRegistrationBean
.getPropertyValues();
assertThat((Map<String, String>) propertyValues.get("initParameters"),
hasEntry("a", "alpha"));
assertThat((Map<String, String>) propertyValues.get("initParameters"),
hasEntry("b", "bravo"));
}
@Test
public void urlMappings() throws IOException {
BeanDefinition servletRegistrationBean = getBeanDefinition(
UrlPatternsServlet.class);
MutablePropertyValues propertyValues = servletRegistrationBean
.getPropertyValues();
assertThat((String[]) propertyValues.get("urlMappings"),
is(arrayContaining("alpha", "bravo")));
}
@Test
public void urlMappingsFromValue() throws IOException {
BeanDefinition servletRegistrationBean = getBeanDefinition(
UrlPatternsFromValueServlet.class);
MutablePropertyValues propertyValues = servletRegistrationBean
.getPropertyValues();
assertThat((String[]) propertyValues.get("urlMappings"),
is(arrayContaining("alpha", "bravo")));
}
@Test
public void urlPatternsDeclaredTwice() throws IOException {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage(
"The urlPatterns and value attributes are mututally " + "exclusive");
getBeanDefinition(UrlPatternsDeclaredTwiceServlet.class);
}
BeanDefinition getBeanDefinition(Class<?> filterClass) throws IOException {
ScannedGenericBeanDefinition scanned = new ScannedGenericBeanDefinition(
new SimpleMetadataReaderFactory()
.getMetadataReader(filterClass.getName()));
this.handler.handle(scanned, this.registry);
return this.registry.getBeanDefinition(filterClass.getName());
}
@WebServlet
class DefaultConfigurationServlet extends HttpServlet {
}
@WebServlet(asyncSupported = true)
class AsyncSupportedServlet extends HttpServlet {
}
@WebServlet(initParams = { @WebInitParam(name = "a", value = "alpha"),
@WebInitParam(name = "b", value = "bravo") })
class InitParametersServlet extends HttpServlet {
}
@WebServlet(urlPatterns = { "alpha", "bravo" })
class UrlPatternsServlet extends HttpServlet {
}
@WebServlet({ "alpha", "bravo" })
class UrlPatternsFromValueServlet extends HttpServlet {
}
@WebServlet(value = { "alpha", "bravo" }, urlPatterns = { "alpha", "bravo" })
class UrlPatternsDeclaredTwiceServlet extends HttpServlet {
}
@WebServlet(name = "custom")
class CustomNameServlet extends HttpServlet {
}
}
| apache-2.0 |
kozake/ermaster-k | org.insightech.er/src/org/insightech/er/db/impl/hsqldb/HSQLDBPreTableImportManager.java | 1627 | package org.insightech.er.db.impl.hsqldb;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.insightech.er.editor.model.dbimport.DBObject;
import org.insightech.er.editor.model.dbimport.PreImportFromDBManager;
public class HSQLDBPreTableImportManager extends PreImportFromDBManager {
@Override
protected List<DBObject> importSequences() throws SQLException {
List<DBObject> list = new ArrayList<DBObject>();
ResultSet resultSet = null;
PreparedStatement stmt = null;
if (this.schemaList.isEmpty()) {
this.schemaList.add(null);
}
for (String schemaPattern : this.schemaList) {
try {
if (schemaPattern == null) {
stmt = con
.prepareStatement("SELECT SEQUENCE_SCHEMA, SEQUENCE_NAME FROM INFORMATION_SCHEMA.SEQUENCES");
} else {
stmt = con
.prepareStatement("SELECT SEQUENCE_SCHEMA, SEQUENCE_NAME FROM INFORMATION_SCHEMA.SEQUENCES WHERE SEQUENCE_SCHEMA = ?");
stmt.setString(1, schemaPattern);
}
resultSet = stmt.executeQuery();
while (resultSet.next()) {
String schema = resultSet.getString("SEQUENCE_SCHEMA");
String name = resultSet.getString("SEQUENCE_NAME");
DBObject dbObject = new DBObject(schema, name,
DBObject.TYPE_SEQUENCE);
list.add(dbObject);
}
} finally {
if (resultSet != null) {
resultSet.close();
resultSet = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
}
}
return list;
}
}
| apache-2.0 |
ahwxl/deep | src/main/java/org/activiti/engine/impl/cmd/GetExecutionVariableCmd.java | 2191 | /* 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.activiti.engine.impl.cmd;
import java.io.Serializable;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.runtime.Execution;
/**
* @author Tom Baeyens
*/
public class GetExecutionVariableCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String executionId;
protected String variableName;
protected boolean isLocal;
public GetExecutionVariableCmd(String executionId, String variableName, boolean isLocal) {
this.executionId = executionId;
this.variableName = variableName;
this.isLocal = isLocal;
}
public Object execute(CommandContext commandContext) {
if(executionId == null) {
throw new ActivitiIllegalArgumentException("executionId is null");
}
if(variableName == null) {
throw new ActivitiIllegalArgumentException("variableName is null");
}
ExecutionEntity execution = commandContext
.getExecutionEntityManager()
.findExecutionById(executionId);
if (execution==null) {
throw new ActivitiObjectNotFoundException("execution "+executionId+" doesn't exist", Execution.class);
}
Object value;
if (isLocal) {
value = execution.getVariableLocal(variableName);
} else {
value = execution.getVariable(variableName);
}
return value;
}
}
| apache-2.0 |
MaDaPHaKa/Orient-object | core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocument.java | 2558 | /*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.db.document;
import com.orientechnologies.orient.core.db.ODatabaseSchemaAware;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.iterator.ORecordIteratorClass;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
/**
* Generic interface for document based Database implementations.
*
* @author Luca Garulli
*/
public interface ODatabaseDocument extends ODatabaseRecord, ODatabaseSchemaAware<ORecordInternal<?>> {
final static String TYPE = "document";
/**
* Browses all the records of the specified class and also all the subclasses. If you've a class Vehicle and Car that extends
* Vehicle then a db.browseClass("Vehicle", true) will return all the instances of Vehicle and Car. The order of the returned
* instance starts from record id with position 0 until the end. Base classes are worked at first.
*
* @param iClassName
* Class name to iterate
* @return Iterator of ODocument instances
*/
public ORecordIteratorClass<ODocument> browseClass(String iClassName);
/**
* Browses all the records of the specified class and if iPolymorphic is true also all the subclasses. If you've a class Vehicle
* and Car that extends Vehicle then a db.browseClass("Vehicle", true) will return all the instances of Vehicle and Car. The order
* of the returned instance starts from record id with position 0 until the end. Base classes are worked at first.
*
* @param iClassName
* Class name to iterate
* @param iPolymorphic
* Consider also the instances of the subclasses or not
* @return Iterator of ODocument instances
*/
public ORecordIteratorClass<ODocument> browseClass(String iClassName, boolean iPolymorphic);
}
| apache-2.0 |
zckrbrt/verteilte-systeme | spring-redis-demo/src/main/java/de/hska/lkit/demo/redis/model/User.java | 993 | package de.hska.lkit.demo.redis.model;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String username;
private String password;
private String firstname;
private String lastname;
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
| apache-2.0 |
kuFEAR/crest | core/src/test/java/org/codegist/crest/param/CollectionMergingParamProcessorTest.java | 5366 | /*
* Copyright 2011 CodeGist.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ===================================================================
*
* More information at http://www.codegist.org.
*/
package org.codegist.crest.param;
import org.codegist.crest.config.ParamConfig;
import org.codegist.crest.serializer.Serializer;
import org.codegist.crest.serializer.ToStringSerializer;
import org.junit.Test;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static java.util.Arrays.asList;
import static org.codegist.crest.test.util.Values.UTF8;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author laurent.gilles@codegist.org
*/
public class CollectionMergingParamProcessorTest {
private final CollectionMergingParamProcessor toTest = new CollectionMergingParamProcessor("--");
@Test
public void shouldProcessParamEncodingThem() throws Exception {
Serializer serializer = new ToStringSerializer();
ParamConfig paramConfig = mock(ParamConfig.class);
when(paramConfig.getSerializer()).thenReturn(serializer);
when(paramConfig.isEncoded()).thenReturn(false);
when(paramConfig.getName()).thenReturn("p1");
Param param = mock(Param.class);
when(param.getParamConfig()).thenReturn(paramConfig);
when(param.getValue()).thenReturn((Collection) asList("v 11", "v 12"));
List<EncodedPair> actual = toTest.process(param, UTF8, true);
assertEquals(1, actual.size());
assertEquals("p1", actual.get(0).getName());
assertEquals("v%2011--v%2012", actual.get(0).getValue());
}
@Test
public void shouldProcessPreEncodedParams() throws Exception {
Serializer serializer = new ToStringSerializer();
ParamConfig paramConfig = mock(ParamConfig.class);
when(paramConfig.getSerializer()).thenReturn(serializer);
when(paramConfig.isEncoded()).thenReturn(true);
when(paramConfig.getName()).thenReturn("p1");
Param param = mock(Param.class);
when(param.getParamConfig()).thenReturn(paramConfig);
when(param.getValue()).thenReturn((Collection) asList("v%2011", "v%2012"));
List<EncodedPair> actual = toTest.process(param, UTF8, true);
assertEquals(1, actual.size());
assertEquals("p1", actual.get(0).getName());
assertEquals("v%2011--v%2012", actual.get(0).getValue());
}
@Test
public void shouldProcessParamIgnoringEncodingFlag() throws Exception {
Serializer serializer = new ToStringSerializer();
ParamConfig paramConfig = mock(ParamConfig.class);
when(paramConfig.getSerializer()).thenReturn(serializer);
when(paramConfig.isEncoded()).thenReturn(false);
when(paramConfig.getName()).thenReturn("p1");
Param param = mock(Param.class);
when(param.getParamConfig()).thenReturn(paramConfig);
when(param.getValue()).thenReturn((Collection) asList("v 11", "v 12"));
List<EncodedPair> actual = toTest.process(param, UTF8, false);
assertEquals(1, actual.size());
assertEquals("p1", actual.get(0).getName());
assertEquals("v 11--v 12", actual.get(0).getValue());
}
@Test
public void shouldProcessPreEncodedParamsIgnoringEncodingFlag() throws Exception {
Serializer serializer = new ToStringSerializer();
ParamConfig paramConfig = mock(ParamConfig.class);
when(paramConfig.getSerializer()).thenReturn(serializer);
when(paramConfig.isEncoded()).thenReturn(true);
when(paramConfig.getName()).thenReturn("p1");
Param param = mock(Param.class);
when(param.getParamConfig()).thenReturn(paramConfig);
when(param.getValue()).thenReturn((Collection) asList("v%2011", "v%2012"));
List<EncodedPair> actual = toTest.process(param, UTF8, false);
assertEquals(1, actual.size());
assertEquals("p1", actual.get(0).getName());
assertEquals("v%2011--v%2012", actual.get(0).getValue());
}
@Test
public void shouldProcessEmptyParams() throws Exception {
Serializer serializer = new ToStringSerializer();
ParamConfig paramConfig = mock(ParamConfig.class);
when(paramConfig.getSerializer()).thenReturn(serializer);
when(paramConfig.isEncoded()).thenReturn(true);
when(paramConfig.getName()).thenReturn("p1");
Param param = mock(Param.class);
when(param.getParamConfig()).thenReturn(paramConfig);
when(param.getValue()).thenReturn(Collections.<Object>emptyList());
List<EncodedPair> actual = toTest.process(param, UTF8, true);
assertEquals(0, actual.size());
}
}
| apache-2.0 |
CommonQ/sms_DualCard | src/edu/bupt/mms/transaction/Transaction.java | 10410 | /*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 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 edu.bupt.mms.transaction;
import edu.bupt.mms.util.SendingProgressTokenManager;
import com.google.android.mms.MmsException;
import android.content.Context;
import android.net.Uri;
import android.net.ConnectivityManager;
import android.util.Log;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Transaction is an abstract class for notification transaction, send transaction
* and other transactions described in MMS spec.
* It provides the interfaces of them and some common methods for them.
*/
public abstract class Transaction extends Observable {
private final int mServiceId;
protected Context mContext;
protected String mId;
protected TransactionState mTransactionState;
protected TransactionSettings mTransactionSettings;
/**
* Identifies push requests.
*/
public static final int NOTIFICATION_TRANSACTION = 0;
/**
* Identifies deferred retrieve requests.
*/
public static final int RETRIEVE_TRANSACTION = 1;
/**
* Identifies send multimedia message requests.
*/
public static final int SEND_TRANSACTION = 2;
/**
* Identifies send read report requests.
*/
public static final int READREC_TRANSACTION = 3;
public Transaction(Context context, int serviceId,
TransactionSettings settings) {
mContext = context;
mTransactionState = new TransactionState();
mServiceId = serviceId;
mTransactionSettings = settings;
}
/**
* Returns the transaction state of this transaction.
*
* @return Current state of the Transaction.
*/
@Override
public TransactionState getState() {
return mTransactionState;
}
/**
* An instance of Transaction encapsulates the actions required
* during a MMS Client transaction.
*/
public abstract void process();
/**
* Used to determine whether a transaction is equivalent to this instance.
*
* @param transaction the transaction which is compared to this instance.
* @return true if transaction is equivalent to this instance, false otherwise.
*/
public boolean isEquivalent(Transaction transaction) {
return getClass().equals(transaction.getClass())
&& mId.equals(transaction.mId);
}
/**
* Get the service-id of this transaction which was assigned by the framework.
* @return the service-id of the transaction
*/
public int getServiceId() {
return mServiceId;
}
public TransactionSettings getConnectionSettings() {
return mTransactionSettings;
}
public void setConnectionSettings(TransactionSettings settings) {
mTransactionSettings = settings;
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws MmsException if pdu is null.
*/
protected byte[] sendPdu(byte[] pdu) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu,
mTransactionSettings.getMmscUrl());
}
/**
* A common method to send a PDU to MMSC.
*
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws MmsException if pdu is null.
*/
protected byte[] sendPdu(byte[] pdu, String mmscUrl) throws IOException, MmsException {
return sendPdu(SendingProgressTokenManager.NO_TOKEN, pdu, mmscUrl);
}
/**
* A common method to send a PDU to MMSC.
*
* @param token The token to identify the sending progress.
* @param pdu A byte array which contains the data of the PDU.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws MmsException if pdu is null.
*/
protected byte[] sendPdu(long token, byte[] pdu) throws IOException, MmsException {
return sendPdu(token, pdu, mTransactionSettings.getMmscUrl());
}
/**
* A common method to send a PDU to MMSC.
*
* @param token The token to identify the sending progress.
* @param pdu A byte array which contains the data of the PDU.
* @param mmscUrl Url of the recipient MMSC.
* @return A byte array which contains the response data.
* If an HTTP error code is returned, an IOException will be thrown.
* @throws IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
* @throws MmsException if pdu is null.
*/
protected byte[] sendPdu(long token, byte[] pdu,
String mmscUrl) throws IOException, MmsException {
if (pdu == null) {
throw new MmsException();
}
ensureRouteToHost(mmscUrl, mTransactionSettings);
return HttpUtils.httpConnection(
mContext, token,
mmscUrl,
pdu, HttpUtils.HTTP_POST_METHOD,
mTransactionSettings.isProxySet(),
mTransactionSettings.getProxyAddress(),
mTransactionSettings.getProxyPort());
}
/**
* A common method to retrieve a PDU from MMSC.
*
* @param url The URL of the message which we are going to retrieve.
* @return A byte array which contains the data of the PDU.
* If the status code is not correct, an IOException will be thrown.
* @throws IOException if any error occurred on network interface or
* an HTTP error code(>=400) returned from the server.
*/
protected byte[] getPdu(String url) throws IOException {
ensureRouteToHost(url, mTransactionSettings);
return HttpUtils.httpConnection(
mContext, SendingProgressTokenManager.NO_TOKEN,
url, null, HttpUtils.HTTP_GET_METHOD,
mTransactionSettings.isProxySet(),
mTransactionSettings.getProxyAddress(),
mTransactionSettings.getProxyPort());
}
/**
* Make sure that a network route exists to allow us to reach the host in the
* supplied URL, and to the MMS proxy host as well, if a proxy is used.
* @param url The URL of the MMSC to which we need a route
* @param settings Specifies the address of the proxy host, if any
* @throws IOException if the host doesn't exist, or adding the route fails.
*/
private void ensureRouteToHost(String url, TransactionSettings settings) throws IOException {
ConnectivityManager connMgr =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
int inetAddr;
if (settings.isProxySet()) {
String proxyAddr = settings.getProxyAddress();
inetAddr = lookupHost(proxyAddr);
if (inetAddr == -1) {
throw new IOException("Cannot establish route for " + url + ": Unknown host");
} else {
if (!connMgr.requestRouteToHost(
ConnectivityManager.TYPE_MOBILE_MMS, inetAddr)) {
throw new IOException("Cannot establish route to proxy " + inetAddr);
}
}
} else {
Uri uri = Uri.parse(url);
inetAddr = lookupHost(uri.getHost());
if (inetAddr == -1) {
throw new IOException("Cannot establish route for " + url + ": Unknown host");
} else {
if (!connMgr.requestRouteToHost(
ConnectivityManager.TYPE_MOBILE_MMS, inetAddr)) {
throw new IOException("Cannot establish route to " + inetAddr + " for " + url);
}
}
}
}
/**
* Look up a host name and return the result as an int. Works if the argument
* is an IP address in dot notation. Obviously, this can only be used for IPv4
* addresses.
* @param hostname the name of the host (or the IP address)
* @return the IP address as an {@code int} in network byte order
*/
// TODO: move this to android-common
public static int lookupHost(String hostname) {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
return -1;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
| ((addrBytes[2] & 0xff) << 16)
| ((addrBytes[1] & 0xff) << 8)
| (addrBytes[0] & 0xff);
return addr;
}
@Override
public String toString() {
return getClass().getName() + ": serviceId=" + mServiceId;
}
/**
* Get the type of the transaction.
*
* @return Transaction type in integer.
*/
abstract public int getType();
}
| apache-2.0 |
yanzhijun/jclouds-aliyun | core/src/test/java/org/jclouds/logging/BufferLogger.java | 5031 | /*
* 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.jclouds.logging;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import com.google.common.base.Predicate;
/** A logger implementation for use in testing; all log messages are remembered, \
* but not written anywhere. The messages can then be inspected {@link #getMessages()}
* or certain assertions applied (see assertXxx methods on these instances) */
public class BufferLogger extends BaseLogger {
final String category;
Level level = Level.INFO;
List<Record> messages = Collections.synchronizedList(new ArrayList<Record>());
public static class Record {
Level level;
String message;
Throwable trace;
public Record(Level level, String message, Throwable trace) {
this.level = level;
this.message = message;
this.trace = trace;
}
public Level getLevel() {
return level;
}
public String getMessage() {
return message;
}
public Throwable getTrace() {
return trace;
}
}
public BufferLogger(String category) {
this.category = category;
}
public List<Record> getMessages() {
return messages;
}
/** throws AssertionError if the log does not contain the indicated fragment;
* otherwise returns a record which does satisfy the constraint
*/
public Record assertLogContains(String fragment) {
for (Record r : messages) {
if (r.getMessage() != null && r.getMessage().contains(fragment)) return r;
}
throw new AssertionError("log did not contain expected '" + fragment + "'");
}
/** fails if log _does_ contain the indicated fragment */
public void assertLogDoesntContain(String fragment) {
for (Record r : messages) {
if (r.getMessage() != null && r.getMessage().contains(fragment))
throw new AssertionError("log contained unexpected '" + fragment + "'");
}
}
/** throws AssertionError if the log does not contain the indicated fragment;
* otherwise returns a record which does satisfy the constraint
*/
public Record assertLogContains(Predicate<Record> test) {
for (Record r : messages) {
if (r.getMessage() != null && test.apply(r)) return r;
}
throw new AssertionError("log did not contain any records satisfying expected predicate");
}
@Override
public String getCategory() {
return category;
}
public void setLevel(Level level) {
this.level = level;
}
public void setAllLevelsEnabled() {
level = Level.ALL;
}
public void setAllLevelsDisabled() {
level = Level.OFF;
}
@Override
public boolean isTraceEnabled() {
return level.intValue() <= Level.FINER.intValue();
}
@Override
public boolean isDebugEnabled() {
return level.intValue() <= Level.FINE.intValue();
}
@Override
public boolean isInfoEnabled() {
return level.intValue() <= Level.INFO.intValue();
}
@Override
public boolean isWarnEnabled() {
return level.intValue() <= Level.WARNING.intValue();
}
@Override
public boolean isErrorEnabled() {
return level.intValue() <= Level.SEVERE.intValue();
}
@Override
protected void logError(String message, Throwable e) {
getMessages().add(new Record(Level.SEVERE, message, e));
}
@Override
protected void logError(String message) {
getMessages().add(new Record(Level.SEVERE, message, null));
}
@Override
protected void logWarn(String message, Throwable e) {
getMessages().add(new Record(Level.WARNING, message, e));
}
@Override
protected void logWarn(String message) {
getMessages().add(new Record(Level.WARNING, message, null));
}
@Override
protected void logInfo(String message) {
getMessages().add(new Record(Level.INFO, message, null));
}
@Override
protected void logDebug(String message) {
getMessages().add(new Record(Level.FINE, message, null));
}
@Override
protected void logTrace(String message) {
getMessages().add(new Record(Level.FINER, message, null));
}
}
| apache-2.0 |
arina-ielchiieva/calcite | core/src/main/java/org/apache/calcite/sql/type/CompositeOperandTypeChecker.java | 9810 | /*
* 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.calcite.sql.type;
import org.apache.calcite.linq4j.Ord;
import org.apache.calcite.sql.SqlCallBinding;
import org.apache.calcite.sql.SqlOperandCountRange;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.util.Util;
import com.google.common.collect.ImmutableList;
import java.util.AbstractList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* This class allows multiple existing {@link SqlOperandTypeChecker} rules to be
* combined into one rule. For example, allowing an operand to be either string
* or numeric could be done by:
*
* <blockquote>
* <pre><code>
* CompositeOperandsTypeChecking newCompositeRule =
* new CompositeOperandsTypeChecking(Composition.OR,
* new SqlOperandTypeChecker[]{stringRule, numericRule});
* </code></pre>
* </blockquote>
*
* <p>Similarly a rule that would only allow a numeric literal can be done by:
*
* <blockquote>
* <pre><code>
* CompositeOperandsTypeChecking newCompositeRule =
* new CompositeOperandsTypeChecking(Composition.AND,
* new SqlOperandTypeChecker[]{numericRule, literalRule});
* </code></pre>
* </blockquote>
*
* <p>Finally, creating a signature expecting a string for the first operand and
* a numeric for the second operand can be done by:
*
* <blockquote>
* <pre><code>
* CompositeOperandsTypeChecking newCompositeRule =
* new CompositeOperandsTypeChecking(Composition.SEQUENCE,
* new SqlOperandTypeChecker[]{stringRule, numericRule});
* </code></pre>
* </blockquote>
*
* <p>For SEQUENCE composition, the rules must be instances of
* SqlSingleOperandTypeChecker, and signature generation is not supported. For
* AND composition, only the first rule is used for signature generation.
*/
public class CompositeOperandTypeChecker implements SqlOperandTypeChecker {
private final SqlOperandCountRange range;
//~ Enums ------------------------------------------------------------------
/** How operands are composed. */
public enum Composition {
AND, OR, SEQUENCE, REPEAT
}
//~ Instance fields --------------------------------------------------------
protected final ImmutableList<? extends SqlOperandTypeChecker> allowedRules;
protected final Composition composition;
private final String allowedSignatures;
//~ Constructors -----------------------------------------------------------
/**
* Package private. Use {@link OperandTypes#and},
* {@link OperandTypes#or}.
*/
CompositeOperandTypeChecker(
Composition composition,
ImmutableList<? extends SqlOperandTypeChecker> allowedRules,
@Nullable String allowedSignatures,
@Nullable SqlOperandCountRange range) {
this.allowedRules = Objects.requireNonNull(allowedRules);
this.composition = Objects.requireNonNull(composition);
this.allowedSignatures = allowedSignatures;
this.range = range;
assert (range != null) == (composition == Composition.REPEAT);
assert allowedRules.size() + (range == null ? 0 : 1) > 1;
}
//~ Methods ----------------------------------------------------------------
public boolean isOptional(int i) {
for (SqlOperandTypeChecker allowedRule : allowedRules) {
if (allowedRule.isOptional(i)) {
return true;
}
}
return false;
}
public ImmutableList<? extends SqlOperandTypeChecker> getRules() {
return allowedRules;
}
public Consistency getConsistency() {
return Consistency.NONE;
}
public String getAllowedSignatures(SqlOperator op, String opName) {
if (allowedSignatures != null) {
return allowedSignatures;
}
if (composition == Composition.SEQUENCE) {
throw new AssertionError(
"specify allowedSignatures or override getAllowedSignatures");
}
StringBuilder ret = new StringBuilder();
for (Ord<SqlOperandTypeChecker> ord
: Ord.<SqlOperandTypeChecker>zip(allowedRules)) {
if (ord.i > 0) {
ret.append(SqlOperator.NL);
}
ret.append(ord.e.getAllowedSignatures(op, opName));
if (composition == Composition.AND) {
break;
}
}
return ret.toString();
}
public SqlOperandCountRange getOperandCountRange() {
switch (composition) {
case REPEAT:
return range;
case SEQUENCE:
return SqlOperandCountRanges.of(allowedRules.size());
case AND:
case OR:
default:
final List<SqlOperandCountRange> ranges =
new AbstractList<SqlOperandCountRange>() {
public SqlOperandCountRange get(int index) {
return allowedRules.get(index).getOperandCountRange();
}
public int size() {
return allowedRules.size();
}
};
final int min = minMin(ranges);
final int max = maxMax(ranges);
SqlOperandCountRange composite =
new SqlOperandCountRange() {
public boolean isValidCount(int count) {
switch (composition) {
case AND:
for (SqlOperandCountRange range : ranges) {
if (!range.isValidCount(count)) {
return false;
}
}
return true;
case OR:
default:
for (SqlOperandCountRange range : ranges) {
if (range.isValidCount(count)) {
return true;
}
}
return false;
}
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
};
if (max >= 0) {
for (int i = min; i <= max; i++) {
if (!composite.isValidCount(i)) {
// Composite is not a simple range. Can't simplify,
// so return the composite.
return composite;
}
}
}
return min == max
? SqlOperandCountRanges.of(min)
: SqlOperandCountRanges.between(min, max);
}
}
private int minMin(List<SqlOperandCountRange> ranges) {
int min = Integer.MAX_VALUE;
for (SqlOperandCountRange range : ranges) {
min = Math.min(min, range.getMax());
}
return min;
}
private int maxMax(List<SqlOperandCountRange> ranges) {
int max = Integer.MIN_VALUE;
for (SqlOperandCountRange range : ranges) {
if (range.getMax() < 0) {
if (composition == Composition.OR) {
return -1;
}
} else {
max = Math.max(max, range.getMax());
}
}
return max;
}
public boolean checkOperandTypes(
SqlCallBinding callBinding,
boolean throwOnFailure) {
if (check(callBinding)) {
return true;
}
if (!throwOnFailure) {
return false;
}
if (composition == Composition.OR) {
for (SqlOperandTypeChecker allowedRule : allowedRules) {
allowedRule.checkOperandTypes(callBinding, true);
}
}
// If no exception thrown, just throw a generic validation
// signature error.
throw callBinding.newValidationSignatureError();
}
private boolean check(SqlCallBinding callBinding) {
switch (composition) {
case REPEAT:
if (!range.isValidCount(callBinding.getOperandCount())) {
return false;
}
for (int operand : Util.range(callBinding.getOperandCount())) {
for (SqlOperandTypeChecker rule : allowedRules) {
if (!((SqlSingleOperandTypeChecker) rule).checkSingleOperandType(
callBinding,
callBinding.getCall().operand(operand),
0,
false)) {
return false;
}
}
}
return true;
case SEQUENCE:
if (callBinding.getOperandCount() != allowedRules.size()) {
return false;
}
for (Ord<SqlOperandTypeChecker> ord
: Ord.<SqlOperandTypeChecker>zip(allowedRules)) {
SqlOperandTypeChecker rule = ord.e;
if (!((SqlSingleOperandTypeChecker) rule).checkSingleOperandType(
callBinding,
callBinding.getCall().operand(ord.i),
0,
false)) {
return false;
}
}
return true;
case AND:
for (Ord<SqlOperandTypeChecker> ord
: Ord.<SqlOperandTypeChecker>zip(allowedRules)) {
SqlOperandTypeChecker rule = ord.e;
if (!rule.checkOperandTypes(callBinding, false)) {
// Avoid trying other rules in AND if the first one fails.
return false;
}
}
return true;
case OR:
for (Ord<SqlOperandTypeChecker> ord
: Ord.<SqlOperandTypeChecker>zip(allowedRules)) {
SqlOperandTypeChecker rule = ord.e;
if (rule.checkOperandTypes(callBinding, false)) {
return true;
}
}
return false;
default:
throw new AssertionError();
}
}
}
// End CompositeOperandTypeChecker.java
| apache-2.0 |
anton415/Job4j | Pre-middle/Part_1_Input_Output/src/test/java/ru/aserdyuchenko/fileManager/RealizationClientTest.java | 1524 | package ru.aserdyuchenko.fileManager;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import static org.hamcrest.core.Is.is;
import org.junit.Test;
import java.net.Socket;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.base.Joiner;
/**
* @author Anton Serdyuchenko (anton415@gmail.com)
*/
public class RealizationClientTest {
/**
* @param LINESEPARATOR LINESEPARATOR.
*/
private static final String LINESEPARATOR = System.getProperty("line.separator");
/**
* Test.
* @throws IOException IOException.
*/
@Test
public void whenSayHelloAndExit() throws IOException {
this.testClient(
Joiner.on(LINESEPARATOR).join(
"Hello file manager",
"Exit"
),
Joiner.on(LINESEPARATOR).join(
"Hello file manager",
"Exit",
""
)
);
}
/**
* Test.
* @param input input.
* @param excepted excepted.
* @throws IOException IOException.
*/
private void testClient(String input, String excepted) throws IOException {
Socket socket = mock(Socket.class);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(
input.getBytes()
);
when(socket.getInputStream()).thenReturn(in);
when(socket.getOutputStream()).thenReturn(out);
RealizationClient client = new RealizationClient(socket);
client.startClient();
assertThat(out.toString(), is(excepted));
}
}
| apache-2.0 |
jk1/intellij-community | platform/vcs-api/src/com/intellij/openapi/vcs/changes/LocalChangeList.java | 2127 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.actions.VcsContextFactory;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* @author max
*/
public abstract class LocalChangeList implements Cloneable, ChangeList {
@NonNls public static final String DEFAULT_NAME = VcsBundle.message("changes.default.changelist.name");
@NonNls public static final String OLD_DEFAULT_NAME = "Default";
public static LocalChangeList createEmptyChangeList(Project project, @NotNull String name) {
return VcsContextFactory.SERVICE.getInstance().createLocalChangeList(project, name);
}
public abstract Collection<Change> getChanges();
/**
* Logical id that identifies the changelist and should survive name changing.
* @return changelist id
*/
@NotNull
public String getId() {
return getName();
}
@NotNull
public abstract String getName();
@Nullable
public abstract String getComment();
public abstract boolean isDefault();
public abstract boolean isReadOnly();
/**
* Get additional data associated with this changelist.
*/
@Nullable
public abstract Object getData();
public abstract LocalChangeList copy();
public boolean hasDefaultName() {
return DEFAULT_NAME.equals(getName()) || OLD_DEFAULT_NAME.equals(getName());
}
public boolean isBlank() {
return hasDefaultName() && getData() == null;
}
/**
* Use {@link ChangeListManager#editName}
*/
@Deprecated
public abstract void setName(@NotNull String name);
/**
* Use {@link ChangeListManager#editComment}
*/
@Deprecated
public abstract void setComment(@Nullable String comment);
/**
* Use {@link ChangeListManager#setReadOnly}
*/
@Deprecated
public abstract void setReadOnly(boolean isReadOnly);
}
| apache-2.0 |
billchen198318/bamboobsc | core-doc/OLD_BASE_DAO_SERVICE/BaseDAO.java | 26738 | /*
* Copyright 2012-2016 bambooCORE, greenstep of copyright Chen Xin Nien
*
* 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: Chen Xin Nien
* contact: chen.xin.nien@gmail.com
*
*/
package com.netsteadfast.greenstep.base.dao;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.netsteadfast.greenstep.base.Constants;
import com.netsteadfast.greenstep.base.SysMessageUtil;
import com.netsteadfast.greenstep.base.model.BaseEntity;
import com.netsteadfast.greenstep.base.model.BaseEntityUtil;
import com.netsteadfast.greenstep.base.model.CustomeOperational;
import com.netsteadfast.greenstep.base.model.GreenStepSysMsgConstants;
import com.netsteadfast.greenstep.base.model.QueryResult;
import com.netsteadfast.greenstep.base.model.SystemMessage;
import com.netsteadfast.greenstep.base.model.dynamichql.DynamicHql;
import com.netsteadfast.greenstep.util.DataUtils;
import com.netsteadfast.greenstep.util.DynamicHqlUtils;
import com.netsteadfast.greenstep.util.GenericsUtils;
public abstract class BaseDAO<T extends java.io.Serializable, PK extends java.io.Serializable> implements IBaseDAO<T, PK> {
protected Logger logger=Logger.getLogger(BaseDAO.class);
protected SessionFactory sessionFactory;
protected Transaction hbmTransaction;
private static String MAPPER_DEFINE_ID_SELECT_BY_PARAMS=".selectByParams";
private static String MAPPER_DEFINE_ID_SELECT_BY_VALUE=".selectByValue";
/*
private static String MAPPER_DEFINE_ID_INSERT=".insert";
private static String MAPPER_DEFINE_ID_UPDATE=".update";
private static String MAPPER_DEFINE_ID_DELETE=".delete";
*/
//private HibernateTemplate hibernateTemplate;
private SqlSession sqlSession;
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
protected Class<T> entityClass;
@SuppressWarnings("unchecked")
public BaseDAO() {
super();
this.entityClass=GenericsUtils.getSuperClassGenricType(getClass());
}
// -------------------------------------------------------------------------------------------
/*
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
@Autowired
@Required
@Resource(name="hibernateTemplate")
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
*/
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Autowired
@Required
@Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SqlSession getSqlSession() {
return sqlSession;
}
@Autowired
@Required
@Resource(name="sqlSession")
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Autowired
@Required
@Resource(name="jdbcTemplate")
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}
@Autowired
@Required
@Resource(name="namedParameterJdbcTemplate")
public void setNamedParameterJdbcTemplate(
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
public Connection getConnection() throws Exception {
return DataUtils.getConnection();
}
public Session getCurrentSession() throws Exception {
/*
this.hbmSession=this.sessionFactory.getCurrentSession();
return this.hbmSession;
*/
return sessionFactory.getCurrentSession();
}
// -------------------------------------------------------------------------------------------
public void updateByNativeSQL(String sql) throws DataAccessException, Exception {
this.getJdbcTemplate().update(sql);
}
public void executeByNativeSQL(String sql) throws DataAccessException, Exception {
this.getJdbcTemplate().execute(sql);
}
@SuppressWarnings({ "unchecked", "hiding"})
public <T> Object queryByNativeSQL(String sql, T rowMapper, Object... args) throws DataAccessException, Exception {
return (T)this.getJdbcTemplate().queryForObject(sql, (RowMapper<T>)rowMapper, args);
}
public int queryByNativeSQL(String sql) throws DataAccessException, Exception {
//return this.getJdbcTemplate().queryForInt(sql);
return this.getJdbcTemplate().queryForObject(sql, Integer.class);
}
@SuppressWarnings("rawtypes")
public List queryForListByNativeSQL(String sql) throws DataAccessException, Exception {
return this.getJdbcTemplate().queryForList(sql);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List queryForListByNativeSQL(String sql, RowMapper rowMapper) throws DataAccessException, Exception {
return this.getJdbcTemplate().query(sql, rowMapper);
}
@SuppressWarnings("rawtypes")
public List queryForListByNativeSQL(String sql, Object[] args) throws DataAccessException, Exception {
return this.getJdbcTemplate().queryForList(sql, args);
}
/*
public List queryForListByNativeSQL(String sql, Map paramMap) throws DataAccessException, Exception {
return this.getNamedParameterJdbcTemplate().queryForList(sql, paramMap);
}
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List queryForListByNativeSQL(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException, Exception {
return this.getJdbcTemplate().query(sql, args, rowMapper);
}
/*
public List queryForListByNativeSQL(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException, Exception {
return this.getNamedParameterJdbcTemplate().query(sql, paramMap, rowMapper);
}
*/
// -------------------------------------------------------------------------------------------
@Override
public int count(String hql) throws Exception {
return DataAccessUtils.intResult(this.getCurrentSession().createQuery(hql).list()); //this.getHibernateTemplate().find(hql)
}
@Override
public int count(String hql, Object... args) throws Exception {
Query query=this.getCurrentSession().createQuery(hql);
for (int position=0; args!=null && position<args.length; position++) {
this.setQueryParams(query, Integer.toString(position), args[position]);
}
return DataAccessUtils.intResult(query.list());
}
@SuppressWarnings("rawtypes")
@Override
public List findList(final String hql, final int offset, final int length) throws Exception {
List list=null;
Session hbmSession=this.getCurrentSession();
if (hbmSession==null) {
return list;
}
try {
Query query=hbmSession.createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
list=query.list();
} catch (Exception e) {
e.printStackTrace();
}
/*
if (hql==null || this.getHibernateTemplate()==null) {
return list;
}
list=this.getHibernateTemplate().executeFind(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Query query=null;
List resultList=null;
try {
query=session.createQuery(hql);
query.setFirstResult(offset);
query.setMaxResults(length);
resultList=query.list();
}
catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
}
);
*/
return list;
}
/**
* 頁面查詢grid資料用
*
* map 放入 key為 persisent obj 欄位名稱
*
*/
@SuppressWarnings("unchecked")
public <RO extends QueryResult<List<VO>>, VO extends java.io.Serializable> QueryResult<List<VO>> findPageQueryResult(
String findHQL, String countHQL,
Map<String, Object> params,
int offset, int limit) throws Exception {
QueryResult<List<VO>> result=new QueryResult<List<VO>>();
List<VO> list=null;
long count=0L;
Session hbmSession = this.getCurrentSession();
try {
Query query=hbmSession.createQuery(countHQL);
if (params!=null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getKey().equals(Constants._RESERVED_PARAM_NAME_QUERY_ORDER_BY)
|| entry.getKey().equals(Constants._RESERVED_PARAM_NAME_QUERY_SORT_TYPE)) {
continue;
}
this.setQueryParams(query, entry.getKey(), entry.getValue());
}
}
count=((Long)query.uniqueResult()).longValue();
int newOffset=offset;
if (count>0) {
if (offset>=count) { // 改掉原本頁面上一次查詢的欄位值 , 2014-10-08 offset>count
newOffset=(int)(count-Long.valueOf(limit));
if (newOffset<0) {
newOffset=0;
}
}
query=hbmSession.createQuery(findHQL);
if (params!=null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getKey().equals(Constants._RESERVED_PARAM_NAME_QUERY_ORDER_BY)
|| entry.getKey().equals(Constants._RESERVED_PARAM_NAME_QUERY_SORT_TYPE)) {
continue;
}
this.setQueryParams(query, entry.getKey(), entry.getValue());
}
}
query.setFirstResult(newOffset); //offset
query.setMaxResults(limit);
list=(List<VO>)query.list();
}
result.setRowCount(count);
result.setOffset(offset);
result.setLimit(limit);
result.setFindHQL(findHQL);
result.setCountHQL(countHQL);
if (list!=null && list.size()>0) {
result.setValue(list);
} else {
result.setSystemMessage(
new SystemMessage(SysMessageUtil.get(GreenStepSysMsgConstants.SEARCH_NO_DATA)));
}
} catch (Exception e) {
e.printStackTrace();
result.setSystemMessage(new SystemMessage(e.getMessage()));
}
return result;
}
/**
* 頁面查詢grid資料用
*
* map 放入 key為 persisent obj 欄位名稱
*
*/
public <RO extends QueryResult<List<VO>>, VO extends java.io.Serializable> QueryResult<List<VO>> findPageQueryResultByQueryName(
String pageQueryName, Map<String, Object> params, int offset, int limit) throws Exception {
String selectQueryName = pageQueryName + "-select";
String countQueryName = pageQueryName + "-count";
return this.findPageQueryResult(
this.getDynamicHql(selectQueryName, params),
this.getDynamicHql(countQueryName, params),
params,
offset,
limit);
}
/**
* for public QueryResult getList... doInHibernate
* @param query JPA-Style : from TB_ACCOUNT where account = ?0
* @param position JPA-Style : "0", "1" .....
* @param params
*/
@SuppressWarnings("rawtypes")
private void setQueryParams(Query query, String position, Object params) {
if (params instanceof java.lang.String ) {
query.setString(position, (java.lang.String)params);
return;
}
if (params instanceof java.lang.Character) {
query.setCharacter(position, (java.lang.Character)params);
return;
}
if (params instanceof java.lang.Double ) {
query.setDouble(position, (java.lang.Double)params);
return;
}
if (params instanceof java.lang.Byte ) {
query.setByte(position, (java.lang.Byte)params);
return;
}
if (params instanceof java.lang.Integer ) {
query.setInteger(position, (java.lang.Integer)params);
return;
}
if (params instanceof java.lang.Long ) {
query.setLong(position, (java.lang.Long)params);
return;
}
if (params instanceof java.lang.Boolean ) {
query.setBoolean(position, (java.lang.Boolean)params);
return;
}
if (params instanceof java.math.BigDecimal ) {
query.setBigDecimal(position, (java.math.BigDecimal)params);
return;
}
if (params instanceof java.util.Date ) {
query.setDate(position, (java.util.Date)params);
return;
}
if (params instanceof java.util.List ) {
List listParams=(List)params;
this.setQueryParamsOfList(query, position, listParams);
return;
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setQueryParamsOfList(Query query, String position, List listParams) {
if (listParams==null || listParams.size()<1) {
return;
}
if (listParams.get(0) instanceof String ) {
query.setParameterList(position, (List<String>)listParams);
return;
}
if (listParams.get(0) instanceof Character) {
query.setParameterList(position, (List<Character>)listParams);
return;
}
if (listParams.get(0) instanceof BigDecimal ) {
query.setParameterList(position, (List<BigDecimal>)listParams);
return;
}
if (listParams.get(0) instanceof Integer ) {
query.setParameterList(position, (List<Integer>)listParams);
return;
}
if (listParams.get(0) instanceof Long ) {
query.setParameterList(position, (List<Long>)listParams);
return;
}
}
@Override
public T save(T entityObject) throws Exception {
//this.getHibernateTemplate().save(entityObject);
this.getCurrentSession().save(entityObject);
return entityObject;
}
public T persist(T entityObject) throws Exception {
this.getCurrentSession().persist(entityObject);
return entityObject;
}
@Override
public T update(T entityObject) throws Exception {
//this.getHibernateTemplate().update(entityObject);
this.getCurrentSession().update(entityObject);
return entityObject;
}
@Override
public T merge(T entityObject) throws Exception {
//this.getHibernateTemplate().merge(entityObject);
this.getCurrentSession().merge(entityObject);
return entityObject;
}
@Override
public T delete(T entityObject) throws Exception {
//this.getHibernateTemplate().delete(entityObject);
this.getCurrentSession().delete(entityObject);
return entityObject;
}
public void clear() throws Exception {
this.getCurrentSession().clear();
}
@SuppressWarnings("unchecked")
@Override
public T findByOid(T entityObj) throws Exception {
//return this.findByPK(((BaseEntity<PK>)entityObj).getOid());
return this.findByPK((PK)BaseEntityUtil.getPKOneValue((BaseEntity<PK>)entityObj));
}
@SuppressWarnings("unchecked")
@Override
public int countByOid(T entityObj) throws Exception {
//return this.count("select count(*) from "+this.getPersisentName()+" where " + PK_FIELD + "=" + ((BaseEntity<PK>)entityObj).getOid() );
//return this.countByPK(((BaseEntity<PK>)entityObj).getOid());
return this.countByPK((PK)BaseEntityUtil.getPKOneValue((BaseEntity<PK>)entityObj));
}
/**
* 只提供給 deleteByPK, findByPK, countByPK 帶入pkMap參數的這3個method使用
* findByBaseEntityUK, countByBaseEntityUK 帶入ukMap參數
*
* @param hqlHeadCmd
* @param pkMap
* @return
* @throws Exception
*/
private Query getQueryByKeyMap(String hqlHeadCmd, Map<String, Object> pkMap) throws Exception {
StringBuilder hql=new StringBuilder();
hql.append(hqlHeadCmd).append(" from ").append(this.getPersisentName()).append(" where 1=1 ");
for (Map.Entry<String, Object> entry : pkMap.entrySet()) {
hql.append(" and ").append(entry.getKey()).append("=:").append(entry.getKey());
}
Query query=this.getCurrentSession().createQuery(hql.toString());
for (Map.Entry<String, Object> entry : pkMap.entrySet()) {
this.setQueryParams(query, entry.getKey(), entry.getValue());
}
return query;
}
public boolean deleteByPK(PK pk) throws Exception {
boolean status=false;
T entity=this.findByPK(pk);
this.delete(entity);
status=true;
return status;
}
public boolean deleteByPK(Map<String, Object> pkMap) throws Exception {
boolean status=false;
if (pkMap==null || pkMap.size()<1) {
return status;
}
Query query=this.getQueryByKeyMap("delete", pkMap);
if (query.executeUpdate()>0) {
status=true;
}
return status;
}
public T findByPK(PK pk) throws Exception {
return (T)this.getCurrentSession().get(this.entityClass, pk);
}
@SuppressWarnings("unchecked")
public T findByPK(Map<String, Object> pkMap) throws Exception {
if (pkMap==null || pkMap.size()<1) {
return null;
}
Query query=this.getQueryByKeyMap("", pkMap);
return (T)query.uniqueResult();
/*
List<T> list=(List<T>)query.list();
if (list==null || list.size()<1) {
return null;
}
return list.get(0);
*/
}
@SuppressWarnings("unchecked")
public int countByPK(PK pk) throws Exception {
return DataAccessUtils.intResult(
this.getCurrentSession().createQuery(
" select count(*) from "+this.getPersisentName() +
" where " + BaseEntityUtil.getPKOneName((BaseEntity<PK>)entityClass.newInstance()) + "=?0 ")
.setString("0", (String)pk).list());
}
public int countByPK(Map<String, Object> pkMap) throws Exception {
if (pkMap==null || pkMap.size()<1) {
return 0;
}
Query query=this.getQueryByKeyMap("select count(*)", pkMap);
return DataAccessUtils.intResult(query.list());
}
/**
* 只提供給 countByParams, findListByParams 用
*
* @param params
* @return
* @throws Exception
*/
private Query getQueryByParams(
String type,
Map<String, Object> params,
Map<String, String> likeParams,
Map<String, String> orderByParams,
Map<String, CustomeOperational> customOperParams) throws Exception {
StringBuilder sb=new StringBuilder();
if (Constants.QUERY_TYPE_OF_COUNT.equals(type)) {
sb.append("select count(*) from ").append(this.getPersisentName()).append(" ");
} else {
sb.append("from ").append(this.getPersisentName()).append(" ");
}
int field=0;
if (params!=null && params.size()>0) { // set hql
sb.append(" where 1=1 ");
for (Map.Entry<String, Object> entry : params.entrySet()) {
sb.append(" and ").append(entry.getKey()).append("=?").append(field).append(" ");
field++;
}
}
if (customOperParams!=null && customOperParams.size()>0) { // set hql with >= , <= , >, < , <>
if (params==null || params.size()<1) {
sb.append(" where 1=1 ");
}
for (Map.Entry<String, CustomeOperational> entry : customOperParams.entrySet()) {
sb.append(" and ").append(entry.getValue().getField()).append(entry.getValue().getOp()).append("?").append(field).append(" ");
field++;
}
}
if (likeParams!=null && likeParams.size()>0) { // set hql like
if ( (params==null || params.size()<1) && (customOperParams==null || customOperParams.size()<1) ) {
sb.append(" where 1=1 ");
}
for (Map.Entry<String, String> entry : likeParams.entrySet()) {
sb.append(" and ").append(entry.getKey()).append(" like ?").append(field).append(" ");
field++;
}
}
if (orderByParams!=null && orderByParams.size()>0) { // order by
sb.append(" order by ");
int order=0;
for (Map.Entry<String, String> entry : orderByParams.entrySet()) {
sb.append(entry.getKey()).append(" ").append(entry.getValue()).append(" ");
if (++order<orderByParams.size()) {
sb.append(" , ");
}
}
}
field=0;
Query query=this.getCurrentSession().createQuery(sb.toString());
if (params!=null && params.size()>0) { // set query params value
for (Map.Entry<String, Object> entry : params.entrySet()) {
//this.setQueryParams(query, entry.getKey(), entry.getValue());
this.setQueryParams(query, String.valueOf(field), entry.getValue());
field++;
}
}
if (customOperParams!=null && customOperParams.size()>0) { // set hql with >= , <= , >, < , <>
for (Map.Entry<String, CustomeOperational> entry : customOperParams.entrySet()) {
this.setQueryParams(query, String.valueOf(field), entry.getValue().getValue());
field++;
}
}
if (likeParams!=null && likeParams.size()>0) { // set query params like value
for (Map.Entry<String, String> entry : likeParams.entrySet()) {
//this.setQueryParams(query, entry.getKey(), entry.getValue());
this.setQueryParams(query, String.valueOf(field), entry.getValue());
field++;
}
}
return query;
}
/**
* 用map 提供的參數select資料
*
* map 放入 key為 persisent obj 欄位名稱
* map 放入 value為 persisent obj 欄位的值
*
* likeParams 的 value 如 '%test%' 'test%'
*
* @param params
* @param likeParams
* @return
* @throws Exception
*/
public long countByParams(
Map<String, Object> params, Map<String, String> likeParams) throws Exception {
return DataAccessUtils.longResult(this.getQueryByParams(Constants.QUERY_TYPE_OF_COUNT, params, likeParams, null, null).list());
}
/**
* 用map 提供的參數select資料
*
* map 放入 key為 persisent obj 欄位名稱
* map 放入 value為 persisent obj 欄位的值
*
* likeParams 的 value 如 '%test%' 'test%'
*
* orderParams 的 value 如 {"account欄位名稱", "asc正排序"} , {"name欄位名稱", "desc倒排序"}
*
* @param params
* @param likeParams
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<T> findListByParams(
Map<String, Object> params, Map<String, String> likeParams, Map<String, String> orderParams) throws Exception {
return (List<T>)this.getQueryByParams(Constants.QUERY_TYPE_OF_SELECT, params, likeParams, orderParams, null).list();
}
@SuppressWarnings("unchecked")
public List<T> findListByParams2(
Map<String, CustomeOperational> customOperParams) throws Exception {
return (List<T>)this.getQueryByParams(Constants.QUERY_TYPE_OF_SELECT, null, null, null, customOperParams).list();
}
@SuppressWarnings("unchecked")
public List<T> findListByParams2(
Map<String, Object> params,
Map<String, CustomeOperational> customOperParams) throws Exception {
return (List<T>)this.getQueryByParams(Constants.QUERY_TYPE_OF_SELECT, params, null, null, customOperParams).list();
}
@SuppressWarnings("unchecked")
public List<T> findListByParams2(
Map<String, Object> params,
Map<String, String> likeParams,
Map<String, CustomeOperational> customOperParams) throws Exception {
return (List<T>)this.getQueryByParams(Constants.QUERY_TYPE_OF_SELECT, params, likeParams, null, customOperParams).list();
}
@SuppressWarnings("unchecked")
public List<T> findListByParams2(
Map<String, Object> params,
Map<String, String> likeParams,
Map<String, CustomeOperational> customOperParams,
Map<String, String> orderParams) throws Exception {
return (List<T>)this.getQueryByParams(Constants.QUERY_TYPE_OF_SELECT, params, likeParams, orderParams, customOperParams).list();
}
//public abstract T findByUK(T entityObject) throws Exception;
//public abstract int countByUK(T entityObject) throws Exception;
@SuppressWarnings("unchecked")
public T findByUK(T entityObject) throws Exception {
return this.findByEntityUK(BaseEntityUtil.getUKParameter((BaseEntity<PK>)entityObject));
}
@SuppressWarnings("unchecked")
public int countByUK(T entityObject) throws Exception {
return this.countByEntityUK(BaseEntityUtil.getUKParameter((BaseEntity<PK>)entityObject));
}
@SuppressWarnings("unchecked")
public T findByEntityUK(Map<String, Object> ukMap) throws Exception {
if (ukMap==null || ukMap.size()<1) {
return null;
}
Query query=this.getQueryByKeyMap("", ukMap);
return (T)query.uniqueResult();
/*
List<T> list=(List<T>)query.list();
if (list==null || list.size()<1) {
return null;
}
return (T)list.get(0);
*/
}
public int countByEntityUK(Map<String, Object> ukMap) throws Exception {
if (ukMap==null || ukMap.size()<1) {
return 0;
}
Query query=this.getQueryByKeyMap("select count(*)", ukMap);
return DataAccessUtils.intResult(query.list());
}
/**
* return a zero persisent object
*/
@SuppressWarnings("unchecked")
public T getZeroPO() throws Exception {
T entity=this.entityClass.newInstance();
if (entity instanceof BaseEntity) {
((BaseEntity<PK>)entity).setOid(null);
}
return entity;
}
public String getPersisentName() {
return this.entityClass.getSimpleName();
}
// -------------------------------------------------------------------------------------------
public String getIbatisMapperNameSpace() {
return this.entityClass.getSimpleName();
}
@Override
public List<T> ibatisSelectListByParams(Map<String, Object> params) throws Exception {
return this.getSqlSession().selectList(this.getIbatisMapperNameSpace()+MAPPER_DEFINE_ID_SELECT_BY_PARAMS, params);
}
@Override
public T ibatisSelectOneByValue(T valueObj) throws Exception {
return this.getSqlSession().selectOne(this.getIbatisMapperNameSpace()+MAPPER_DEFINE_ID_SELECT_BY_VALUE, valueObj);
}
/*
@Override
public boolean ibatisInsert(T valueObj) throws Exception {
if (this.getSqlSession().insert(this.getIbatisMapperNameSpace()+MAPPER_DEFINE_ID_INSERT, valueObj)>0) {
return true;
}
return false;
}
@Override
public boolean ibatisUpdate(T valueObj) throws Exception {
if (this.getSqlSession().update(this.getIbatisMapperNameSpace()+MAPPER_DEFINE_ID_UPDATE, valueObj)>0) {
return true;
}
return false;
}
@Override
public boolean ibatisDelete(T valueObj) throws Exception {
if (this.getSqlSession().delete(this.getIbatisMapperNameSpace()+MAPPER_DEFINE_ID_DELETE, valueObj)>0) {
return true;
}
return false;
}
*/
public DynamicHql getDynamicHqlResource(String resource) throws Exception {
return DynamicHqlUtils.loadResource(resource);
}
public String getDynamicHql(String queryName, Map<String, Object> paramMap) throws Exception {
return this.getDynamicHql(this.getPersisentName()+"-dynamic-hql.xml", queryName, paramMap);
}
public String getDynamicHql(String resource, String queryName, Map<String, Object> paramMap) throws Exception {
return DynamicHqlUtils.process(resource, queryName, paramMap);
}
}
| apache-2.0 |
alexsh/cw-omnibus | RecyclerViewPager/PlainRVP/app/src/main/java/com/commonsware/android/rvp/MainActivity.java | 1884 | /***
Copyright (c) 2012-16 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
Covered in detail in the book _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.rvp;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;
public class MainActivity extends Activity {
private static final String STATE_ADAPTER="adapter";
private PageAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecyclerViewPager pager=(RecyclerViewPager)findViewById(R.id.pager);
pager.setLayoutManager(new LinearLayoutManager(this,
LinearLayoutManager.HORIZONTAL, false));
adapter=new PageAdapter(pager, getLayoutInflater());
pager.setAdapter(adapter);
}
@Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
Bundle adapterState=new Bundle();
adapter.onSaveInstanceState(adapterState);
state.putBundle(STATE_ADAPTER, adapterState);
}
@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
adapter.onRestoreInstanceState(state.getBundle(STATE_ADAPTER));
}
} | apache-2.0 |
philihp/weblabora | src/main/java/com/philihp/weblabora/model/building/ForgersWorkshop.java | 1162 | package com.philihp.weblabora.model.building;
import static com.philihp.weblabora.model.TerrainTypeEnum.COAST;
import static com.philihp.weblabora.model.TerrainTypeEnum.HILLSIDE;
import static com.philihp.weblabora.model.TerrainTypeEnum.PLAINS;
import java.util.EnumSet;
import com.philihp.weblabora.model.Board;
import com.philihp.weblabora.model.BuildCost;
import com.philihp.weblabora.model.Player;
import com.philihp.weblabora.model.SettlementRound;
import com.philihp.weblabora.model.UsageParam;
import com.philihp.weblabora.model.WeblaboraException;
public class ForgersWorkshop extends Building {
public ForgersWorkshop() {
super("F35", SettlementRound.D, 1, "Forger's Workshop", BuildCost.is()
.clay(2).straw(1), 2, 4, EnumSet.of(PLAINS, HILLSIDE, COAST),
false);
}
@Override
public void use(Board board, UsageParam input) throws WeblaboraException {
Player player = board.getPlayer(board.getActivePlayer());
if (input.getCoins() >= 5) {
player.addReliquary(1);
player.subtractCoins(5);
}
if (input.getCoins() >= 15) {
player.addReliquary(1);
player.subtractCoins(10);
}
}
}
| apache-2.0 |
jsimsa/alluxio | tests/src/test/java/alluxio/shell/command/CopyFromLocalCommandIntegrationTest.java | 21205 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.shell.command;
import alluxio.AlluxioURI;
import alluxio.SystemPropertyRule;
import alluxio.client.ReadType;
import alluxio.client.file.FileInStream;
import alluxio.client.file.URIStatus;
import alluxio.client.file.options.OpenFileOptions;
import alluxio.exception.AlluxioException;
import alluxio.shell.AbstractAlluxioShellTest;
import alluxio.shell.AlluxioShellUtilsTest;
import alluxio.util.io.BufferUtils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
/**
* Tests for copyFromLocal command.
*/
public final class CopyFromLocalCommandIntegrationTest extends AbstractAlluxioShellTest {
/** Rule to create a new temporary folder during each test. */
@Rule
public TemporaryFolder mTestFolder = new TemporaryFolder();
@Test
public void copyDirectoryFromLocalAtomic() throws Exception {
File localDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir");
localDir.mkdir();
File testFile =
generateFileContent("/localDir/testFile", BufferUtils.getIncreasingByteArray(10));
File testDir = testFile.getParentFile();
AlluxioURI alluxioDirPath = new AlluxioURI("/testDir");
testFile.setReadable(false);
String[] cmd = {"copyFromLocal", testDir.getPath(), alluxioDirPath.getPath()};
Assert.assertEquals(-1, mFsShell.run(cmd));
Assert.assertEquals(testFile.getPath() + " (Permission denied)\n", mOutput.toString());
Assert.assertFalse(mFileSystem.exists(alluxioDirPath));
mOutput.reset();
// If we put a copyable file in the directory, we should be able to copy just that file
generateFileContent("/localDir/testFile2", BufferUtils.getIncreasingByteArray(20));
Assert.assertEquals(-1, mFsShell.run(cmd));
Assert.assertEquals(testFile.getPath() + " (Permission denied)\n", mOutput.toString());
Assert.assertTrue(mFileSystem.exists(alluxioDirPath));
Assert.assertTrue(mFileSystem.exists(new AlluxioURI("/testDir/testFile2")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/testFile")));
// The directory should also be deleted from Alluxio filesystem when all files in the
// directory are failed.
File innerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir/innerDir");
innerDir.mkdir();
File innerFile = generateFileContent("/localDir/innerDir/innerFile1",
BufferUtils.getIncreasingByteArray(30));
innerFile.setReadable(false);
Assert.assertEquals(-1, mFsShell.run(cmd));
Assert.assertTrue(mFileSystem.exists(alluxioDirPath));
Assert.assertTrue(mFileSystem.exists(new AlluxioURI("/testDir/testFile2")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/testFile")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/innerDir")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/innerDir/innerFile1")));
}
@Test
public void copyDirectoryFromLocalToExistingDirAtomic() throws Exception {
File localDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir");
localDir.mkdir();
File testFile =
generateFileContent("/localDir/testFile", BufferUtils.getIncreasingByteArray(10));
File testDir = testFile.getParentFile();
AlluxioURI alluxioDirPath = new AlluxioURI("/testDir");
// Create the destination directory before call command of 'copyFromLocal'.
mFileSystem.createDirectory(alluxioDirPath);
testFile.setReadable(false);
String[] cmd = {"copyFromLocal", testDir.getPath(), alluxioDirPath.getPath()};
Assert.assertEquals(-1, mFsShell.run(cmd));
Assert.assertEquals(testFile.getPath() + " (Permission denied)\n", mOutput.toString());
// The destination directory should not be deleted.
Assert.assertTrue(mFileSystem.exists(alluxioDirPath));
mOutput.reset();
// If we put a copyable file in the directory, we should be able to copy just that file
generateFileContent("/localDir/testFile2", BufferUtils.getIncreasingByteArray(20));
Assert.assertEquals(-1, mFsShell.run(cmd));
Assert.assertEquals(testFile.getPath() + " (Permission denied)\n", mOutput.toString());
Assert.assertTrue(mFileSystem.exists(alluxioDirPath));
Assert.assertTrue(mFileSystem.exists(new AlluxioURI("/testDir/testFile2")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/testFile")));
// The directory should also be deleted from Alluxio filesystem when all files in the
// directory are failed.
File innerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir/innerDir");
innerDir.mkdir();
File innerFile = generateFileContent("/localDir/innerDir/innerFile1",
BufferUtils.getIncreasingByteArray(30));
innerFile.setReadable(false);
Assert.assertEquals(-1, mFsShell.run(cmd));
Assert.assertTrue(mFileSystem.exists(alluxioDirPath));
Assert.assertTrue(mFileSystem.exists(new AlluxioURI("/testDir/testFile2")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/testFile")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/innerDir")));
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/testDir/innerDir/innerFile1")));
}
@Test
public void copyFromLocalAtomic() throws Exception {
// copyFromLocal should not leave around any empty file metadata if it fails in the middle of
// copying a file
File testFile1 = generateFileContent("/testFile1", BufferUtils.getIncreasingByteArray(10));
AlluxioURI alluxioFilePath = new AlluxioURI("/testFile");
// Set testFile1 to be not readable, so that when we try to open it, we fail. NOTE: for this to
// test anything, we depend on the implementation of copyFromLocal creating the destination file
// in Alluxio before it tries to open the source file
testFile1.setReadable(false);
String[] cmd = {"copyFromLocal", testFile1.getPath(), alluxioFilePath.getPath()};
Assert.assertEquals(-1, mFsShell.run(cmd));
Assert.assertEquals(testFile1.getPath() + " (Permission denied)\n", mOutput.toString());
// Make sure the alluxio file wasn't created anyways
Assert.assertFalse(mFileSystem.exists(alluxioFilePath));
}
@Test
public void copyFromLocalFileToDstPath() throws IOException, AlluxioException {
String dataString = "copyFromLocalFileToDstPathTest";
byte[] data = dataString.getBytes();
File localDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir");
localDir.mkdir();
File localFile = generateFileContent("/localDir/testFile", data);
mFsShell.run("mkdir", "/dstDir");
mFsShell.run("copyFromLocal", localFile.getPath(), "/dstDir");
AlluxioURI uri = new AlluxioURI("/dstDir/testFile");
URIStatus status = mFileSystem.getStatus(uri);
Assert.assertNotNull(status);
byte[] read = readContent(uri, data.length);
Assert.assertEquals(new String(read), dataString);
}
@Test
public void copyFromLocalDir() throws IOException, AlluxioException {
// Copy a directory from local to Alluxio filesystem, which the destination uri was not created
// before.
File srcOuterDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir");
File srcInnerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/innerDir");
File emptyDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/emptyDir");
srcOuterDir.mkdir();
srcInnerDir.mkdir();
emptyDir.mkdir();
generateFileContent("/outerDir/srcFile1", BufferUtils.getIncreasingByteArray(10));
generateFileContent("/outerDir/innerDir/srcFile2", BufferUtils.getIncreasingByteArray(10));
int ret = mFsShell.run("copyFromLocal", srcOuterDir.getPath() + "/", "/dstDir");
Assert.assertEquals(0, ret);
AlluxioURI dstURI1 = new AlluxioURI("/dstDir/srcFile1");
AlluxioURI dstURI2 = new AlluxioURI("/dstDir/innerDir/srcFile2");
AlluxioURI dstURI3 = new AlluxioURI("/dstDir/emptyDir");
Assert.assertNotNull(mFileSystem.getStatus(dstURI1));
Assert.assertNotNull(mFileSystem.getStatus(dstURI2));
Assert.assertNotNull(mFileSystem.getStatus(dstURI3));
}
@Test
public void copyFromLocalDirNotReadable() throws IOException, AlluxioException {
// Copy a directory from local to Alluxio filesystem, which the destination uri was not created
// before.
File srcOuterDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir");
File srcInnerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/innerDir");
File emptyDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/emptyDir");
srcOuterDir.mkdir();
srcInnerDir.mkdir();
emptyDir.mkdir();
generateFileContent("/outerDir/srcFile1", BufferUtils.getIncreasingByteArray(10));
generateFileContent("/outerDir/innerDir/srcFile2", BufferUtils.getIncreasingByteArray(10));
srcOuterDir.setReadable(false);
int ret = mFsShell.run("copyFromLocal", srcOuterDir.getPath() + "/", "/dstDir");
Assert.assertEquals(-1, ret);
Assert.assertEquals("Failed to list files for directory "
+ srcOuterDir.getAbsolutePath() + "\n", mOutput.toString());
}
@Test
public void copyFromLocalDirNotReadableInnerDir() throws IOException, AlluxioException {
// Copy a directory from local to Alluxio filesystem, which the destination uri was not created
// before.
File srcOuterDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir");
File srcInnerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/innerDir");
File emptyDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir");
srcOuterDir.mkdir();
srcInnerDir.mkdir();
emptyDir.mkdir();
generateFileContent("/outerDir/srcFile1", BufferUtils.getIncreasingByteArray(10));
generateFileContent("/outerDir/innerDir/srcFile2", BufferUtils.getIncreasingByteArray(10));
srcInnerDir.setReadable(false);
int ret = mFsShell.run("copyFromLocal", srcOuterDir.getPath() + "/", "/dstDir");
Assert.assertEquals(-1, ret);
Assert.assertEquals("Failed to list files for directory "
+ srcInnerDir.getAbsolutePath() + "\n", mOutput.toString());
}
@Test
public void copyFromLocalDirToExistingFile() throws IOException, AlluxioException {
// Copy a directory from local to a file which exists in Alluxio filesystem. This case should
// fail.
File localDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir");
File innerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/localDir/innerDir");
localDir.mkdir();
innerDir.mkdir();
generateFileContent("/localDir/srcFile", BufferUtils.getIncreasingByteArray(10));
mFileSystem.createFile(new AlluxioURI("/dstFile")).close();
int ret = mFsShell.run("copyFromLocal", localDir.getPath(), "/dstFile");
Assert.assertEquals(-1, ret);
Assert.assertFalse(mFileSystem.getStatus(new AlluxioURI("/dstFile")).isFolder());
Assert.assertFalse(mFileSystem.exists(new AlluxioURI("/dstFile/innerDir")));
}
@Test
public void copyFromLocalDirToExistingDir() throws IOException, AlluxioException {
// Copy a directory from local to Alluxio filesystem, which the destination uri has been
// created before.
File srcOuterDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir");
File srcInnerDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/innerDir");
File emptyDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/outerDir/emptyDir");
srcOuterDir.mkdir();
srcInnerDir.mkdir();
emptyDir.mkdir();
generateFileContent("/outerDir/srcFile1", BufferUtils.getIncreasingByteArray(10));
generateFileContent("/outerDir/innerDir/srcFile2", BufferUtils.getIncreasingByteArray(10));
// Copying a directory to a destination directory which exists and doesn't contain the copied
// directory.
mFileSystem.createDirectory(new AlluxioURI("/dstDir"));
int ret = mFsShell.run("copyFromLocal", srcOuterDir.getPath(), "/dstDir");
Assert.assertEquals(0, ret);
AlluxioURI dstURI1 = new AlluxioURI("/dstDir/srcFile1");
AlluxioURI dstURI2 = new AlluxioURI("/dstDir/innerDir/srcFile2");
AlluxioURI dstURI3 = new AlluxioURI("/dstDir/emptyDir");
Assert.assertNotNull(mFileSystem.getStatus(dstURI1));
Assert.assertNotNull(mFileSystem.getStatus(dstURI2));
Assert.assertNotNull(mFileSystem.getStatus(dstURI3));
// Copying a directory to a destination directory which exists and does contain the copied
// directory.
mFileSystem.createDirectory(new AlluxioURI("/dstDir1"));
mFileSystem.createDirectory(new AlluxioURI("/dstDir1/innerDir"));
int ret1 = mFsShell.run("copyFromLocal", srcOuterDir.getPath(), "/dstDir1");
Assert.assertEquals(-1, ret1);
dstURI1 = new AlluxioURI("/dstDir1/srcFile1");
dstURI2 = new AlluxioURI("/dstDir1/innerDir/srcFile2");
dstURI3 = new AlluxioURI("/dstDir1/emptyDir");
Assert.assertNotNull(mFileSystem.getStatus(dstURI1));
// The directory already exists. But the sub directory shouldn't be copied.
Assert.assertFalse(mFileSystem.exists(dstURI2));
Assert.assertNotNull(mFileSystem.getStatus(dstURI3));
}
@Test
public void copyFromLocalLarge() throws IOException, AlluxioException {
File testFile = new File(mLocalAlluxioCluster.getAlluxioHome() + "/testFile");
testFile.createNewFile();
FileOutputStream fos = new FileOutputStream(testFile);
byte[] toWrite = BufferUtils.getIncreasingByteArray(SIZE_BYTES);
fos.write(toWrite);
fos.close();
mFsShell.run("copyFromLocal", testFile.getAbsolutePath(), "/testFile");
Assert.assertEquals(
getCommandOutput(new String[] {"copyFromLocal", testFile.getAbsolutePath(),
"/testFile"}),
mOutput.toString());
AlluxioURI uri = new AlluxioURI("/testFile");
URIStatus status = mFileSystem.getStatus(uri);
Assert.assertNotNull(status);
Assert.assertEquals(SIZE_BYTES, status.getLength());
try (FileInStream tfis =
mFileSystem.openFile(uri, OpenFileOptions.defaults().setReadType(ReadType.NO_CACHE))) {
byte[] read = new byte[SIZE_BYTES];
tfis.read(read);
Assert.assertTrue(BufferUtils.equalIncreasingByteArray(SIZE_BYTES, read));
}
}
@Test
public void copyFromLocalOverwrite() throws Exception {
// This tests makes sure copyFromLocal will not overwrite an existing Alluxio file
final int LEN1 = 10;
final int LEN2 = 20;
File testFile1 = generateFileContent("/testFile1", BufferUtils.getIncreasingByteArray(LEN1));
File testFile2 = generateFileContent("/testFile2", BufferUtils.getIncreasingByteArray(LEN2));
AlluxioURI alluxioFilePath = new AlluxioURI("/testFile");
// Write the first file
String[] cmd1 = {"copyFromLocal", testFile1.getPath(), alluxioFilePath.getPath()};
mFsShell.run(cmd1);
Assert.assertEquals(getCommandOutput(cmd1), mOutput.toString());
mOutput.reset();
Assert.assertTrue(BufferUtils
.equalIncreasingByteArray(LEN1, readContent(alluxioFilePath, LEN1)));
// Write the second file to the same location, which should cause an exception
String[] cmd2 = {"copyFromLocal", testFile2.getPath(), alluxioFilePath.getPath()};
Assert.assertEquals(-1, mFsShell.run(cmd2));
Assert.assertEquals(alluxioFilePath.getPath() + " already exists\n", mOutput.toString());
// Make sure the original file is intact
Assert.assertTrue(BufferUtils
.equalIncreasingByteArray(LEN1, readContent(alluxioFilePath, LEN1)));
}
@Test
public void copyFromLocal() throws IOException, AlluxioException {
File testDir = new File(mLocalAlluxioCluster.getAlluxioHome() + "/testDir");
testDir.mkdir();
File testDirInner = new File(mLocalAlluxioCluster.getAlluxioHome() + "/testDir/testDirInner");
testDirInner.mkdir();
File testFile =
generateFileContent("/testDir/testFile", BufferUtils.getIncreasingByteArray(10));
generateFileContent("/testDir/testDirInner/testFile2",
BufferUtils.getIncreasingByteArray(10, 20));
mFsShell.run("copyFromLocal", testFile.getParent(), "/testDir");
Assert.assertEquals(
getCommandOutput(new String[]{"copyFromLocal", testFile.getParent(), "/testDir"}),
mOutput.toString());
AlluxioURI uri1 = new AlluxioURI("/testDir/testFile");
AlluxioURI uri2 = new AlluxioURI("/testDir/testDirInner/testFile2");
URIStatus status1 = mFileSystem.getStatus(uri1);
URIStatus status2 = mFileSystem.getStatus(uri2);
Assert.assertNotNull(status1);
Assert.assertNotNull(status2);
Assert.assertEquals(10, status1.getLength());
Assert.assertEquals(20, status2.getLength());
byte[] read = readContent(uri1, 10);
Assert.assertTrue(BufferUtils.equalIncreasingByteArray(10, read));
read = readContent(uri2, 20);
Assert.assertTrue(BufferUtils.equalIncreasingByteArray(10, 20, read));
}
@Test
public void copyFromLocalTestWithFullURI() throws IOException, AlluxioException {
File testFile = generateFileContent("/srcFileURI", BufferUtils.getIncreasingByteArray(10));
String alluxioURI = "alluxio://" + mLocalAlluxioCluster.getHostname() + ":"
+ mLocalAlluxioCluster.getMasterRpcPort() + "/destFileURI";
// when
mFsShell.run("copyFromLocal", testFile.getPath(), alluxioURI);
String cmdOut =
getCommandOutput(new String[]{"copyFromLocal", testFile.getPath(), alluxioURI});
// then
Assert.assertEquals(cmdOut, mOutput.toString());
AlluxioURI uri = new AlluxioURI("/destFileURI");
URIStatus status = mFileSystem.getStatus(uri);
Assert.assertEquals(10L, status.getLength());
byte[] read = readContent(uri, 10);
Assert.assertTrue(BufferUtils.equalIncreasingByteArray(10, read));
}
@Test
public void copyFromLocalWildcardExistingDir() throws IOException, AlluxioException {
String testDir = AlluxioShellUtilsTest.resetLocalFileHierarchy(mLocalAlluxioCluster);
mFileSystem.createDirectory(new AlluxioURI("/testDir"));
int ret = mFsShell.run("copyFromLocal", testDir + "/*/foo*", "/testDir");
Assert.assertEquals(0, ret);
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foobar1")));
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foobar2")));
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foobar3")));
}
@Test
public void copyFromLocalWildcardHier() throws IOException {
String testDir = AlluxioShellUtilsTest.resetLocalFileHierarchy(mLocalAlluxioCluster);
int ret = mFsShell.run("copyFromLocal", testDir + "/*", "/testDir");
Assert.assertEquals(0, ret);
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foo/foobar1")));
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foo/foobar2")));
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/bar/foobar3")));
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foobar4")));
}
@Test
public void copyFromLocalWildcardNotDir() throws IOException, AlluxioException {
String localTestDir = AlluxioShellUtilsTest.resetFileHierarchy(mFileSystem);
String alluxioTestDir = AlluxioShellUtilsTest.resetFileHierarchy(mFileSystem);
int ret = mFsShell.run("copyFromLocal", localTestDir + "/*/foo*", alluxioTestDir + "/foobar4");
Assert.assertEquals(-1, ret);
}
@Test
public void copyFromLocalWildcard() throws IOException {
String testDir = AlluxioShellUtilsTest.resetLocalFileHierarchy(mLocalAlluxioCluster);
int ret = mFsShell.run("copyFromLocal", testDir + "/*/foo*", "/testDir");
Assert.assertEquals(0, ret);
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foobar1")));
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foobar2")));
Assert.assertTrue(fileExists(new AlluxioURI("/testDir/foobar3")));
Assert.assertFalse(fileExists(new AlluxioURI("/testDir/foobar4")));
}
@Test
public void copyFromLocalRelativePath() throws Exception {
HashMap<String, String> sysProps = new HashMap<>();
sysProps.put("user.dir", mTestFolder.getRoot().getAbsolutePath());
try (Closeable p = new SystemPropertyRule(sysProps).toResource()) {
File localDir = mTestFolder.newFolder("testDir");
generateRelativeFileContent(localDir.getPath() + "/testFile",
BufferUtils.getIncreasingByteArray(10));
int ret = mFsShell.run("copyFromLocal", "testDir/testFile", "/testFile");
Assert.assertEquals(0, ret);
Assert.assertTrue(fileExists(new AlluxioURI(("/testFile"))));
}
}
}
| apache-2.0 |
KleeGroup/deprecated-vertigo-demo | demo-uistruts/src/main/javagen/io/vertigo/demo/domain/referentiel/Departement.java | 5456 | package io.vertigo.demo.domain.referentiel;
import io.vertigo.dynamo.domain.model.Entity;
import io.vertigo.dynamo.domain.model.URI;
import io.vertigo.dynamo.domain.stereotype.Field;
import io.vertigo.dynamo.domain.util.DtObjectUtil;
/**
* Attention cette classe est générée automatiquement !
* Objet de données Departement
*/
public final class Departement implements Entity {
/** SerialVersionUID. */
private static final long serialVersionUID = 1L;
private Long depId;
private String libelle;
private Long regId;
private io.vertigo.demo.domain.referentiel.Region region;
private io.vertigo.dynamo.domain.model.DtList<io.vertigo.demo.domain.referentiel.Ville> ville;
/** {@inheritDoc} */
@Override
public URI<Departement> getURI() {
return DtObjectUtil.createURI(this);
}
/**
* Champ : ID.
* Récupère la valeur de la propriété 'DEP_ID'.
* @return Long depId <b>Obligatoire</b>
*/
@Field(domain = "DO_IDENTIFIANT", type = "ID", required = true, label = "DEP_ID")
public Long getDepId() {
return depId;
}
/**
* Champ : ID.
* Définit la valeur de la propriété 'DEP_ID'.
* @param depId Long <b>Obligatoire</b>
*/
public void setDepId(final Long depId) {
this.depId = depId;
}
/**
* Champ : DATA.
* Récupère la valeur de la propriété 'LIBELLE'.
* @return String libelle <b>Obligatoire</b>
*/
@Field(domain = "DO_LIBELLE", required = true, label = "LIBELLE")
public String getLibelle() {
return libelle;
}
/**
* Champ : DATA.
* Définit la valeur de la propriété 'LIBELLE'.
* @param libelle String <b>Obligatoire</b>
*/
public void setLibelle(final String libelle) {
this.libelle = libelle;
}
/**
* Champ : FOREIGN_KEY.
* Récupère la valeur de la propriété 'Region'.
* @return Long regId <b>Obligatoire</b>
*/
@Field(domain = "DO_IDENTIFIANT", type = "FOREIGN_KEY", required = true, label = "Region")
public Long getRegId() {
return regId;
}
/**
* Champ : FOREIGN_KEY.
* Définit la valeur de la propriété 'Region'.
* @param regId Long <b>Obligatoire</b>
*/
public void setRegId(final Long regId) {
this.regId = regId;
}
/**
* Association : Region.
* @return io.vertigo.demo.domain.referentiel.Region
*/
public io.vertigo.demo.domain.referentiel.Region getRegion() {
final io.vertigo.dynamo.domain.model.URI<io.vertigo.demo.domain.referentiel.Region> fkURI = getRegionURI();
if (fkURI == null) {
return null;
}
//On est toujours dans un mode lazy. On s'assure cependant que l'objet associé n'a pas changé
if (region == null || !fkURI.equals(region.getURI())) {
region = io.vertigo.app.Home.getApp().getComponentSpace().resolve(io.vertigo.dynamo.store.StoreManager.class).getDataStore().readOne(fkURI);
}
return region;
}
/**
* Retourne l'URI: Region.
* @return URI de l'association
*/
@io.vertigo.dynamo.domain.stereotype.Association (
name = "A_REG_DEP",
fkFieldName = "REG_ID",
primaryDtDefinitionName = "DT_REGION",
primaryIsNavigable = true,
primaryRole = "Region",
primaryLabel = "Region",
primaryMultiplicity = "1..1",
foreignDtDefinitionName = "DT_DEPARTEMENT",
foreignIsNavigable = true,
foreignRole = "Departement",
foreignLabel = "Departement",
foreignMultiplicity = "0..*")
public io.vertigo.dynamo.domain.model.URI<io.vertigo.demo.domain.referentiel.Region> getRegionURI() {
return io.vertigo.dynamo.domain.util.DtObjectUtil.createURI(this, "A_REG_DEP", io.vertigo.demo.domain.referentiel.Region.class);
}
/**
* Association : Ville.
* @return io.vertigo.dynamo.domain.model.DtList<io.vertigo.demo.domain.referentiel.Ville>
*/
public io.vertigo.dynamo.domain.model.DtList<io.vertigo.demo.domain.referentiel.Ville> getVilleList() {
// return this.<io.vertigo.demo.domain.referentiel.Ville> getList(getVilleListURI());
// On doit avoir une clé primaire renseignée. Si ce n'est pas le cas, on renvoie une liste vide
if (io.vertigo.dynamo.domain.util.DtObjectUtil.getId(this) == null) {
return new io.vertigo.dynamo.domain.model.DtList<>(io.vertigo.demo.domain.referentiel.Ville.class);
}
final io.vertigo.dynamo.domain.model.DtListURI fkDtListURI = getVilleDtListURI();
io.vertigo.lang.Assertion.checkNotNull(fkDtListURI);
//---------------------------------------------------------------------
//On est toujours dans un mode lazy.
if (ville == null) {
ville = io.vertigo.app.Home.getApp().getComponentSpace().resolve(io.vertigo.dynamo.store.StoreManager.class).getDataStore().findAll(fkDtListURI);
}
return ville;
}
/**
* Association URI: Ville.
* @return URI de l'association
*/
@io.vertigo.dynamo.domain.stereotype.Association (
name = "A_DEP_VIL",
fkFieldName = "DEP_ID",
primaryDtDefinitionName = "DT_DEPARTEMENT",
primaryIsNavigable = true,
primaryRole = "Departement",
primaryLabel = "Departement",
primaryMultiplicity = "1..1",
foreignDtDefinitionName = "DT_VILLE",
foreignIsNavigable = true,
foreignRole = "Ville",
foreignLabel = "Ville",
foreignMultiplicity = "0..*")
public io.vertigo.dynamo.domain.metamodel.association.DtListURIForSimpleAssociation getVilleDtListURI() {
return io.vertigo.dynamo.domain.util.DtObjectUtil.createDtListURIForSimpleAssociation(this, "A_DEP_VIL", "Ville");
}
// Association : D�partement non navigable
/** {@inheritDoc} */
@Override
public String toString() {
return DtObjectUtil.toString(this);
}
}
| apache-2.0 |
gchq/Gaffer | store-implementation/parquet-store/src/main/java/uk/gov/gchq/gaffer/parquetstore/operation/handler/utilities/ParquetElementRetriever.java | 7681 | /*
* Copyright 2017-2021 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.parquetstore.operation.handler.utilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.gov.gchq.gaffer.commonutil.iterable.CloseableIterable;
import uk.gov.gchq.gaffer.commonutil.iterable.CloseableIterator;
import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.data.elementdefinition.view.View;
import uk.gov.gchq.gaffer.operation.Operation;
import uk.gov.gchq.gaffer.operation.OperationException;
import uk.gov.gchq.gaffer.operation.impl.get.GetAllElements;
import uk.gov.gchq.gaffer.operation.impl.get.GetElements;
import uk.gov.gchq.gaffer.parquetstore.ParquetStore;
import uk.gov.gchq.gaffer.parquetstore.query.ParquetQuery;
import uk.gov.gchq.gaffer.parquetstore.query.QueryGenerator;
import uk.gov.gchq.gaffer.user.User;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
/**
* Converts the inputs for get element operations to a mapping of files to Parquet filters which is
* then looped over to retrieve the filtered Elements.
*/
public class ParquetElementRetriever implements CloseableIterable<Element> {
private static final Logger LOGGER = LoggerFactory.getLogger(ParquetElementRetriever.class);
private final ParquetStore store;
private final Operation operation;
private final User user;
public ParquetElementRetriever(final ParquetStore store, final Operation operation, final User user) {
if (!(operation instanceof GetElements) && !(operation instanceof GetAllElements)) {
throw new IllegalArgumentException("Only operations of type GetElements and GetAllElements are supported");
}
this.store = store;
this.operation = operation;
this.user = user;
}
@Override
public void close() {
}
@Override
public CloseableIterator<Element> iterator() {
try {
return new ParquetIterator(store, operation, user);
} catch (final OperationException e) {
throw new RuntimeException("Exception in iterator()", e);
}
}
protected static class ParquetIterator implements CloseableIterator<Element> {
private ConcurrentLinkedQueue<Element> queue;
private List<Future<OperationException>> runningTasks;
private ExecutorService executorServicePool;
protected ParquetIterator(final ParquetStore store, final Operation operation, final User user) throws OperationException {
final QueryGenerator queryGenerator = new QueryGenerator(store);
final View view;
if (operation instanceof GetAllElements) {
view = ((GetAllElements) operation).getView();
} else {
view = ((GetElements) operation).getView();
}
try {
final ParquetQuery parquetQuery = queryGenerator.getParquetQuery(operation);
LOGGER.debug("Created ParquetQuery {}", parquetQuery);
if (!parquetQuery.isEmpty()) {
queue = new ConcurrentLinkedQueue<>();
executorServicePool = Executors.newFixedThreadPool(store.getProperties().getThreadsAvailable());
final List<RetrieveElementsFromFile> tasks = new ArrayList<>();
tasks.addAll(parquetQuery.getAllParquetFileQueries()
.stream()
.map(entry -> new RetrieveElementsFromFile(entry.getFile(), entry.getFilter(),
store.getSchema(), queue, !entry.isFullyApplied(),
store.getProperties().getSkipValidation(), view, user))
.collect(Collectors.toList()));
LOGGER.info("Invoking {} RetrieveElementsFromFile tasks", tasks.size());
runningTasks = executorServicePool.invokeAll(tasks);
} else {
LOGGER.warn("No paths found - there will be no results from this query");
}
} catch (final IOException | OperationException e) {
LOGGER.error("Exception while creating the mapping of file paths to Parquet filters: {}", e.getMessage());
throw new OperationException("Exception creating ParquetIterator", e);
} catch (final InterruptedException e) {
LOGGER.error("InterruptedException in ParquetIterator {}", e.getMessage());
throw new OperationException("InterruptedException in ParquetIterator", e);
}
}
@Override
public boolean hasNext() {
if (null != queue) {
if (queue.isEmpty()) {
boolean finishedAllTasks = runningTasks.isEmpty();
while (!finishedAllTasks && queue.isEmpty()) {
try {
finishedAllTasks = hasFinishedAllTasks();
if (!finishedAllTasks) {
wait(100L);
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
finishedAllTasks = true;
}
}
return !queue.isEmpty();
} else {
return true;
}
} else {
return false;
}
}
private boolean hasFinishedAllTasks() throws ExecutionException, InterruptedException, OperationException {
final List<Future<OperationException>> completedTasks = new ArrayList<>();
for (final Future<OperationException> task : runningTasks) {
if (task.isDone()) {
final OperationException taskResult = task.get();
if (null != taskResult) {
throw taskResult;
} else {
completedTasks.add(task);
}
}
}
runningTasks.removeAll(completedTasks);
return runningTasks.isEmpty();
}
@Override
public Element next() throws NoSuchElementException {
Element e;
while (hasNext()) {
e = queue.poll();
if (null != e) {
return e;
}
}
throw new NoSuchElementException();
}
@Override
public void close() {
if (null != executorServicePool) {
executorServicePool.shutdown();
executorServicePool = null;
}
queue = null;
runningTasks = null;
}
}
}
| apache-2.0 |
tecknowledgeable/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java | 26621 | /**
* 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.yarn.server.resourcemanager.scheduler.capacity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.AccessControlList;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.QueueACL;
import org.apache.hadoop.yarn.api.records.QueueInfo;
import org.apache.hadoop.yarn.api.records.QueueState;
import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode;
import org.apache.hadoop.yarn.util.resource.Resources;
import com.google.common.collect.Sets;
@Private
@Evolving
public class ParentQueue extends AbstractCSQueue {
private static final Log LOG = LogFactory.getLog(ParentQueue.class);
protected final Set<CSQueue> childQueues;
private final boolean rootQueue;
final Comparator<CSQueue> queueComparator;
volatile int numApplications;
private final CapacitySchedulerContext scheduler;
private final RecordFactory recordFactory =
RecordFactoryProvider.getRecordFactory(null);
public ParentQueue(CapacitySchedulerContext cs,
String queueName, CSQueue parent, CSQueue old) throws IOException {
super(cs, queueName, parent, old);
this.scheduler = cs;
this.queueComparator = cs.getQueueComparator();
this.rootQueue = (parent == null);
float rawCapacity = cs.getConfiguration().getNonLabeledQueueCapacity(getQueuePath());
if (rootQueue &&
(rawCapacity != CapacitySchedulerConfiguration.MAXIMUM_CAPACITY_VALUE)) {
throw new IllegalArgumentException("Illegal " +
"capacity of " + rawCapacity + " for queue " + queueName +
". Must be " + CapacitySchedulerConfiguration.MAXIMUM_CAPACITY_VALUE);
}
this.childQueues = new TreeSet<CSQueue>(queueComparator);
setupQueueConfigs(cs.getClusterResource());
LOG.info("Initialized parent-queue " + queueName +
" name=" + queueName +
", fullname=" + getQueuePath());
}
synchronized void setupQueueConfigs(Resource clusterResource)
throws IOException {
super.setupQueueConfigs(clusterResource);
StringBuilder aclsString = new StringBuilder();
for (Map.Entry<QueueACL, AccessControlList> e : acls.entrySet()) {
aclsString.append(e.getKey() + ":" + e.getValue().getAclString());
}
StringBuilder labelStrBuilder = new StringBuilder();
if (accessibleLabels != null) {
for (String s : accessibleLabels) {
labelStrBuilder.append(s);
labelStrBuilder.append(",");
}
}
LOG.info(queueName +
", capacity=" + this.queueCapacities.getCapacity() +
", asboluteCapacity=" + this.queueCapacities.getAbsoluteCapacity() +
", maxCapacity=" + this.queueCapacities.getMaximumCapacity() +
", asboluteMaxCapacity=" + this.queueCapacities.getAbsoluteMaximumCapacity() +
", state=" + state +
", acls=" + aclsString +
", labels=" + labelStrBuilder.toString() + "\n" +
", reservationsContinueLooking=" + reservationsContinueLooking);
}
private static float PRECISION = 0.0005f; // 0.05% precision
void setChildQueues(Collection<CSQueue> childQueues) {
// Validate
float childCapacities = 0;
for (CSQueue queue : childQueues) {
childCapacities += queue.getCapacity();
}
float delta = Math.abs(1.0f - childCapacities); // crude way to check
// allow capacities being set to 0, and enforce child 0 if parent is 0
if (((queueCapacities.getCapacity() > 0) && (delta > PRECISION)) ||
((queueCapacities.getCapacity() == 0) && (childCapacities > 0))) {
throw new IllegalArgumentException("Illegal" +
" capacity of " + childCapacities +
" for children of queue " + queueName);
}
// check label capacities
for (String nodeLabel : labelManager.getClusterNodeLabels()) {
float capacityByLabel = queueCapacities.getCapacity(nodeLabel);
// check children's labels
float sum = 0;
for (CSQueue queue : childQueues) {
sum += queue.getQueueCapacities().getCapacity(nodeLabel);
}
if ((capacityByLabel > 0 && Math.abs(1.0f - sum) > PRECISION)
|| (capacityByLabel == 0) && (sum > 0)) {
throw new IllegalArgumentException("Illegal" + " capacity of "
+ sum + " for children of queue " + queueName
+ " for label=" + nodeLabel);
}
}
this.childQueues.clear();
this.childQueues.addAll(childQueues);
if (LOG.isDebugEnabled()) {
LOG.debug("setChildQueues: " + getChildQueuesToPrint());
}
}
@Override
public String getQueuePath() {
String parentPath = ((parent == null) ? "" : (parent.getQueuePath() + "."));
return parentPath + getQueueName();
}
@Override
public synchronized QueueInfo getQueueInfo(
boolean includeChildQueues, boolean recursive) {
QueueInfo queueInfo = getQueueInfo();
List<QueueInfo> childQueuesInfo = new ArrayList<QueueInfo>();
if (includeChildQueues) {
for (CSQueue child : childQueues) {
// Get queue information recursively?
childQueuesInfo.add(
child.getQueueInfo(recursive, recursive));
}
}
queueInfo.setChildQueues(childQueuesInfo);
return queueInfo;
}
private synchronized QueueUserACLInfo getUserAclInfo(
UserGroupInformation user) {
QueueUserACLInfo userAclInfo =
recordFactory.newRecordInstance(QueueUserACLInfo.class);
List<QueueACL> operations = new ArrayList<QueueACL>();
for (QueueACL operation : QueueACL.values()) {
if (hasAccess(operation, user)) {
operations.add(operation);
}
}
userAclInfo.setQueueName(getQueueName());
userAclInfo.setUserAcls(operations);
return userAclInfo;
}
@Override
public synchronized List<QueueUserACLInfo> getQueueUserAclInfo(
UserGroupInformation user) {
List<QueueUserACLInfo> userAcls = new ArrayList<QueueUserACLInfo>();
// Add parent queue acls
userAcls.add(getUserAclInfo(user));
// Add children queue acls
for (CSQueue child : childQueues) {
userAcls.addAll(child.getQueueUserAclInfo(user));
}
return userAcls;
}
public String toString() {
return queueName + ": " +
"numChildQueue= " + childQueues.size() + ", " +
"capacity=" + queueCapacities.getCapacity() + ", " +
"absoluteCapacity=" + queueCapacities.getAbsoluteCapacity() + ", " +
"usedResources=" + queueUsage.getUsed() +
"usedCapacity=" + getUsedCapacity() + ", " +
"numApps=" + getNumApplications() + ", " +
"numContainers=" + getNumContainers();
}
@Override
public synchronized void reinitialize(CSQueue newlyParsedQueue,
Resource clusterResource) throws IOException {
// Sanity check
if (!(newlyParsedQueue instanceof ParentQueue) ||
!newlyParsedQueue.getQueuePath().equals(getQueuePath())) {
throw new IOException("Trying to reinitialize " + getQueuePath() +
" from " + newlyParsedQueue.getQueuePath());
}
ParentQueue newlyParsedParentQueue = (ParentQueue)newlyParsedQueue;
// Set new configs
setupQueueConfigs(clusterResource);
// Re-configure existing child queues and add new ones
// The CS has already checked to ensure all existing child queues are present!
Map<String, CSQueue> currentChildQueues = getQueues(childQueues);
Map<String, CSQueue> newChildQueues =
getQueues(newlyParsedParentQueue.childQueues);
for (Map.Entry<String, CSQueue> e : newChildQueues.entrySet()) {
String newChildQueueName = e.getKey();
CSQueue newChildQueue = e.getValue();
CSQueue childQueue = currentChildQueues.get(newChildQueueName);
// Check if the child-queue already exists
if (childQueue != null) {
// Re-init existing child queues
childQueue.reinitialize(newChildQueue, clusterResource);
LOG.info(getQueueName() + ": re-configured queue: " + childQueue);
} else {
// New child queue, do not re-init
// Set parent to 'this'
newChildQueue.setParent(this);
// Save in list of current child queues
currentChildQueues.put(newChildQueueName, newChildQueue);
LOG.info(getQueueName() + ": added new child queue: " + newChildQueue);
}
}
// Re-sort all queues
childQueues.clear();
childQueues.addAll(currentChildQueues.values());
}
Map<String, CSQueue> getQueues(Set<CSQueue> queues) {
Map<String, CSQueue> queuesMap = new HashMap<String, CSQueue>();
for (CSQueue queue : queues) {
queuesMap.put(queue.getQueueName(), queue);
}
return queuesMap;
}
@Override
public void submitApplication(ApplicationId applicationId, String user,
String queue) throws AccessControlException {
synchronized (this) {
// Sanity check
if (queue.equals(queueName)) {
throw new AccessControlException("Cannot submit application " +
"to non-leaf queue: " + queueName);
}
if (state != QueueState.RUNNING) {
throw new AccessControlException("Queue " + getQueuePath() +
" is STOPPED. Cannot accept submission of application: " +
applicationId);
}
addApplication(applicationId, user);
}
// Inform the parent queue
if (parent != null) {
try {
parent.submitApplication(applicationId, user, queue);
} catch (AccessControlException ace) {
LOG.info("Failed to submit application to parent-queue: " +
parent.getQueuePath(), ace);
removeApplication(applicationId, user);
throw ace;
}
}
}
@Override
public void submitApplicationAttempt(FiCaSchedulerApp application,
String userName) {
// submit attempt logic.
}
@Override
public void finishApplicationAttempt(FiCaSchedulerApp application,
String queue) {
// finish attempt logic.
}
private synchronized void addApplication(ApplicationId applicationId,
String user) {
++numApplications;
LOG.info("Application added -" +
" appId: " + applicationId +
" user: " + user +
" leaf-queue of parent: " + getQueueName() +
" #applications: " + getNumApplications());
}
@Override
public void finishApplication(ApplicationId application, String user) {
synchronized (this) {
removeApplication(application, user);
}
// Inform the parent queue
if (parent != null) {
parent.finishApplication(application, user);
}
}
private synchronized void removeApplication(ApplicationId applicationId,
String user) {
--numApplications;
LOG.info("Application removed -" +
" appId: " + applicationId +
" user: " + user +
" leaf-queue of parent: " + getQueueName() +
" #applications: " + getNumApplications());
}
@Override
public synchronized CSAssignment assignContainers(
Resource clusterResource, FiCaSchedulerNode node, boolean needToUnreserve) {
CSAssignment assignment =
new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL);
Set<String> nodeLabels = node.getLabels();
// if our queue cannot access this node, just return
if (!SchedulerUtils.checkQueueAccessToNode(accessibleLabels, nodeLabels)) {
return assignment;
}
while (canAssign(clusterResource, node)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Trying to assign containers to child-queue of "
+ getQueueName());
}
boolean localNeedToUnreserve = false;
// Are we over maximum-capacity for this queue?
if (!canAssignToThisQueue(clusterResource, nodeLabels)) {
// check to see if we could if we unreserve first
localNeedToUnreserve = assignToQueueIfUnreserve(clusterResource);
if (!localNeedToUnreserve) {
break;
}
}
// Schedule
CSAssignment assignedToChild =
assignContainersToChildQueues(clusterResource, node, localNeedToUnreserve | needToUnreserve);
assignment.setType(assignedToChild.getType());
// Done if no child-queue assigned anything
if (Resources.greaterThan(
resourceCalculator, clusterResource,
assignedToChild.getResource(), Resources.none())) {
// Track resource utilization for the parent-queue
super.allocateResource(clusterResource, assignedToChild.getResource(),
nodeLabels);
// Track resource utilization in this pass of the scheduler
Resources.addTo(assignment.getResource(), assignedToChild.getResource());
LOG.info("assignedContainer" +
" queue=" + getQueueName() +
" usedCapacity=" + getUsedCapacity() +
" absoluteUsedCapacity=" + getAbsoluteUsedCapacity() +
" used=" + queueUsage.getUsed() +
" cluster=" + clusterResource);
} else {
break;
}
if (LOG.isDebugEnabled()) {
LOG.debug("ParentQ=" + getQueueName()
+ " assignedSoFarInThisIteration=" + assignment.getResource()
+ " usedCapacity=" + getUsedCapacity()
+ " absoluteUsedCapacity=" + getAbsoluteUsedCapacity());
}
// Do not assign more than one container if this isn't the root queue
// or if we've already assigned an off-switch container
if (!rootQueue || assignment.getType() == NodeType.OFF_SWITCH) {
if (LOG.isDebugEnabled()) {
if (rootQueue && assignment.getType() == NodeType.OFF_SWITCH) {
LOG.debug("Not assigning more than one off-switch container," +
" assignments so far: " + assignment);
}
}
break;
}
}
return assignment;
}
private synchronized boolean canAssignToThisQueue(Resource clusterResource,
Set<String> nodeLabels) {
Set<String> labelCanAccess =
new HashSet<String>(
accessibleLabels.contains(CommonNodeLabelsManager.ANY) ? nodeLabels
: Sets.intersection(accessibleLabels, nodeLabels));
if (nodeLabels.isEmpty()) {
// Any queue can always access any node without label
labelCanAccess.add(RMNodeLabelsManager.NO_LABEL);
}
boolean canAssign = true;
for (String label : labelCanAccess) {
float currentAbsoluteLabelUsedCapacity =
Resources.divide(resourceCalculator, clusterResource,
queueUsage.getUsed(label),
labelManager.getResourceByLabel(label, clusterResource));
// if any of the label doesn't beyond limit, we can allocate on this node
if (currentAbsoluteLabelUsedCapacity >=
queueCapacities.getAbsoluteMaximumCapacity(label)) {
if (LOG.isDebugEnabled()) {
LOG.debug(getQueueName() + " used=" + queueUsage.getUsed()
+ " current-capacity (" + queueUsage.getUsed(label) + ") "
+ " >= max-capacity ("
+ labelManager.getResourceByLabel(label, clusterResource) + ")");
}
canAssign = false;
break;
}
}
return canAssign;
}
private synchronized boolean assignToQueueIfUnreserve(Resource clusterResource) {
if (this.reservationsContinueLooking) {
// check to see if we could potentially use this node instead of a reserved
// node
Resource reservedResources = Resources.createResource(getMetrics()
.getReservedMB(), getMetrics().getReservedVirtualCores());
float capacityWithoutReservedCapacity = Resources.divide(
resourceCalculator, clusterResource,
Resources.subtract(queueUsage.getUsed(), reservedResources),
clusterResource);
if (capacityWithoutReservedCapacity <= queueCapacities
.getAbsoluteMaximumCapacity()) {
if (LOG.isDebugEnabled()) {
LOG.debug("parent: try to use reserved: " + getQueueName()
+ " usedResources: " + queueUsage.getUsed().getMemory()
+ " clusterResources: " + clusterResource.getMemory()
+ " reservedResources: " + reservedResources.getMemory()
+ " currentCapacity " + ((float) queueUsage.getUsed().getMemory())
/ clusterResource.getMemory()
+ " potentialNewWithoutReservedCapacity: "
+ capacityWithoutReservedCapacity + " ( " + " max-capacity: "
+ queueCapacities.getAbsoluteMaximumCapacity() + ")");
}
// we could potentially use this node instead of reserved node
return true;
}
}
return false;
}
private boolean canAssign(Resource clusterResource, FiCaSchedulerNode node) {
return (node.getReservedContainer() == null) &&
Resources.greaterThanOrEqual(resourceCalculator, clusterResource,
node.getAvailableResource(), minimumAllocation);
}
private synchronized CSAssignment assignContainersToChildQueues(Resource cluster,
FiCaSchedulerNode node, boolean needToUnreserve) {
CSAssignment assignment =
new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL);
printChildQueues();
// Try to assign to most 'under-served' sub-queue
for (Iterator<CSQueue> iter=childQueues.iterator(); iter.hasNext();) {
CSQueue childQueue = iter.next();
if(LOG.isDebugEnabled()) {
LOG.debug("Trying to assign to queue: " + childQueue.getQueuePath()
+ " stats: " + childQueue);
}
assignment = childQueue.assignContainers(cluster, node, needToUnreserve);
if(LOG.isDebugEnabled()) {
LOG.debug("Assigned to queue: " + childQueue.getQueuePath() +
" stats: " + childQueue + " --> " +
assignment.getResource() + ", " + assignment.getType());
}
// If we do assign, remove the queue and re-insert in-order to re-sort
if (Resources.greaterThan(
resourceCalculator, cluster,
assignment.getResource(), Resources.none())) {
// Remove and re-insert to sort
iter.remove();
LOG.info("Re-sorting assigned queue: " + childQueue.getQueuePath() +
" stats: " + childQueue);
childQueues.add(childQueue);
if (LOG.isDebugEnabled()) {
printChildQueues();
}
break;
}
}
return assignment;
}
String getChildQueuesToPrint() {
StringBuilder sb = new StringBuilder();
for (CSQueue q : childQueues) {
sb.append(q.getQueuePath() +
"usedCapacity=(" + q.getUsedCapacity() + "), " +
" label=("
+ StringUtils.join(q.getAccessibleNodeLabels().iterator(), ",")
+ ")");
}
return sb.toString();
}
private void printChildQueues() {
if (LOG.isDebugEnabled()) {
LOG.debug("printChildQueues - queue: " + getQueuePath()
+ " child-queues: " + getChildQueuesToPrint());
}
}
@Override
public void completedContainer(Resource clusterResource,
FiCaSchedulerApp application, FiCaSchedulerNode node,
RMContainer rmContainer, ContainerStatus containerStatus,
RMContainerEventType event, CSQueue completedChildQueue,
boolean sortQueues) {
if (application != null) {
// Careful! Locking order is important!
// Book keeping
synchronized (this) {
super.releaseResource(clusterResource, rmContainer.getContainer()
.getResource(), node.getLabels());
LOG.info("completedContainer" +
" queue=" + getQueueName() +
" usedCapacity=" + getUsedCapacity() +
" absoluteUsedCapacity=" + getAbsoluteUsedCapacity() +
" used=" + queueUsage.getUsed() +
" cluster=" + clusterResource);
}
// Note that this is using an iterator on the childQueues so this can't be
// called if already within an iterator for the childQueues. Like
// from assignContainersToChildQueues.
if (sortQueues) {
// reinsert the updated queue
for (Iterator<CSQueue> iter=childQueues.iterator(); iter.hasNext();) {
CSQueue csqueue = iter.next();
if(csqueue.equals(completedChildQueue))
{
iter.remove();
LOG.info("Re-sorting completed queue: " + csqueue.getQueuePath() +
" stats: " + csqueue);
childQueues.add(csqueue);
break;
}
}
}
// Inform the parent
if (parent != null) {
// complete my parent
parent.completedContainer(clusterResource, application,
node, rmContainer, null, event, this, sortQueues);
}
}
}
@Override
public synchronized void updateClusterResource(Resource clusterResource) {
// Update all children
for (CSQueue childQueue : childQueues) {
childQueue.updateClusterResource(clusterResource);
}
// Update metrics
CSQueueUtils.updateQueueStatistics(
resourceCalculator, this, parent, clusterResource, minimumAllocation);
}
@Override
public synchronized List<CSQueue> getChildQueues() {
return new ArrayList<CSQueue>(childQueues);
}
@Override
public void recoverContainer(Resource clusterResource,
SchedulerApplicationAttempt attempt, RMContainer rmContainer) {
if (rmContainer.getState().equals(RMContainerState.COMPLETED)) {
return;
}
// Careful! Locking order is important!
synchronized (this) {
FiCaSchedulerNode node =
scheduler.getNode(rmContainer.getContainer().getNodeId());
super.allocateResource(clusterResource, rmContainer.getContainer()
.getResource(), node.getLabels());
}
if (parent != null) {
parent.recoverContainer(clusterResource, attempt, rmContainer);
}
}
@Override
public ActiveUsersManager getActiveUsersManager() {
// Should never be called since all applications are submitted to LeafQueues
return null;
}
@Override
public void collectSchedulerApplications(
Collection<ApplicationAttemptId> apps) {
for (CSQueue queue : childQueues) {
queue.collectSchedulerApplications(apps);
}
}
@Override
public void attachContainer(Resource clusterResource,
FiCaSchedulerApp application, RMContainer rmContainer) {
if (application != null) {
FiCaSchedulerNode node =
scheduler.getNode(rmContainer.getContainer().getNodeId());
super.allocateResource(clusterResource, rmContainer.getContainer()
.getResource(), node.getLabels());
LOG.info("movedContainer" + " queueMoveIn=" + getQueueName()
+ " usedCapacity=" + getUsedCapacity() + " absoluteUsedCapacity="
+ getAbsoluteUsedCapacity() + " used=" + queueUsage.getUsed() + " cluster="
+ clusterResource);
// Inform the parent
if (parent != null) {
parent.attachContainer(clusterResource, application, rmContainer);
}
}
}
@Override
public void detachContainer(Resource clusterResource,
FiCaSchedulerApp application, RMContainer rmContainer) {
if (application != null) {
FiCaSchedulerNode node =
scheduler.getNode(rmContainer.getContainer().getNodeId());
super.releaseResource(clusterResource,
rmContainer.getContainer().getResource(),
node.getLabels());
LOG.info("movedContainer" + " queueMoveOut=" + getQueueName()
+ " usedCapacity=" + getUsedCapacity() + " absoluteUsedCapacity="
+ getAbsoluteUsedCapacity() + " used=" + queueUsage.getUsed() + " cluster="
+ clusterResource);
// Inform the parent
if (parent != null) {
parent.detachContainer(clusterResource, application, rmContainer);
}
}
}
public synchronized int getNumApplications() {
return numApplications;
}
}
| apache-2.0 |
imJackson/videoword | src/com/handheld_english/dao/SelectCourseDAO.java | 1266 | package com.handheld_english.dao;
import com.handheld_english.AppSession;
import com.handheld_english.data.Course;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class SelectCourseDAO {
private MyDatabaseHelper dbHelper;
public SelectCourseDAO( MyDatabaseHelper dbHelper )
{
this.dbHelper = dbHelper;
}
public void save(int user_id, int course_id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values1 = new ContentValues();
values1.put("u_id", user_id);
values1.put("c_id", course_id);
db.insert("Selectcourses", null, values1);
}
public Course getSelectedCourse(String username) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor1 = db.rawQuery("select * from Selectcourses,Courses,User where Selectcourses.c_id=Courses.c_id and u_name=?",
new String[] { username });
Course course =null;
if (cursor1.moveToFirst()) {
int id = cursor1.getInt(cursor1.getColumnIndex("c_id"));
String name2 = cursor1.getString(cursor1.getColumnIndex("c_name"));
course = new Course();
course.setId(id);
course.setName(name2);
}
cursor1.close();
return course;
}
}
| apache-2.0 |
lanceleverich/drools | drools-traits/src/main/java/org/drools/traits/core/factmodel/TraitCoreWrapperClassBuilder.java | 785 | /*
* Copyright 2020 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.
* 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.drools.traits.core.factmodel;
import org.drools.core.factmodel.ClassBuilder;
public interface TraitCoreWrapperClassBuilder extends ClassBuilder {
}
| apache-2.0 |
medgar/click | framework/src/org/apache/click/element/ResourceElement.java | 15802 | /*
* 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.click.element;
import org.apache.click.util.HtmlStringBuffer;
import org.apache.commons.lang.StringUtils;
/**
* Provides a base class for rendering HEAD resources of an HTML page, for
* example JavaScript (<script>) and Cascading Stylesheets
* (<link>/<style>).
* <p/>
* Subclasses should override {@link #getTag()} to return a specific HTML tag.
* <p/>
* Below are some example Resource elements:
* <ul>
* <li>{@link JsImport}, for importing <tt>external</tt> JavaScript using the
* <script> element.</li>
* <li>{@link JsScript}, for including <tt>inline</tt> JavaScript using the
* <script> element.</li>
* <li>{@link CssImport}, for importing <tt>external</tt> Cascading Stylesheets
* using the <link> element.</li>
* <li>{@link CssStyle}, for including <tt>inline</tt> Cascading Stylesheets
* using the <style> element.</li>
* </ul>
*
* <a name="remove-duplicates"></a>
* <h3>Remove duplicates</h3>
* Click will ensure that duplicate Resource elements are removed by checking
* the {@link #isUnique()} property. Thus if the same Resource is imported
* multiple times by the Page or different Controls, only one Resource will be
* rendered, if {@link #isUnique()} returns <tt>true</tt>.
* <p/>
* The rules for defining a unique Resource is as follows:
* <ul>
* <li>{@link JsImport} and {@link CssImport} is unique based on the
* attributes {@link JsImport#getSrc()} and {@link CssImport#getHref()}
* respectively.</li>
* <li>{@link JsScript} and {@link CssStyle} is unique if their HTML
* {@link #setId(java.lang.String) ID} attribute is set. The HTML
* spec defines that an element's HTML ID must be unique per page.</li>
* </ul>
* For example:
* <pre class="prettyprint">
* public class MyPage extends Page {
*
* public List getHeadElements() {
* // We use lazy loading to ensure the JavaScript and Css is only added
* // the first time this method is called.
* if (headElements == null) {
* // Get the head elements from the super implementation
* headElements = super.getHeadElements();
*
* JsImport jsImport = new JsImport("/js/mylib.js");
* // Click will ensure the library "/js/mylib.js" is only included
* // once in the Page
* headElements.add(jsImport);
*
* JsScript jsScript = new JsScript("alert('Hello!');");
* // Click won't ensure the script is unique because its ID
* // attribute is not defined
* headElements.add(jsScript);
*
* jsScript = new JsScript("alert('Hello!');");
* jsScript.setId("my-unique-script-id");
* // Click will ensure the script is unique because its ID attribute
* // is defined. Click will remove other scripts with the same ID
* headElements.add(jsScript);
*
* CssImport cssImport = new CssImport("/css/style.css");
* // Click will ensure the library "/css/style.css" is only
* // included once in the Page
* headElements.add(cssImport);
*
* CssScript cssScript = new CssScript("body { font-weight: bold; }");
* cssScript.setId("my-unique-style-id");
* // Click will ensure the css is unique because its ID attribute
* // is defined. Click will remove other css styles with the same ID
* headElements.add(cssScript);
* }
* return headElements;
* }
* } </pre>
*
* <a name="versioning"></a>
* <h3>Automatic Resource versioning</h3>
*
* ResourceElement provides the ability to automatically version elements
* according to Yahoo Performance Rule: <a target="_blank" href="http://developer.yahoo.com/performance/rules.html#expires">Add an Expires or a Cache-Control Header</a>.
* This rule recommends adding an expiry header to JavaScript, Css
* and image resources, which forces the browser to cache the resources. It also
* suggests <em>versioning</em> the resources so that each new release of the
* web application renders resources with different paths, forcing the browser
* to download the new resources.
* <p/>
* For detailed information on versioning JavaScript, Css and image resources
* see the <a href="../../../../extras-api/org/apache/click/extras/filter/PerformanceFilter.html">PerformanceFilter</a>.
* <p/>
* To enable versioning of JavaScript, Css and image resources the following
* conditions must be met:
* <ul>
* <li>the {@link org.apache.click.util.ClickUtils#ENABLE_RESOURCE_VERSION}
* request attribute must be set to <tt>true</tt></li>
* <li>the application mode must be either "production" or "profile"</li>
* <li>the {@link org.apache.click.util.ClickUtils#setApplicationVersion(java.lang.String)
* application version} must be set</li>
* </ul>
* <b>Please note:</b> <a href="../../../../extras-api/org/apache/click/extras/filter/PerformanceFilter.html">PerformanceFilter</a>
* handles the above steps for you.
*
* <a name="conditional-comment"></a>
* <h3>Conditional comment support for Internet Explorer</h3>
*
* Sometimes it is necessary to provide additional JavaScript and Css for
* Internet Explorer because it deviates quite often from the standards.
* <p/>
* Conditional comments allows you to wrap the resource in a special comment
* which only IE understands, meaning other browsers won't process the resource.
* <p/>
* You can read more about conditional comments
* <a target="_blank" href="http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx#syntax">here</a>
* and <a target="_blank" href="http://www.quirksmode.org/css/condcom.html">here</a>
* <p/>
* It has to be said that IE7 and up has much better support for Css, thus
* conditional comments are mostly used for IE6 and below.
* <pre class="prettyprint">
* public class MyPage extends Page {
*
* public List getHeadElements() {
* // We use lazy loading to ensure the JavaScript and Css is only added
* // the first time this method is called.
* if (headElements == null) {
* // Get the head elements from the super implementation
* headElements = super.getHeadElements();
*
* CssImport cssImport = new CssImport("/css/ie-style.css");
* // Use one of the predefined conditional comments to target IE6
* // and below
* cssImport.setConditionalComment(IE_LESS_THAN_IE7);
* headElements.add(cssImport);
*
* cssImport = new CssImport("/css/ie-style2.css");
* // Use a custom predefined conditional comments to target only IE6
* cssImport.setConditionalComment("[if IE 6]");
* headElements.add(cssImport);
* }
* return headElements;
* }
* } </pre>
*
* ResourceElement contains some predefined Conditional Comments namely
* {@link #IF_IE}, {@link #IF_LESS_THAN_IE7} and {@link #IF_IE7}.
*/
public class ResourceElement extends Element {
private static final long serialVersionUID = 1L;
// Constants --------------------------------------------------------------
/**
* A predefined conditional comment to test if browser is IE. Value:
* <tt>[if IE]</tt>.
*/
public static final String IF_IE = "[if IE]";
/**
* A predefined conditional comment to test if browser is less than IE7.
* Value: <tt>[if lt IE 7]</tt>.
*/
public static final String IF_LESS_THAN_IE7 = "[if lt IE 7]";
/**
* A predefined conditional comment to test if browser is IE7. Value:
* <tt>[if IE 7]</tt>.
*/
public static final String IF_IE7 = "[if IE 7]";
/**
* A predefined conditional comment to test if browser is less than
* or equal to IE7. Value: <tt>[if lte IE 7]</tt>.
*/
public static final String IF_LESS_THAN_OR_EQUAL_TO_IE7 = "[if lte IE 7]";
/**
* A predefined conditional comment to test if browser is less than IE9.
* Value: <tt>[if lt IE 9]</tt>.
*/
public static final String IF_LESS_THAN_IE9 = "[if lt IE 9]";
// Variables --------------------------------------------------------------
/**
* The Internet Explorer conditional comment to wrap the Resource with.
*/
private String conditionalComment;
/**
* Indicates whether the {@link #getId() ID} attribute should be rendered
* or not, default value is <tt>true</tt>.
*/
private boolean renderId = true;
/**
* The <tt>version indicator</tt> to append to the Resource element.
*/
private String versionIndicator;
// ------------------------------------------------------ Public properties
/**
* Return the <tt>version indicator</tt> to be appended to the resource
* path.
*
* @return the <tt>version indicator</tt> to be appended to the resource
* path.
*/
public String getVersionIndicator() {
return versionIndicator;
}
/**
* Set the <tt>version indicator</tt> to be appended to the resource path.
*
* @param versionIndicator the version indicator to be appended to the
* resource path
*/
public void setVersionIndicator(String versionIndicator) {
this.versionIndicator = versionIndicator;
}
/**
* Returns whether or not the Resource unique. This method returns
* <tt>true</tt> if the {@link #getId() ID} attribute is defined,
* false otherwise.
*
* @return true if the Resource should be unique, false otherwise.
*/
public boolean isUnique() {
String id = getId();
// If id is defined, import will be any duplicate import found will be
// filtered out
if (StringUtils.isNotBlank(id)) {
return true;
}
return false;
}
/**
* Returns the element render {@link #getId() ID} attribute status, default
* value is true.
*
* @see #setRenderId(boolean)
*
* @return the element render id attribute status, default value is true
*/
public boolean isRenderId() {
return renderId;
}
/**
* Set the element render {@link #getId() ID} attribute status.
* <p/>
* If renderId is false the element {@link #getId() ID} attribute will not
* be rendered.
*
* @param renderId set the element render id attribute status
*/
public void setRenderId(boolean renderId) {
this.renderId = renderId;
}
/**
* Return Internal Explorer's <tt>conditional comment</tt> to wrap the
* Resource with.
*
* @return Internal Explorer's conditional comment to wrap the Resource with.
*/
public String getConditionalComment() {
return conditionalComment;
}
/**
* Set Internet Explorer's conditional comment to wrap the Resource with.
*
* @param conditionalComment Internet Explorer's conditional comment to wrap
* the Resource with
*/
public void setConditionalComment(String conditionalComment) {
this.conditionalComment = conditionalComment;
}
// Public Methods ---------------------------------------------------------
/**
* Render the HTML representation of the Resource element to the specified
* buffer.
* <p/>
* If {@link #getTag()} returns null, this method will return an empty
* string.
*
* @param buffer the specified buffer to render the Resource element output
* to
*/
@Override
public void render(HtmlStringBuffer buffer) {
renderConditionalCommentPrefix(buffer);
if (getTag() == null) {
return;
}
renderTagBegin(getTag(), buffer);
renderTagEnd(getTag(), buffer);
renderConditionalCommentSuffix(buffer);
}
// Package Private Methods ------------------------------------------------
/**
* Render the given attribute and resourcePath and append the
* {@link #getVersionIndicator()} to the resourcePath, if it was set.
* If the version indicator is not defined this method will only render the
* resourcePath.
*
* @param buffer the buffer to render to
* @param attribute the attribute name to render
* @param resourcePath the resource path to render
*/
void renderResourcePath(HtmlStringBuffer buffer, String attribute,
String resourcePath) {
String versionIndicator = getVersionIndicator();
// If resourcePath is null exit early
if (resourcePath == null) {
return;
}
// If version indicator is not defined render resource path only
if (StringUtils.isBlank(versionIndicator)) {
buffer.appendAttribute(attribute, resourcePath);
return;
}
// If the resourcePath has no extension render the resource path only
int start = resourcePath.lastIndexOf(".");
if (start < 0) {
buffer.appendAttribute(attribute, resourcePath);
return;
}
buffer.append(" ");
buffer.append(attribute);
buffer.append("=\"");
buffer.append(resourcePath.substring(0, start));
buffer.append(versionIndicator);
buffer.append(resourcePath.substring(start));
buffer.append("\"");
}
/**
* Render the {@link #getConditionalComment() conditional comment} prefix
* to the specified buffer. If the conditional comment is not defined this
* method won't append to the buffer.
*
* @param buffer buffer to append the conditional comment prefix
*/
void renderConditionalCommentPrefix(HtmlStringBuffer buffer) {
String conditional = getConditionalComment();
// Render IE conditional comment
if (StringUtils.isNotBlank(conditional)) {
buffer.append("<!--").append(conditional).append(">\n");
}
}
/**
* Render the {@link #getConditionalComment() conditional comment} suffix
* to the specified buffer. If the conditional comment is not defined this
* method won't append to the buffer.
*
* @param buffer buffer to append the conditional comment suffix
*/
void renderConditionalCommentSuffix(HtmlStringBuffer buffer) {
String conditional = getConditionalComment();
// Close IE conditional comment
if (StringUtils.isNotBlank(conditional)) {
buffer.append("\n<![endif]-->");
}
}
}
| apache-2.0 |
chenxiuheng/js4ms | js4ms-jsdk/common/src/main/java/org/js4ms/common/exception/BoundException.java | 1592 | package org.js4ms.common.exception;
/*
* #%L
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* BoundException.java [org.js4ms.jsdk:common]
* %%
* Copyright (C) 2009 - 2014 Cisco Systems, 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.
* #L%
*/
/**
* @author Greg Bumgardner (gbumgard)
*/
public class BoundException
extends Exception {
private static final long serialVersionUID = -5587197699181393667L;
protected final Object object;
protected final Throwable throwable;
/**
* @param object
* @param throwable
*/
public BoundException(final Object object, final Throwable throwable) {
this.object = object;
this.throwable = throwable;
}
/**
* @return
*/
public Object getObject() {
return this.object;
}
/**
* @return
*/
public Throwable getThrowable() {
return this.throwable;
}
/**
* @throws Throwable
*/
public void rethrow() throws Throwable {
throw this.throwable;
}
}
| apache-2.0 |
welterde/ewok | com/planet_ink/coffee_mud/Abilities/Properties/Prop_NewDeathMsg.java | 2344 | package com.planet_ink.coffee_mud.Abilities.Properties;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2010 Bo Zimmerman
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.
*/
public class Prop_NewDeathMsg extends Property
{
public String ID() { return "Prop_NewDeathMsg"; }
public String name(){ return "NewDeathMsg";}
protected int canAffectCode(){return Ability.CAN_MOBS;}
public String accountForYourself()
{ return "Changed death msg"; }
public boolean okMessage(Environmental myHost, CMMsg msg)
{
if((affected==msg.source())
&&(msg.targetMessage()==null)
&&(msg.othersMinor()==CMMsg.TYP_DEATH)
&&(text().length()>0)
&&(msg.othersMessage()!=null)
&&(msg.othersMessage().toUpperCase().indexOf("<S-NAME> IS DEAD")>0))
{
int x=msg.othersMessage().indexOf("\n\r");
if(x>=0)
{
msg.modify(msg.source(),msg.target(),msg.tool(),msg.sourceCode(),text()+msg.othersMessage().substring(x),
msg.targetCode(),msg.targetMessage(),
msg.othersCode(),text()+msg.othersMessage().substring(x));
}
}
return super.okMessage(myHost,msg);
}
}
| apache-2.0 |
paas-training/huaweiair-order-service-exercise | src/main/java/com/huaweiair/order/controller/OrderDelegate.java | 1005 | package com.huaweiair.order.controller;
import com.huaweiair.order.dao.OrderDelegateImpl;
import com.huaweiair.order.model.FlightFlag;
import com.huaweiair.order.model.FlightOrder;
import java.util.List;
import org.springframework.stereotype.Component;
@Component
public class OrderDelegate{
private OrderDelegateImpl delegateImpl;
public OrderDelegate() {
delegateImpl = new OrderDelegateImpl();
}
public Boolean createOrders(FlightFlag order){
// Do Some Magic Here!
return delegateImpl.createOrders(order);
};
public Boolean deleteOrder(String orderId){
// Do Some Magic Here!
return delegateImpl.deleteOrder(orderId);
};
public List<FlightOrder> getAllOrders(String userId){
// Do Some Magic Here!
return delegateImpl.getAllOrders(userId);
};
public Boolean modifyOrder(String orderId, Integer action){
// Do Some Magic Here!
return delegateImpl.modifyOrder(orderId, action);
};
} | apache-2.0 |
0359xiaodong/YiBo | YiBo/src/com/shejiaomao/weibo/service/task/UpdateProfilePhotoTask.java | 4431 | package com.shejiaomao.weibo.service.task;
import java.io.File;
import com.shejiaomao.maobo.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import com.cattong.commons.LibException;
import com.cattong.commons.Logger;
import com.cattong.commons.util.FileUtil;
import com.cattong.entity.User;
import com.cattong.weibo.Weibo;
import com.shejiaomao.common.ImageQuality;
import com.shejiaomao.common.ImageUtil;
import com.shejiaomao.common.NetType;
import com.shejiaomao.common.ResourceBook;
import com.shejiaomao.weibo.SheJiaoMaoApplication;
import com.shejiaomao.weibo.activity.ProfileEditActivity;
import com.shejiaomao.weibo.common.GlobalVars;
import com.shejiaomao.weibo.service.cache.ImageCache;
public class UpdateProfilePhotoTask extends AsyncTask<Void, Void, User> {
private static final String TAG = "UpdateProfilePhotoTask";
private ProfileEditActivity context;
private SheJiaoMaoApplication sheJiaoMao;
private long accountId;
private File image;
private ProgressDialog dialog;
private boolean isShowDialog;
private String resultMsg;
public UpdateProfilePhotoTask(ProfileEditActivity context, File image) {
this.context = context;
this.sheJiaoMao = (SheJiaoMaoApplication)context.getApplication();
this.accountId = sheJiaoMao.getCurrentAccount().getAccountId();
this.image = image;
this.isShowDialog = true;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (isShowDialog) {
dialog = ProgressDialog.show(context, null, context.getString(R.string.msg_profile_photo_uploading));
dialog.setCancelable(true);
dialog.setOnCancelListener(onCancelListener);
dialog.setOwnerActivity((Activity)context);
}
}
@Override
protected User doInBackground(Void... params) {
if (image == null) {
return null;
}
Weibo microBlog = GlobalVars.getMicroBlog(accountId);
if (microBlog == null) {
return null;
}
User user = null;
try {
if (image != null) {
String fileExtension = FileUtil.getFileExtensionFromName(image.getName());
int size = ImageQuality.Low.getSize();
ImageQuality quality = sheJiaoMao.getImageUploadQuality();
if (quality == ImageQuality.High
|| GlobalVars.NET_TYPE == NetType.WIFI) {
size = ImageQuality.High.getSize();
} else if (quality == ImageQuality.Middle
|| quality == ImageQuality.Low ) {
size = quality.getSize();
if(Logger.isDebug()) Log.d(TAG, "prefix size: " + size);
//对低速网络进行压缩
if (GlobalVars.NET_TYPE == NetType.MOBILE_GPRS ||
GlobalVars.NET_TYPE == NetType.MOBILE_EDGE
) {
size = ImageQuality.Low.getSize();
}
}
String destName = ImageCache.getTempFolder() + File.separator +
System.currentTimeMillis() + "." + fileExtension;
File dest = new File(destName);
boolean isSuccess = ImageUtil.scaleImageFile(image, dest, size);
if (isSuccess) {
image = dest;
}
user = microBlog.updateProfileImage(image);
}
} catch (LibException e) {
if (Logger.isDebug()) Log.e(TAG, "Task", e);
resultMsg = ResourceBook.getResultCodeValue(e.getErrorCode(), context);
}
return user;
}
@Override
protected void onPostExecute(User resultUser) {
super.onPostExecute(resultUser);
if (isShowDialog
&& dialog != null
&& dialog.getContext() != null ) {
try {
dialog.dismiss();
} catch(Exception e){}
}
if (resultUser != null) {
Toast.makeText(context, R.string.msg_profile_photo_uploaded, Toast.LENGTH_LONG).show();
context.updateProfileImage(resultUser.getProfileImageUrl());
context.updateUser(resultUser);
} else {
Toast.makeText(context, resultMsg, Toast.LENGTH_LONG).show();
}
}
private OnCancelListener onCancelListener = new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
Button btnSend = (Button)((Activity)context).findViewById(R.id.btnOperate);
btnSend.setEnabled(true);
UpdateProfilePhotoTask.this.cancel(true);
}
};
}
| apache-2.0 |
dswarm/dswarm | controller/src/test/java/org/dswarm/controller/resources/job/test/NQuadsResponseTasksResourceTest.java | 1820 | /**
* Copyright (C) 2013 – 2017 SLUB Dresden & Avantgarde Labs GmbH (<code@dswarm.org>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dswarm.controller.resources.job.test;
import org.dswarm.common.MediaTypeUtil;
import org.dswarm.persistence.util.DMPPersistenceUtil;
import org.junit.Assert;
import java.io.IOException;
/**
* Created by tgaengler on 04.03.16.
*/
public class NQuadsResponseTasksResourceTest extends AbstractResponseMediaTypeTasksResourceTest {
public NQuadsResponseTasksResourceTest() {
super(MediaTypeUtil.N_QUADS_TYPE, "controller_task-result.nq");
}
@Override
public void testTaskExecution() throws Exception {
super.testTaskExecution();
}
@Override
protected void compareResult(final String actualResult) throws IOException {
final String expectedResult = DMPPersistenceUtil.getResourceAsString(expectedResultFileName);
final int expectedLength = expectedResult.length();
final int actualLength = actualResult.length();
final boolean result = expectedLength == actualLength || 21378 == actualLength || 20658 == actualLength;
Assert.assertTrue(String.format("expected length = '%d' :: actual length = '%d' \n\nexpected = '\n%s\n'\n\nactual = '\n%s\n'\n", expectedLength, actualLength, expectedResult, actualResult), result);
}
}
| apache-2.0 |
WeRockStar/iosched | lib/src/main/java/com/google/samples/apps/iosched/fcm/command/SyncCommand.java | 3023 | /*
* Copyright 2014 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.samples.apps.iosched.fcm.command;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.samples.apps.iosched.fcm.FcmCommand;
import com.google.samples.apps.iosched.sync.TriggerSyncReceiver;
import java.util.Random;
import static com.google.samples.apps.iosched.util.LogUtils.LOGI;
import static com.google.samples.apps.iosched.util.LogUtils.makeLogTag;
public class SyncCommand extends FcmCommand {
private static final String TAG = makeLogTag("SyncCommand");
private static final int DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS = 15 * 60 * 1000; // 15 minutes
private static final Random RANDOM = new Random();
@Override
public void execute(Context context, String type, String extraData) {
LOGI(TAG, "Received FCM message: " + type);
int syncJitter;
SyncData syncData = null;
if (extraData != null) {
try {
Gson gson = new Gson();
syncData = gson.fromJson(extraData, SyncData.class);
} catch (JsonSyntaxException e) {
LOGI(TAG, "Error while decoding extraData: " + e.toString());
}
}
if (syncData != null && syncData.sync_jitter != 0) {
syncJitter = syncData.sync_jitter;
} else {
syncJitter = DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS;
}
scheduleSync(context, syncJitter);
}
private void scheduleSync(Context context, int syncJitter) {
int jitterMillis = (int) (RANDOM.nextFloat() * syncJitter);
final String debugMessage = "Scheduling next sync for " + jitterMillis + "ms";
LOGI(TAG, debugMessage);
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE))
.set(
AlarmManager.RTC,
System.currentTimeMillis() + jitterMillis,
PendingIntent.getBroadcast(
context,
0,
new Intent(context, TriggerSyncReceiver.class),
PendingIntent.FLAG_CANCEL_CURRENT));
}
class SyncData {
private int sync_jitter;
SyncData() {
}
}
}
| apache-2.0 |
antoinesd/weld-core | impl/src/main/java/org/jboss/weld/injection/package-info.java | 880 | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual 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.
*/
@Vetoed
package org.jboss.weld.injection;
import javax.enterprise.inject.Vetoed;
| apache-2.0 |
mdogan/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/monitor/impl/OnDemandIndexStats.java | 6917 | /*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.internal.monitor.impl;
/**
* Holds the intermediate results while combining the partitioned index stats
* to produce the final per-index stats.
*/
@SuppressWarnings("checkstyle:methodcount")
public class OnDemandIndexStats {
private long creationTime;
private long entryCount;
private long queryCount;
private long hitCount;
private long averageHitLatency;
private double averageHitSelectivity;
private long insertCount;
private long totalInsertLatency;
private long updateCount;
private long totalUpdateLatency;
private long removeCount;
private long totalRemoveLatency;
private long memoryCost;
private long totalHitCount;
/**
* Returns the creation time.
*/
public long getCreationTime() {
return creationTime;
}
/**
* Sets the creation time the given value.
*
* @param creationTime the creation time to set.
*/
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
/**
* Returns the query count.
*/
public long getQueryCount() {
return queryCount;
}
/**
* Sets the query count to the given value.
*
* @param queryCount the query count value to set.
*/
public void setQueryCount(long queryCount) {
this.queryCount = queryCount;
}
/**
* Returns the hit count.
*/
public long getHitCount() {
return hitCount;
}
/**
* Sets the hit count to the given value.
*
* @param hitCount the hit count value to set.
*/
public void setHitCount(long hitCount) {
this.hitCount = hitCount;
}
/**
* Returns the average hit latency.
*/
public long getAverageHitLatency() {
return averageHitLatency;
}
/**
* Sets the average hit latency to the given value.
*
* @param averageHitLatency the average hit latency value to set.
*/
public void setAverageHitLatency(long averageHitLatency) {
this.averageHitLatency = averageHitLatency;
}
/**
* Returns the average hit selectivity.
*/
public double getAverageHitSelectivity() {
return averageHitSelectivity;
}
/**
* Sets the average hit selectivity to the given value.
*
* @param averageHitSelectivity the average hit selectivity value to set.
*/
public void setAverageHitSelectivity(double averageHitSelectivity) {
this.averageHitSelectivity = averageHitSelectivity;
}
/**
* Returns the insert count.
*/
public long getInsertCount() {
return insertCount;
}
/**
* Sets the insert count to the given value.
*
* @param insertCount the insert count value to set.
*/
public void setInsertCount(long insertCount) {
this.insertCount = insertCount;
}
/**
* Returns the total insert latency.
*/
public long getTotalInsertLatency() {
return totalInsertLatency;
}
/**
* Sets the total insert latency to the given value.
*
* @param totalInsertLatency the total insert latency value to set.
*/
public void setTotalInsertLatency(long totalInsertLatency) {
this.totalInsertLatency = totalInsertLatency;
}
/**
* Returns the update count.
*/
public long getUpdateCount() {
return updateCount;
}
/**
* Sets the update count to the given value.
*
* @param updateCount the update count value to set.
*/
public void setUpdateCount(long updateCount) {
this.updateCount = updateCount;
}
/**
* Returns the total update latency.
*/
public long getTotalUpdateLatency() {
return totalUpdateLatency;
}
/**
* Sets the total update latency to the given value.
*
* @param totalUpdateLatency the total update latency value to set.
*/
public void setTotalUpdateLatency(long totalUpdateLatency) {
this.totalUpdateLatency = totalUpdateLatency;
}
/**
* Returns the remove count.
*/
public long getRemoveCount() {
return removeCount;
}
/**
* Sets the remove count to the given value.
*
* @param removeCount the remove count value to set.
*/
public void setRemoveCount(long removeCount) {
this.removeCount = removeCount;
}
/**
* Returns the total remove latency.
*/
public long getTotalRemoveLatency() {
return totalRemoveLatency;
}
/**
* Sets the total remove latency to the given value.
*
* @param totalRemoveLatency the total remove latency value to set.
*/
public void setTotalRemoveLatency(long totalRemoveLatency) {
this.totalRemoveLatency = totalRemoveLatency;
}
/**
* Returns the memory cost.
*/
public long getMemoryCost() {
return memoryCost;
}
/**
* Sets the memory cost to the given value.
*
* @param memoryCost the memory cost value to set.
*/
public void setMemoryCost(long memoryCost) {
this.memoryCost = memoryCost;
}
/**
* Returns the total hit count.
*/
public long getTotalHitCount() {
return totalHitCount;
}
/**
* Sets the total hit count to the given value.
*
* @param totalHitCount the total hit count value to set.
*/
public void setTotalHitCount(long totalHitCount) {
this.totalHitCount = totalHitCount;
}
@Override
public String toString() {
return "LocalIndexStatsImpl{" + "creationTime=" + creationTime + ", hitCount=" + hitCount + ", entryCount=" + entryCount
+ ", queryCount=" + queryCount + ", averageHitSelectivity=" + averageHitSelectivity + ", averageHitLatency="
+ averageHitLatency + ", insertCount=" + insertCount + ", totalInsertLatency=" + totalInsertLatency
+ ", updateCount=" + updateCount + ", totalUpdateLatency=" + totalUpdateLatency + ", removeCount=" + removeCount
+ ", totalRemoveLatency=" + totalRemoveLatency + ", memoryCost=" + memoryCost + ", totalHitCount=" + totalHitCount
+ '}';
}
}
| apache-2.0 |
sankarh/hive | ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/show/ShowPartitionAnalyzer.java | 11494 | /*
* 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.hive.ql.ddl.table.partition.show;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.ddl.DDLWork;
import org.apache.hadoop.hive.ql.ddl.DDLSemanticAnalyzerFactory.DDLType;
import org.apache.hadoop.hive.ql.ddl.table.partition.PartitionUtils;
import org.apache.hadoop.hive.ql.exec.ColumnInfo;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer;
import org.apache.hadoop.hive.ql.parse.ColumnAccessInfo;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.HiveTableName;
import org.apache.hadoop.hive.ql.parse.RowResolver;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.type.ExprNodeTypeCheck;
import org.apache.hadoop.hive.ql.parse.type.TypeCheckCtx;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBaseCompare;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
/**
* Analyzer for show partition commands.
*/
@DDLType(types = HiveParser.TOK_SHOWPARTITIONS)
public class ShowPartitionAnalyzer extends BaseSemanticAnalyzer {
public ShowPartitionAnalyzer(QueryState queryState) throws SemanticException {
super(queryState);
}
@Override
public void analyzeInternal(ASTNode ast) throws SemanticException {
ctx.setResFile(ctx.getLocalTmpPath());
String tableName = getUnescapedName((ASTNode) ast.getChild(0));
List<Map<String, String>> partSpecs = getPartitionSpecs(getTable(tableName), ast);
assert (partSpecs.size() <= 1);
Map<String, String> partSpec = (partSpecs.size() > 0) ? partSpecs.get(0) : null;
Table table = getTable(HiveTableName.of(tableName));
inputs.add(new ReadEntity(table));
setColumnAccessInfo(new ColumnAccessInfo());
table.getPartColNames().forEach(col -> getColumnAccessInfo().add(table.getCompleteName(), col));
ExprNodeDesc filter = getShowPartitionsFilter(table, ast);
String orderBy = getShowPartitionsOrder(table, ast);
short limit = getShowPartitionsLimit(ast);
ShowPartitionsDesc desc = new ShowPartitionsDesc(tableName, ctx.getResFile(),
partSpec, filter, orderBy, limit);
Task<DDLWork> task = TaskFactory.get(new DDLWork(getInputs(), getOutputs(), desc));
rootTasks.add(task);
task.setFetchSource(true);
setFetchTask(createFetchTask(ShowPartitionsDesc.SCHEMA));
}
@VisibleForTesting
ExprNodeDesc getShowPartitionsFilter(Table table, ASTNode command) throws SemanticException {
ExprNodeDesc showFilter = null;
for (int childIndex = 0; childIndex < command.getChildCount(); childIndex++) {
ASTNode astChild = (ASTNode)command.getChild(childIndex);
if (astChild.getType() == HiveParser.TOK_WHERE) {
RowResolver rwsch = new RowResolver();
Map<String, String> colTypes = new HashMap<String, String>();
for (FieldSchema fs : table.getPartCols()) {
rwsch.put(table.getTableName(), fs.getName(), new ColumnInfo(fs.getName(),
TypeInfoFactory.stringTypeInfo, null, true));
colTypes.put(fs.getName().toLowerCase(), fs.getType());
}
TypeCheckCtx tcCtx = new TypeCheckCtx(rwsch);
ASTNode conds = (ASTNode) astChild.getChild(0);
Map<ASTNode, ExprNodeDesc> nodeOutputs = ExprNodeTypeCheck.genExprNode(conds, tcCtx);
ExprNodeDesc target = nodeOutputs.get(conds);
if (!(target instanceof ExprNodeGenericFuncDesc) || !target.getTypeInfo().equals(
TypeInfoFactory.booleanTypeInfo)) {
String errorMsg = tcCtx.getError() != null ? ". " + tcCtx.getError() : "";
throw new SemanticException("Not a filter expr: " +
(target == null ? "null" : target.getExprString()) + errorMsg);
}
showFilter = replaceDefaultPartNameAndCastType(target, colTypes,
HiveConf.getVar(conf, HiveConf.ConfVars.DEFAULTPARTITIONNAME));
}
}
return showFilter;
}
private ExprNodeDesc replaceDefaultPartNameAndCastType(ExprNodeDesc nodeDesc,
Map<String, String> colTypes, String defaultPartName) throws SemanticException {
if (!(nodeDesc instanceof ExprNodeGenericFuncDesc)) {
return nodeDesc;
}
ExprNodeGenericFuncDesc funcDesc = (ExprNodeGenericFuncDesc) nodeDesc;
if (FunctionRegistry.isOpAnd(funcDesc) || FunctionRegistry.isOpOr(funcDesc)) {
List<ExprNodeDesc> newChildren = new ArrayList<ExprNodeDesc>();
for (ExprNodeDesc child : funcDesc.getChildren()) {
newChildren.add(replaceDefaultPartNameAndCastType(child, colTypes, defaultPartName));
}
funcDesc.setChildren(newChildren);
return funcDesc;
}
List<ExprNodeDesc> children = funcDesc.getChildren();
int colIdx = -1, constIdx = -1;
for (int i = 0; i < children.size(); i++) {
ExprNodeDesc child = children.get(i);
if (child instanceof ExprNodeColumnDesc) {
String col = ((ExprNodeColumnDesc)child).getColumn().toLowerCase();
String type = colTypes.get(col);
if (!type.equals(child.getTypeString())) {
child.setTypeInfo(TypeInfoFactory.getPrimitiveTypeInfo(type));
}
colIdx = i;
} else if (child instanceof ExprNodeConstantDesc) {
constIdx = i;
}
}
if (funcDesc.getGenericUDF() instanceof GenericUDFBaseCompare && children.size() == 2 &&
colIdx > -1 && constIdx > -1) {
ExprNodeConstantDesc constantDesc = (ExprNodeConstantDesc)children.get(constIdx);
ExprNodeColumnDesc columnDesc = (ExprNodeColumnDesc)children.get(colIdx);
Object val = constantDesc.getValue();
boolean isDefaultPartitionName = defaultPartName.equals(val);
String type = colTypes.get(columnDesc.getColumn().toLowerCase());
PrimitiveTypeInfo pti = TypeInfoFactory.getPrimitiveTypeInfo(type);
if (!isDefaultPartitionName) {
if (!constantDesc.getTypeString().equals(type)) {
Object converted = ObjectInspectorConverters.getConverter(
TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(constantDesc.getTypeInfo()),
TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(pti))
.convert(val);
if (converted == null) {
throw new SemanticException("Cannot convert to " + type + " from " +
constantDesc.getTypeString() + ", value: " + val);
}
ExprNodeConstantDesc newConstantDesc = new ExprNodeConstantDesc(pti, converted);
children.set(constIdx, newConstantDesc);
}
} else {
GenericUDF originalOp = funcDesc.getGenericUDF();
String fnName;
if (FunctionRegistry.isEq(originalOp)) {
fnName = "isnull";
} else if (FunctionRegistry.isNeq(originalOp)) {
fnName = "isnotnull";
} else {
throw new SemanticException(
"Only '=' and '!=' are allowed for the default partition, function: " + originalOp.getUdfName());
}
funcDesc = PartitionUtils.makeUnaryPredicate(fnName, columnDesc);
}
}
return funcDesc;
}
private String getShowPartitionsOrder(Table table, ASTNode command) throws SemanticException {
String orderBy = null;
for (int childIndex = 0; childIndex < command.getChildCount(); childIndex++) {
ASTNode astChild = (ASTNode) command.getChild(childIndex);
if (astChild.getType() == HiveParser.TOK_ORDERBY) {
Map<String, Integer> poses = new HashMap<String, Integer>();
RowResolver rwsch = new RowResolver();
for (int i = 0; i < table.getPartCols().size(); i++) {
FieldSchema fs = table.getPartCols().get(i);
rwsch.put(table.getTableName(), fs.getName(), new ColumnInfo(fs.getName(),
TypeInfoFactory.getPrimitiveTypeInfo(fs.getType()), null, true));
poses.put(fs.getName().toLowerCase(), i);
}
TypeCheckCtx tcCtx = new TypeCheckCtx(rwsch);
StringBuilder colIndices = new StringBuilder();
StringBuilder order = new StringBuilder();
int ccount = astChild.getChildCount();
for (int i = 0; i < ccount; ++i) {
// @TODO: implement null first or last
ASTNode cl = (ASTNode) astChild.getChild(i);
if (cl.getType() == HiveParser.TOK_TABSORTCOLNAMEASC) {
order.append("+");
cl = (ASTNode) cl.getChild(0).getChild(0);
} else if (cl.getType() == HiveParser.TOK_TABSORTCOLNAMEDESC) {
order.append("-");
cl = (ASTNode) cl.getChild(0).getChild(0);
} else {
order.append("+");
}
Map<ASTNode, ExprNodeDesc> nodeOutputs = ExprNodeTypeCheck.genExprNode(cl, tcCtx);
ExprNodeDesc desc = nodeOutputs.get(cl);
if (!(desc instanceof ExprNodeColumnDesc)) {
throw new SemanticException("Only partition keys are allowed for " +
"sorting partition names, input: " + cl.toStringTree());
}
String col = ((ExprNodeColumnDesc) desc).getColumn().toLowerCase();
colIndices.append(poses.get(col)).append(",");
}
colIndices.setLength(colIndices.length() - 1);
orderBy = colIndices + ":" + order;
}
}
return orderBy;
}
private short getShowPartitionsLimit(ASTNode command) {
short limit = -1;
for (int childIndex = 0; childIndex < command.getChildCount(); childIndex++) {
ASTNode astChild = (ASTNode) command.getChild(childIndex);
if (astChild.getType() == HiveParser.TOK_LIMIT) {
limit = Short.valueOf((astChild.getChild(0)).getText());
}
}
return limit;
}
}
| apache-2.0 |
eurekaclinical/protempa | protempa-framework/src/main/java/org/protempa/DataStreamingEvent.java | 1480 | /*
* #%L
* Protempa Framework
* %%
* Copyright (C) 2012 - 2013 Emory University
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.protempa;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
*
* @author Andrew Post
*/
public final class DataStreamingEvent<E> {
private final String keyId;
private final List<E> data;
public DataStreamingEvent(String keyId, List<E> data) {
if (keyId == null) {
throw new IllegalArgumentException("keyId cannot be null");
}
if (data == null) {
throw new IllegalArgumentException("data cannot be null");
}
this.keyId = keyId;
this.data = data;
}
public String getKeyId() {
return keyId;
}
public List<E> getData() {
return data;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| apache-2.0 |
wildfly-extras/wildfly-camel | itests/standalone/basic/src/test/java/org/wildfly/camel/test/fhir/FhirJsonIntegrationTest.java | 3994 | /*
* #%L
* Wildfly Camel :: Testsuite
* %%
* Copyright (C) 2013 - 2018 RedHat
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.wildfly.camel.test.fhir;
import ca.uhn.fhir.context.FhirContext;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.hl7.fhir.dstu3.model.Address;
import org.hl7.fhir.dstu3.model.Base;
import org.hl7.fhir.dstu3.model.HumanName;
import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extension.camel.CamelAware;
@CamelAware
@RunWith(Arquillian.class)
public class FhirJsonIntegrationTest {
private static final String PATIENT_JSON = "{\"resourceType\":\"Patient\","
+ "\"name\":[{\"family\":\"Holmes\",\"given\":[\"Sherlock\"]}],"
+ "\"address\":[{\"line\":[\"221b Baker St, Marylebone, London NW1 6XE, UK\"]}]}";
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class, "camel-fhir-json-tests.jar");
}
@Test
public void testFhirJsonMarshal() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.marshal().fhirJson("DSTU3");
}
});
camelctx.start();
try {
Patient patient = createPatient();
ProducerTemplate template = camelctx.createProducerTemplate();
InputStream inputStream = template.requestBody("direct:start", patient, InputStream.class);
IBaseResource result = FhirContext.forDstu3().newJsonParser().parseResource(new InputStreamReader(inputStream));
Assert.assertTrue("Expected marshaled patient to be equal", patient.equalsDeep((Base)result));
} finally {
camelctx.close();
}
}
@Test
public void testFhirJsonUnmarshal() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.unmarshal().fhirJson("DSTU3");
}
});
camelctx.start();
try {
ProducerTemplate template = camelctx.createProducerTemplate();
Patient result = template.requestBody("direct:start", PATIENT_JSON, Patient.class);
Assert.assertTrue("Expected unmarshaled patient to be equal", result.equalsDeep(createPatient()));
} finally {
camelctx.close();
}
}
private Patient createPatient() {
Patient patient = new Patient();
patient.addName(new HumanName()
.addGiven("Sherlock")
.setFamily("Holmes"))
.addAddress(new Address().addLine("221b Baker St, Marylebone, London NW1 6XE, UK"));
return patient;
}
}
| apache-2.0 |
fastcat-co/fastcatsearch | server/src/main/java/org/fastcatsearch/cli/Console.java | 6622 | /*
* Copyright (c) 2013 Websquared, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* swsong - initial API and implementation
*/
package org.fastcatsearch.cli;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* CLI환경에서 명령을 내리는 프로그램.
*
* [Usage]java Console 192.168.0.100 8080 과 같이 접속하여 사용한다.
*
* @see ConsoleActionServlet
*/
public class Console {
String host;
int port;
String[] CMD_USE_COLLECTION = new String[]{"use"};
List<String> history;
String currentCollection;
public Console(String host, int port) {
history = new ArrayList<String>();
this.host = host;
this.port = port;
}
/**
*
* First Of All You Must Call "use ${Collection-Name} " And Use It (Collection) Until Session Close
*
* */
public static void main(String[] args) {
if(args.length < 2){
printUsage();
System.exit(0);
} else {
printLicenseHeader();
}
String host = args[0];
String portStr = args[1];
int port = 8080; // default port
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
System.out.println("port number is not numeric");
printUsage();
System.exit(0);
}
Console console = new Console(host,port);
console.interpret();
}
public void interpret() {
//
// Real Command Logic Described To ConsoleActionServlet.java
// It Uses Simple Interpret Logic Without Call-Wait Thread
//
//
// Show One Of Two Prompt When Command Phrase Complete Or Not
// (Like Mysql Prompt)
//
String[] prompt = new String[] {
"fastcatsearch> ",
" -> "
};
boolean completed = true;
StringBuilder cmdBuf = new StringBuilder();
err = System.err;
while(true) {
String cmd = readLine(
completed?prompt[0]:prompt[1]);
//
// Command Phrase Will Completed When ';' Appears At End
// Except System Command ( help, exit ...)
//
if(cmd.endsWith(";")) {
cmd = cmd.substring(0,cmd.length() -1);
completed = true;
} else {
completed = false;
}
cmdBuf.append(cmd);
if(cmdBuf.length()==0) {
completed = true;
}
cmd = cmdBuf.toString().trim();
//
// System Command ( help, exit ... )
//
if(cmd.equals("help")) {
//printHelp();
//cmdBuf.setLength(0);
completed = true;
//continue;
} else if(cmd.equals("exit")) {
System.exit(1);
}
//
// Append Command Buffer When Command Phrase Not Completed
//
if(!completed) {
cmdBuf.append(" ");
} else {
cmdBuf.setLength(0);
}
//
// Execute Command (Completed Command Phrase)
//
if(completed) {
if(!"".equals(cmd)) {
String result = communicate(cmd);
//우선 임시로 json string 을 그대로 출력하도록 한다.
printf("command : %s \nresult : \n%s\n", cmd, result);
}
}
}
}
private HttpClient httpClient;
private HttpPost httpPost;
private HttpResponse httpResponse;
private PrintStream err;
public String communicate (String command) {
if(httpClient==null) {
httpClient = new DefaultHttpClient();
String url = "http://"+host+":"+port+"/console/command";
httpPost = new HttpPost(url);
}
InputStreamReader ir = null;
BufferedReader br = null;
String result = null;
try {
if(httpPost!=null) {
List<NameValuePair>npList = new ArrayList<NameValuePair>();
npList.add(new BasicNameValuePair("command", command));
httpPost.setHeader("Content-type","application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(npList, "UTF-8"));
httpResponse = httpClient.execute(httpPost);
StringBuffer sb = new StringBuffer();
if(httpResponse != null){
ir = new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8");
br = new BufferedReader(ir);
int inx=0;
for(String rline; (rline = br.readLine()) !=null; inx++) {
if(inx==0) {
result = rline;
} else {
sb.append(rline).append("\n");
}
}
if("ERROR".equals(result)) {
} else if("SUCCESS".equals(result)) {
} else {
}
}
return sb.toString();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(err);
} catch (ClientProtocolException e) {
e.printStackTrace(err);
} catch (IOException e) {
e.printStackTrace(err);
} catch (NullPointerException e) {
e.printStackTrace(err);
} finally {
if(br!=null) {
try {
br.close();
} catch (IOException e) {
}
}
if(ir!=null) {
try {
ir.close();
} catch (IOException e) {
}
}
}
return null;
}
private static void printLicenseHeader() {
System.out.println("###########################################");
System.out.println("# Copyright FastSearch. GPL 2.0 License.");
System.out.println("# FastcatSearch CLI Tool");
System.out.println("###########################################");
}
private static void printUsage() {
System.err.println("[Usage] java Console [host] [port]");
}
private static void printHelp() {
System.out.println("\nhelp : \n");
}
/**
* Read Input Line With Showing Prompt
* @param prompt
* @return
*/
private static String readLine(String prompt) {
String line = null;
// java.io.Console c = System.console();
// if (c != null) {
// line = c.readLine(prompt);
// } else {
// For Eclipse User
System.out.print(prompt);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
try {
line = bufferedReader.readLine();
} catch (IOException ignore) {
}
// }
return line;
}
/**
* Printout Formatted String
* @param format
* @param args
*/
private static void printf(String format, Object... args) {
// java.io.Console c = System.console();
// if (c != null) {
// c.printf(format, args);
// } else {
// For Eclipse User
System.out.print(String.format(format, args));
// }
}
}
| apache-2.0 |
guilhermedias/twu-biblioteca-guilherme | test/com/twu/biblioteca/options/CheckoutOptionTest.java | 261 | package com.twu.biblioteca.options;
import org.junit.Test;
/**
* Created by gdias on 8/3/15.
*/
public class CheckoutOptionTest {
@Test
public void execute_ShouldReturnAChooseBookMessage() throws Exception {
// TODO Test using mocks
}
}
| apache-2.0 |
xasx/assertj-core | src/main/java/org/assertj/core/error/ShouldContainCharSequenceOnlyOnce.java | 3013 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2019 the original author or authors.
*/
package org.assertj.core.error;
import org.assertj.core.internal.*;
/**
* Creates an error message indicating that an assertion that verifies that a {@code CharSequence} contains another {@code CharSequence} only
* once failed.
*
* @author Pauline Iogna
* @author Joel Costigliola
* @author Mikhail Mazursky
*/
public class ShouldContainCharSequenceOnlyOnce extends BasicErrorMessageFactory {
/**
* Creates a new <code>{@link ShouldContainCharSequenceOnlyOnce}</code>.
*
* @param actual the actual value in the failed assertion.
* @param sequence the String expected to be in {@code actual} only once.
* @param occurrences the number of occurrences of sequence in actual.
* @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldContainOnlyOnce(CharSequence actual, CharSequence sequence, int occurrences,
ComparisonStrategy comparisonStrategy) {
if (occurrences == 0) return new ShouldContainCharSequenceOnlyOnce(actual, sequence, comparisonStrategy);
return new ShouldContainCharSequenceOnlyOnce(actual, sequence, occurrences, comparisonStrategy);
}
/**
* Creates a new <code>{@link ShouldContainCharSequenceOnlyOnce}</code>.
*
* @param actual the actual value in the failed assertion.
* @param sequence the String expected to be in {@code actual} only once.
* @param occurrences the number of occurrences of sequence in actual.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldContainOnlyOnce(CharSequence actual, CharSequence sequence, int occurrences) {
return shouldContainOnlyOnce(actual, sequence, occurrences, StandardComparisonStrategy.instance());
}
private ShouldContainCharSequenceOnlyOnce(CharSequence actual, CharSequence expected, int occurrences, ComparisonStrategy comparisonStrategy) {
super("%nExpecting:%n <%s>%nto appear only once in:%n <%s>%nbut it appeared %s times %s", expected, actual,
occurrences,
comparisonStrategy);
}
private ShouldContainCharSequenceOnlyOnce(CharSequence actual, CharSequence expected, ComparisonStrategy comparisonStrategy) {
super("%nExpecting:%n <%s>%nto appear only once in:%n <%s>%nbut it did not appear %s", expected, actual,
comparisonStrategy);
}
}
| apache-2.0 |
ruhan1/pnc | rest/src/main/java/org/jboss/pnc/rest/notifications/websockets/BuildRecordPushResultRestEvent.java | 1230 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.rest.notifications.websockets;
import org.jboss.pnc.rest.restmodel.BuildRecordPushResultRest;
/**
* @author <a href="mailto:matejonnet@gmail.com">Matej Lazar</a>
*/
public class BuildRecordPushResultRestEvent extends BuildRecordPushResultRest {
public BuildRecordPushResultRestEvent(BuildRecordPushResultRest buildRecordPushResultRest) {
super(buildRecordPushResultRest.toDBEntityBuilder().build());
}
public String getEventType() {
return "BREW_PUSH_RESULT";
}
}
| apache-2.0 |
freiby/flex | server/nirvana-core/src/main/java/com/wxxr/nirvana/workbench/impl/SecurityManager.java | 2023 | /*
* @(#)SecurityManager.java 2007-11-3
*
* Copyright 2004-2007 WXXR Network Technology Co. Ltd.
* All rights reserved.
*
* WXXR PROPRIETARY/CONFIDENTIAL.
*/
package com.wxxr.nirvana.workbench.impl;
import java.security.Principal;
import org.apache.commons.lang3.StringUtils;
import com.wxxr.nirvana.workbench.ISecurityManager;
/**
* @author fudapeng
*
*/
public class SecurityManager implements ISecurityManager {
/*
* (non-Javadoc)
*
* @see
* com.wxxr.web.ui.ISecurityManager#currentUserHasARoleOf(java.lang.String
* [])
*/
public boolean currentUserHasARoleOf(String[] roles) {
if ((roles == null) || (roles.length == 0)) {
throw new IllegalArgumentException();
}
for (int i = 0; i < roles.length; i++) {
String role = roles[i];
if (StringUtils.isNotBlank(role) && currentUserHasRole(role)) {
return true;
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see
* com.wxxr.web.ui.ISecurityManager#currentUserHasRole(java.lang.String)
*/
public boolean currentUserHasRole(String role) {
if (StringUtils.isBlank(role)) {
throw new IllegalArgumentException();
}
return false;// FacesContext.getCurrentInstance().getExternalContext().isUserInRole(role);
}
/*
* (non-Javadoc)
*
* @see
* com.wxxr.web.ui.ISecurityManager#currentUserHasRoles(java.lang.String[])
*/
public boolean currentUserHasRoles(String[] roles) {
if ((roles == null) || (roles.length == 0)) {
throw new IllegalArgumentException();
}
for (int i = 0; i < roles.length; i++) {
String role = roles[i];
if (StringUtils.isNotBlank(role) && (!currentUserHasRole(role))) {
return false;
}
}
return true;
}
/*
* (non-Javadoc)
*
* @see com.wxxr.web.ui.ISecurityManager#destroy()
*/
public void destroy() {
}
/*
* (non-Javadoc)
*
* @see com.wxxr.web.ui.ISecurityManager#getCurrentUser()
*/
public Principal getCurrentUser() {
return null;// FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
}
}
| apache-2.0 |
FAU-Inf2/fablab-android | app/src/main/java/de/fau/cs/mad/fablab/android/view/fragments/projects/LicenseInformationDialogFragment.java | 2046 | package de.fau.cs.mad.fablab.android.view.fragments.projects;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import javax.inject.Inject;
import butterknife.Bind;
import de.fau.cs.mad.fablab.android.R;
import de.fau.cs.mad.fablab.android.view.common.binding.ViewCommandBinding;
import de.fau.cs.mad.fablab.android.view.common.fragments.BaseDialogFragment;
public class LicenseInformationDialogFragment extends BaseDialogFragment
implements LicenseInformationDialogFragmentViewModel.Listener {
@Bind(R.id.project_license_information_title_tv)
TextView title_tv;
@Bind(R.id.project_license_ok_button)
Button ok_button;
@Bind(R.id.project_license_cancel_button)
Button cancel_button;
@Inject
LicenseInformationDialogFragmentViewModel mViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return inflater.inflate(R.layout.fragment_license_information_dialog, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new ViewCommandBinding().bind(ok_button, mViewModel.getOKCommand());
new ViewCommandBinding().bind(cancel_button, mViewModel.getCancelCommand());
title_tv.setText(Html.fromHtml(getString(R.string.license_information_title)));
title_tv.setMovementMethod(LinkMovementMethod.getInstance());
mViewModel.setListener(this);
}
@Override
public void buttonClicked() {
dismiss();
}
}
| apache-2.0 |
Plonk42/mytracks | myTracks/src/androidTest/java/com/google/android/apps/mytracks/endtoendtest/sync/SyncMyTracksWithDriveTest.java | 4593 | /*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.endtoendtest.sync;
import com.google.android.apps.mytracks.TrackListActivity;
import com.google.android.apps.mytracks.endtoendtest.EndToEndTestUtils;
import com.google.android.apps.mytracks.endtoendtest.GoogleUtils;
import com.google.android.apps.mytracks.endtoendtest.RunConfiguration;
import com.google.android.apps.mytracks.io.sync.SyncUtils;
import com.google.android.maps.mytracks.R;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import java.io.IOException;
/**
* Tests making changes on My Tracks when syncing My Tracks with Google Drive.
*
* @author Youtao Liu
*/
public class SyncMyTracksWithDriveTest extends ActivityInstrumentationTestCase2<TrackListActivity> {
private Drive drive;
private Instrumentation instrumentation;
private TrackListActivity trackListActivity;
public SyncMyTracksWithDriveTest() {
super(TrackListActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
trackListActivity = getActivity();
SyncTestUtils.setUpForSyncTest(instrumentation, trackListActivity);
SyncTestUtils.enableSync(GoogleUtils.ACCOUNT_1);
drive = SyncTestUtils
.getGoogleDrive(EndToEndTestUtils.trackListActivity.getApplicationContext());
}
/**
* Deletes all tracks on Google Drive and checks in MyTracks.
*
* @throws IOException
*/
public void testDeleteAllTracksOnDrive() throws IOException {
if (!RunConfiguration.getInstance().getRunSyncTest()) {
return;
}
EndToEndTestUtils.createTrackIfEmpty(0, true);
EndToEndTestUtils.findMenuItem(
EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
SyncTestUtils.checkFilesNumber(drive);
SyncTestUtils.removeKMLFiles(drive);
EndToEndTestUtils.findMenuItem(
EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
SyncTestUtils.checkTracksNumber(0);
}
/**
* Deletes one file on Google Drive and checks it in MyTracks.
*
* @throws IOException
*/
public void testDeleteOneFileOnDrive() throws IOException {
if (!RunConfiguration.getInstance().getRunSyncTest()) {
return;
}
instrumentation.waitForIdleSync();
EndToEndTestUtils.createSimpleTrack(0, true);
EndToEndTestUtils.createSimpleTrack(0, true);
EndToEndTestUtils.findMenuItem(
EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
SyncTestUtils.checkFilesNumber(drive);
// Remove one track from Google Drive
File file = SyncTestUtils.getFile(EndToEndTestUtils.trackName, drive);
SyncTestUtils.removeFile(file, drive);
EndToEndTestUtils.findMenuItem(
EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
SyncTestUtils.checkFilesNumber(drive);
SyncTestUtils.checkTracksNumber(1);
}
/**
* Tests deleting and creating MyTracks folder on Google Dive by MyTracks.
*
* @throws IOException
*/
public void testCreateMyTracksOnDrive() throws IOException {
if (!RunConfiguration.getInstance().getRunSyncTest()) {
return;
}
instrumentation.waitForIdleSync();
EndToEndTestUtils.createSimpleTrack(0, true);
EndToEndTestUtils.createSimpleTrack(0, true);
EndToEndTestUtils.findMenuItem(
EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
instrumentation.waitForIdleSync();
SyncTestUtils.checkFilesNumber(drive);
File folder = SyncUtils.getMyTracksFolder(trackListActivity.getApplicationContext(), drive);
assertNotNull(folder);
SyncTestUtils.removeFile(folder, drive);
EndToEndTestUtils.findMenuItem(
EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
SyncTestUtils.checkFilesNumber(drive);
}
}
| apache-2.0 |
raidenovski/webapp | src/test/java/selenium/web/content/number/NumberCreatePage.java | 1088 | package selenium.web.content.number;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import selenium.ErrorHelper;
public class NumberCreatePage {
private WebDriver driver;
private WebElement errorPanel;
private WebElement submitButton;
public NumberCreatePage(WebDriver driver) {
this.driver = driver;
WebDriverWait webDriverWait = new WebDriverWait(driver, 10);
webDriverWait.until(ExpectedConditions.presenceOfElementLocated(By.id("numberCreatePage")));
ErrorHelper.verifyNoScriptOrMarkupError(driver);
}
public boolean isErrorMessageDisplayed() {
try {
return errorPanel.isDisplayed();
} catch (NoSuchElementException e) {
return false;
}
}
public void submitForm() {
submitButton.click();
}
}
| apache-2.0 |
JDA-Applications/JDA-Utilities | oauth2/src/main/java/com/jagrosh/jdautilities/oauth2/entities/impl/OAuth2GuildImpl.java | 2718 | /*
* Copyright 2016-2018 John Grosh (jagrosh) & Kaidan Gustave (TheMonitorLizard)
*
* 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.jagrosh.jdautilities.oauth2.entities.impl;
import com.jagrosh.jdautilities.oauth2.OAuth2Client;
import com.jagrosh.jdautilities.oauth2.entities.OAuth2Guild;
import net.dv8tion.jda.api.Permission;
import java.util.EnumSet;
/**
*
* @author John Grosh (john.a.grosh@gmail.com)
*/
public class OAuth2GuildImpl implements OAuth2Guild
{
private final OAuth2Client client;
private final long id;
private final String name, icon;
private final boolean owner;
private final int permissions;
public OAuth2GuildImpl(OAuth2Client client, long id, String name, String icon, boolean owner, int permissions)
{
this.client = client;
this.id = id;
this.name = name;
this.icon = icon;
this.owner = owner;
this.permissions = permissions;
}
@Override
public OAuth2Client getClient()
{
return client;
}
@Override
public long getIdLong()
{
return id;
}
@Override
public String getName()
{
return name;
}
@Override
public String getIconId()
{
return icon;
}
@Override
public String getIconUrl()
{
return icon == null ? null : "https://cdn.discordapp.com/icons/" + id + "/" + icon + ".png";
}
@Override
public int getPermissionsRaw()
{
return permissions;
}
@Override
public EnumSet<Permission> getPermissions()
{
return Permission.getPermissions(permissions);
}
@Override
public boolean isOwner()
{
return owner;
}
@Override
public boolean hasPermission(Permission... perms)
{
if(isOwner())
return true;
long adminPermRaw = Permission.ADMINISTRATOR.getRawValue();
int permissions = getPermissionsRaw();
if ((permissions & adminPermRaw) == adminPermRaw)
return true;
long checkPermsRaw = Permission.getRaw(perms);
return (permissions & checkPermsRaw) == checkPermsRaw;
}
}
| apache-2.0 |
rahulkumar66/Performance-Tweaker | app/src/main/java/com/performancetweaker/app/utils/VmUtils.java | 1341 | package com.performancetweaker.app.utils;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class VmUtils {
//private static List<String> vmEntries = new ArrayList<>();
private static LinkedHashMap<String, String> vmEntries = new LinkedHashMap<>();
public static void setVM(final String value, final String name) {
SysUtils.executeRootCommand(new ArrayList<String>() {{
add("echo " + value + " > " + Constants.VM_PATH + "/" + name);
}});
}
public static String getVMValue(String file) {
if (new File(Constants.VM_PATH + "/" + file).exists()) {
String value = SysUtils.readOutputFromFile(Constants.VM_PATH + "/" + file);
if (value != null) return value;
}
return null;
}
public static LinkedHashMap<String, String> getVMfiles() {
vmEntries.clear();
File[] files = new File(Constants.VM_PATH).listFiles();
if (files.length > 0) {
for (String supported : Constants.SUPPORTED_VM)
for (File file : files)
if (file.getName().equals(supported)) {
vmEntries.put(file.getName(), getVMValue(file.getName()));
}
}
return vmEntries;
}
}
| apache-2.0 |
pfirmstone/river-internet | qa/src/org/apache/river/test/impl/end2end/e2etest/KerberosSubjectProvider.java | 4298 | /*
* 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.river.test.impl.end2end.e2etest;
import java.security.AccessController;
import java.security.Principal;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosKey;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import net.jini.core.constraint.ClientAuthentication;
import net.jini.core.constraint.ClientMinPrincipal;
import net.jini.core.constraint.ClientMinPrincipalType;
import net.jini.core.constraint.ClientMaxPrincipal;
import net.jini.core.constraint.ConstraintAlternatives;
import net.jini.core.constraint.InvocationConstraint;
import net.jini.core.constraint.ServerAuthentication;
import net.jini.core.constraint.ServerMinPrincipal;
public class KerberosSubjectProvider implements SubjectProvider {
private static Subject clientSubject = new Subject();
private static Subject serverSubject = new Subject();
private static Logger log = Logger.getLogger(
"e2eTest.KerberosSubjectProvider");
public static void initialize() throws LoginException {
LoginContext lc = new LoginContext("e2etest.KerberosClient");
lc.login();
synchronized(clientSubject){
clientSubject = lc.getSubject();
clientSubject.setReadOnly();
}
lc = new LoginContext("e2etest.KerberosServer");
lc.login();
synchronized(serverSubject) {
serverSubject = lc.getSubject();
serverSubject.setReadOnly();
}
}
public Subject getClientSubject() {
synchronized (clientSubject) {
return clientSubject;
}
}
public Subject getServerSubject() {
synchronized(serverSubject) {
return serverSubject;
}
}
public Subject getSubject() {
return Subject.getSubject(AccessController.getContext());
}
public ClientMinPrincipal getClientMinPrincipal() {
return new ClientMinPrincipal(clientSubject.getPrincipals());
}
public ClientMinPrincipalType getClientMinPrincipalType() {
return new ClientMinPrincipalType(KerberosPrincipal.class);
}
public ClientMaxPrincipal getClientMaxPrincipal() {
Set principals = clientSubject.getPrincipals(KerberosPrincipal.class);
return new ClientMaxPrincipal(principals);
}
public ConstraintAlternatives getConstraintAlternatives1() {
return new ConstraintAlternatives(new InvocationConstraint[] {
new ClientMinPrincipal(clientSubject.getPrincipals()),
new ClientMinPrincipal(new KerberosPrincipal("dummy"))
});
}
public ConstraintAlternatives getConstraintAlternatives2() {
return new ConstraintAlternatives(new InvocationConstraint[] {
new ClientMinPrincipal(clientSubject.getPrincipals()),
new ClientMinPrincipal(new KerberosPrincipal("dummy"))
});
}
public ConstraintAlternatives getServerMinPrincipal() {
return new ConstraintAlternatives(new InvocationConstraint[] {
new ServerMinPrincipal(serverSubject.getPrincipals()),
new ServerMinPrincipal(new KerberosPrincipal("dummy"))
});
}
public ServerMinPrincipal getServerMainPrincipal() {
return new ServerMinPrincipal(serverSubject.getPrincipals());
}
}
| apache-2.0 |
yanzhijun/jclouds-aliyun | common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/parse/ParseAuthTest.java | 3296 | /*
* 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.jclouds.openstack.keystone.v1_1.parse;
import java.net.URI;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.openstack.keystone.v1_1.domain.Auth;
import org.jclouds.openstack.keystone.v1_1.domain.Endpoint;
import org.jclouds.openstack.keystone.v1_1.domain.Token;
import org.jclouds.rest.annotations.SelectJson;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
@Test(groups = "unit", testName = "ParseAuthTest")
public class ParseAuthTest extends BaseItemParserTest<Auth> {
@Override
public String resource() {
return "/auth1_1.json";
}
@Override
@SelectJson("auth")
@Consumes(MediaType.APPLICATION_JSON)
public Auth expected() {
return Auth
.builder()
.token(
Token.builder()
.expires(new SimpleDateFormatDateService().iso8601DateParse("2012-01-30T02:30:54.000-06:00"))
.id("118fb907-0786-4799-88f0-9a5b7963d1ab").build())
.serviceCatalog(
ImmutableMultimap.of(
"cloudFilesCDN",
Endpoint
.builder()
.region("LON")
.publicURL(
URI.create("https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953"))
.v1Default(true).build(),
"cloudFiles",
Endpoint
.builder()
.region("LON")
.publicURL(
URI.create("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953"))
.v1Default(true)
.internalURL(
URI.create("https://snet-storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953"))
.build(),
"cloudServers",
Endpoint.builder()
.publicURL(URI.create("https://lon.servers.api.rackspacecloud.com/v1.0/10001786"))
.v1Default(true).build())).build();
}
}
| apache-2.0 |
chirino/activemq | activemq-client/src/main/java/org/apache/activemq/openwire/v12/FlushCommandMarshaller.java | 3523 | /**
*
* 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.activemq.openwire.v12;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.*;
import org.apache.activemq.command.*;
/**
* Marshalling code for Open Wire Format for FlushCommandMarshaller
*
*
* NOTE!: This file is auto generated - do not modify!
* if you need to make a change, please see the modify the groovy scripts in the
* under src/gram/script and then use maven openwire:generate to regenerate
* this file.
*
*
*/
public class FlushCommandMarshaller extends BaseCommandMarshaller {
/**
* Return the type of Data Structure we marshal
* @return short representation of the type data structure
*/
public byte getDataStructureType() {
return FlushCommand.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
public DataStructure createObject() {
return new FlushCommand();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o the object to un-marshal
* @param dataIn the data input stream to build the object from
* @throws IOException
*/
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
int rc = super.tightMarshal1(wireFormat, o, bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o the instance to be marshaled
* @param dataOut the output stream
* @throws IOException thrown if an error occurs
*/
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o the object to un-marshal
* @param dataIn the data input stream to build the object from
* @throws IOException
*/
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
super.looseMarshal(wireFormat, o, dataOut);
}
}
| apache-2.0 |
Ben-Zvi/drill | exec/java-exec/src/main/java/org/apache/drill/exec/expr/fn/FunctionImplementationRegistry.java | 27280 | /*
* 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.drill.exec.expr.fn;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.drill.common.expression.fn.FunctionReplacementUtils;
import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
import org.apache.drill.shaded.guava.com.google.common.collect.Sets;
import org.apache.drill.shaded.guava.com.google.common.io.Files;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.io.FileUtils;
import org.apache.drill.common.config.ConfigConstants;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.expression.FunctionCall;
import org.apache.drill.common.scanner.ClassPathScanner;
import org.apache.drill.common.scanner.RunTimeScan;
import org.apache.drill.common.scanner.persistence.ScanResult;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.coord.store.TransientStoreEvent;
import org.apache.drill.exec.coord.store.TransientStoreListener;
import org.apache.drill.exec.exception.FunctionValidationException;
import org.apache.drill.exec.exception.JarValidationException;
import org.apache.drill.exec.expr.fn.registry.LocalFunctionRegistry;
import org.apache.drill.exec.expr.fn.registry.FunctionHolder;
import org.apache.drill.exec.expr.fn.registry.JarScan;
import org.apache.drill.exec.expr.fn.registry.RemoteFunctionRegistry;
import org.apache.drill.exec.planner.sql.DrillOperatorTable;
import org.apache.drill.exec.proto.UserBitShared.Jar;
import org.apache.drill.exec.resolver.FunctionResolver;
import org.apache.drill.exec.resolver.FunctionResolverFactory;
import org.apache.drill.exec.server.options.OptionManager;
import org.apache.drill.exec.server.options.OptionSet;
import org.apache.drill.shaded.guava.com.google.common.annotations.VisibleForTesting;
import org.apache.drill.shaded.guava.com.google.common.base.Stopwatch;
import org.apache.drill.exec.store.sys.store.DataChangeVersion;
import org.apache.drill.exec.util.JarUtil;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* This class offers the registry for functions. Notably, in addition to Drill its functions
* (in {@link LocalFunctionRegistry}), other PluggableFunctionRegistry (e.g., {@link org.apache.drill.exec.expr.fn.HiveFunctionRegistry})
* is also registered in this class
*/
public class FunctionImplementationRegistry implements FunctionLookupContext, AutoCloseable {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FunctionImplementationRegistry.class);
private final LocalFunctionRegistry localFunctionRegistry;
private final RemoteFunctionRegistry remoteFunctionRegistry;
private final Path localUdfDir;
private boolean deleteTmpDir = false;
private File tmpDir;
private List<PluggableFunctionRegistry> pluggableFuncRegistries = new ArrayList<>();
private OptionSet optionManager;
private final boolean useDynamicUdfs;
@VisibleForTesting
public FunctionImplementationRegistry(DrillConfig config){
this(config, ClassPathScanner.fromPrescan(config));
}
public FunctionImplementationRegistry(DrillConfig config, ScanResult classpathScan) {
this(config, classpathScan, null);
}
public FunctionImplementationRegistry(DrillConfig config, ScanResult classpathScan, OptionManager optionManager) {
Stopwatch w = Stopwatch.createStarted();
logger.debug("Generating function registry.");
this.optionManager = optionManager;
// Unit tests fail if dynamic UDFs are turned on AND the test happens
// to access an undefined function. Since we want a reasonable failure
// rather than a crash, we provide a boot-time option, set only by
// tests, to disable DUDF lookup.
useDynamicUdfs = ! config.getBoolean(ExecConstants.UDF_DISABLE_DYNAMIC);
localFunctionRegistry = new LocalFunctionRegistry(classpathScan);
Set<Class<? extends PluggableFunctionRegistry>> registryClasses =
classpathScan.getImplementations(PluggableFunctionRegistry.class);
for (Class<? extends PluggableFunctionRegistry> clazz : registryClasses) {
for (Constructor<?> c : clazz.getConstructors()) {
Class<?>[] params = c.getParameterTypes();
if (params.length != 1 || params[0] != DrillConfig.class) {
logger.warn("Skipping PluggableFunctionRegistry constructor {} for class {} since it doesn't implement a " +
"[constructor(DrillConfig)]", c, clazz);
continue;
}
try {
PluggableFunctionRegistry registry = (PluggableFunctionRegistry)c.newInstance(config);
pluggableFuncRegistries.add(registry);
} catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
logger.warn("Unable to instantiate PluggableFunctionRegistry class '{}'. Skipping it.", clazz, e);
}
break;
}
}
logger.info("Function registry loaded. {} functions loaded in {} ms.", localFunctionRegistry.size(), w.elapsed(TimeUnit.MILLISECONDS));
this.remoteFunctionRegistry = new RemoteFunctionRegistry(new UnregistrationListener());
this.localUdfDir = getLocalUdfDir(config);
}
public FunctionImplementationRegistry(DrillConfig config, ScanResult classpathScan, OptionSet optionManager) {
this(config, classpathScan);
this.optionManager = optionManager;
}
/**
* Register functions in given operator table.
* @param operatorTable operator table
*/
public void register(DrillOperatorTable operatorTable) {
// Register Drill functions first and move to pluggable function registries.
localFunctionRegistry.register(operatorTable);
for(PluggableFunctionRegistry registry : pluggableFuncRegistries) {
registry.register(operatorTable);
}
}
/**
* First attempts to find the Drill function implementation that matches the name, arg types and return type.
* If exact function implementation was not found,
* syncs local function registry with remote function registry if needed
* and tries to find function implementation one more time
* but this time using given <code>functionResolver</code>.
*
* @param functionResolver function resolver
* @param functionCall function call
* @return best matching function holder
*/
@Override
public DrillFuncHolder findDrillFunction(FunctionResolver functionResolver, FunctionCall functionCall) {
AtomicInteger version = new AtomicInteger();
String newFunctionName = functionReplacement(functionCall);
// Dynamic UDFS: First try with exact match. If not found, we may need to
// update the registry, so sync with remote.
if (useDynamicUdfs) {
List<DrillFuncHolder> functions = localFunctionRegistry.getMethods(newFunctionName, version);
FunctionResolver exactResolver = FunctionResolverFactory.getExactResolver(functionCall);
DrillFuncHolder holder = exactResolver.getBestMatch(functions, functionCall);
if (holder != null) {
return holder;
}
syncWithRemoteRegistry(version.get());
}
// Whether Dynamic UDFs or not: look in the registry for
// an inexact match.
List<DrillFuncHolder> functions = localFunctionRegistry.getMethods(newFunctionName, version);
return functionResolver.getBestMatch(functions, functionCall);
}
/**
* Checks if this function replacement is needed.
*
* @param functionCall function call
* @return new function name is replacement took place, otherwise original function name
*/
private String functionReplacement(FunctionCall functionCall) {
String funcName = functionCall.getName();
if (functionCall.args.size() == 0) {
return funcName;
}
boolean castEmptyStringToNull = optionManager != null &&
optionManager.getOption(ExecConstants.CAST_EMPTY_STRING_TO_NULL_OPTION);
if (!castEmptyStringToNull) {
return funcName;
}
MajorType majorType = functionCall.args.get(0).getMajorType();
DataMode dataMode = majorType.getMode();
MinorType minorType = majorType.getMinorType();
if (FunctionReplacementUtils.isReplacementNeeded(funcName, minorType)) {
funcName = FunctionReplacementUtils.getReplacingFunction(funcName, dataMode, minorType);
}
return funcName;
}
/**
* Finds the Drill function implementation that matches the name, arg types and return type.
*
* @param name function name
* @param argTypes input parameters types
* @param returnType function return type
* @return exactly matching function holder
*/
public DrillFuncHolder findExactMatchingDrillFunction(String name, List<MajorType> argTypes, MajorType returnType) {
return findExactMatchingDrillFunction(name, argTypes, returnType, useDynamicUdfs);
}
/**
* Finds the Drill function implementation that matches the name, arg types and return type.
* If exact function implementation was not found,
* checks if local function registry is in sync with remote function registry.
* If not syncs them and tries to find exact function implementation one more time
* but with retry flag set to false.
*
* @param name function name
* @param argTypes input parameters types
* @param returnType function return type
* @param retry retry on failure flag
* @return exactly matching function holder
*/
private DrillFuncHolder findExactMatchingDrillFunction(String name,
List<MajorType> argTypes,
MajorType returnType,
boolean retry) {
AtomicInteger version = new AtomicInteger();
for (DrillFuncHolder h : localFunctionRegistry.getMethods(name, version)) {
if (h.matches(returnType, argTypes)) {
return h;
}
}
if (retry && syncWithRemoteRegistry(version.get())) {
return findExactMatchingDrillFunction(name, argTypes, returnType, false);
}
return null;
}
/**
* Find function implementation for given <code>functionCall</code> in non-Drill function registries such as Hive UDF
* registry.
*
* Note: Order of searching is same as order of {@link org.apache.drill.exec.expr.fn.PluggableFunctionRegistry}
* implementations found on classpath.
*
* @param functionCall function call
* @return drill function holder
*/
@Override
public AbstractFuncHolder findNonDrillFunction(FunctionCall functionCall) {
for(PluggableFunctionRegistry registry : pluggableFuncRegistries) {
AbstractFuncHolder h = registry.getFunction(functionCall);
if (h != null) {
return h;
}
}
return null;
}
// Method to find if the output type of a drill function if of complex type
public boolean isFunctionComplexOutput(String name) {
List<DrillFuncHolder> methods = localFunctionRegistry.getMethods(name);
for (DrillFuncHolder holder : methods) {
if (holder.getReturnValue().isComplexWriter()) {
return true;
}
}
return false;
}
public LocalFunctionRegistry getLocalFunctionRegistry() {
return localFunctionRegistry;
}
public RemoteFunctionRegistry getRemoteFunctionRegistry() {
return remoteFunctionRegistry;
}
/**
* Using given local path to jar creates unique class loader for this jar.
* Class loader is closed to release opened connection to jar when validation is finished.
* Scan jar content to receive list of all scanned classes
* and starts validation process against local function registry.
* Checks if received list of validated function is not empty.
*
* @param path local path to jar we need to validate
* @return list of validated function signatures
*/
public List<String> validate(Path path) throws IOException {
URL url = path.toUri().toURL();
URL[] urls = {url};
try (URLClassLoader classLoader = new URLClassLoader(urls)) {
ScanResult jarScanResult = scan(classLoader, path, urls);
List<String> functions = localFunctionRegistry.validate(path.getName(), jarScanResult);
if (functions.isEmpty()) {
throw new FunctionValidationException(String.format("Jar %s does not contain functions", path.getName()));
}
return functions;
}
}
/**
* Purpose of this method is to synchronize remote and local function registries if needed
* and to inform if function registry was changed after given version.
* <p/>
* To make synchronization as much light-weigh as possible, first only versions of both registries are checked
* without any locking. If synchronization is needed, enters synchronized block to prevent others loading the same jars.
* The need of synchronization is checked again (double-check lock) before comparing jars.
* If any missing jars are found, they are downloaded to local udf area, each is wrapped into {@link JarScan}.
* Once jar download is finished, all missing jars are registered in one batch.
* In case if any errors during jars download / registration, these errors are logged.
* <p/>
* During registration local function registry is updated with remote function registry version it is synced with.
* When at least one jar of the missing jars failed to download / register,
* local function registry version are not updated but jars that where successfully downloaded / registered
* are added to local function registry.
* <p/>
* If synchronization between remote and local function registry was not needed,
* checks if given registry version matches latest sync version
* to inform if function registry was changed after given version.
*
* @param version remote function registry local function registry was based on
* @return true if remote and local function registries were synchronized after given version
*/
public boolean syncWithRemoteRegistry(int version) {
// Do the version check only if a remote registry exists. It does
// not exist for some JMockit-based unit tests.
if (isRegistrySyncNeeded()) {
synchronized (this) {
int localRegistryVersion = localFunctionRegistry.getVersion();
if (isRegistrySyncNeeded(remoteFunctionRegistry.getRegistryVersion(), localRegistryVersion)) {
DataChangeVersion remoteVersion = new DataChangeVersion();
List<String> missingJars = getMissingJars(this.remoteFunctionRegistry, localFunctionRegistry, remoteVersion);
List<JarScan> jars = new ArrayList<>();
if (!missingJars.isEmpty()) {
logger.info("Starting dynamic UDFs lazy-init process.\n" +
"The following jars are going to be downloaded and registered locally: " + missingJars);
for (String jarName : missingJars) {
Path binary = null;
Path source = null;
URLClassLoader classLoader = null;
try {
binary = copyJarToLocal(jarName, this.remoteFunctionRegistry);
source = copyJarToLocal(JarUtil.getSourceName(jarName), this.remoteFunctionRegistry);
URL[] urls = {binary.toUri().toURL(), source.toUri().toURL()};
classLoader = new URLClassLoader(urls);
ScanResult scanResult = scan(classLoader, binary, urls);
localFunctionRegistry.validate(jarName, scanResult);
jars.add(new JarScan(jarName, scanResult, classLoader));
} catch (Exception e) {
deleteQuietlyLocalJar(binary);
deleteQuietlyLocalJar(source);
if (classLoader != null) {
try {
classLoader.close();
} catch (Exception ex) {
logger.warn("Problem during closing class loader for {}", jarName, e);
}
}
logger.error("Problem during remote functions load from {}", jarName, e);
}
}
}
int latestRegistryVersion = jars.size() != missingJars.size() ?
localRegistryVersion : remoteVersion.getVersion();
localFunctionRegistry.register(jars, latestRegistryVersion);
return true;
}
}
}
return version != localFunctionRegistry.getVersion();
}
/**
* Checks if remote and local registries should be synchronized.
* Before comparing versions, checks if remote function registry is actually exists.
*
* @return true is local registry should be refreshed, false otherwise
*/
private boolean isRegistrySyncNeeded() {
logger.trace("Has remote function registry: {}", remoteFunctionRegistry.hasRegistry());
return remoteFunctionRegistry.hasRegistry() &&
isRegistrySyncNeeded(remoteFunctionRegistry.getRegistryVersion(), localFunctionRegistry.getVersion());
}
/**
* Checks if local function registry should be synchronized with remote function registry.
*
* <ul>If remote function registry version is {@link DataChangeVersion#UNDEFINED},
* it means that remote function registry does not support versioning
* thus we need to synchronize both registries.</ul>
* <ul>If remote function registry version is {@link DataChangeVersion#NOT_AVAILABLE},
* it means that remote function registry is unreachable
* or is not configured thus we skip synchronization and return false.</ul>
* <ul>For all other cases synchronization is needed if remote
* and local function registries versions do not match.</ul>
*
* @param remoteVersion remote function registry version
* @param localVersion local function registry version
* @return true is local registry should be refreshed, false otherwise
*/
private boolean isRegistrySyncNeeded(int remoteVersion, int localVersion) {
logger.trace("Compare remote [{}] and local [{}] registry versions.", remoteVersion, localVersion);
return remoteVersion == DataChangeVersion.UNDEFINED ||
(remoteVersion != DataChangeVersion.NOT_AVAILABLE && remoteVersion != localVersion);
}
/**
* First finds path to marker file url, otherwise throws {@link JarValidationException}.
* Then scans jar classes according to list indicated in marker files.
* Additional logic is added to close {@link URL} after {@link ConfigFactory#parseURL(URL)}.
* This is extremely important for Windows users where system doesn't allow to delete file if it's being used.
*
* @param classLoader unique class loader for jar
* @param path local path to jar
* @param urls urls associated with the jar (ex: binary and source)
* @return scan result of packages, classes, annotations found in jar
*/
private ScanResult scan(ClassLoader classLoader, Path path, URL[] urls) throws IOException {
Enumeration<URL> markerFileEnumeration = classLoader.getResources(
ConfigConstants.DRILL_JAR_MARKER_FILE_RESOURCE_PATHNAME);
while (markerFileEnumeration.hasMoreElements()) {
URL markerFile = markerFileEnumeration.nextElement();
if (markerFile.getPath().contains(path.toUri().getPath())) {
URLConnection markerFileConnection = null;
try {
markerFileConnection = markerFile.openConnection();
DrillConfig drillConfig = DrillConfig.create(ConfigFactory.parseURL(markerFile));
return RunTimeScan.dynamicPackageScan(drillConfig, Sets.newHashSet(urls));
} finally {
if (markerFileConnection instanceof JarURLConnection) {
((JarURLConnection) markerFileConnection).getJarFile().close();
}
}
}
}
throw new JarValidationException(String.format("Marker file %s is missing in %s",
ConfigConstants.DRILL_JAR_MARKER_FILE_RESOURCE_PATHNAME, path.getName()));
}
/**
* Return list of jars that are missing in local function registry
* but present in remote function registry.
* Also updates version holder with remote function registry version.
*
* @param remoteFunctionRegistry remote function registry
* @param localFunctionRegistry local function registry
* @param version holder for remote function registry version
* @return list of missing jars
*/
private List<String> getMissingJars(RemoteFunctionRegistry remoteFunctionRegistry,
LocalFunctionRegistry localFunctionRegistry,
DataChangeVersion version) {
List<Jar> remoteJars = remoteFunctionRegistry.getRegistry(version).getJarList();
List<String> localJars = localFunctionRegistry.getAllJarNames();
List<String> missingJars = new ArrayList<>();
for (Jar jar : remoteJars) {
if (!localJars.contains(jar.getName())) {
missingJars.add(jar.getName());
}
}
return missingJars;
}
/**
* Retrieve all functions, mapped by source jars (after syncing)
* @return Map of source jars and their functionHolders
*/
public Map<String, List<FunctionHolder>> getAllJarsWithFunctionsHolders() {
if (useDynamicUdfs) {
syncWithRemoteRegistry(localFunctionRegistry.getVersion());
}
return localFunctionRegistry.getAllJarsWithFunctionsHolders();
}
/**
* Creates local udf directory, if it doesn't exist.
* Checks if local udf directory is a directory and if current application has write rights on it.
* Attempts to clean up local udf directory in case jars were left after previous drillbit run.
*
* @param config drill config
* @return path to local udf directory
*/
private Path getLocalUdfDir(DrillConfig config) {
tmpDir = getTmpDir(config);
File udfDir = new File(tmpDir, config.getString(ExecConstants.UDF_DIRECTORY_LOCAL));
String udfPath = udfDir.getPath();
if (udfDir.mkdirs()) {
logger.debug("Local udf directory [{}] was created", udfPath);
}
Preconditions.checkState(udfDir.exists(), "Local udf directory [%s] must exist", udfPath);
Preconditions.checkState(udfDir.isDirectory(), "Local udf directory [%s] must be a directory", udfPath);
Preconditions.checkState(udfDir.canWrite(), "Local udf directory [%s] must be writable for application user", udfPath);
try {
FileUtils.cleanDirectory(udfDir);
} catch (IOException e) {
throw new DrillRuntimeException("Error during local udf directory clean up", e);
}
logger.info("Created and validated local udf directory [{}]", udfPath);
return new Path(udfDir.toURI());
}
/**
* First tries to get drill temporary directory value from from config ${drill.tmp-dir},
* then checks environmental variable $DRILL_TMP_DIR.
* If value is still missing, generates directory using {@link Files#createTempDir()}.
* If temporary directory was generated, sets {@link #deleteTmpDir} to true
* to delete directory on drillbit exit.
*
* @param config drill config
* @return drill temporary directory path
*/
private File getTmpDir(DrillConfig config) {
String drillTempDir;
if (config.hasPath(ExecConstants.DRILL_TMP_DIR)) {
drillTempDir = config.getString(ExecConstants.DRILL_TMP_DIR);
} else {
drillTempDir = System.getenv("DRILL_TMP_DIR");
}
if (drillTempDir == null) {
deleteTmpDir = true;
return Files.createTempDir();
}
return new File(drillTempDir);
}
/**
* Copies jar from remote udf area to local udf area.
*
* @param jarName jar name to be copied
* @param remoteFunctionRegistry remote function registry
* @return local path to jar that was copied
* @throws IOException in case of problems during jar coping process
*/
private Path copyJarToLocal(String jarName, RemoteFunctionRegistry remoteFunctionRegistry) throws IOException {
Path registryArea = remoteFunctionRegistry.getRegistryArea();
FileSystem fs = remoteFunctionRegistry.getFs();
Path remoteJar = new Path(registryArea, jarName);
Path localJar = new Path(localUdfDir, jarName);
try {
fs.copyToLocalFile(remoteJar, localJar);
} catch (IOException e) {
String message = String.format("Error during jar [%s] coping from [%s] to [%s]",
jarName, registryArea.toUri().getPath(), localUdfDir.toUri().getPath());
throw new IOException(message, e);
}
return localJar;
}
/**
* Deletes quietly local jar but first checks if path to jar is not null.
*
* @param jar path to jar
*/
private void deleteQuietlyLocalJar(Path jar) {
if (jar != null) {
FileUtils.deleteQuietly(new File(jar.toUri().getPath()));
}
}
/**
* If {@link #deleteTmpDir} is set to true, deletes generated temporary directory.
* Otherwise cleans up {@link #localUdfDir}.
*/
@Override
public void close() {
localFunctionRegistry.close();
if (deleteTmpDir) {
FileUtils.deleteQuietly(tmpDir);
} else {
try {
File localDir = new File(localUdfDir.toUri().getPath());
if (localDir.exists()) {
FileUtils.cleanDirectory(localDir);
}
} catch (IOException e) {
logger.warn("Problems during local udf directory clean up", e);
}
}
}
/**
* Fires when jar name is submitted for unregistration.
* Will unregister all functions associated with the jar name
* and delete binary and source associated with the jar from local udf directory
*/
private class UnregistrationListener implements TransientStoreListener {
@Override
public void onChange(TransientStoreEvent<?> event) {
String jarName = (String) event.getValue();
localFunctionRegistry.unregister(jarName);
String localDir = localUdfDir.toUri().getPath();
FileUtils.deleteQuietly(new File(localDir, jarName));
FileUtils.deleteQuietly(new File(localDir, JarUtil.getSourceName(jarName)));
}
}
}
| apache-2.0 |
papicella/snappy-store | gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/engine/store/entry/VMLocalRowLocationThinRegionEntryOffHeap.java | 19166 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.pivotal.gemfirexd.internal.engine.store.entry;
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import com.gemstone.gemfire.internal.concurrent.AtomicUpdaterFactory;
import com.gemstone.gemfire.internal.offheap.OffHeapRegionEntryHelper;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.offheap.annotations.Retained;
import com.gemstone.gemfire.internal.offheap.annotations.Unretained;
import com.gemstone.gemfire.internal.concurrent.CustomEntryConcurrentHashMap.HashEntry;
import java.io.DataOutput;
import java.io.IOException;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.RegionEntry;
import com.gemstone.gemfire.internal.cache.RegionEntryContext;
import com.gemstone.gemfire.internal.cache.RegionEntryFactory;
import com.gemstone.gemfire.internal.shared.Version;
import com.gemstone.gemfire.internal.util.ArrayUtils;
import com.pivotal.gemfirexd.internal.engine.sql.catalog.ExtraTableInfo;
import com.pivotal.gemfirexd.internal.engine.store.CompactCompositeKey;
import com.pivotal.gemfirexd.internal.engine.store.GemFireContainer;
import com.pivotal.gemfirexd.internal.engine.store.RegionEntryUtils;
import com.pivotal.gemfirexd.internal.engine.store.RowFormatter;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.cache.ClassSize;
import com.pivotal.gemfirexd.internal.iapi.services.io.ArrayInputStream;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ExecRow;
import com.pivotal.gemfirexd.internal.iapi.types.BooleanDataValue;
import com.pivotal.gemfirexd.internal.iapi.types.DataTypeDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueDescriptor;
import com.pivotal.gemfirexd.internal.iapi.types.DataValueFactory;
import com.pivotal.gemfirexd.internal.iapi.types.RowLocation;
import com.pivotal.gemfirexd.internal.shared.common.StoredFormatIds;
import com.gemstone.gemfire.cache.CacheWriterException;
import com.gemstone.gemfire.cache.EntryNotFoundException;
import com.gemstone.gemfire.cache.TimeoutException;
import com.gemstone.gemfire.internal.cache.CachedDeserializable;
import com.gemstone.gemfire.internal.cache.EntryEventImpl;
import com.gemstone.gemfire.internal.cache.RegionClearedException;
import com.gemstone.gemfire.internal.cache.Token;
import com.gemstone.gemfire.internal.cache.OffHeapRegionEntry;
import com.pivotal.gemfirexd.internal.engine.store.CompactCompositeRegionKey;
import com.pivotal.gemfirexd.internal.engine.store.offheap.OffHeapRegionEntryUtils;
// macros whose definition changes this class:
// disk: DISK
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// rowlocation: ROWLOCATION
// local: LOCAL
// bucket: BUCKET
// package: PKG
/**
* Do not modify this class. It was generated.
* Instead modify LeafRegionEntry.cpp and then run
* bin/generateRegionEntryClasses.sh from the directory
* that contains your build.xml.
*/
public class VMLocalRowLocationThinRegionEntryOffHeap extends RowLocationThinRegionEntry
implements OffHeapRegionEntry
{
public VMLocalRowLocationThinRegionEntryOffHeap (RegionEntryContext context, Object key,
@Retained
Object value
) {
super(context,
value
);
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
this.tableInfo = RegionEntryUtils.entryGetTableInfo(context, key, value);
this.key = RegionEntryUtils.entryGetRegionKey(key, value);
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// common code
protected int hash;
private HashEntry<Object, Object> next;
@SuppressWarnings("unused")
private volatile long lastModified;
private static final AtomicLongFieldUpdater<VMLocalRowLocationThinRegionEntryOffHeap> lastModifiedUpdater
= AtomicUpdaterFactory.newLongFieldUpdater(VMLocalRowLocationThinRegionEntryOffHeap.class, "lastModified");
protected long getlastModifiedField() {
return lastModifiedUpdater.get(this);
}
protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
}
/**
* @see HashEntry#getEntryHash()
*/
@Override
public final int getEntryHash() {
return this.hash;
}
@Override
protected void setEntryHash(int v) {
this.hash = v;
}
/**
* @see HashEntry#getNextEntry()
*/
@Override
public final HashEntry<Object, Object> getNextEntry() {
return this.next;
}
/**
* @see HashEntry#setNextEntry
*/
@Override
public final void setNextEntry(final HashEntry<Object, Object> n) {
this.next = n;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
// key code
private Object key;
@Override
public final Object getRawKey() {
return this.key;
}
@Override
protected void _setRawKey(Object key) {
this.key = key;
}
/**
* All access done using ohAddrUpdater so it is used even though the compiler can not tell it is.
*/
@Retained @Released private volatile long ohAddress;
/**
* I needed to add this because I wanted clear to call setValue which normally can only be called while the re is synced.
* But if I sync in that code it causes a lock ordering deadlock with the disk regions because they also get a rw lock in clear.
* Some hardware platforms do not support CAS on a long. If gemfire is run on one of those the AtomicLongFieldUpdater does a sync
* on the re and we will once again be deadlocked.
* I don't know if we support any of the hardware platforms that do not have a 64bit CAS. If we do then we can expect deadlocks
* on disk regions.
*/
private final static AtomicLongFieldUpdater<VMLocalRowLocationThinRegionEntryOffHeap> ohAddrUpdater =
AtomicUpdaterFactory.newLongFieldUpdater(VMLocalRowLocationThinRegionEntryOffHeap.class, "ohAddress");
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
@Override
public Token getValueAsToken() {
return OffHeapRegionEntryHelper.getValueAsToken(this);
}
@Override
@Unretained
protected Object getValueField() {
return OffHeapRegionEntryHelper._getValue(this);
}
@Override
protected void setValueField(@Unretained Object v) {
OffHeapRegionEntryHelper.setValue(this, v);
}
@Override
@Retained
public Object _getValueRetain(RegionEntryContext context, boolean decompress) {
return OffHeapRegionEntryHelper._getValueRetain(this, decompress);
}
@Override
public long getAddress() {
return ohAddrUpdater.get(this);
}
@Override
public boolean setAddress(long expectedAddr, long newAddr) {
return ohAddrUpdater.compareAndSet(this, expectedAddr, newAddr);
}
@Override
@Released
public void release() {
OffHeapRegionEntryHelper.releaseEntry(this);
}
private transient ExtraTableInfo tableInfo;
@Override
public final ExtraTableInfo getTableInfo(GemFireContainer baseContainer) {
return this.tableInfo;
}
@Override
public final Object getContainerInfo() {
return this.tableInfo;
}
@Override
public final Object setContainerInfo(final LocalRegion owner, final Object val) {
final GemFireContainer container;
ExtraTableInfo tabInfo;
if (owner == null) {
final RowFormatter rf;
if ((tabInfo = this.tableInfo) != null
&& (rf = tabInfo.getRowFormatter()) != null) {
container = rf.container;
}
else {
return null;
}
}
else {
container = (GemFireContainer)owner.getUserAttribute();
}
if (container != null && container.isByteArrayStore()) {
tabInfo = container.getExtraTableInfo(val);
this.tableInfo = tabInfo;
// cleanup the key if required
if (tabInfo != null && tabInfo.regionKeyPartOfValue()) {
return tabInfo;
}
}
return null;
}
@Override
public int estimateMemoryUsage() {
return ClassSize.refSize;
}
@Override
public int getTypeFormatId() {
return StoredFormatIds.ACCESS_MEM_HEAP_ROW_LOCATION_ID;
}
@Override
public final Object cloneObject() {
return this;
}
@Override
public final RowLocation getClone() {
return this;
}
@Override
public final int compare(DataValueDescriptor other) {
// just use some arbitrary criteria like hashCode for ordering
if (this == other) {
return 0;
}
return this.hashCode() - other.hashCode();
}
@Override
public DataValueDescriptor recycle() {
return this;
}
@Override
public DataValueDescriptor getNewNull() {
return DataValueFactory.DUMMY;
}
@Override
public boolean isNull() {
return this == DataValueFactory.DUMMY;
}
@Override
public Object getObject() throws StandardException {
return this;
}
// Unimplemented methods not expected to be invoked
@Override
public DataValueDescriptor coalesce(DataValueDescriptor[] list,
DataValueDescriptor returnValue) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public int compare(DataValueDescriptor other, boolean nullsOrderedLow)
throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public boolean compare(int op, DataValueDescriptor other,
boolean orderedNulls, boolean unknownRV) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public boolean compare(int op, DataValueDescriptor other,
boolean orderedNulls, boolean nullsOrderedLow, boolean unknownRV)
throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue equals(DataValueDescriptor left,
DataValueDescriptor right) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public int getLengthInBytes(DataTypeDescriptor dtd) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue greaterOrEquals(DataValueDescriptor left,
DataValueDescriptor right) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue greaterThan(DataValueDescriptor left,
DataValueDescriptor right) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue in(DataValueDescriptor left,
DataValueDescriptor[] inList, boolean orderedList)
throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue isNotNull() {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue isNullOp() {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue lessOrEquals(DataValueDescriptor left,
DataValueDescriptor right) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public BooleanDataValue lessThan(DataValueDescriptor left,
DataValueDescriptor right) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public void normalize(DataTypeDescriptor dtd, DataValueDescriptor source)
throws StandardException {
}
@Override
public BooleanDataValue notEquals(DataValueDescriptor left,
DataValueDescriptor right) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public void readExternalFromArray(ArrayInputStream ais) throws IOException,
ClassNotFoundException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public void setValue(DataValueDescriptor theValue) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public int writeBytes(byte[] outBytes, int offset, DataTypeDescriptor dtd) {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public int computeHashCode(int maxWidth, int hash) {
throw new UnsupportedOperationException("unexpected invocation for " + toString());
}
@Override
public final DataValueDescriptor getKeyColumn(int index) {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public final void getKeyColumns(DataValueDescriptor[] keys) {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public boolean compare(int op, ExecRow row, boolean byteArrayStore,
int colIdx, boolean orderedNulls, boolean unknownRV)
throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public boolean compare(int op, CompactCompositeKey key, int colIdx,
boolean orderedNulls, boolean unknownRV) throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public int equals(RowFormatter rf, byte[] bytes, boolean isKeyBytes,
int logicalPosition, int keyBytesPos, final DataValueDescriptor[] outDVD)
throws StandardException {
throw new UnsupportedOperationException("unexpected invocation");
}
@Override
public byte getTypeId() {
throw new UnsupportedOperationException("Implement the method for DataType="+ this);
}
@Override
public void writeNullDVD(DataOutput out) throws IOException{
throw new UnsupportedOperationException("Implement the method for DataType="+ this);
}
@Override
public Object getValueWithoutFaultInOrOffHeapEntry(LocalRegion owner) {
return this;
}
@Override
public Object getValueOrOffHeapEntry(LocalRegion owner) {
return this;
}
@Override
public Object getRawValue() {
Object val = OffHeapRegionEntryHelper._getValueRetain(this, false);
if (val != null && !Token.isInvalidOrRemoved(val)
&& val != Token.NOT_AVAILABLE) {
CachedDeserializable storedObject = (CachedDeserializable) val;
return storedObject.getDeserializedValue(null, this);
}
return null;
}
@Override
public Object prepareValueForCache(RegionEntryContext r, Object val,
boolean isEntryUpdate, boolean valHasMetadataForGfxdOffHeapUpdate) {
if (okToStoreOffHeap(val)
&& OffHeapRegionEntryUtils.isValidValueForGfxdOffHeapStorage(val)) {
// TODO:Asif:Check if this is a valid supposition
// final long address = this.getAddress();
if (isEntryUpdate
/*
* (address == OffHeapRegionEntryHelper.REMOVED_PHASE1_ADDRESS || address
* == OffHeapRegionEntryHelper.NULL_ADDRESS) || r instanceof
* PlaceHolderDiskRegion
*/
) {
return OffHeapRegionEntryUtils.prepareValueForUpdate(this, r, val, valHasMetadataForGfxdOffHeapUpdate);
} else {
return OffHeapRegionEntryUtils.prepareValueForCreate(r, val, false);
}
}
return super.prepareValueForCache(r, val, isEntryUpdate, valHasMetadataForGfxdOffHeapUpdate);
}
@Override
public boolean destroy(LocalRegion region, EntryEventImpl event,
boolean inTokenMode, boolean cacheWrite, @Unretained Object expectedOldValue,
boolean forceDestroy, boolean removeRecoveredEntry)
throws CacheWriterException, EntryNotFoundException, TimeoutException,
RegionClearedException {
Object key = event.getKey();
if (key instanceof CompactCompositeRegionKey) {
byte[] keyBytes = ((CompactCompositeRegionKey)key)
.snapshotKeyFromValue(false);
if (keyBytes != null) {
this._setRawKey(keyBytes);
}
}
return super.destroy(region, event, inTokenMode, cacheWrite,
expectedOldValue, forceDestroy, removeRecoveredEntry);
}
@Override
public Version[] getSerializationVersions() {
return null;
}
@Override
public Object getValue(GemFireContainer baseContainer) {
return RegionEntryUtils.getValue(baseContainer.getRegion(), this);
}
@Override
public Object getValueWithoutFaultIn(GemFireContainer baseContainer) {
return RegionEntryUtils.getValueWithoutFaultIn(baseContainer.getRegion(), this);
}
@Override
public ExecRow getRow(GemFireContainer baseContainer) {
return RegionEntryUtils.getRow(baseContainer, baseContainer.getRegion(), this, this.tableInfo);
}
@Override
public ExecRow getRowWithoutFaultIn(GemFireContainer baseContainer) {
return RegionEntryUtils.getRowWithoutFaultIn(baseContainer, baseContainer.getRegion(), this, this.tableInfo);
}
@Override
public int getBucketID() {
return -1;
}
@Override
protected StringBuilder appendFieldsToString(final StringBuilder sb) {
sb.append("key=");
// OFFHEAP _getValue ok: the current toString on OffHeapCachedDeserializable
// is safe to use without incing refcount.
final Object k = getKeyCopy();
final Object val = OffHeapRegionEntryUtils.getHeapRowForInVMValue(this);
RegionEntryUtils.entryKeyString(k, val, getTableInfo(null), sb);
sb.append("; byte source = "+ this._getValue());
sb.append("; rawValue=");
ArrayUtils.objectStringNonRecursive(val, sb);
sb.append("; lockState=0x").append(Integer.toHexString(getState()));
return sb;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
private static RegionEntryFactory factory = new RegionEntryFactory() {
public final RegionEntry createEntry(RegionEntryContext context, Object key, Object value) {
return new VMLocalRowLocationThinRegionEntryOffHeap(context, key, value);
}
public final Class<?> getEntryClass() {
return VMLocalRowLocationThinRegionEntryOffHeap.class;
}
public RegionEntryFactory makeVersioned() {
return VersionedLocalRowLocationThinRegionEntryOffHeap.getEntryFactory();
}
@Override
public RegionEntryFactory makeOnHeap() {
return VMLocalRowLocationThinRegionEntryHeap.getEntryFactory();
}
};
public static RegionEntryFactory getEntryFactory() {
return factory;
}
// DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}
| apache-2.0 |
spark/spark-sdk-android | cloudsdk/src/main/java/org/kaazing/gateway/client/impl/wseb/WebSocketEmulatedDecoderImpl.java | 8210 | /**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.kaazing.gateway.client.impl.wseb;
import org.kaazing.gateway.client.impl.DecoderInput;
import org.kaazing.gateway.client.util.WrappedByteBuffer;
import java.nio.charset.Charset;
import java.util.logging.Logger;
public class WebSocketEmulatedDecoderImpl<C> implements WebSocketEmulatedDecoder<C> {
private static final String CLASS_NAME = WebSocketEmulatedDecoderImpl.class.getName();
private static final Logger LOG = Logger.getLogger(CLASS_NAME);
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final byte WSF_COMMAND_FRAME_START = (byte) 0x01;
private static final byte WS_TEXT_FRAME_END = (byte) 0xff;
private static final byte WS_BINARY_FRAME_START = (byte) 0x80;
private static final byte WS_SPECIFIEDLENGTH_TEXT_FRAME_START = (byte) 0x81;
private static final byte WSE_PING_FRAME_CODE = (byte) 0x89;
/*
* Processing state machine
*/
enum DecodingState {
START_OF_FRAME,
READING_TEXT_FRAME,
READING_COMMAND_FRAME,
READING_BINARY_FRAME_HEADER,
READING_BINARY_FRAME,
READING_PING_FRAME
};
private DecodingState processingState = DecodingState.START_OF_FRAME;
private WrappedByteBuffer readBuffer = null;
private WrappedByteBuffer messageBuffer = null;
private int binaryFrameLength = 0;
private byte opCode = 0;
@Override
public void decode(C channel, DecoderInput<C> in, WebSocketEmulatedDecoderListener<C> listener) {
LOG.fine("process() START");
while (true) {
if (readBuffer == null) {
readBuffer = in.read(channel);
if (readBuffer == null) {
break;
}
}
if (!readBuffer.hasRemaining()) {
readBuffer = null;
continue;
}
if (processingState == DecodingState.START_OF_FRAME) {
// handle alignment with start-of-frame boundary (after mark)
opCode = readBuffer.get();
if (opCode == WSF_COMMAND_FRAME_START) {
processingState = DecodingState.READING_COMMAND_FRAME;
messageBuffer = WrappedByteBuffer.allocate(512);
}
else if (opCode == WSE_PING_FRAME_CODE) {
processingState = DecodingState.READING_PING_FRAME;
}
else if (opCode == WS_BINARY_FRAME_START || opCode == WS_SPECIFIEDLENGTH_TEXT_FRAME_START) {
processingState = DecodingState.READING_BINARY_FRAME_HEADER;
binaryFrameLength = 0;
}
}
else if (processingState == DecodingState.READING_COMMAND_FRAME) {
int endOfFrameAt = readBuffer.indexOf(WS_TEXT_FRAME_END);
if (endOfFrameAt == -1) {
int numBytes = readBuffer.remaining();
//LOG.finest("process() TEXT_FRAME: partial: "+numBytes);
messageBuffer.putBuffer(readBuffer);
//KG-6984 putBuffer already move position in readBuffer, no skip required
//readBuffer.skip(numBytes);
}
else {
// complete payload + maybe next payload
int dataLength = endOfFrameAt - readBuffer.position();
messageBuffer.putBytes(readBuffer.getBytes(dataLength)); // Should advance both buffers
readBuffer.skip(1); //skip endOfFrame byte
boolean isCommandFrame = (processingState == DecodingState.READING_COMMAND_FRAME);
processingState = DecodingState.START_OF_FRAME;
// is this a command frame
if (isCommandFrame) {
//LOG.finest("process() COMMAND_FRAME");
messageBuffer.flip();
if (messageBuffer.array()[0] == 0x30 && messageBuffer.array()[1] == 0x30) {
//NOOP_COMMAND:
// ignore
}
else {
listener.commandDecoded(channel, messageBuffer.duplicate());
}
}
// otherwise it is a text frame
else {
// deliver the text frame
messageBuffer.flip();
String text = messageBuffer.getString(UTF8);
listener.messageDecoded(channel, text);
}
}
}
else if (processingState == DecodingState.READING_BINARY_FRAME_HEADER) {
while (readBuffer.hasRemaining()) {
byte b = readBuffer.get();
binaryFrameLength <<= 7;
binaryFrameLength |= (b & 0x7f);
if ((b & 0x80) != 0x80) {
//LOG.finest("process() BINARY_FRAME_HEADER: " + binaryFrameLength);
processingState = DecodingState.READING_BINARY_FRAME;
messageBuffer = WrappedByteBuffer.allocate(binaryFrameLength);
break;
}
}
}
else if (processingState == DecodingState.READING_BINARY_FRAME) {
if (readBuffer.remaining() < binaryFrameLength) {
// incomplete payload
int numbytes = readBuffer.remaining();
messageBuffer.putBuffer(readBuffer);
binaryFrameLength -= numbytes;
//LOG.finest("process() BINARY_FRAME: partial: " + numbytes);
}
else {
//completed payload + maybe next payload
messageBuffer.putBytes(readBuffer.getBytes(binaryFrameLength));
processingState = DecodingState.START_OF_FRAME;
// deliver the binary frame
messageBuffer.flip();
if (opCode == WS_SPECIFIEDLENGTH_TEXT_FRAME_START) {
String text = messageBuffer.getString(UTF8);
listener.messageDecoded(channel, text);
} else if (opCode == WS_BINARY_FRAME_START){
listener.messageDecoded(channel, messageBuffer);
}
else {
throw new IllegalArgumentException("Invalid frame opcode. opcode = " + opCode);
}
}
}
else if (processingState == DecodingState.READING_PING_FRAME) {
byte byteFollowingPingFrameCode = readBuffer.get();
processingState = DecodingState.START_OF_FRAME;
if (byteFollowingPingFrameCode != 0x00) {
throw new IllegalArgumentException("Expected 0x00 after the PING frame code but received - " + byteFollowingPingFrameCode);
}
listener.pingReceived(channel);
}
}
}
}
| apache-2.0 |
fengshao0907/joda-time-hibernate | src/main/java/org/joda/time/contrib/hibernate/PersistentDateTimeTZ.java | 3599 | /*
* Copyright 2001-2012 Stephen Colebourne
*
* 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.joda.time.contrib.hibernate;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.usertype.UserType;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
/**
* Persist {@link org.joda.time.DateTime} via hibernate. The timezone will be
* stored in an extra column.
*
* @author Mario Ivankovits (mario@ops.co.at)
*/
public class PersistentDateTimeTZ implements UserType, Serializable {
public static final PersistentDateTimeTZ INSTANCE = new PersistentDateTimeTZ();
private static final int[] SQL_TYPES = new int[] { Types.TIMESTAMP, Types.VARCHAR, };
public int[] sqlTypes() {
return SQL_TYPES;
}
public Class returnedClass() {
return DateTime.class;
}
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y) {
return true;
}
if (x == null || y == null) {
return false;
}
DateTime dtx = (DateTime) x;
DateTime dty = (DateTime) y;
return dtx.equals(dty);
}
public int hashCode(Object object) throws HibernateException {
return object.hashCode();
}
public Object nullSafeGet(ResultSet resultSet, String[] strings, Object object) throws HibernateException, SQLException {
Object timestamp = StandardBasicTypes.TIMESTAMP.nullSafeGet(resultSet, strings[0]);
Object timezone = StandardBasicTypes.STRING.nullSafeGet(resultSet, strings[1]);
if (timestamp == null || timezone == null) {
return null;
}
return new DateTime(timestamp, DateTimeZone.forID(timezone.toString()));
}
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
if (value == null) {
StandardBasicTypes.TIMESTAMP.nullSafeSet(preparedStatement, null, index);
StandardBasicTypes.STRING.nullSafeSet(preparedStatement, null, index + 1);
} else {
DateTime dt = (DateTime) value;
StandardBasicTypes.TIMESTAMP.nullSafeSet(preparedStatement, dt.toDate(), index);
StandardBasicTypes.STRING.nullSafeSet(preparedStatement, dt.getZone().getID(), index + 1);
}
}
public Object deepCopy(Object value) throws HibernateException {
return value;
}
public boolean isMutable() {
return false;
}
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
public Object assemble(Serializable cached, Object value) throws HibernateException {
return cached;
}
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}
| apache-2.0 |
HyVar/DarwinSPL | plugins/eu.hyvar.mspl.manifest.resource.hymanifest.ui/src-gen/eu/hyvar/mspl/manifest/resource/hymanifest/ui/HymanifestQuickAssistAssistant.java | 1568 | /**
* <copyright>
* </copyright>
*
*
*/
package eu.hyvar.mspl.manifest.resource.hymanifest.ui;
import org.eclipse.jface.text.AbstractReusableInformationControlCreator;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DefaultInformationControl.IInformationPresenter;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.quickassist.IQuickAssistAssistant;
import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
import org.eclipse.jface.text.quickassist.QuickAssistAssistant;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.swt.widgets.Shell;
public class HymanifestQuickAssistAssistant extends QuickAssistAssistant implements IQuickAssistAssistant {
public HymanifestQuickAssistAssistant(eu.hyvar.mspl.manifest.resource.hymanifest.IHymanifestResourceProvider resourceProvider, eu.hyvar.mspl.manifest.resource.hymanifest.ui.IHymanifestAnnotationModelProvider annotationModelProvider) {
setQuickAssistProcessor(new eu.hyvar.mspl.manifest.resource.hymanifest.ui.HymanifestQuickAssistProcessor(resourceProvider, annotationModelProvider));
setInformationControlCreator(new AbstractReusableInformationControlCreator() {
public IInformationControl doCreateInformationControl(Shell parent) {
return new DefaultInformationControl(parent, (IInformationPresenter) null);
}
});
}
public boolean canAssist(IQuickAssistInvocationContext invocationContext) {
return false;
}
public boolean canFix(Annotation annotation) {
return true;
}
}
| apache-2.0 |
yanzhijun/jclouds-aliyun | apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/ExtensionNamespaces.java | 1289 | /*
* 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.jclouds.openstack.keystone.v2_0.extensions;
/**
* Extension namespaces
*
* @see <a href= "http://docs.openstack.org/developer/keystone/extension_development.html" />
*/
public final class ExtensionNamespaces {
/**
* OpenStack Keystone Admin Support
*/
public static final String OS_KSADM = "http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0";
private ExtensionNamespaces() {
throw new AssertionError("intentionally unimplemented");
}
}
| apache-2.0 |
apache/commons-collections | src/test/java/org/apache/commons/collections4/multimap/UnmodifiableMultiValuedMapTest.java | 10748 | /*
* 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.commons.collections4.multimap;
import java.util.Set;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import junit.framework.Test;
import org.apache.commons.collections4.BulkTest;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.MultiSet;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.Unmodifiable;
/**
* Tests for UnmodifiableMultiValuedMap
*
* @since 4.1
*/
public class UnmodifiableMultiValuedMapTest<K, V> extends AbstractMultiValuedMapTest<K, V> {
public UnmodifiableMultiValuedMapTest(final String testName) {
super(testName);
}
public static Test suite() {
return BulkTest.makeSuite(UnmodifiableMultiValuedMapTest.class);
}
/**
* Assert the given map contains all added values after it was initialized
* with makeFullMap(). See COLLECTIONS-769.
* @param map the MultiValuedMap<K, V> to check
*/
private void assertMapContainsAllValues(final MultiValuedMap<K, V> map) {
assertEquals("[uno, un]", map.get((K) "one").toString());
assertEquals("[dos, deux]", map.get((K) "two").toString());
assertEquals("[tres, trois]", map.get((K) "three").toString());
}
@Override
public boolean isAddSupported() {
return false;
}
@Override
public boolean isRemoveSupported() {
return false;
}
@Override
public MultiValuedMap<K, V> makeObject() {
return UnmodifiableMultiValuedMap.<K, V>unmodifiableMultiValuedMap(
new ArrayListValuedHashMap<K, V>());
}
@Override
protected MultiValuedMap<K, V> makeFullMap() {
final MultiValuedMap<K, V> map = new ArrayListValuedHashMap<>();
addSampleMappings(map);
return UnmodifiableMultiValuedMap.<K, V>unmodifiableMultiValuedMap(map);
}
// -----------------------------------------------------------------------
public void testUnmodifiable() {
assertTrue(makeObject() instanceof Unmodifiable);
assertTrue(makeFullMap() instanceof Unmodifiable);
}
public void testDecorateFactory() {
final MultiValuedMap<K, V> map = makeFullMap();
assertSame(map, UnmodifiableMultiValuedMap.unmodifiableMultiValuedMap(map));
}
public void testDecoratorFactoryNullMap() {
try {
UnmodifiableMultiValuedMap.unmodifiableMultiValuedMap(null);
fail("map must not be null");
} catch (final NullPointerException e) {
// expected
}
}
@SuppressWarnings("unchecked")
public void testAddException() {
final MultiValuedMap<K, V> map = makeObject();
try {
map.put((K) "one", (V) "uno");
fail();
} catch (final UnsupportedOperationException e) {
}
}
public void testRemoveException() {
final MultiValuedMap<K, V> map = makeFullMap();
try {
map.remove("one");
fail();
} catch (final UnsupportedOperationException e) {
// expected, not support remove() method
// UnmodifiableMultiValuedMap does not support change
}
this.assertMapContainsAllValues(map);
}
public void testRemoveMappingException() {
final MultiValuedMap<K, V> map = makeFullMap();
try {
map.removeMapping("one", "uno");
fail();
} catch (final UnsupportedOperationException e) {
// expected, not support removeMapping() method
// UnmodifiableMultiValuedMap does not support change
}
this.assertMapContainsAllValues(map);
}
public void testClearException() {
final MultiValuedMap<K, V> map = makeFullMap();
try {
map.clear();
fail();
} catch (final UnsupportedOperationException e) {
// expected, not support clear() method
// UnmodifiableMultiValuedMap does not support change
}
this.assertMapContainsAllValues(map);
}
public void testPutAllException() {
final MultiValuedMap<K, V> map = makeObject();
final MultiValuedMap<K, V> original = new ArrayListValuedHashMap<>();
final Map<K, V> originalMap = new HashMap<>();
final Collection<V> coll = (Collection<V>) Arrays.asList("X", "Y", "Z");
original.put((K) "key", (V) "object1");
original.put((K) "key", (V) "object2");
originalMap.put((K) "keyX", (V) "object1");
originalMap.put((K) "keyY", (V) "object2");
try {
map.putAll(original);
fail();
} catch (final UnsupportedOperationException e) {
// expected, not support putAll() method
// UnmodifiableMultiValuedMap does not support change
}
assertEquals("{}", map.toString());
try {
map.putAll(originalMap);
fail();
} catch (final UnsupportedOperationException e) {
// expected
}
assertEquals("{}", map.toString());
try {
map.putAll((K) "A", coll);
fail();
} catch (final UnsupportedOperationException e) {
// expected
}
assertEquals("{}", map.toString());
}
@SuppressWarnings("unchecked")
public void testUnmodifiableEntries() {
resetFull();
final Collection<Entry<K, V>> entries = getMap().entries();
try {
entries.clear();
fail();
} catch (final UnsupportedOperationException e) {
}
final Iterator<Entry<K, V>> it = entries.iterator();
final Entry<K, V> entry = it.next();
try {
it.remove();
fail();
} catch (final UnsupportedOperationException e) {
}
try {
entry.setValue((V) "three");
fail();
} catch (final UnsupportedOperationException e) {
}
}
@SuppressWarnings("unchecked")
public void testUnmodifiableMapIterator() {
resetFull();
final MapIterator<K, V> mapIt = getMap().mapIterator();
try {
mapIt.remove();
fail();
} catch (final UnsupportedOperationException e) {
}
try {
mapIt.setValue((V) "three");
fail();
} catch (final UnsupportedOperationException e) {
}
}
@SuppressWarnings("unchecked")
public void testUnmodifiableKeySet() {
resetFull();
final Set<K> keySet = getMap().keySet();
try {
keySet.add((K) "four");
fail();
} catch (final UnsupportedOperationException e) {
}
try {
keySet.remove("four");
fail();
} catch (final UnsupportedOperationException e) {
}
try {
keySet.clear();
fail();
} catch (final UnsupportedOperationException e) {
}
final Iterator<K> it = keySet.iterator();
try {
it.remove();
fail();
} catch (final UnsupportedOperationException e) {
}
}
@SuppressWarnings("unchecked")
public void testUnmodifiableValues() {
resetFull();
final Collection<V> values = getMap().values();
try {
values.add((V) "four");
fail();
} catch (final UnsupportedOperationException e) {
}
try {
values.remove("four");
fail();
} catch (final UnsupportedOperationException e) {
}
try {
values.clear();
fail();
} catch (final UnsupportedOperationException e) {
}
final Iterator<V> it = values.iterator();
try {
it.remove();
fail();
} catch (final UnsupportedOperationException e) {
}
}
@SuppressWarnings("unchecked")
public void testUnmodifiableAsMap() {
resetFull();
final Map<K, Collection<V>> mapCol = getMap().asMap();
try {
mapCol.put((K) "four", (Collection<V>) Arrays.asList("four"));
fail();
} catch (final UnsupportedOperationException e) {
}
try {
mapCol.remove("four");
fail();
} catch (final UnsupportedOperationException e) {
}
try {
mapCol.clear();
fail();
} catch (final UnsupportedOperationException e) {
}
try {
mapCol.clear();
fail();
} catch (final UnsupportedOperationException e) {
}
}
@SuppressWarnings("unchecked")
public void testUnmodifiableKeys() {
resetFull();
final MultiSet<K> keys = getMap().keys();
try {
keys.add((K) "four");
fail();
} catch (final UnsupportedOperationException e) {
}
try {
keys.remove("four");
fail();
} catch (final UnsupportedOperationException e) {
}
try {
keys.clear();
fail();
} catch (final UnsupportedOperationException e) {
}
final Iterator<K> it = keys.iterator();
try {
it.remove();
fail();
} catch (final UnsupportedOperationException e) {
}
}
// public void testCreate() throws Exception {
// writeExternalFormToDisk((java.io.Serializable) makeObject(),
// "src/test/resources/data/test/UnmodifiableMultiValuedMap.emptyCollection.version4.1.obj");
// writeExternalFormToDisk((java.io.Serializable) makeFullMap(),
// "src/test/resources/data/test/UnmodifiableMultiValuedMap.fullCollection.version4.1.obj");
// }
}
| apache-2.0 |
mmusgrov/quickstart | helloworld-html5/src/main/java/org/jboss/as/quickstarts/poh5helloworld/HelloService.java | 1043 | /**
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual 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.jboss.as.quickstarts.poh5helloworld;
/**
* A simple CDI service which is able to say hello to someone
*
* @author Pete Muir
*
*/
public class HelloService {
String createHelloMessage(String name) {
return "Hello " + name + "!";
}
}
| apache-2.0 |
AndreyBurikhin/big-data-plugin | src/org/pentaho/di/job/entries/sqoop/SqoopExportJobEntry.java | 4653 | /*******************************************************************************
*
* Pentaho Big Data
*
* Copyright (C) 2002-2013 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.job.entries.sqoop;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ProvidesDatabaseConnectionInformation;
import org.pentaho.di.core.annotations.JobEntry;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.w3c.dom.Node;
import java.util.List;
/**
* Provides a way to orchestrate <a href="http://sqoop.apache.org/">Sqoop</a> exports.
*/
@JobEntry( id = "SqoopExport", name = "Sqoop.Export.PluginName", description = "Sqoop.Export.PluginDescription",
categoryDescription = "i18n:org.pentaho.di.job:JobCategory.Category.BigData", image = "sqoop-export.png",
i18nPackageName = "org.pentaho.di.job.entries.sqoop", version = "1" )
public class SqoopExportJobEntry extends AbstractSqoopJobEntry<SqoopExportConfig> implements
ProvidesDatabaseConnectionInformation {
// Database meta object for UI interactions. Populated during transformation load or configuration changes via UI.
private transient DatabaseMeta databaseMeta;
@Override
protected SqoopExportConfig buildSqoopConfig() {
return new SqoopExportConfig();
}
/**
* @return the name of the Sqoop export tool: "export"
*/
@Override
protected String getToolName() {
return "export";
}
/**
* @return the current database meta. Agile BI uses this to generate a model.
*/
@Override
public DatabaseMeta getDatabaseMeta() {
return databaseMeta;
}
/**
* @return the current table name from the configuration. Agile BI uses this to generate a model.
*/
@Override
public String getTableName() {
return environmentSubstitute( getJobConfig().getTable() );
}
/**
* @return the current schema name from the configuration. Agile BI uses this to generate a model.
*/
@Override
public String getSchemaName() {
return environmentSubstitute( getJobConfig().getSchema() );
}
@Override
public String getMissingDatabaseConnectionInformationMessage() {
if ( Const.isEmpty( getJobConfig().getDatabase() ) && !Const.isEmpty( getJobConfig().getConnect() ) ) {
// We're using advanced configuration, alert the user we cannot visualize unless we're not using a database
// managed by Kettle
return BaseMessages.getString( AbstractSqoopJobEntry.class, "ErrorMustConfigureDatabaseConnectionFromList" );
}
// Use the default error message
return null;
}
/**
* Additionally sets the database meta if a database is set.
*/
@Override
public void loadXML( Node node, List<DatabaseMeta> databaseMetas, List<SlaveServer> slaveServers,
Repository repository ) throws KettleXMLException {
super.loadXML( node, databaseMetas, slaveServers, repository );
setDatabaseMeta( DatabaseMeta.findDatabase( databaseMetas, getJobConfig().getDatabase() ) );
}
/**
* Additionally sets the database meta if a database is set.
*/
@Override
public void loadRep( Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases,
List<SlaveServer> slaveServers ) throws KettleException {
super.loadRep( rep, id_jobentry, databases, slaveServers );
setDatabaseMeta( DatabaseMeta.findDatabase( databases, getJobConfig().getDatabase() ) );
}
/**
* Set the current database meta.
*
* @param databaseMeta
* Database meta representing the database this job is currently configured to export to
*/
public void setDatabaseMeta( DatabaseMeta databaseMeta ) {
this.databaseMeta = databaseMeta;
}
}
| apache-2.0 |
taochaoqiang/druid | server/src/main/java/io/druid/curator/discovery/CuratorDruidLeaderSelector.java | 6666 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.curator.discovery;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import io.druid.concurrent.LifecycleLock;
import io.druid.discovery.DruidLeaderSelector;
import io.druid.guice.annotations.Self;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.concurrent.Execs;
import io.druid.java.util.common.guava.CloseQuietly;
import io.druid.java.util.emitter.EmittingLogger;
import io.druid.server.DruidNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.framework.recipes.leader.Participant;
import javax.annotation.Nullable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicReference;
/**
*/
public class CuratorDruidLeaderSelector implements DruidLeaderSelector
{
private static final EmittingLogger log = new EmittingLogger(CuratorDruidLeaderSelector.class);
private final LifecycleLock lifecycleLock = new LifecycleLock();
private final DruidNode self;
private final CuratorFramework curator;
private final String latchPath;
private ExecutorService listenerExecutor;
private DruidLeaderSelector.Listener listener = null;
private final AtomicReference<LeaderLatch> leaderLatch = new AtomicReference<>();
private volatile boolean leader = false;
private volatile int term = 0;
public CuratorDruidLeaderSelector(CuratorFramework curator, @Self DruidNode self, String latchPath)
{
this.curator = curator;
this.self = self;
this.latchPath = latchPath;
// Creating a LeaderLatch here allows us to query for the current leader. We will not be considered for leadership
// election until LeaderLatch.start() is called in registerListener(). This allows clients to observe the current
// leader without being involved in the election.
this.leaderLatch.set(createNewLeaderLatch());
}
private LeaderLatch createNewLeaderLatch()
{
return new LeaderLatch(curator, latchPath, self.getServiceScheme() + "://" + self.getHostAndPortToUse());
}
private LeaderLatch createNewLeaderLatchWithListener()
{
final LeaderLatch newLeaderLatch = createNewLeaderLatch();
newLeaderLatch.addListener(
new LeaderLatchListener()
{
@Override
public void isLeader()
{
try {
if (leader) {
log.warn("I'm being asked to become leader. But I am already the leader. Ignored event.");
return;
}
leader = true;
term++;
listener.becomeLeader();
}
catch (Exception ex) {
log.makeAlert(ex, "listener becomeLeader() failed. Unable to become leader").emit();
// give others a chance to become leader.
final LeaderLatch oldLatch = createNewLeaderLatchWithListener();
CloseQuietly.close(oldLatch);
leader = false;
try {
//Small delay before starting the latch so that others waiting are chosen to become leader.
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
leaderLatch.get().start();
}
catch (Exception e) {
// If an exception gets thrown out here, then the node will zombie out 'cause it won't be looking for
// the latch anymore. I don't believe it's actually possible for an Exception to throw out here, but
// Curator likes to have "throws Exception" on methods so it might happen...
log.makeAlert(e, "I am a zombie").emit();
}
}
}
@Override
public void notLeader()
{
try {
if (!leader) {
log.warn("I'm being asked to stop being leader. But I am not the leader. Ignored event.");
return;
}
leader = false;
listener.stopBeingLeader();
}
catch (Exception ex) {
log.makeAlert(ex, "listener.stopBeingLeader() failed. Unable to stopBeingLeader").emit();
}
}
},
listenerExecutor
);
return leaderLatch.getAndSet(newLeaderLatch);
}
@Nullable
@Override
public String getCurrentLeader()
{
try {
final LeaderLatch latch = leaderLatch.get();
Participant participant = latch.getLeader();
if (participant.isLeader()) {
return participant.getId();
}
return null;
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
@Override
public boolean isLeader()
{
return leader;
}
@Override
public int localTerm()
{
return term;
}
@Override
public void registerListener(DruidLeaderSelector.Listener listener)
{
Preconditions.checkArgument(listener != null, "listener is null.");
if (!lifecycleLock.canStart()) {
throw new ISE("can't start.");
}
try {
this.listener = listener;
this.listenerExecutor = Execs.singleThreaded(StringUtils.format("LeaderSelector[%s]", latchPath));
createNewLeaderLatchWithListener();
leaderLatch.get().start();
lifecycleLock.started();
}
catch (Exception ex) {
throw Throwables.propagate(ex);
}
finally {
lifecycleLock.exitStart();
}
}
@Override
public void unregisterListener()
{
if (!lifecycleLock.canStop()) {
throw new ISE("can't stop.");
}
CloseQuietly.close(leaderLatch.get());
listenerExecutor.shutdownNow();
}
}
| apache-2.0 |
OleksandrProshak/Alexandr_Proshak | Level_Junior/Part_004_Servlet_JSP/7_Mockito/src/main/java/ru/job4j/task1/controller/LogoutController.java | 1624 | package ru.job4j.task1.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import java.io.IOException;
import static ru.job4j.task1.controller.ControllerConstants.ATTRIBUTE_SYSTEM_USER;
import static ru.job4j.task1.controller.ControllerConstants.USER_LOGIN;
import static ru.job4j.task1.controller.ControllerConstants.USER_PASSWORD;
/**
* The LogoutController class.
*
* @author Alex Proshak (olexandr_proshak@ukr.net)
*/
public class LogoutController extends HttpServlet {
/**
* The logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(LogoutController.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
HttpSession session = req.getSession();
if (session.getAttribute(ATTRIBUTE_SYSTEM_USER) != null) {
session.invalidate();
resp.addCookie(new Cookie(USER_LOGIN, "invalid"));
resp.addCookie(new Cookie(USER_PASSWORD, "invalid"));
resp.sendRedirect(String.format("%s/login", req.getContextPath()));
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
try {
resp.sendRedirect(String.format("%s/login", req.getContextPath()));
} catch (IOException e1) {
LOG.error(e.getMessage(), e1);
}
}
}
}
| apache-2.0 |
longjl/JFinal_Authority | jfinal-authority/src/main/java/com/jayqqaa12/system/validator/BugValidator.java | 386 | package com.jayqqaa12.system.validator;
import com.jayqqaa12.jbase.jfinal.ext.Validator;
import com.jfinal.core.Controller;
public class BugValidator extends Validator
{
@Override
protected void validate(Controller c)
{
validateString("bug.name", 1, 50, "名称不能超过50个字符");
validateString("bug.des", 0, 10000, "字符不能为空 或者太多了");
}
}
| apache-2.0 |
ddebrunner/incubator-quarks | apps/iot/src/test/java/org/apache/edgent/test/apps/iot/EchoIotDevice.java | 3948 | /*
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.edgent.test.apps.iot;
import static org.apache.edgent.function.Functions.discard;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.edgent.connectors.iot.IotDevice;
import org.apache.edgent.function.Function;
import org.apache.edgent.function.UnaryOperator;
import org.apache.edgent.topology.TSink;
import org.apache.edgent.topology.TStream;
import org.apache.edgent.topology.Topology;
import org.apache.edgent.topology.plumbing.PlumbingStreams;
import com.google.gson.JsonObject;
/**
* A test IotDevice that echos back every event as a command with command
* identifier equal to the {@code cmdId} value in the event payload. If {@code cmdId}
* is not set then the event identifier is used.
*
*/
public class EchoIotDevice implements IotDevice {
public static final String EVENT_CMD_ID = "cmdId";
private final Topology topology;
private TStream<JsonObject> echoCmds;
public EchoIotDevice(Topology topology) {
this.topology = topology;
}
@Override
public Topology topology() {
return topology;
}
@Override
public TSink<JsonObject> events(TStream<JsonObject> stream, Function<JsonObject, String> eventId,
UnaryOperator<JsonObject> payload, Function<JsonObject, Integer> qos) {
stream = stream.map(e -> {
JsonObject c = new JsonObject();
JsonObject evPayload = payload.apply(e);
c.addProperty(CMD_ID, getCommandIdFromEvent(eventId.apply(e), evPayload));
c.add(CMD_PAYLOAD, evPayload);
c.addProperty(CMD_FORMAT, "json");
c.addProperty(CMD_TS, System.currentTimeMillis());
return c;
});
return handleEvents(stream);
}
private static String getCommandIdFromEvent(String eventId, JsonObject evPayload) {
if (evPayload.has(EVENT_CMD_ID))
return evPayload.getAsJsonPrimitive(EVENT_CMD_ID).getAsString();
else
return eventId;
}
@Override
public TSink<JsonObject> events(TStream<JsonObject> stream, String eventId, int qos) {
stream = stream.map(e -> {
JsonObject c = new JsonObject();
c.addProperty(CMD_ID, getCommandIdFromEvent(eventId, e));
c.add(CMD_PAYLOAD, e);
c.addProperty(CMD_FORMAT, "json");
c.addProperty(CMD_TS, System.currentTimeMillis());
return c;
});
return handleEvents(stream);
}
private TSink<JsonObject> handleEvents(TStream<JsonObject> stream) {
if (echoCmds == null)
echoCmds = PlumbingStreams.isolate(stream, true);
else
echoCmds = PlumbingStreams.isolate(stream.union(echoCmds), true);
return stream.sink(discard());
}
@Override
public TStream<JsonObject> commands(String... commands) {
if (commands.length == 0)
return echoCmds;
Set<String> cmds = new HashSet<>(Arrays.asList(commands));
return echoCmds.filter(cmd -> cmds.contains(cmd.getAsJsonPrimitive(CMD_ID).getAsString()));
}
}
| apache-2.0 |
devdattakulkarni/Cassandra-KVAC | src/java/org/apache/cassandra/streaming/IncomingStreamReader.java | 4444 | /**
* 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.cassandra.streaming;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.utils.Pair;
public class IncomingStreamReader
{
private static final Logger logger = LoggerFactory.getLogger(IncomingStreamReader.class);
protected final PendingFile localFile;
protected final PendingFile remoteFile;
private final SocketChannel socketChannel;
protected final StreamInSession session;
public IncomingStreamReader(StreamHeader header, Socket socket) throws IOException
{
this.socketChannel = socket.getChannel();
InetSocketAddress remoteAddress = (InetSocketAddress)socket.getRemoteSocketAddress();
session = StreamInSession.get(remoteAddress.getAddress(), header.sessionId);
session.addFiles(header.pendingFiles);
// set the current file we are streaming so progress shows up in jmx
session.setCurrentFile(header.file);
session.setTable(header.table);
// pendingFile gets the new context for the local node.
remoteFile = header.file;
localFile = remoteFile != null ? StreamIn.getContextMapping(remoteFile) : null;
}
public void read() throws IOException
{
if (remoteFile != null)
readFile();
session.closeIfFinished();
}
protected void readFile() throws IOException
{
if (logger.isDebugEnabled())
{
logger.debug("Receiving stream");
logger.debug("Creating file for {}", localFile.getFilename());
}
FileOutputStream fos = new FileOutputStream(localFile.getFilename(), true);
FileChannel fc = fos.getChannel();
long offset = 0;
try
{
for (Pair<Long, Long> section : localFile.sections)
{
long length = section.right - section.left;
long bytesRead = 0;
while (bytesRead < length)
{
bytesRead = readnwrite(length, bytesRead, offset, fc);
}
offset += length;
}
}
catch (IOException ex)
{
/* Ask the source node to re-stream this file. */
session.retry(remoteFile);
/* Delete the orphaned file. */
FileUtils.deleteWithConfirm(new File(localFile.getFilename()));
throw ex;
}
finally
{
fc.close();
}
session.finished(remoteFile, localFile);
}
protected long readnwrite(long length, long bytesRead, long offset, FileChannel fc) throws IOException
{
long toRead = Math.min(FileStreamTask.CHUNK_SIZE, length - bytesRead);
long lastRead = fc.transferFrom(socketChannel, offset + bytesRead, toRead);
// if the other side fails, we will not get an exception, but instead transferFrom will constantly return 0 byte read
// and we would thus enter an infinite loop. So intead, if no bytes are tranferred we assume the other side is dead and
// raise an exception (that will be catch belove and 'the right thing' will be done).
if (lastRead == 0)
throw new IOException("Transfer failed for remote file " + remoteFile);
bytesRead += lastRead;
remoteFile.progress += lastRead;
return bytesRead;
}
}
| apache-2.0 |
papegaaij/jsr-352 | JSR352.JobXML.Model/jaxbgen/com/ibm/jbatch/jsl/model/JSLProperties.java | 4434 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vIBM 2.2.3-11/28/2011 06:21 AM(foreman)-
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.04.04 at 11:02:42 PM EDT
//
package com.ibm.jbatch.jsl.model;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Properties complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Properties">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="property" type="{http://xmlns.jcp.org/xml/ns/javaee}Property" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="partition" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Properties", propOrder = {
"propertyList"
})
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2013-04-04T11:02:42-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public class JSLProperties {
@XmlElement(name = "property")
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2013-04-04T11:02:42-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected List<Property> propertyList;
@XmlAttribute(name = "partition")
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2013-04-04T11:02:42-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected String partition;
/**
* Gets the value of the propertyList property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the propertyList property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPropertyList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Property }
*
*
*/
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2013-04-04T11:02:42-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public List<Property> getPropertyList() {
if (propertyList == null) {
propertyList = new ArrayList<Property>();
}
return this.propertyList;
}
/**
* Gets the value of the partition property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2013-04-04T11:02:42-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public String getPartition() {
return partition;
}
/**
* Sets the value of the partition property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2013-04-04T11:02:42-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public void setPartition(String value) {
this.partition = value;
}
/*
* Appended by build tooling.
*/
public String toString() {
StringBuffer buf = new StringBuffer(140);
buf.append("JSL Properties: ");
List<Property> propList = getPropertyList();
if (propList.size() == 0) {
buf.append("<no properties>");
} else {
for (Property p : propList) {
buf.append(p.toString() + "\n");
}
}
return buf.toString();
}
} | apache-2.0 |
prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/XQueryVariablePropertiesEditionPart.java | 2286 | /**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts;
// Start of user code for imports
import org.eclipse.emf.common.util.Enumerator;
import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty;
// End of user code
/**
*
*
*/
public interface XQueryVariablePropertiesEditionPart {
/**
* @return the variableName
*
*/
public String getVariableName();
/**
* Defines a new variableName
* @param newValue the new variableName to set
*
*/
public void setVariableName(String newValue);
/**
* @return the variableType
*
*/
public Enumerator getVariableType();
/**
* Init the variableType
* @param input the viewer input
* @param current the current value
*/
public void initVariableType(Object input, Enumerator current);
/**
* Defines a new variableType
* @param newValue the new variableType to set
*
*/
public void setVariableType(Enumerator newValue);
/**
* @return the valueType
*
*/
public Enumerator getValueType();
/**
* Init the valueType
* @param input the viewer input
* @param current the current value
*/
public void initValueType(Object input, Enumerator current);
/**
* Defines a new valueType
* @param newValue the new valueType to set
*
*/
public void setValueType(Enumerator newValue);
/**
* @return the valueLiteral
*
*/
public String getValueLiteral();
/**
* Defines a new valueLiteral
* @param newValue the new valueLiteral to set
*
*/
public void setValueLiteral(String newValue);
// Start of user code for valueExpression specific getters and setters declaration
public void setValueExpression(NamespacedProperty namespacedProperty);
public NamespacedProperty getValueExpression();
// End of user code
// Start of user code for valueKey specific getters and setters declaration
public void setValueKey(RegistryKeyProperty registryKeyProperty);
public RegistryKeyProperty getValueKey();
// End of user code
/**
* Returns the internationalized title text.
*
* @return the internationalized title text.
*
*/
public String getTitle();
// Start of user code for additional methods
// End of user code
}
| apache-2.0 |
mcraken/platform | repository/src/main/java/org/cradle/repository/cassandra/CassandraRowMapper.java | 1377 | /**
* Copyright mcplissken.
*
* 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.cradle.repository.cassandra;
import org.cradle.repository.BasicRowMapper;
import org.springframework.cassandra.core.RowMapper;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.exceptions.DriverException;
/**
* @author Sherief Shawky
* @email mcrakens@gmail.com
* @date Jan 26, 2015
*/
public class CassandraRowMapper<T> implements RowMapper<T>{
private BasicRowMapper<T> rowMapper;
public CassandraRowMapper(BasicRowMapper<T> rowMapper) {
this.rowMapper = rowMapper;
}
/* (non-Javadoc)
* @see org.springframework.cassandra.core.RowMapper#mapRow(com.datastax.driver.core.Row, int)
*/
@Override
public T mapRow(Row row, int rowNum) throws DriverException {
return rowMapper.map(new CassandraRowAdapter(row));
}
}
| apache-2.0 |
astrapi69/jaulp.wicket | jaulp-wicket-dialogs/src/main/java/de/alpharogroup/wicket/dialogs/ajax/modal/BaseModalPanel.java | 5580 | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.wicket.dialogs.ajax.modal;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import de.alpharogroup.wicket.base.BasePanel;
import de.alpharogroup.wicket.components.factory.ComponentFactory;
import lombok.Getter;
/**
* The Class {@link BaseModalPanel}.
*
* @param <T>
* the generic type
*/
public abstract class BaseModalPanel<T> extends BasePanel<T>
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/** The form. */
private Form<T> form;
/** The note. */
private TextArea<String> note;
/** The cancel. */
@Getter
private AjaxButton cancel;
/** The ok. */
@Getter
private AjaxButton ok;
/**
* Instantiates a new {@link BaseModalPanel}.
*
* @param id
* the id
* @param model
* the model
*/
public BaseModalPanel(final String id, final IModel<T> model)
{
super(id, model);
setOutputMarkupId(true);
add(form = newForm("form", model));
form.add(note = newTextArea("messageContent", model));
form.add(cancel = newCancelButton("cancelButton"));
form.add(ok = newOkButton("okButton"));
}
/**
* Factory method for creating the new cancel {@link AjaxButton}. This method is invoked in the
* constructor from the derived classes and can be overridden so users can provide their own
* version of a new cancel {@link AjaxButton}.
*
* @param id
* the id
* @return the new cancel {@link AjaxButton}
*/
protected AjaxButton newCancelButton(final String id)
{
final AjaxButton close = new AjaxButton(id)
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected void onError(final AjaxRequestTarget target, final Form<?> form)
{
target.add(note);
onCancel(target);
}
/**
* {@inheritDoc}
*/
@Override
public void onSubmit(final AjaxRequestTarget target, final Form<?> form)
{
target.add(note);
onCancel(target);
}
};
return close;
}
/**
* Factory method for create the new {@link Form}. This method is invoked in the constructor
* from the derived classes and can be overridden so users can provide their own version of a
* new {@link Form}.
*
* @param id
* the id
* @param model
* the model
* @return the new {@link Form}
*/
protected Form<T> newForm(final String id, final IModel<T> model)
{
return ComponentFactory.newForm(id, model);
}
/**
* Factory method for creating the new ok {@link AjaxButton}. This method is invoked in the
* constructor from the derived classes and can be overridden so users can provide their own
* version of a new ok {@link AjaxButton}.
*
* @param id
* the id
* @return the new ok {@link AjaxButton}
*/
protected AjaxButton newOkButton(final String id)
{
final AjaxButton ok = new AjaxButton(id)
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected void onError(final AjaxRequestTarget target, final Form<?> form)
{
final T obj = BaseModalPanel.this.getModelObject();
onSelect(target, obj);
}
/**
* {@inheritDoc}
*/
@Override
protected void onSubmit(final AjaxRequestTarget target, final Form<?> form)
{
final T obj = BaseModalPanel.this.getModelObject();
onSelect(target, obj);
}
};
return ok;
}
/**
* Factory method for create the new {@link TextArea}. This method is invoked in the constructor
* from the derived classes and can be overridden so users can provide their own version of a
* new {@link TextArea}.
*
* @param id
* the id
* @param model
* the model
* @return the new {@link TextArea}
*/
protected TextArea<String> newTextArea(final String id, final IModel<T> model)
{
return ComponentFactory.newTextArea(id, new PropertyModel<String>(model, "messageContent"));
}
/**
* Abstract callback method that have to be overwritten to provide specific action for cancel.
*
* @param target
* the target
*/
protected abstract void onCancel(final AjaxRequestTarget target);
/**
* Abstract callback method that have to be overwritten to provide specific action for select.
*
* @param target
* the target
* @param object
* the object
*/
protected abstract void onSelect(final AjaxRequestTarget target, final T object);
}
| apache-2.0 |
jandockx/ppwcode-recovered-from-google-code | java/vernacular/value/trunk/src/main/java/org/ppwcode/vernacular/value_III/dwr/ImmutableValueConverter.java | 13043 | /*<license>
Copyright 2004 - $Date$ by PeopleWare n.v..
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
</license>*/
package org.ppwcode.vernacular.value_III.dwr;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import static org.ppwcode.metainfo_I.License.Type.APACHE_V2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import org.directwebremoting.convert.BaseV20Converter;
import org.directwebremoting.convert.BeanConverter;
import org.directwebremoting.dwrp.ObjectOutboundVariable;
import org.directwebremoting.dwrp.ParseUtil;
import org.directwebremoting.dwrp.ProtocolConstants;
import org.directwebremoting.extend.ConverterManager;
import org.directwebremoting.extend.InboundContext;
import org.directwebremoting.extend.InboundVariable;
import org.directwebremoting.extend.MarshallException;
import org.directwebremoting.extend.NamedConverter;
import org.directwebremoting.extend.OutboundContext;
import org.directwebremoting.extend.OutboundVariable;
import org.directwebremoting.extend.Property;
import org.directwebremoting.extend.TypeHintContext;
import org.directwebremoting.util.LocalUtil;
import org.directwebremoting.util.Logger;
import org.directwebremoting.util.Messages;
import org.ppwcode.metainfo_I.Copyright;
import org.ppwcode.metainfo_I.License;
import org.ppwcode.metainfo_I.vcs.SvnInfo;
import org.ppwcode.util.reflect_I.InstanceHelpers;
@Copyright("2004 - $Date$, PeopleWare n.v.")
@License(APACHE_V2)
@SvnInfo(revision = "$Revision$",
date = "$Date$")
public class ImmutableValueConverter extends BaseV20Converter implements NamedConverter {
private static final Logger log = Logger.getLogger(ImmutableValueConverter.class);
/* (non-Javadoc)
* @see org.directwebremoting.Converter#convertInbound(java.lang.Class, org.directwebremoting.InboundVariable, org.directwebremoting.InboundContext)
*/
public Object convertInbound(Class paramType, InboundVariable iv, InboundContext inctx) throws MarshallException
{
String value = iv.getValue();
// If the text is null then the whole bean is null
if (value.trim().equals(ProtocolConstants.INBOUND_NULL))
{
return null;
}
if (!value.startsWith(ProtocolConstants.INBOUND_MAP_START))
{
throw new MarshallException(paramType, Messages.getString("BeanConverter.FormatError", ProtocolConstants.INBOUND_MAP_START));
}
if (!value.endsWith(ProtocolConstants.INBOUND_MAP_END))
{
throw new MarshallException(paramType, Messages.getString("BeanConverter.FormatError", ProtocolConstants.INBOUND_MAP_START));
}
value = value.substring(1, value.length() - 1);
// first mark the current object as converted by adding it in the working map -> we need a reference :(
// next convert the given properties in the given order
// finally call the constructor with the properties in the given order as parameters
try
{
Object obj = null;
Map<String, Object> args = new HashMap<String, Object>();
// we cannot mark the current object as converted yet by adding it in the working map:
// the reason is that we cannot use a default constructor
// we will add the object to the working map, after we finished converting it
// since we are working depth-first, this simply means that we cannot handle circular
// references, which should not be a problem for the aimed usage
Map<String, Property> properties = null;
if (instanceType != null) {
properties = getPropertyMapFromClass(instanceType, false, true);
} else {
properties = getPropertyMapFromClass(paramType, false, true);
}
// Loop through the properties passed in
Map<String, String> tokens = extractInboundTokens(paramType, value);
for (Iterator<Map.Entry<String, String>> it = tokens.entrySet().iterator(); it.hasNext();)
{
Map.Entry<String, String> entry = it.next();
String key = entry.getKey();
String val = entry.getValue();
Property property = properties.get(key);
if (property == null)
{
log.warn("Missing property to match javascript property: " + key + ".");
StringBuffer all = new StringBuffer();
for (Iterator<String> pit = properties.keySet().iterator(); pit.hasNext();)
{
all.append(pit.next());
if (pit.hasNext())
{
all.append(',');
}
}
log.warn("Fields exist for (" + all + ").");
continue;
}
Class propType = property.getPropertyType();
String[] split = ParseUtil.splitInbound(val);
String splitValue = split[LocalUtil.INBOUND_INDEX_VALUE];
String splitType = split[LocalUtil.INBOUND_INDEX_TYPE];
InboundVariable nested = new InboundVariable(iv.getLookup(), null, splitType, splitValue);
TypeHintContext incc = createTypeHintContext(inctx, property);
Object output = converterManager.convertInbound(propType, nested, inctx, incc);
// adding in argument map
args.put(key, output);
}
// build argument list for constructor
Object[] arguments = new Object[fields.size()];
int i = 0;
for (String arg : fields) {
arguments[i] = args.get(arg);
i++;
}
if (instanceType != null) {
obj = InstanceHelpers.robustNewInstance(instanceType, arguments);
inctx.addConverted(iv, instanceType, obj);
}
else
{
obj = InstanceHelpers.robustNewInstance(paramType, arguments);
inctx.addConverted(iv, paramType, obj);
}
return obj;
}
catch (MarshallException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new MarshallException(paramType, ex);
}
}
/**
* {@link #convertInbound(Class, InboundVariable, InboundContext)} needs to
* create a {@link TypeHintContext} for the {@link Property} it is
* converting so that the type guessing system can do its work.
* <p>The method of generating a {@link TypeHintContext} is different for
* the {@link BeanConverter} and the {@link ObjectConverter}.
* @param inctx The parent context
* @param property The property being converted
* @return The new TypeHintContext
*/
protected TypeHintContext createTypeHintContext(InboundContext inctx, Property property) {
return inctx.getCurrentTypeHintContext();
}
/* (non-Javadoc)
* @see org.directwebremoting.Converter#convertOutbound(java.lang.Object, org.directwebremoting.OutboundContext)
*/
public OutboundVariable convertOutbound(Object data, OutboundContext outctx) throws MarshallException
{
// Where we collect out converted children
Map<String, OutboundVariable> ovs = new TreeMap<String, OutboundVariable>();
// We need to do this before collecing the children to save recurrsion
ObjectOutboundVariable ov = new ObjectOutboundVariable(outctx);
outctx.put(data, ov);
try
{
Map<String, Property> properties = getPropertyMapFromObject(data, true, false);
for (Iterator<Map.Entry<String, Property>> it = properties.entrySet().iterator(); it.hasNext();)
{
Map.Entry<String, Property> entry = it.next();
String name = entry.getKey();
Property property = entry.getValue();
Object value = property.getValue(data);
OutboundVariable nested = getConverterManager().convertOutbound(value, outctx);
ovs.put(name, nested);
}
}
catch (MarshallException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new MarshallException(data.getClass(), ex);
}
ov.init(ovs, getJavascript());
return ov;
}
public Map<String, Property> getPropertyMapFromClass(Class type, boolean readRequired, boolean writeRequired) throws MarshallException {
try {
BeanInfo info = Introspector.getBeanInfo(type);
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
Map<String, Property> properties = new HashMap<String, Property>();
for (int i = 0; i < descriptors.length; i++) {
PropertyDescriptor descriptor = descriptors[i];
String name = descriptor.getName();
// only store properties for names that are also in the fields parameter
if (fields.contains(name)) {
properties.put(name, new ImmutableValueProperty(descriptor));
}
}
return properties;
} catch (IntrospectionException exc) {
throw new MarshallException(type, exc);
}
}
public Map<String, Property> getPropertyMapFromObject(Object example, boolean readRequired, boolean writeRequired) throws MarshallException {
return getPropertyMapFromClass(example.getClass(), readRequired, writeRequired);
}
/**
* Set a list of properties included from conversion
* @param includes The space or comma separated list of properties to exclude
*/
public void setFields(String paramFields)
{
if ((paramFields == null) || (paramFields.equals("")))
{
throw new IllegalArgumentException("Fields should not be empty.");
}
fields = new ArrayList<String>();
String toSplit = LocalUtil.replace(paramFields, ",", " ");
StringTokenizer st = new StringTokenizer(toSplit);
while (st.hasMoreTokens())
{
String field = st.nextToken();
if (field.startsWith("get"))
{
log.warn("Fields are based on property names and not method names. '" + field + "' starts with 'get' so it looks like a method name and not a property name.");
}
fields.add(field);
}
}
protected List<String> fields;
/**
* Loop over all the inputs and extract a Map of key:value pairs
* @param paramType The type we are converting to
* @param value The input string
* @return A Map of the tokens in the string
* @throws MarshallException If the marshalling fails
*/
protected Map<String, String> extractInboundTokens(Class paramType, String value) throws MarshallException
{
Map<String, String> tokens = new HashMap<String, String>();
StringTokenizer st = new StringTokenizer(value, ProtocolConstants.INBOUND_MAP_SEPARATOR);
int size = st.countTokens();
for (int i = 0; i < size; i++)
{
String token = st.nextToken();
if (token.trim().length() == 0)
{
continue;
}
int colonpos = token.indexOf(ProtocolConstants.INBOUND_MAP_ENTRY);
if (colonpos == -1)
{
throw new MarshallException(paramType, Messages.getString("BeanConverter.MissingSeparator", ProtocolConstants.INBOUND_MAP_ENTRY, token));
}
String key = token.substring(0, colonpos).trim();
String val = token.substring(colonpos + 1).trim();
tokens.put(key, val);
}
return tokens;
}
public String getJavascript()
{
return javascript;
}
public void setJavascript(String javascript)
{
this.javascript = javascript;
}
/**
* The javascript class name for the converted objects
*/
protected String javascript;
public Class getInstanceType()
{
return instanceType;
}
public void setInstanceType(Class instanceType)
{
this.instanceType = instanceType;
}
/**
* A type that allows us to fulfill an interface or subtype requirement
*/
protected Class instanceType = null;
public void setConverterManager(ConverterManager converterManager)
{
this.converterManager = converterManager;
}
public ConverterManager getConverterManager()
{
return converterManager;
}
/**
* To forward marshalling requests
*/
protected ConverterManager converterManager = null;
}
| apache-2.0 |
fengyouchao/fucksocks | src/main/java/sockslib/server/SessionManager.java | 1999 | package sockslib.server;
import sockslib.server.listener.CloseSessionException;
import sockslib.server.listener.CommandListener;
import sockslib.server.listener.ExceptionListener;
import sockslib.server.listener.SessionCloseListener;
import sockslib.server.listener.SessionCreateListener;
import sockslib.server.listener.SessionListener;
import sockslib.server.msg.CommandMessage;
import java.net.Socket;
import java.util.Map;
/**
* The interface <code>SessionManager</code> represents a session manager.
*
* @author Youchao Feng
* @version 1.0
* @date Sep 30, 2015 12:36 PM
*/
public interface SessionManager {
/**
* Create a new {@link Session}.
*
* @param socket socket.
* @return session.
*/
Session newSession(Socket socket);
/**
* Returns the session by giving a id.
*
* @param id id of session.
* @return session.
*/
Session getSession(long id);
void sessionOnCreate(Session session) throws CloseSessionException;
void sessionOnCommand(Session session, CommandMessage message) throws CloseSessionException;
void sessionOnException(Session session, Exception exception);
void sessionOnClose(Session session);
/**
* Remove a {@link SessionListener} by name.
*
* @param name name of {@link SessionListener}.
*/
void removeSessionListener(String name);
/**
* Add a {@link SessionListener}.
*
* @param name name of {@link SessionListener}.
* @param listener instance of {@link SessionListener}.
*/
void addSessionListener(String name, SessionListener listener);
/**
* Returns all managed sessions.
*
* @return all managed sessions.
*/
Map<Long, Session> getManagedSessions();
SessionManager onSessionClose(String name, SessionCloseListener listener);
SessionManager onSessionCreate(String name, SessionCreateListener listener);
SessionManager onCommand(String name, CommandListener listener);
SessionManager onException(String name, ExceptionListener listener);
}
| apache-2.0 |
leafclick/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/optionalToIf/beforePreserveComments.java | 674 | // "Fix all 'Optional can be replaced with sequence of if statements' problems in file" "true"
import java.util.*;
class Test {
private LicenseManager ourInstance = null;
LicenseManager setInstance(LicenseManager instance) {
LicenseManager old = this.ourInstance;
this.ourInstance = instance;
return old;
}
private static interface LicenseManager {
}
private static class IdeaLicenseManager implements LicenseManager {
}
public LicenseManager getInstance() {
final LicenseManager instance = ourInstance;
return/*1*/ Optional.ofNul<caret>lable(instance/*2*/).orElseGet(() -> setInstance(new IdeaLicenseManager(/*3*/))) /*4*/;
}
} | apache-2.0 |
gpolitis/libjitsi | src/org/jitsi/impl/neomedia/recording/RecorderEventHandlerJSONImpl.java | 7320 | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.impl.neomedia.recording;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.recording.*;
import org.jitsi.util.*;
import org.json.simple.*;
import java.io.*;
import java.util.*;
/**
* Implements a <tt>RecorderEventHandler</tt> which handles
* <tt>RecorderEvents</tt> by writing them to a file in JSON format.
*
* @author Boris Grozev
*/
public class RecorderEventHandlerJSONImpl
implements RecorderEventHandler
{
/**
* The <tt>Logger</tt> used by the <tt>RecorderEventHandlerJSONImpl</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(RecorderEventHandlerJSONImpl.class);
/**
* Compares <tt>RecorderEvent</tt>s by their instant (e.g. timestamp).
*/
private static final Comparator<RecorderEvent> eventComparator
= new Comparator<RecorderEvent>() {
@Override
public int compare(RecorderEvent a, RecorderEvent b)
{
return ((Long)a.getInstant()).compareTo(b.getInstant());
}
};
File file;
private boolean closed = false;
private final List<RecorderEvent> audioEvents
= new LinkedList<RecorderEvent>();
private final List<RecorderEvent> videoEvents
= new LinkedList<RecorderEvent>();
/**
* {@inheritDoc}
*/
public RecorderEventHandlerJSONImpl(String filename)
throws IOException
{
file = new File(filename);
if (!file.createNewFile())
throw new IOException("File exists or cannot be created: " + file);
if (!file.canWrite())
throw new IOException("Cannot write to file: " + file);
}
/**
* {@inheritDoc}
*/
@Override
public synchronized boolean handleEvent(RecorderEvent ev)
{
if (closed)
return false;
MediaType mediaType = ev.getMediaType();
RecorderEvent.Type type = ev.getType();
long duration = ev.getDuration();
long ssrc = ev.getSsrc();
/*
* For a RECORDING_ENDED event without a valid instant, find it's
* associated (i.e. with the same SSRC) RECORDING_STARTED event and
* compute the RECORDING_ENDED instance based on its duration.
*/
if (RecorderEvent.Type.RECORDING_ENDED.equals(type)
&& ev.getInstant() == -1
&& duration != -1)
{
List<RecorderEvent> events =
MediaType.AUDIO.equals(mediaType)
? audioEvents
: videoEvents;
RecorderEvent start = null;
for (RecorderEvent e : events)
{
if (RecorderEvent.Type.RECORDING_STARTED.equals(e.getType())
&& e.getSsrc() == ssrc)
{
start = e;
break;
}
}
if (start != null)
ev.setInstant(start.getInstant() + duration);
}
if (MediaType.AUDIO.equals(mediaType))
audioEvents.add(ev);
else if (MediaType.VIDEO.equals(mediaType))
videoEvents.add(ev);
try
{
writeAllEvents();
}
catch (IOException ioe)
{
logger.warn("Failed to write recorder events to file: ", ioe);
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void close()
{
//XXX do we want to write everything again?
try
{
writeAllEvents();
}
catch (IOException ioe)
{
logger.warn("Failed to write recorder events to file: " + ioe);
}
finally
{
closed = true;
}
}
private void writeAllEvents()
throws IOException
{
Collections.sort(audioEvents, eventComparator);
Collections.sort(videoEvents, eventComparator);
int nbAudio = audioEvents.size();
int nbVideo = videoEvents.size();
if (nbAudio + nbVideo > 0)
{
FileWriter writer = new FileWriter(file, false);
writer.write("{\n");
if (nbAudio > 0)
{
writer.write(" \"audio\" : [\n");
writeEvents(audioEvents, writer);
if (nbVideo > 0)
writer.write(" ],\n\n");
else
writer.write(" ]\n\n");
}
if (nbVideo > 0)
{
writer.write(" \"video\" : [\n");
writeEvents(videoEvents, writer);
writer.write(" ]\n");
}
writer.write("}\n");
writer.close();
}
}
private void writeEvents(List<RecorderEvent> events,
FileWriter writer)
throws IOException
{
int idx = 0;
int size = events.size();
for (RecorderEvent ev : events)
{
if (++idx == size)
writer.write(" " + getJSON(ev) + "\n");
else
writer.write(" " + getJSON(ev)+",\n");
}
}
@SuppressWarnings("unchecked")
private String getJSON(RecorderEvent ev)
{
JSONObject json = new JSONObject();
json.put("instant", ev.getInstant());
json.put("type", ev.getType().toString());
MediaType mediaType = ev.getMediaType();
if (mediaType != null)
json.put("mediaType", mediaType.toString());
json.put("ssrc", ev.getSsrc());
long audioSsrc = ev.getAudioSsrc();
if (audioSsrc != -1)
json.put("audioSsrc", audioSsrc);
RecorderEvent.AspectRatio aspectRatio = ev.getAspectRatio();
if (aspectRatio != RecorderEvent.AspectRatio.ASPECT_RATIO_UNKNOWN)
json.put("aspectRatio", aspectRatio.toString());
long rtpTimestamp = ev.getRtpTimestamp();
if (rtpTimestamp != -1)
json.put("rtpTimestamp", rtpTimestamp);
String endpointId = ev.getEndpointId();
if (endpointId != null)
json.put("endpointId", endpointId);
String filename = ev.getFilename();
if (filename != null)
{
String bareFilename = filename;
int idx = filename.lastIndexOf('/');
int len = filename.length();
if (idx != -1 && idx != len-1)
bareFilename = filename.substring(1 + idx, len);
json.put("filename", bareFilename);
}
return json.toJSONString();
}
}
| apache-2.0 |
maximegens/ng-cordova-demo | plugins/com.phonegap.plugins.barcodescanner/src/android/LibraryProject/src/com/google/zxing/client/result/AddressBookAUResultParser.java | 3537 | /*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.result;
import com.google.zxing.Result;
import java.util.ArrayList;
import java.util.List;
/**
* Implements KDDI AU's address book format. See
* <a href="http://www.au.kddi.com/ezfactory/tec/two_dimensions/index.html">
* http://www.au.kddi.com/ezfactory/tec/two_dimensions/index.html</a>.
* (Thanks to Yuzo for translating!)
*
* @author Sean Owen
*/
public final class AddressBookAUResultParser extends ResultParser {
@Override
public AddressBookParsedResult parse(Result result) {
String rawText = getMassagedText(result);
// MEMORY is mandatory; seems like a decent indicator, as does end-of-record separator CR/LF
if (!rawText.contains("MEMORY") || !rawText.contains("\r\n")) {
return null;
}
// NAME1 and NAME2 have specific uses, namely written name and pronunciation, respectively.
// Therefore we treat them specially instead of as an array of names.
String name = matchSinglePrefixedField("NAME1:", rawText, '\r', true);
String pronunciation = matchSinglePrefixedField("NAME2:", rawText, '\r', true);
String[] phoneNumbers = matchMultipleValuePrefix("TEL", 3, rawText, true);
String[] emails = matchMultipleValuePrefix("MAIL", 3, rawText, true);
String note = matchSinglePrefixedField("MEMORY:", rawText, '\r', false);
String address = matchSinglePrefixedField("ADD:", rawText, '\r', true);
String[] addresses = address == null ? null : new String[] {address};
return new AddressBookParsedResult(maybeWrap(name),
pronunciation,
phoneNumbers,
null,
emails,
null,
null,
note,
addresses,
null,
null,
null,
null,
null);
}
private static String[] matchMultipleValuePrefix(String prefix,
int max,
String rawText,
boolean trim) {
List<String> values = null;
for (int i = 1; i <= max; i++) {
String value = matchSinglePrefixedField(prefix + i + ':', rawText, '\r', trim);
if (value == null) {
break;
}
if (values == null) {
values = new ArrayList<String>(max); // lazy init
}
values.add(value);
}
if (values == null) {
return null;
}
return values.toArray(new String[values.size()]);
}
}
| apache-2.0 |
gpolitis/libjitsi | src/org/jitsi/impl/neomedia/transform/zrtp/ZrtpControlImpl.java | 11711 | /*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.impl.neomedia.transform.zrtp;
import gnu.java.zrtp.*;
import gnu.java.zrtp.utils.*;
import java.util.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.service.neomedia.*;
/**
* Controls zrtp in the MediaStream.
*
* @author Damian Minkov
*/
public class ZrtpControlImpl
extends AbstractSrtpControl<ZRTPTransformEngine>
implements ZrtpControl
{
/**
* Additional info codes for and data to support ZRTP4J.
* These could be added to the library. However they are specific for this
* implementation, needing them for various GUI changes.
*/
public static enum ZRTPCustomInfoCodes
{
ZRTPDisabledByCallEnd,
ZRTPEnabledByDefault,
ZRTPEngineInitFailure,
ZRTPNotEnabledByUser
}
/**
* Whether current is master session.
*/
private boolean masterSession = false;
/**
* This is the connector, required to send ZRTP packets
* via the DatagramSocket.
*/
private AbstractRTPConnector zrtpConnector = null;
/**
* Creates the control.
*/
public ZrtpControlImpl()
{
super(SrtpControlType.ZRTP);
}
/**
* Cleans up the current zrtp control and its engine.
*/
@Override
public void cleanup(Object user)
{
super.cleanup(user);
zrtpConnector = null;
}
/*
* (non-Javadoc)
*
* @see
* net.java.sip.communicator.service.neomedia.ZrtpControl#getCiperString()
*/
public String getCipherString()
{
return getTransformEngine().getUserCallback().getCipherString();
}
/**
* Get negotiated ZRTP protocol version.
*
* @return the integer representation of the negotiated ZRTP protocol version.
*/
public int getCurrentProtocolVersion()
{
ZRTPTransformEngine zrtpEngine = this.transformEngine;
return
(zrtpEngine != null) ? zrtpEngine.getCurrentProtocolVersion() : 0;
}
/**
* Return the zrtp hello hash String.
*
* @param index
* Hello hash of the Hello packet identfied by index. Index must
* be 0 <= index < SUPPORTED_ZRTP_VERSIONS.
* @return String the zrtp hello hash.
*/
public String getHelloHash(int index)
{
return getTransformEngine().getHelloHash(index);
}
/**
* Get the ZRTP Hello Hash data - separate strings.
*
* @param index
* Hello hash of the Hello packet identfied by index. Index must
* be 0 <= index < SUPPORTED_ZRTP_VERSIONS.
* @return String array containing the version string at offset 0, the Hello
* hash value as hex-digits at offset 1. Hello hash is available
* immediately after class instantiation. Returns <code>null</code>
* if ZRTP is not available.
*/
public String[] getHelloHashSep(int index)
{
return getTransformEngine().getHelloHashSep(index);
}
/**
* Get number of supported ZRTP protocol versions.
*
* @return the number of supported ZRTP protocol versions.
*/
public int getNumberSupportedVersions()
{
ZRTPTransformEngine zrtpEngine = this.transformEngine;
return
(zrtpEngine != null) ? zrtpEngine.getNumberSupportedVersions() : 0;
}
/**
* Get the peer's Hello Hash data.
*
* Use this method to get the peer's Hello Hash data. The method returns the
* data as a string.
*
* @return a String containing the Hello hash value as hex-digits.
* Peer Hello hash is available after we received a Hello packet
* from our peer. If peer's hello hash is not available return null.
*/
public String getPeerHelloHash() {
ZRTPTransformEngine zrtpEngine = this.transformEngine;
return (zrtpEngine != null) ? zrtpEngine.getPeerHelloHash() : "";
}
/*
* (non-Javadoc)
*
* @see
* net.java.sip.communicator.service.neomedia.ZrtpControl#getPeerZid
* ()
*/
public byte[] getPeerZid()
{
return getTransformEngine().getPeerZid();
}
/*
* (non-Javadoc)
*
* @see
* net.java.sip.communicator.service.neomedia.ZrtpControl#getPeerZidString()
*/
public String getPeerZidString()
{
byte[] zid = getPeerZid();
String s = new String(ZrtpUtils.bytesToHexString(zid, zid.length));
return s;
}
/**
* Method for getting the default secure status value for communication
*
* @return the default enabled/disabled status value for secure
* communication
*/
public boolean getSecureCommunicationStatus()
{
ZRTPTransformEngine zrtpEngine = this.transformEngine;
return
(zrtpEngine != null) && zrtpEngine.getSecureCommunicationStatus();
}
/*
* (non-Javadoc)
*
* @see
* net.java.sip.communicator.service.neomedia.ZrtpControl#getSecurityString
* ()
*/
public String getSecurityString()
{
return getTransformEngine().getUserCallback().getSecurityString();
}
/**
* Returns the timeout value that will we will wait
* and fire timeout secure event if call is not secured.
* The value is in milliseconds.
* @return the timeout value that will we will wait
* and fire timeout secure event if call is not secured.
*/
public long getTimeoutValue()
{
// this is the default value as mentioned in rfc6189
// we will later grab this setting from zrtp
return 3750;
}
/**
* Initializes a new <tt>ZRTPTransformEngine</tt> instance to be associated
* with and used by this <tt>ZrtpControlImpl</tt> instance.
*
* @return a new <tt>ZRTPTransformEngine</tt> instance to be associated with
* and used by this <tt>ZrtpControlImpl</tt> instance
*/
protected ZRTPTransformEngine createTransformEngine()
{
ZRTPTransformEngine transformEngine = new ZRTPTransformEngine();
// NOTE: set paranoid mode before initializing
// zrtpEngine.setParanoidMode(paranoidMode);
transformEngine.initialize(
"GNUZRTP4J.zid",
false,
ZrtpConfigureUtils.getZrtpConfiguration());
transformEngine.setUserCallback(new SecurityEventManager(this));
return transformEngine;
}
/*
* (non-Javadoc)
*
* @see
* net.java.sip.communicator.service.neomedia.ZrtpControl#isSecurityVerified
* ()
*/
public boolean isSecurityVerified()
{
return getTransformEngine().getUserCallback().isSecurityVerified();
}
/**
* Returns false, ZRTP exchanges is keys over the media path.
*
* @return false
*/
public boolean requiresSecureSignalingTransport()
{
return false;
}
/**
* Sets the <tt>RTPConnector</tt> which is to use or uses this ZRTP engine.
*
* @param connector the <tt>RTPConnector</tt> which is to use or uses this
* ZRTP engine
*/
public void setConnector(AbstractRTPConnector connector)
{
zrtpConnector = connector;
}
/**
* When in multistream mode, enables the master session.
*
* @param masterSession whether current control, controls the master session
*/
@Override
public void setMasterSession(boolean masterSession)
{
// by default its not master, change only if set to be master
// sometimes (jingle) streams are re-initing and
// we must reuse old value (true) event that false is submitted
if(masterSession)
this.masterSession = masterSession;
}
/**
* Start multi-stream ZRTP sessions. After the ZRTP Master (DH) session
* reached secure state the SCCallback calls this method to start the
* multi-stream ZRTP sessions. Enable auto-start mode (auto-sensing) to the
* engine.
*
* @param master master SRTP data
*/
@Override
public void setMultistream(SrtpControl master)
{
if(master == null || master == this)
return;
if(!(master instanceof ZrtpControlImpl))
throw new IllegalArgumentException("master is no ZRTP control");
ZrtpControlImpl zm = (ZrtpControlImpl)master;
ZRTPTransformEngine engine = getTransformEngine();
engine.setMultiStrParams(zm.getTransformEngine().getMultiStrParams());
engine.setEnableZrtp(true);
engine.getUserCallback().setMasterEventManager(
zm.getTransformEngine().getUserCallback());
}
/**
* Sets the SAS verification
*
* @param verified the new SAS verification status
*/
public void setSASVerification(boolean verified)
{
ZRTPTransformEngine engine = getTransformEngine();
if (verified)
engine.SASVerified();
else
engine.resetSASVerified();
}
/**
* Starts and enables zrtp in the stream holding this control.
* @param mediaType the media type of the stream this control controls.
*/
public void start(MediaType mediaType)
{
boolean zrtpAutoStart;
// ZRTP engine initialization
ZRTPTransformEngine engine = getTransformEngine();
// Create security user callback for each peer.
SecurityEventManager securityEventManager = engine.getUserCallback();
// Decide if this will become the ZRTP Master session:
// - Statement: audio media session will be started before video
// media session
// - if no other audio session was started before then this will
// become
// ZRTP Master session
// - only the ZRTP master sessions start in "auto-sensing" mode
// to immediately catch ZRTP communication from other client
// - after the master session has completed its key negotiation
// it will start other media sessions (see SCCallback)
if (masterSession)
{
zrtpAutoStart = true;
// we know that audio is considered as master for zrtp
securityEventManager.setSessionType(mediaType);
}
else
{
// check whether video was not already started
// it may happen when using multistreams, audio has inited
// and started video
// initially engine has value enableZrtp = false
zrtpAutoStart = transformEngine.isEnableZrtp();
securityEventManager.setSessionType(mediaType);
}
engine.setConnector(zrtpConnector);
securityEventManager.setSrtpListener(getSrtpListener());
// tells the engine whether to autostart(enable)
// zrtp communication, if false it just passes packets without
// transformation
engine.setEnableZrtp(zrtpAutoStart);
engine.sendInfo(
ZrtpCodes.MessageSeverity.Info,
EnumSet.of(ZRTPCustomInfoCodes.ZRTPEnabledByDefault));
}
}
| apache-2.0 |
quangnguyen9x/bamboobsc_quangnv | gsbsc-web/src/com/netsteadfast/greenstep/bsc/action/MeasureDataCalendarQueryAction.java | 6767 | /*
* Copyright 2012-2016 bambooCORE, greenstep of copyright Chen Xin Nien
*
* 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: Chen Xin Nien
* contact: chen.xin.nien@gmail.com
*
*/
package com.netsteadfast.greenstep.bsc.action;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.json.annotations.JSON;
import org.joda.time.DateTime;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.netsteadfast.greenstep.BscConstants;
import com.netsteadfast.greenstep.base.action.BaseJsonAction;
import com.netsteadfast.greenstep.base.exception.AuthorityException;
import com.netsteadfast.greenstep.base.exception.ControllerException;
import com.netsteadfast.greenstep.base.exception.ServiceException;
import com.netsteadfast.greenstep.base.model.ControllerAuthority;
import com.netsteadfast.greenstep.base.model.ControllerMethodAuthority;
import com.netsteadfast.greenstep.bsc.model.BscMeasureDataFrequency;
import com.netsteadfast.greenstep.bsc.util.MeasureDataCalendarUtils;
@ControllerAuthority(check=true)
@Controller("bsc.web.controller.MeasureDataCalendarQueryAction")
@Scope
public class MeasureDataCalendarQueryAction extends BaseJsonAction {
private static final long serialVersionUID = -4686051236562296624L;
protected Logger logger=Logger.getLogger(MeasureDataCalendarQueryAction.class);
private String message = "";
private String success = IS_NO;
private String body = "";
private String dateValue = "";
public MeasureDataCalendarQueryAction() {
super();
}
private void checkFields() throws ControllerException {
String oid = this.getFields().get("oid");
String dataFor = this.getFields().get("dataFor");
String organizationOid = this.getFields().get("organizationOid");
String employeeOid = this.getFields().get("employeeOid");
String frequency = this.getFields().get("frequency");
if (StringUtils.isBlank(oid) || oid.startsWith(BscConstants.KPI_TREE_NOT_ITEM)) {
super.throwMessage( "mainInfoTemp", "Please select KPI!" );
}
this.getCheckFieldHandler()
.single("employeeOid", ( BscConstants.MEASURE_DATA_FOR_EMPLOYEE.equals(dataFor) && this.isNoSelectId(employeeOid) ), this.getText("BSC_PROG002D0005Q_msg1") )
.single("frequency", (this.isNoSelectId(frequency)), this.getText("BSC_PROG002D0005Q_msg2") )
.single("organizationOid", ( BscConstants.MEASURE_DATA_FOR_ORGANIZATION.equals(dataFor) && this.isNoSelectId(organizationOid) ), this.getText("BSC_PROG002D0005Q_msg3") )
.single("dataFor", ( BscConstants.MEASURE_DATA_FOR_ALL.equals(dataFor) && !this.isNoSelectId(employeeOid) && !this.isNoSelectId(organizationOid) ), this.getText("BSC_PROG002D0005Q_msg4") )
.throwMessage();
}
private String handlerDate() throws Exception {
String dateStr = this.getFields().get("date");
String frequency = this.getFields().get("frequency");
String dateStatus = this.getFields().get("dateStatus");
DateTime dateTime = new DateTime(dateStr);
if ("-1".equals(dateStatus)) { // 上一個
if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency) ) { // 上一個月
dateTime = dateTime.plusMonths(-1);
} else { // 上一個年
dateTime = dateTime.plusYears(-1);
}
}
if ("1".equals(dateStatus)) { // 下一個
if (BscMeasureDataFrequency.FREQUENCY_DAY.equals(frequency) || BscMeasureDataFrequency.FREQUENCY_WEEK.equals(frequency) ) { // 下一個月
dateTime = dateTime.plusMonths(1);
} else { // 下一個年
dateTime = dateTime.plusYears(1);
}
}
return dateTime.toString("yyyy-MM-dd");
}
private Map<String, String> getLabels() {
Map<String, String> labels = new HashMap<String, String>();
labels.put("management", this.getText("TPL.BSC_PROG002D0005Q_management"));
labels.put("calculation", this.getText("TPL.BSC_PROG002D0005Q_calculation"));
labels.put("unit", this.getText("TPL.BSC_PROG002D0005Q_unit"));
labels.put("target", this.getText("TPL.BSC_PROG002D0005Q_target"));
labels.put("min", this.getText("TPL.BSC_PROG002D0005Q_min"));
labels.put("formulaName", this.getText("TPL.BSC_PROG002D0005Q_formulaName"));
labels.put("targetValueName", this.getText("TPL.BSC_PROG002D0005Q_targetValueName"));
labels.put("actualValueName", this.getText("TPL.BSC_PROG002D0005Q_actualValueName"));
return labels;
}
private void renderCalendar() throws ControllerException, ServiceException, Exception {
this.checkFields();
this.dateValue = this.handlerDate();
this.body = MeasureDataCalendarUtils.renderBody(
this.getFields().get("oid"),
this.dateValue,
this.getFields().get("frequency"),
this.getFields().get("dataFor"),
this.getFields().get("organizationOid"),
this.getFields().get("employeeOid"),
this.getLabels());
this.success = IS_YES;
}
/**
* bsc.measureDataCalendarQueryAction.action
*
* @return
* @throws Exception
*/
@ControllerMethodAuthority(programId="BSC_PROG002D0005Q")
public String execute() throws Exception {
try {
if (!this.allowJob()) {
this.message = this.getNoAllowMessage();
return SUCCESS;
}
this.renderCalendar();
} catch (AuthorityException | ControllerException | ServiceException e) {
this.message = e.getMessage().toString();
} catch (Exception e) {
this.message = this.logException(e);
this.success = IS_EXCEPTION;
}
return SUCCESS;
}
@JSON
@Override
public String getLogin() {
return super.isAccountLogin();
}
@JSON
@Override
public String getIsAuthorize() {
return super.isActionAuthorize();
}
@JSON
@Override
public String getMessage() {
return this.message;
}
@JSON
@Override
public String getSuccess() {
return this.success;
}
@JSON
@Override
public List<String> getFieldsId() {
return this.fieldsId;
}
public String getBody() {
return body;
}
public String getDateValue() {
return dateValue;
}
@JSON
@Override
public Map<String, String> getFieldsMessage() {
return this.fieldsMessage;
}
}
| apache-2.0 |
wjw465150/jodd | jodd-db/src/main/java/jodd/db/oom/DbMetaUtil.java | 5929 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.db.oom;
import jodd.db.oom.meta.DbColumn;
import jodd.db.oom.meta.DbId;
import jodd.db.oom.meta.DbMapTo;
import jodd.db.oom.meta.DbTable;
import jodd.db.oom.naming.ColumnNamingStrategy;
import jodd.db.oom.naming.TableNamingStrategy;
import jodd.db.type.SqlType;
import jodd.introspector.PropertyDescriptor;
/**
* Meta-data resolving utils.
*/
public class DbMetaUtil {
/**
* Resolves table name from a type. If type is annotated, table name
* will be read from annotation value. If this value is empty or if
* type is not annotated, table name will be set to wildcard pattern '*'
* (to match all tables).
*/
public static String resolveTableName(Class<?> type, TableNamingStrategy tableNamingStrategy) {
String tableName = null;
DbTable dbTable = type.getAnnotation(DbTable.class);
if (dbTable != null) {
tableName = dbTable.value().trim();
}
if ((tableName == null) || (tableName.length() == 0)) {
tableName = tableNamingStrategy.convertEntityNameToTableName(type);
} else {
if (!tableNamingStrategy.isStrictAnnotationNames()) {
tableName = tableNamingStrategy.applyToTableName(tableName);
}
}
return tableName;
}
/**
* Resolves schema name from a type. Uses default schema name if not specified.
*/
public static String resolveSchemaName(Class<?> type, String defaultSchemaName) {
String schemaName = null;
DbTable dbTable = type.getAnnotation(DbTable.class);
if (dbTable != null) {
schemaName = dbTable.schema().trim();
}
if ((schemaName == null) || (schemaName.length() == 0)) {
schemaName = defaultSchemaName;
}
return schemaName;
}
/**
* Returns <code>true</code> if class is annotated with <code>DbTable</code> annotation.
*/
public static boolean resolveIsAnnotated(Class<?> type) {
DbTable dbTable = type.getAnnotation(DbTable.class);
return dbTable != null;
}
/**
* Resolves column descriptor from property. If property is annotated value will be read
* from annotation. If property is not annotated, then property will be ignored
* if entity is annotated. Otherwise, column name is generated from the property name.
*/
public static DbEntityColumnDescriptor resolveColumnDescriptors(
DbEntityDescriptor dbEntityDescriptor,
PropertyDescriptor property,
boolean isAnnotated,
ColumnNamingStrategy columnNamingStrategy) {
String columnName = null;
boolean isId = false;
Class<? extends SqlType> sqlTypeClass = null;
// read ID annotation
DbId dbId = null;
if (property.getFieldDescriptor() != null) {
dbId = property.getFieldDescriptor().getField().getAnnotation(DbId.class);
}
if (dbId == null && property.getReadMethodDescriptor() != null) {
dbId = property.getReadMethodDescriptor().getMethod().getAnnotation(DbId.class);
}
if (dbId == null && property.getWriteMethodDescriptor() != null) {
dbId = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbId.class);
}
if (dbId != null) {
columnName = dbId.value().trim();
sqlTypeClass = dbId.sqlType();
isId = true;
} else {
DbColumn dbColumn = null;
if (property.getFieldDescriptor() != null) {
dbColumn = property.getFieldDescriptor().getField().getAnnotation(DbColumn.class);
}
if (dbColumn == null && property.getReadMethodDescriptor() != null) {
dbColumn = property.getReadMethodDescriptor().getMethod().getAnnotation(DbColumn.class);
}
if (dbColumn == null && property.getWriteMethodDescriptor() != null) {
dbColumn = property.getWriteMethodDescriptor().getMethod().getAnnotation(DbColumn.class);
}
if (dbColumn != null) {
columnName = dbColumn.value().trim();
sqlTypeClass = dbColumn.sqlType();
} else {
if (isAnnotated) {
return null;
}
}
}
if ((columnName == null) || (columnName.length() == 0)) {
columnName = columnNamingStrategy.convertPropertyNameToColumnName(property.getName());
} else {
if (!columnNamingStrategy.isStrictAnnotationNames()) {
columnName = columnNamingStrategy.applyToColumnName(columnName);
}
}
if (sqlTypeClass == SqlType.class) {
sqlTypeClass = null;
}
return new DbEntityColumnDescriptor(
dbEntityDescriptor, columnName, property.getName(), property.getType(), isId, sqlTypeClass);
}
/**
* Resolves mapped types from {@link jodd.db.oom.meta.DbMapTo} annotation.
*/
public static Class[] resolveMappedTypes(Class type) {
DbMapTo dbMapTo = (DbMapTo) type.getAnnotation(DbMapTo.class);
if (dbMapTo == null) {
return null;
}
return dbMapTo.value();
}
} | bsd-2-clause |
jayfans3/example | liupeng/src/main/java/liupeng/Ch13_MobileMonitor/HBaseDao/HBaseDao.java | 505 | package HBaseIndexAndQuery.HBaseDao;
import java.io.IOException;
import java.util.List;
public abstract interface HBaseDao
{
public abstract void CreateHbaseConnect();
public abstract void CreateTable(String paramString, boolean paramBoolean);
public abstract void TableAddFaminly(String paramString1, String paramString2);
public abstract void TableAddData(String paramString1, String paramString2, String paramString3, String paramString4, byte[] paramArrayOfByte)
throws IOException;
} | bsd-2-clause |
Zabot/2015-Robot | RobotFramework/src/org/frc4931/robot/component/Solenoid.java | 1346 | /*
* FRC 4931 (http://www.evilletech.com)
*
* Open source software. Licensed under the FIRST BSD license file in the
* root directory of this project's Git repository.
*/
package org.frc4931.robot.component;
/**
* A solenoid is a device that can be extended and retracted.
*
* @author Zach Anderson
*
*/
public interface Solenoid {
static enum Direction {
EXTENDING, RETRACTING;
}
/**
* Get the current action of this solenoid.
*
* @return the current action; never null
*/
Direction getDirection();
/**
* Extends this <code>Solenoid</code>.
*/
void extend();
/**
* Retracts this <code>Solenoid</code>.
*/
void retract();
/**
* Tests if this <code>Solenoid</code> is extending.
*
* @return {@code true} if this solenoid is in the process of extending but not yet fully extended, or {@code false} otherwise
*/
default boolean isExtending() {
return getDirection() == Direction.EXTENDING;
}
/**
* Tests if this <code>Solenoid</code> is retracting.
*
* @return {@code true} if this solenoid is in the process of retracting but not yet fully retracted, or {@code false} otherwise
*/
default boolean isRetracting() {
return getDirection() == Direction.RETRACTING;
}
}
| bsd-3-clause |
NCIP/stats-analysis | cacoretoolkit 3.1/src/gov/nih/nci/system/server/mgmt/SessionMonitor.java | 1755 | /*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/stats-analysis/LICENSE.txt for details.
*/
/*
* Created on May 26, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package gov.nih.nci.system.server.mgmt;
import java.util.Iterator;
import java.util.Set;
/**
* This class is a daemon thread which runs in the background monitoring
* the {@link UserSession}. It goes through the internal cache of the
* {@link SessionManager} and removes all the sessions that have expired
*
* @author Ekagra Software Technologies Ltd.
*/
public class SessionMonitor extends Thread
{
/**
* Default Constructor. It starts the thread as a daemon running in the background
*/
public SessionMonitor()
{
this.start();
}
/**
* This methods obtains all the session keys from the {@link SessionManager}'s
* internal cache. It then retrieves the {@link UserSession} object passing each
* of the session keys. It checks if the session was last access within the timeout
* period. If not then it kills the user session.
*
* @see java.lang.Runnable#run()
*/
public void run()
{
monitor();
}
private void monitor()
{
SessionManager sessionManager = SessionManager.getInstance();
Set keys = sessionManager.getSessionKeySet();
Iterator it = keys.iterator();
while (it.hasNext())
{
String sessionKey = (String) it.next();
UserSession userSession = sessionManager.getSessionForMonitoring(sessionKey);
if (System.currentTimeMillis() - userSession.getLastAccessedTime() > sessionManager.getTimeOut())
{
sessionManager.killSession(sessionKey);
}
}
}
}
| bsd-3-clause |
ropas/infer | infer/tests/codetoanalyze/java/eradicate/ParameterNotNullable.java | 2041 | /*
* Copyright (c) 2013 - 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.
*/
package codetoanalyze.java.eradicate;
import java.lang.System;
import java.net.URL;
import javax.annotation.Nullable;
import android.annotation.SuppressLint;
public class ParameterNotNullable {
boolean field = false;
ParameterNotNullable() {
testPrimitive(field);
}
void testPrimitive(boolean f) {
}
void test(String s) {
int n = s.length();
}
void testN(@Nullable String s) {
int n = s != null ? s.length() : 0;
}
void callNull() {
String s = null;
test(s);
}
@SuppressLint("ERADICATE_PARAMETER_NOT_NULLABLE")
void callNullSuppressed() {
String s = null;
test(s);
}
void callNullable(@Nullable String s) {
test(s);
}
void callNullOK() {
String s = null;
testN(s);
}
void callNullableOK(@Nullable String s) {
testN(s);
}
private ParameterNotNullable(@Nullable String s) {
}
class Builder {
ParameterNotNullable getEradicateParameterNotNullable() {
return new ParameterNotNullable(null);
}
}
public @Nullable String testSystemGetPropertyArgument() {
String s = System.getProperty(null);
return s;
}
@Nullable String testSystemGetenvBad() {
return System.getenv(null);
}
static @Nullable URL testClassGetResourceArgument(Class cls) {
return cls.getResource(null);
}
void threeParameters(String s1, String s2, String s3) {
}
void testThreeParameters() {
String s = "";
threeParameters(null, s, s);
threeParameters(s, null, s);
threeParameters(s, s, null);
}
class ConstructorCall {
ConstructorCall(int x, String s) {
}
ConstructorCall() {
this(3, ""); // OK
}
ConstructorCall(int x) {
this(3, null); // NPE
}
}
}
| bsd-3-clause |
NCIP/cacore-sdk | RestGen/examples/cxf2x/CustSOAPService/generated/gov/nih/nci/restgen/generated/client/GetCustomerByNameResponse.java | 1820 | /*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC, SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk/LICENSE.txt for details.
*/
package gov.nih.nci.restgen.generated.client;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="return" type="{http://customerservice.example.com/}customer"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"_return"
})
@XmlRootElement(name = "getCustomerByNameResponse")
public class GetCustomerByNameResponse {
@XmlElement(name = "return", required = true)
protected Customer _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link Customer }
*
*/
public Customer getReturn() {
return _return;
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link Customer }
*
*/
public void setReturn(Customer value) {
this._return = value;
}
}
| bsd-3-clause |
dalinhuang/suduforum | src/net/jforum/entities/AttachmentExtension.java | 4403 | /*
* Copyright (c) JForum Team
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* 2) Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 3) Neither the name of "Rafael Steil" 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
*
* Created on Jan 17, 2005 8:21:32 PM
* The JForum Project
* http://www.jforum.net
*/
package net.jforum.entities;
import java.io.Serializable;
/**
* @author Rafael Steil
* @version $Id: AttachmentExtension.java,v 1.7 2006/08/20 22:47:35 rafaelsteil Exp $
*/
public class AttachmentExtension implements Serializable
{
private int id;
private int extensionGroupId;
private boolean allow;
private boolean unknown;
private String comment;
private String extension;
private String uploadIcon;
/**
* @return Returns the allow.
*/
public boolean isAllow()
{
return this.allow;
}
/**
* @param allow The allow to set.
*/
public void setAllow(boolean allow)
{
this.allow = allow;
}
/**
* @return Returns the comment.
*/
public String getComment()
{
return this.comment;
}
/**
* @param comment The comment to set.
*/
public void setComment(String comment)
{
this.comment = comment;
}
/**
* @return Returns the extension.
*/
public String getExtension()
{
return this.extension;
}
/**
* @param extension The extension to set.
*/
public void setExtension(String extension)
{
if (extension != null) {
this.extension = extension.toLowerCase();
}
}
/**
* @return Returns the extensionGroupId.
*/
public int getExtensionGroupId()
{
return this.extensionGroupId;
}
/**
* @param extensionGroupId The extensionGroupId to set.
*/
public void setExtensionGroupId(int extensionGroupId)
{
this.extensionGroupId = extensionGroupId;
}
/**
* @return Returns the id.
*/
public int getId()
{
return this.id;
}
/**
* @param id The id to set.
*/
public void setId(int id)
{
this.id = id;
}
/**
* @return Returns the upload_icon.
*/
public String getUploadIcon()
{
return this.uploadIcon;
}
/**
* @param uploadIcon The upload_icon to set.
*/
public void setUploadIcon(String uploadIcon)
{
this.uploadIcon = uploadIcon;
}
/**
* @return Returns the unknown.
*/
public boolean isUnknown()
{
return this.unknown;
}
/**
* @param unknown The unknown to set.
*/
public void setUnknown(boolean unknown)
{
this.unknown = unknown;
}
public String toString() {
return "AttachmentExtension{" +
"id=" + id +
", extensionGroupId=" + extensionGroupId +
", allow=" + allow +
", unknown=" + unknown +
", comment='" + comment + '\'' +
", extension='" + extension + '\'' +
", uploadIcon='" + uploadIcon + '\'' +
'}';
}
}
| bsd-3-clause |
ngs-doo/dsl-client-java | core/src/test/java-generated/com/dslplatform/client/json/Point/OneSetOfOnePointsDefaultValueTurtle.java | 3710 | package com.dslplatform.client.json.Point;
import com.dslplatform.client.JsonSerialization;
import com.dslplatform.patterns.Bytes;
import java.io.IOException;
public class OneSetOfOnePointsDefaultValueTurtle {
private static JsonSerialization jsonSerialization;
@org.junit.BeforeClass
public static void initializeJsonSerialization() throws IOException {
jsonSerialization = com.dslplatform.client.StaticJson.getSerialization();
}
@org.junit.Test
public void testDefaultValueEquality() throws IOException {
final java.util.Set<java.awt.Point> defaultValue = new java.util.HashSet<java.awt.Point>(0);
final Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue);
final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length);
final java.util.Set<java.awt.Point> defaultValueJsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(defaultValue, defaultValueJsonDeserialized);
}
@org.junit.Test
public void testBorderValue1Equality() throws IOException {
final java.util.Set<java.awt.Point> borderValue1 = new java.util.HashSet<java.awt.Point>(java.util.Arrays.asList(new java.awt.Point()));
final Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1);
final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length);
final java.util.Set<java.awt.Point> borderValue1JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(borderValue1, borderValue1JsonDeserialized);
}
@org.junit.Test
public void testBorderValue2Equality() throws IOException {
final java.util.Set<java.awt.Point> borderValue2 = new java.util.HashSet<java.awt.Point>(java.util.Arrays.asList(new java.awt.Point(0, 1000000000)));
final Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2);
final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length);
final java.util.Set<java.awt.Point> borderValue2JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(borderValue2, borderValue2JsonDeserialized);
}
@org.junit.Test
public void testBorderValue3Equality() throws IOException {
final java.util.Set<java.awt.Point> borderValue3 = new java.util.HashSet<java.awt.Point>(java.util.Arrays.asList(new java.awt.Point(), new java.awt.Point(Integer.MIN_VALUE, Integer.MIN_VALUE), new java.awt.Point(Integer.MAX_VALUE, Integer.MAX_VALUE), new java.awt.Point(0, -1000000000), new java.awt.Point(0, 1000000000)));
final Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3);
final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length);
final java.util.Set<java.awt.Point> borderValue3JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(borderValue3, borderValue3JsonDeserialized);
}
}
| bsd-3-clause |
chaoscause/org.caleydo.view.dynamicpathway | src/main/java/org/caleydo/view/dynamicpathway/internal/NodeMergingException.java | 378 | package org.caleydo.view.dynamicpathway.internal;
public class NodeMergingException extends Exception {
private static final long serialVersionUID = 1L;
private static final String ERROR_PREFIX = "Internal Tool Error (Node Merging): ";
public NodeMergingException() {
super();
}
public NodeMergingException(String message) {
super(ERROR_PREFIX + message);
}
}
| bsd-3-clause |