repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
MaSeKind/watcher | sample/src/test/java/com/github/masekind/watcher/sample/ExampleUnitTest.java | 327 | package com.github.masekind.watcher.sample;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
sfischer13/robot-openthesaurus | app/src/main/java/sfischer13/openthesaurus/util/Info.java | 1687 | /*
Copyright 2015-2017 Stefan Fischer
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 sfischer13.openthesaurus.util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import java.util.Locale;
public class Info {
private static PackageInfo packageInfo(Context context) {
PackageManager pm = context.getPackageManager();
String pn = context.getPackageName();
try {
return pm.getPackageInfo(pn, 0);
} catch (PackageManager.NameNotFoundException e) {
return null;
}
}
private static String versionName(Context context) {
PackageInfo pi = packageInfo(context);
if (null == pi) {
return "null";
}
return pi.versionName;
}
private static int versionCode(Context context) {
PackageInfo pi = packageInfo(context);
if (null == pi) {
return -1;
}
return pi.versionCode;
}
public static String versionString(Context context) {
return String.format(Locale.US, "%s (%d)", versionName(context), versionCode(context));
}
}
| apache-2.0 |
ldp4j/ldp4j | framework/application/kernel/api/src/main/java/org/ldp4j/application/kernel/resource/Resource.java | 2512 | /**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the LDP4j Project:
* http://www.ldp4j.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2014-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.ldp4j.framework:ldp4j-application-kernel-api:0.2.2
* Bundle : ldp4j-application-kernel-api-0.2.2.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.ldp4j.application.kernel.resource;
import java.net.URI;
import java.util.Date;
import java.util.Set;
import org.ldp4j.application.data.constraints.Constraints;
import org.ldp4j.application.engine.context.HttpRequest;
import org.ldp4j.application.kernel.constraints.ConstraintReport;
import org.ldp4j.application.kernel.constraints.ConstraintReportId;
/**
* TODO: Update API to enable using Individual identifiers instead of plain
* URIs when dealing with indirect identifiers.
*/
public interface Resource {
ResourceId id();
void setIndirectId(URI indirectId);
URI indirectId();
boolean isRoot();
ResourceId parentId();
Attachment findAttachment(ResourceId resourceId);
Resource attach(String attachmentId, ResourceId resourceId);
<T extends Resource> T attach(String attachmentId, ResourceId resourceId, Class<? extends T> clazz);
boolean detach(Attachment attachment);
Set<? extends Attachment> attachments();
void accept(ResourceVisitor visitor);
ConstraintReport addConstraintReport(Constraints constraints, Date date, HttpRequest request);
Set<ConstraintReportId> constraintReports();
void removeFailure(ConstraintReport report);
} | apache-2.0 |
fransfilastap/pm5 | src/main/java/id/franspratama/geol/core/pojo/SiteEventFilter.java | 77 | package id.franspratama.geol.core.pojo;
public class SiteEventFilter {
}
| apache-2.0 |
cloudfoundry/cf-java-client | cloudfoundry-client/src/main/java/org/cloudfoundry/uaa/serverinformation/_Prompts.java | 1539 | /*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.cloudfoundry.uaa.serverinformation;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.Nullable;
import org.immutables.value.Value;
import java.util.List;
/**
* The payload for the server information prompts
*/
@JsonDeserialize
@Value.Immutable
abstract class _Prompts {
/**
* If a SAML identity provider is configured, this prompt contains a URL to where the user can initiate the SAML authentication flow
*/
@JsonProperty("passcode")
@Nullable
abstract List<String> getPasscode();
/**
* Information about the password prompt
*/
@JsonProperty("password")
@Nullable
abstract List<String> getPassword();
/**
* Information about the username prompt
*/
@JsonProperty("username")
@Nullable
abstract List<String> getUsername();
}
| apache-2.0 |
ivangag/SMApp | app/src/main/java/org/symptomcheck/capstone/adapters/MedicationQuestionItem.java | 1550 | package org.symptomcheck.capstone.adapters;
import com.google.common.collect.Lists;
import org.symptomcheck.capstone.model.Question;
import java.util.List;
/**
* Created by igaglioti on 16/02/2015.
*/
public class MedicationQuestionItem {
private String medicationName;
private String medicationTakingTime;
private boolean isTaken;
public String getMedicationName() {
return medicationName;
}
public void setMedicationName(String medicationName) {
this.medicationName = medicationName;
}
public String getMedicationTakingTime() {
return medicationTakingTime;
}
public void setMedicationTakingTime(String medicationTakingTime) {
this.medicationTakingTime = medicationTakingTime;
}
public boolean IsTaken() {
return isTaken;
}
public void setIsTaken(boolean IsTaken) {
this.isTaken = IsTaken;
}
public static List<MedicationQuestionItem> makeItemByCheckinQuestions(List<Question> CheckInQuestions){
List<MedicationQuestionItem> questionItems = Lists.newArrayList();
for(Question question:CheckInQuestions){
final String resp = question.getResponse();
MedicationQuestionItem item = new MedicationQuestionItem();
item.setIsTaken(resp.equals("YES"));
item.setMedicationTakingTime(question.getMedicationTime());
item.setMedicationName(question.getQuestion());
questionItems.add(item);
}
return questionItems;
}
} | apache-2.0 |
CognizantOneDevOps/Insights | PlatformRegressionTest/src/main/java/com/cognizant/devops/platformregressiontest/test/ui/reportmanagement/ContentConfigurationTest.java | 5293 | /*******************************************************************************
* Copyright 2021 Cognizant Technology Solutions
*
* 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.cognizant.devops.platformregressiontest.test.ui.reportmanagement;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.cognizant.devops.platformregressiontest.test.common.LoginAndSelectModule;
import com.cognizant.devops.platformregressiontest.test.ui.testdata.ReportManagementDataProvider;
public class ContentConfigurationTest extends LoginAndSelectModule {
ContentConfigurationPage contentConfigurationPage;
@BeforeTest
public void setUp() {
initialization();
selectMenuOption("Content Configuration");
contentConfigurationPage = new ContentConfigurationPage();
}
@BeforeMethod
public void beforeEachTestCase() {
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
/**
* This method tests content creation screen
*
* @param contentId
* @param contentName
* @param expectedTrend
* @param directionOfThreshold
* @param kpiId
* @param noOfResult
* @param threshold
* @param resultField
* @param action
* @param message
* @param isActive
*/
@Test(priority = 1, dataProvider = "createContentdataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void saveContent(String contentId, String contentName, String expectedTrend, String directionOfThreshold,
String kpiId, String noOfResult, String threshold, String resultField, String action, String message,
String isActive) {
Assert.assertEquals(contentId,
contentConfigurationPage.saveContent(contentId, expectedTrend, directionOfThreshold, contentName,
action, kpiId, noOfResult, threshold, resultField, message, isActive));
}
@Test(priority = 2, dataProvider = "createContentvalidatedataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void saveValaidateContent(String contentId, String contentName, String expectedTrend,
String directionOfThreshold, String kpiId, String noOfResult, String threshold, String resultField,
String action, String message, String isActive, String category) {
Assert.assertEquals(
contentConfigurationPage.saveValidateContent(contentId, expectedTrend, directionOfThreshold,
contentName, action, kpiId, noOfResult, threshold, resultField, message, isActive, category),
true);
}
/**
* This method tests content edit screen
*
* @param contentId
* @param expectedTrend
*/
@Test(priority = 3, dataProvider = "editContentdataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void editContent(String contentId, String expectedTrend) {
Assert.assertEquals(contentConfigurationPage.editContent(contentId, expectedTrend), true);
}
/**
* This method take json file and tests the bulkupload functionality
*
* @param fileName
*/
@Test(priority = 4, dataProvider = "uploadJsonContentdataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void uploadJsonTest(String validateFile, String invalidFile) {
Assert.assertEquals(contentConfigurationPage.uploadJson(validateFile), true);
}
@Test(priority = 5, dataProvider = "uploadJsonContentdataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void validateUploadJsonTest(String validateFile, String invalidFile) {
Assert.assertEquals(contentConfigurationPage.validateUploadJson(invalidFile), true);
}
/**
* This method tests content search functionality
*
* @param contentId
*/
@Test(priority = 6, dataProvider = "searchContentdataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void searchContent(String contentId) {
Assert.assertEquals(contentConfigurationPage.searchContent(contentId), true);
}
@Test(priority = 7, dataProvider = "searchContentdataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void checkRefreshButton(String contentId) {
Assert.assertEquals(contentConfigurationPage.checkRefreshButton(contentId), true);
}
/**
* This method tests content delete functionality
*
* @param contentId
*/
@Test(priority = 8, dataProvider = "deleteContentdataprovider", dataProviderClass = ReportManagementDataProvider.class, enabled = true)
public void deleteContent(String contentId) {
Assert.assertEquals(contentConfigurationPage.deleteContent(contentId), true);
}
} | apache-2.0 |
pirinthapan/app-cloud | modules/components/org.wso2.appcloud.provisioning.runtime/src/main/java/org/wso2/appcloud/provisioning/runtime/RuntimeProvisioningException.java | 1126 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.appcloud.provisioning.runtime;
/**
* Runtime provisioning API related exception.
*/
public class RuntimeProvisioningException extends Exception {
public RuntimeProvisioningException() {
}
public RuntimeProvisioningException(String s) {
super(s);
}
public RuntimeProvisioningException(String s, Throwable throwable) {
super(s, throwable);
}
public RuntimeProvisioningException(Throwable throwable) {
super(throwable);
}
}
| apache-2.0 |
etulupov/nsu-connect-android | nsu-connect/src/main/java/ru/tulupov/nsuconnect/model/Success.java | 427 | package ru.tulupov.nsuconnect.model;
import com.google.gson.annotations.SerializedName;
public class Success {
@SerializedName("success")
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String toString() {
return "Success{" +
"code=" + code +
'}';
}
}
| apache-2.0 |
komoot/graphhopper | web/src/test/java/com/graphhopper/http/isochrone/PtIsochroneResourceTest.java | 5591 | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.http.isochrone;
import com.graphhopper.http.GHPointConverterProvider;
import com.graphhopper.jackson.Jackson;
import com.graphhopper.reader.gtfs.GraphHopperGtfs;
import com.graphhopper.reader.gtfs.GtfsStorage;
import com.graphhopper.reader.gtfs.PtFlagEncoder;
import com.graphhopper.resources.PtIsochroneResource;
import com.graphhopper.routing.util.CarFlagEncoder;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.FootFlagEncoder;
import com.graphhopper.storage.GHDirectory;
import com.graphhopper.storage.GraphHopperStorage;
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.util.Helper;
import io.dropwizard.testing.junit.ResourceTestRule;
import org.junit.AfterClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import java.io.File;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PtIsochroneResourceTest {
private static final String GRAPH_LOC = "target/PtIsochroneResourceTest";
private static final ZoneId zoneId = ZoneId.of("America/Los_Angeles");
private static GraphHopperStorage graphHopperStorage;
private static LocationIndex locationIndex;
private static PtIsochroneResource isochroneResource;
private GeometryFactory geometryFactory = new GeometryFactory();
static {
Helper.removeDir(new File(GRAPH_LOC));
final PtFlagEncoder ptFlagEncoder = new PtFlagEncoder();
final CarFlagEncoder carFlagEncoder = new CarFlagEncoder();
final FootFlagEncoder footFlagEncoder = new FootFlagEncoder();
EncodingManager encodingManager = new EncodingManager.Builder(12).add(carFlagEncoder).add(footFlagEncoder).add(ptFlagEncoder).build();
GHDirectory directory = GraphHopperGtfs.createGHDirectory(GRAPH_LOC);
GtfsStorage gtfsStorage = GraphHopperGtfs.createGtfsStorage();
graphHopperStorage = GraphHopperGtfs.createOrLoad(directory, encodingManager, ptFlagEncoder, gtfsStorage, Collections.singleton("../reader-gtfs/files/sample-feed.zip"), Collections.emptyList());
locationIndex = GraphHopperGtfs.createOrLoadIndex(directory, graphHopperStorage);
isochroneResource = new PtIsochroneResource(gtfsStorage, graphHopperStorage.getEncodingManager(), graphHopperStorage, locationIndex);
}
@ClassRule
public static final ResourceTestRule resources = ResourceTestRule.builder()
.addProvider(new GHPointConverterProvider())
.setMapper(Jackson.newObjectMapper())
.addResource(isochroneResource)
.build();
@Test
public void testIsoline() {
WebTarget webTarget = resources
.target("/isochrone")
.queryParam("point", "36.914893,-116.76821") // NADAV
.queryParam("pt.earliest_departure_time", LocalDateTime.of(2007, 1, 1, 0, 0, 0).atZone(zoneId).toInstant())
.queryParam("time_limit", 6 * 60 * 60 + 49 * 60); // exactly the time I should arrive at NANAA
Invocation.Builder request = webTarget.request();
PtIsochroneResource.Response isochroneResponse = request.get(PtIsochroneResource.Response.class);
Geometry isoline = isochroneResponse.polygons.get(0).getGeometry();
// NADAV is in
assertTrue(isoline.covers(geometryFactory.createPoint(makePrecise(new Coordinate(-116.76821, 36.914893)))));
// NANAA is in
assertTrue(isoline.covers(geometryFactory.createPoint(makePrecise(new Coordinate(-116.761472, 36.914944)))));
// DADAN is in
assertTrue(isoline.covers(geometryFactory.createPoint(makePrecise(new Coordinate(-116.768242, 36.909489)))));
// EMSI is in
assertTrue(isoline.covers(geometryFactory.createPoint(makePrecise(new Coordinate(-116.76218, 36.905697)))));
// STAGECOACH is out
assertFalse(isoline.covers(geometryFactory.createPoint(makePrecise(new Coordinate(-116.751677, 36.915682)))));
}
// Snap coordinate to GraphHopper's implicit grid of allowable points.
// Otherwise, we can't reliably use coordinates from input data in tests.
private Coordinate makePrecise(Coordinate coordinate) {
return new Coordinate(Helper.intToDegree(Helper.degreeToInt(coordinate.x)), Helper.intToDegree(Helper.degreeToInt(coordinate.y)));
}
@AfterClass
public static void close() {
graphHopperStorage.close();
locationIndex.close();
}
}
| apache-2.0 |
goeckeler/jcommons.import | src/org/jcommons/db/jdbc/IntegerHandler.java | 811 | package org.jcommons.db.jdbc;
import java.sql.*;
import org.apache.commons.dbutils.ResultSetHandler;
/**
* Extracts a single integer from the given query.
*
* Useful for count(*), max(), min(), and so on.
*
* @author Thorsten Goeckeler
*/
class IntegerHandler
implements ResultSetHandler<Integer>
{
/**
* Retrieve the first column as an integer.
*
* @param rs the current result set of a database query
* @return the first column as an integer of the query
* @throws SQLException if the database cannot be accessed
*/
public Integer handle(final ResultSet rs)
throws SQLException
{
if (!rs.next()) return 0;
ResultSetMetaData meta = rs.getMetaData();
if (meta.getColumnCount() != 1) return 0;
return rs.getInt(1);
}
}
| apache-2.0 |
ljcservice/autumnprogram | src/main/java/com/ts/controller/Report/InHospitalRep/AntiDrugRep/AntiDrugUseController.java | 2821 | package com.ts.controller.Report.InHospitalRep.AntiDrugRep;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ts.controller.base.BaseController;
import com.ts.entity.Page;
import com.ts.service.Report.InHospitalRep.AntiDrugRep.IAntiDrugUseService;
import com.ts.util.PageData;
/**
*
* @author autumn
*
*/
@Controller
@RequestMapping(value="/InHospitalRep")
public class AntiDrugUseController extends BaseController
{
@Resource(name="antiDrugUseServiceBean")
private IAntiDrugUseService adu;
@RequestMapping(value="/DRANO013UI")
public ModelAndView DRANO013UI()throws Exception{
ModelAndView mv = this.getModelAndView();
PageData pd = this.getPageData();
try{
mv.setViewName("DoctOrder/report/antiDrugUse/antiDrugUseList");
} catch(Exception e){
logger.error(e.toString(), e);
}
return mv;
}
@RequestMapping(value="/DRANO013")
public ModelAndView DRANO013(Page page)throws Exception{
ModelAndView mv = this.getModelAndView();
PageData pd = this.getPageData();
page.setPd(pd);
try
{
List<PageData> pds = adu.DRANO013(page);
PageData pdsum = adu.DRANO013Sum(pd);
mv.addObject("antiUses", pds);
mv.addObject("antiUseSum",pdsum);
mv.addObject("pd", pd);
}
catch(Exception e)
{
logger.error(e.toString(), e);
}
mv.setViewName("DoctOrder/report/antiDrugUse/antiDrugUseList");
return mv ;
}
@RequestMapping(value="/DRANO014UI")
public ModelAndView DRANO014UI()throws Exception{
ModelAndView mv = this.getModelAndView();
PageData pd = this.getPageData();
try{
mv.setViewName("DoctOrder/report/antiDrugUse/antiDrugUsePatList");
} catch(Exception e){
logger.error(e.toString(), e);
}
return mv;
}
@RequestMapping(value="/DRANO014")
public ModelAndView DRANO014(Page page)throws Exception{
ModelAndView mv = this.getModelAndView();
PageData pd = this.getPageData();
page.setPd(pd);
try
{
List<PageData> pds = adu.DRANO014(page);
mv.addObject("antiUses", pds);
mv.addObject("pd", pd);
}
catch(Exception e)
{
logger.error(e.toString(), e);
}
mv.setViewName("DoctOrder/report/antiDrugUse/antiDrugUsePatList");
return mv ;
}
}
| apache-2.0 |
realityforge/gwt-presenter | src/main/java/net/customware/gwt/presenter/client/widget/WidgetPresenter.java | 616 | package net.customware.gwt.presenter.client.widget;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.EventBus;
import net.customware.gwt.presenter.client.BasicPresenter;
/**
* Abstract super-class for {@link BasicPresenter}s that work with GWT
* {@link Widget}s via {@link WidgetDisplay}s.
*
* @param <D> The {@link WidgetDisplay} type.
* @author David Peterson
*/
public abstract class WidgetPresenter<D extends WidgetDisplay>
extends BasicPresenter<D>
{
public WidgetPresenter( final D display, final EventBus eventBus )
{
super( display, eventBus );
}
}
| apache-2.0 |
charles-cooper/idylfin | src/com/opengamma/analytics/math/function/special/JacobiPolynomialFunction.java | 3568 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.math.function.special;
import org.apache.commons.lang.Validate;
import com.opengamma.analytics.math.function.DoubleFunction1D;
import com.opengamma.analytics.math.function.RealPolynomialFunction1D;
import com.opengamma.util.tuple.Pair;
/**
*
*/
public class JacobiPolynomialFunction extends OrthogonalPolynomialFunctionGenerator {
@Override
public DoubleFunction1D[] getPolynomials(final int n) {
throw new UnsupportedOperationException("Need values for alpha and beta for Jacobi polynomial function generation");
}
@Override
public Pair<DoubleFunction1D, DoubleFunction1D>[] getPolynomialsAndFirstDerivative(final int n) {
throw new UnsupportedOperationException("Need values for alpha and beta for Jacobi polynomial function generation");
}
public DoubleFunction1D[] getPolynomials(final int n, final double alpha, final double beta) {
Validate.isTrue(n >= 0);
final DoubleFunction1D[] polynomials = new DoubleFunction1D[n + 1];
for (int i = 0; i <= n; i++) {
if (i == 0) {
polynomials[i] = getOne();
} else if (i == 1) {
polynomials[i] = new RealPolynomialFunction1D(new double[] {(alpha - beta) / 2, (alpha + beta + 2) / 2});
} else {
final int j = i - 1;
polynomials[i] = (polynomials[j].multiply(getB(alpha, beta, j)).add(polynomials[j].multiply(getX()).multiply(getC(alpha, beta, j)).add(polynomials[j - 1].multiply(getD(alpha, beta, j)))))
.divide(getA(alpha, beta, j));
}
}
return polynomials;
}
public Pair<DoubleFunction1D, DoubleFunction1D>[] getPolynomialsAndFirstDerivative(final int n, final double alpha, final double beta) {
Validate.isTrue(n >= 0);
@SuppressWarnings("unchecked")
final Pair<DoubleFunction1D, DoubleFunction1D>[] polynomials = new Pair[n + 1];
DoubleFunction1D p, dp, p1, p2;
for (int i = 0; i <= n; i++) {
if (i == 0) {
polynomials[i] = Pair.of(getOne(), getZero());
} else if (i == 1) {
final double a1 = (alpha + beta + 2) / 2;
polynomials[i] = Pair.of((DoubleFunction1D) new RealPolynomialFunction1D(new double[] {(alpha - beta) / 2, a1}), (DoubleFunction1D) new RealPolynomialFunction1D(new double[] {a1}));
} else {
final int j = i - 1;
p1 = polynomials[j].getFirst();
p2 = polynomials[j - 1].getFirst();
final DoubleFunction1D temp1 = p1.multiply(getB(alpha, beta, j));
final DoubleFunction1D temp2 = p1.multiply(getX()).multiply(getC(alpha, beta, j));
final DoubleFunction1D temp3 = p2.multiply(getD(alpha, beta, j));
p = (temp1.add(temp2).add(temp3)).divide(getA(alpha, beta, j));
dp = p.derivative();
polynomials[i] = Pair.of(p, dp);
}
}
return polynomials;
}
private double getA(final double alpha, final double beta, final int n) {
return 2 * (n + 1) * (n + alpha + beta + 1) * (2 * n + alpha + beta);
}
private double getB(final double alpha, final double beta, final int n) {
return (2 * n + alpha + beta + 1) * (alpha * alpha - beta * beta);
}
private double getC(final double alpha, final double beta, final int n) {
final double x = 2 * n + alpha + beta;
return x * (x + 1) * (x + 2);
}
private double getD(final double alpha, final double beta, final int n) {
return -2 * (n + alpha) * (n + beta) * (2 * n + alpha + beta + 2);
}
}
| apache-2.0 |
Wiezzel/changeanalyzer | src/main/java/pl/edu/mimuw/changeanalyzer/models/standard/StandardDataSetProvider.java | 1460 | package pl.edu.mimuw.changeanalyzer.models.standard;
import pl.edu.mimuw.changeanalyzer.models.DataSetProvider;
import pl.edu.mimuw.changeanalyzer.models.attributes.Attributes;
import pl.edu.mimuw.changeanalyzer.models.measures.BugPronenessMeasure;
/**
* Satndard data set provider uses a {@link StandardDataSetBuilder}
* and a {@link StandardDataSetProcessor} to create & process data sets.
*
* @author Adam Wierzbicki
*/
public class StandardDataSetProvider extends DataSetProvider {
/**
* Cosntruct a new SatndardDataSetProvider.
*
* @param builder Data set builder to be used by this provider
* @param processor Data set processor to be used by this provider
*/
private StandardDataSetProvider(StandardDataSetBuilder builder, StandardDataSetProcessor processor) {
super(builder, processor);
}
/**
* Get a new StandardDataSetProvider instance (factory method).
*
* @param measure Bug-proneness measure to be used by the provider
* @return A new StandardDataSetProvder using the given measure
*/
public static StandardDataSetProvider getInstance(BugPronenessMeasure measure) {
StandardDataSetBuilder builder = new StandardDataSetBuilder().addMeasure(measure);
Attributes attributes = builder.getAttributes();
String classAttrName = measure.getName();
StandardDataSetProcessor processor = new StandardDataSetProcessor(attributes, classAttrName);
return new StandardDataSetProvider(builder, processor);
}
}
| apache-2.0 |
agwlvssainokuni/springapp | common/src/main/java/cherry/common/testtool/factory/YamlInvokerServiceFactoryBean.java | 1535 | /*
* Copyright 2015 agwlvssainokuni
*
* 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 cherry.common.testtool.factory;
import static cherry.common.testtool.factory.BeanName.YAML_INVOKER;
import static cherry.common.testtool.factory.BeanName.YAML_INVOKER_SERVICE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import cherry.foundation.testtool.invoker.Invoker;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component(YAML_INVOKER_SERVICE)
public class YamlInvokerServiceFactoryBean extends InvokerServiceFactoryBeanSupport {
@Autowired
@Qualifier("yamlObjectMapper")
private ObjectMapper objectMapper;
@Autowired
@Qualifier(YAML_INVOKER)
private Invoker invoker;
@Override
protected ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
protected Invoker getInvoker() {
return invoker;
}
}
| apache-2.0 |
line/line-bot-sdk-java | line-bot-model/src/main/java/com/linecorp/bot/model/message/TemplateMessage.java | 2158 | /*
* Copyright 2016 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.bot.model.message;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.linecorp.bot.model.message.quickreply.QuickReply;
import com.linecorp.bot.model.message.sender.Sender;
import com.linecorp.bot.model.message.template.Template;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;
/**
* Template messages are messages with predefined layouts which you can customize. There are three types of
* templates available that can be used to interact with users through your bot.
*/
@Value
@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@JsonTypeName("template")
@JsonDeserialize(builder = TemplateMessage.TemplateMessageBuilder.class)
public class TemplateMessage implements Message {
/**
* Alternative text.
*/
String altText;
/**
* Object with the contents of the template.
*/
Template template;
QuickReply quickReply;
Sender sender;
/**
* Constructor without {@link #quickReply} parameter.
*
* <p>If you want use {@link QuickReply}, please use {@link #builder()} instead.
*/
public TemplateMessage(final String altText, final Template template) {
this(altText, template, null, null);
}
@JsonPOJOBuilder(withPrefix = "")
public static class TemplateMessageBuilder {
}
}
| apache-2.0 |
udoprog/ffwd-client-java | src/main/java/com/google/protobuf250/BoundedByteString.java | 5459 | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.google.protobuf250;
import java.util.NoSuchElementException;
/**
* This class is used to represent the substring of a {@link ByteString} over a
* single byte array. In terms of the public API of {@link ByteString}, you end
* up here by calling {@link ByteString#copyFrom(byte[])} followed by {@link
* ByteString#substring(int, int)}.
*
* <p>This class contains most of the overhead involved in creating a substring
* from a {@link LiteralByteString}. The overhead involves some range-checking
* and two extra fields.
*
* @author carlanton@google.com (Carl Haverl)
*/
class BoundedByteString extends LiteralByteString {
private final int bytesOffset;
private final int bytesLength;
/**
* Creates a {@code BoundedByteString} backed by the sub-range of given array,
* without copying.
*
* @param bytes array to wrap
* @param offset index to first byte to use in bytes
* @param length number of bytes to use from bytes
* @throws IllegalArgumentException if {@code offset < 0}, {@code length < 0},
* or if {@code offset + length >
* bytes.length}.
*/
BoundedByteString(byte[] bytes, int offset, int length) {
super(bytes);
if (offset < 0) {
throw new IllegalArgumentException("Offset too small: " + offset);
}
if (length < 0) {
throw new IllegalArgumentException("Length too small: " + offset);
}
if ((long) offset + length > bytes.length) {
throw new IllegalArgumentException(
"Offset+Length too large: " + offset + "+" + length);
}
this.bytesOffset = offset;
this.bytesLength = length;
}
/**
* Gets the byte at the given index.
* Throws {@link ArrayIndexOutOfBoundsException}
* for backwards-compatibility reasons although it would more properly be
* {@link IndexOutOfBoundsException}.
*
* @param index index of byte
* @return the value
* @throws ArrayIndexOutOfBoundsException {@code index} is < 0 or >= size
*/
@Override
public byte byteAt(int index) {
// We must check the index ourselves as we cannot rely on Java array index
// checking for substrings.
if (index < 0) {
throw new ArrayIndexOutOfBoundsException("Index too small: " + index);
}
if (index >= size()) {
throw new ArrayIndexOutOfBoundsException(
"Index too large: " + index + ", " + size());
}
return bytes[bytesOffset + index];
}
@Override
public int size() {
return bytesLength;
}
@Override
protected int getOffsetIntoBytes() {
return bytesOffset;
}
// =================================================================
// ByteString -> byte[]
@Override
protected void copyToInternal(byte[] target, int sourceOffset,
int targetOffset, int numberToCopy) {
System.arraycopy(bytes, getOffsetIntoBytes() + sourceOffset, target,
targetOffset, numberToCopy);
}
// =================================================================
// ByteIterator
@Override
public ByteIterator iterator() {
return new BoundedByteIterator();
}
private class BoundedByteIterator implements ByteIterator {
private int position;
private final int limit;
private BoundedByteIterator() {
position = getOffsetIntoBytes();
limit = position + size();
}
public boolean hasNext() {
return (position < limit);
}
public Byte next() {
// Boxing calls Byte.valueOf(byte), which does not instantiate.
return nextByte();
}
public byte nextByte() {
if (position >= limit) {
throw new NoSuchElementException();
}
return bytes[position++];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| apache-2.0 |
adbrucker/SecureBPMN | designer/src/org.activiti.designer.model.tests/src/org/eclipse/bpmn2/tests/GlobalManualTaskTest.java | 1893 | /**
* <copyright>
*
* Copyright (c) 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation
*
* </copyright>
*/
package org.eclipse.bpmn2.tests;
import junit.textui.TestRunner;
import org.eclipse.bpmn2.Bpmn2Factory;
import org.eclipse.bpmn2.GlobalManualTask;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Global Manual Task</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class GlobalManualTaskTest extends GlobalTaskTest {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(GlobalManualTaskTest.class);
}
/**
* Constructs a new Global Manual Task test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public GlobalManualTaskTest(String name) {
super(name);
}
/**
* Returns the fixture for this Global Manual Task test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected GlobalManualTask getFixture() {
return (GlobalManualTask) fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
@Override
protected void setUp() throws Exception {
setFixture(Bpmn2Factory.eINSTANCE.createGlobalManualTask());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
@Override
protected void tearDown() throws Exception {
setFixture(null);
}
} //GlobalManualTaskTest
| apache-2.0 |
melthaw/spring-backend-boilerplate | menu/core/src/main/java/in/clouthink/daas/sbb/menu/core/MenuPlugin.java | 201 | package in.clouthink.daas.sbb.menu.core;
import java.util.List;
/**
* @author dz
*/
public interface MenuPlugin {
String getPluginId();
String getExtensionPointId();
List<Menu> getMenu();
}
| apache-2.0 |
davinash/geode | geode-redis/src/distributedTest/java/org/apache/geode/redis/session/springRedisTestApplication/config/WebMvcConfig.java | 1786 | /*
* 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.geode.redis.session.springRedisTestApplication.config;
import io.lettuce.core.resource.ClientResources;
import org.springframework.boot.ApplicationArguments;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
@Bean(destroyMethod = "shutdown")
ClientResources clientResources(ApplicationArguments applicationArguments) {
DUnitSocketAddressResolver dUnitSocketAddressResolver =
new DUnitSocketAddressResolver(applicationArguments.getSourceArgs());
return ClientResources.builder()
.socketAddressResolver(dUnitSocketAddressResolver).build();
}
}
| apache-2.0 |
TranscendComputing/TopStackAutoScale | src/com/amazonaws/services/autoscaling/model/transform/CreateAutoScalingGroupRequestUnmarshaller.java | 2333 | package com.amazonaws.services.autoscaling.model.transform;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import com.amazonaws.transform.Unmarshaller;
import com.google.common.base.Strings;
import com.msi.tough.query.QueryUtil;
import com.transcend.autoscale.message.CreateAutoScalingGroupMessage.CreateAutoScalingGroupRequestMessage;
/**
* CreateLoadBalancerRequestUnmarshaller
*/
public class CreateAutoScalingGroupRequestUnmarshaller implements
Unmarshaller<CreateAutoScalingGroupRequestMessage, Map<String, String[]>> {
private static CreateAutoScalingGroupRequestUnmarshaller instance;
public static CreateAutoScalingGroupRequestUnmarshaller getInstance() {
if (instance == null) {
instance = new CreateAutoScalingGroupRequestUnmarshaller();
}
return instance;
}
@Override
public CreateAutoScalingGroupRequestMessage unmarshall(
final Map<String, String[]> in) {
final CreateAutoScalingGroupRequestMessage.Builder req =
CreateAutoScalingGroupRequestMessage.newBuilder();
req.setAutoScalingGroupName(QueryUtil.requiredString(in,
"AutoScalingGroupName"));
req.addAllAvailabilityZone(QueryUtil.requiredStringArray(in,
"AvailabilityZones.member", Integer.MAX_VALUE));
req.setDefaultCooldown(QueryUtil.getInt(in, "DefaultCooldown"));
req.setDesiredCapacity(QueryUtil.getInt(in, "DesiredCapacity"));
req.setHealthCheckGracePeriod(QueryUtil.getInt(in,
"HealthCheckGracePeriod"));
req.setHealthCheckType(Strings.nullToEmpty(QueryUtil.getString(in, "HealthCheckType")));
req.setLaunchConfigurationName(QueryUtil.requiredString(in,
"LaunchConfigurationName"));
req.addAllLoadBalancerName(QueryUtil.getStringArray(in,
"LoadBalancerNames.member", Integer.MAX_VALUE));
req.setMaxSize(QueryUtil.requiredInt(in, "MaxSize"));
req.setMinSize(QueryUtil.requiredInt(in, "MinSize"));
// req.setPlacementGroup(placementGroup);
final Collection<String> terminationPolicies = new ArrayList<String>();
for (int i = 0;; i++) {
if (in.get("TerminationPolicies.member." + i) == null) {
break;
}
terminationPolicies
.add(in.get("TerminationPolicies.member." + i)[0]);
}
req.addAllTerminationPolicy(terminationPolicies);
// req.setVPCZoneIdentifier(vPCZoneIdentifier);
return req.buildPartial();
}
}
| apache-2.0 |
zerkseez/generic-reflection | src/test/java/com/github/zerkseez/reflection/types/ExtendedGenericInterface.java | 1002 | /*******************************************************************************
* Copyright 2016 Xerxes Tsang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.github.zerkseez.reflection.types;
public interface ExtendedGenericInterface<T>
extends GenericInterfaceWithDefaultFunction<Short, Long>, GenericInterface<T> {
@Override
default Short getA() {
return null;
}
}
| apache-2.0 |
Intel-bigdata/OAP | oap-native-sql/core/src/main/java/com/intel/oap/datasource/VectorizedParquetArrowReader.java | 8784 | /*
* 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 com.intel.oap.datasource;
import com.intel.oap.vectorized.ArrowWritableColumnVector;
import java.io.IOException;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.spark.sql.execution.datasources.parquet.VectorizedParquetRecordReader;
import com.intel.oap.datasource.parquet.ParquetReader;
import org.apache.arrow.vector.VectorSchemaRoot;
import org.apache.arrow.vector.ipc.message.ArrowRecordBatch;
import org.apache.arrow.vector.types.pojo.Schema;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.parquet.HadoopReadOptions;
import org.apache.parquet.ParquetReadOptions;
import org.apache.parquet.hadoop.ParquetFileReader;
import org.apache.parquet.hadoop.ParquetInputSplit;
import org.apache.parquet.hadoop.metadata.BlockMetaData;
import org.apache.parquet.hadoop.util.ContextUtil;
import org.apache.parquet.hadoop.util.HadoopInputFile;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.types.StructType;
import org.apache.spark.sql.vectorized.ColumnarBatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class VectorizedParquetArrowReader extends VectorizedParquetRecordReader {
private static final Logger LOG =
LoggerFactory.getLogger(VectorizedParquetArrowReader.class);
private ParquetReader reader = null;
private String path;
private long capacity;
private VectorSchemaRoot schemaRoot = null;
private long lastReadLength = 0;
private int numLoaded = 0;
private int numReaded = 0;
private long totalLength;
private String tmp_dir;
private ArrowRecordBatch next_batch;
// private ColumnarBatch last_columnar_batch;
private StructType sourceSchema;
private StructType readDataSchema;
private Schema schema = null;
public VectorizedParquetArrowReader(String path, ZoneId convertTz, boolean useOffHeap,
int capacity, StructType sourceSchema, StructType readDataSchema, String tmp_dir) {
super(convertTz, "", useOffHeap, capacity);
this.capacity = capacity;
this.path = path;
this.tmp_dir = tmp_dir;
this.sourceSchema = sourceSchema;
this.readDataSchema = readDataSchema;
}
@Override
public void initBatch(StructType partitionColumns, InternalRow partitionValues) {}
@Override
public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext)
throws IOException, InterruptedException, UnsupportedOperationException {
final ParquetInputSplit parquetInputSplit = toParquetSplit(inputSplit);
final Configuration configuration = ContextUtil.getConfiguration(taskAttemptContext);
initialize(parquetInputSplit, configuration);
}
public void initialize(ParquetInputSplit inputSplit, Configuration configuration)
throws IOException, InterruptedException, UnsupportedOperationException {
this.totalLength = inputSplit.getLength();
int ordinal = 0;
int cur_index = 0;
int[] column_indices = new int[readDataSchema.size()];
List<String> targetSchema = Arrays.asList(readDataSchema.names());
for (String fieldName : sourceSchema.names()) {
if (targetSchema.contains(fieldName)) {
column_indices[cur_index++] = ordinal;
}
ordinal++;
}
final int[] rowGroupIndices = filterRowGroups(inputSplit, configuration);
String uriPath = this.path;
if (uriPath.contains("hdfs")) {
uriPath = this.path + "?user=root&replication=1";
}
ParquetInputSplit split = (ParquetInputSplit) inputSplit;
LOG.info("ParquetReader uri path is " + uriPath + ", rowGroupIndices is "
+ Arrays.toString(rowGroupIndices) + ", column_indices is "
+ Arrays.toString(column_indices));
this.reader = new ParquetReader(uriPath, split.getStart(), split.getEnd(),
column_indices, capacity, ArrowWritableColumnVector.getAllocator(), tmp_dir);
}
@Override
public void initialize(String path, List<String> columns)
throws IOException, UnsupportedOperationException {}
@Override
public boolean nextKeyValue() throws IOException {
return nextBatch();
}
@Override
public boolean nextBatch() throws IOException {
next_batch = reader.readNext();
if (schema == null) {
schema = reader.getSchema();
}
if (next_batch == null) {
lastReadLength = 0;
return false;
}
lastReadLength = next_batch.getLength();
numLoaded += lastReadLength;
return true;
}
@Override
public Object getCurrentValue() {
if (numReaded == numLoaded) {
return null;
}
numReaded += lastReadLength;
ArrowWritableColumnVector[] columnVectors =
ArrowWritableColumnVector.loadColumns(next_batch.getLength(), schema, next_batch);
next_batch.close();
return new ColumnarBatch(columnVectors, next_batch.getLength());
}
@Override
public void close() throws IOException {
if (reader != null) {
reader.close();
reader = null;
}
}
@Override
public float getProgress() {
return (float) (numReaded / totalLength);
}
private int[] filterRowGroups(ParquetInputSplit parquetInputSplit,
Configuration configuration) throws IOException {
final long[] rowGroupOffsets = parquetInputSplit.getRowGroupOffsets();
if (rowGroupOffsets != null) {
throw new UnsupportedOperationException();
}
final Path path = parquetInputSplit.getPath();
final List<BlockMetaData> filteredRowGroups;
final List<BlockMetaData> unfilteredRowGroups;
try (ParquetFileReader reader =
ParquetFileReader.open(HadoopInputFile.fromPath(path, configuration),
createOptions(parquetInputSplit, configuration))) {
unfilteredRowGroups = reader.getFooter().getBlocks();
filteredRowGroups = reader.getRowGroups();
}
final int[] acc = {0};
final Map<BlockMetaDataWrapper, Integer> dict = unfilteredRowGroups.stream().collect(
Collectors.toMap(BlockMetaDataWrapper::wrap, b -> acc[0]++));
return filteredRowGroups.stream()
.map(BlockMetaDataWrapper::wrap)
.map(b -> {
if (!dict.containsKey(b)) {
// This should not happen
throw new IllegalStateException("Unrecognizable filtered row group: " + b);
}
return dict.get(b);
})
.mapToInt(n -> n)
.toArray();
}
private ParquetReadOptions createOptions(
ParquetInputSplit split, Configuration configuration) {
return HadoopReadOptions.builder(configuration)
.withRange(split.getStart(), split.getEnd())
.build();
}
private ParquetInputSplit toParquetSplit(InputSplit split) throws IOException {
if (split instanceof ParquetInputSplit) {
return (ParquetInputSplit) split;
} else {
throw new IllegalArgumentException(
"Invalid split (not a ParquetInputSplit): " + split);
}
}
// ID for BlockMetaData, to prevent from resulting in mutable BlockMetaData instances
// after being filtered
private static class BlockMetaDataWrapper {
private BlockMetaData m;
private BlockMetaDataWrapper(BlockMetaData m) {
this.m = m;
}
public static BlockMetaDataWrapper wrap(BlockMetaData m) {
return new BlockMetaDataWrapper(m);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BlockMetaDataWrapper that = (BlockMetaDataWrapper) o;
return equals(m, that.m);
}
private boolean equals(BlockMetaData one, BlockMetaData other) {
return Objects.equals(one.getStartingPos(), other.getStartingPos());
}
@Override
public int hashCode() {
return hash(m);
}
private int hash(BlockMetaData m) {
return Objects.hash(m.getStartingPos());
}
}
}
| apache-2.0 |
frroliveira/sqlipa | src/main/sqlipa/ast/stmt/event/select/SelectSrc.java | 563 | package main.sqlipa.ast.stmt.event.select;
import main.sqlipa.ast.Block;
import main.sqlipa.ast.Name;
import main.sqlipa.ast.visitor.VoidVisitor;
public class SelectSrc extends SingleSrc {
public SelectStmt select;
public Name alias;
public SelectSrc() {
super();
}
public SelectSrc(Block block, SelectStmt select, Name alias) {
super(block);
this.select = select;
this.alias = alias;
}
@Override
public void accept(VoidVisitor visitor) {
visitor.visit(this);
}
} | apache-2.0 |
McLeodMoores/starling | projects/master-db/src/main/java/com/opengamma/masterdb/security/hibernate/EnumWithDescriptionBean.java | 1622 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.masterdb.security.hibernate;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* Hibernate bean for storing an enum with description.
*/
public class EnumWithDescriptionBean extends EnumBean {
private String _description;
public EnumWithDescriptionBean() {
super();
}
public EnumWithDescriptionBean(final String name, final String description) {
super(name);
_description = description;
}
public String getDescription() {
return _description;
}
public void setDescription(final String description) {
_description = description;
}
@Override
public boolean equals(final Object o) {
if (!(o instanceof EnumWithDescriptionBean)) {
return false;
}
final EnumWithDescriptionBean ewd = (EnumWithDescriptionBean) o;
if (getId() != -1 && ewd.getId() != -1) {
return getId().longValue() == ewd.getId().longValue();
}
return new EqualsBuilder().append(getName(), ewd.getName()).append(getDescription(), ewd.getDescription()).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(getName()).append(getDescription()).toHashCode();
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| apache-2.0 |
z123/datacollector | basic-lib/src/main/java/com/streamsets/pipeline/lib/websocket/Errors.java | 1201 | /*
* Copyright 2017 StreamSets 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.streamsets.pipeline.lib.websocket;
import com.streamsets.pipeline.api.ErrorCode;
import com.streamsets.pipeline.api.GenerateResourceBundle;
@GenerateResourceBundle
public enum Errors implements ErrorCode {
WEB_SOCKET_01("Failed to connect : {}"),
WEB_SOCKET_02("Invalid Resource URI. Reason : {}"),
WEB_SOCKET_03("Error when disconnecting WebSocket Client. Reason: {}"),
;
private final String msg;
Errors(String msg) {
this.msg = msg;
}
@Override
public String getCode() {
return name();
}
@Override
public String getMessage() {
return msg;
}
}
| apache-2.0 |
robgil/Aleph2 | aleph2_data_model/test/com/ikanow/aleph2/data_model/interfaces/data_access/samples/SampleModule.java | 1118 | /*******************************************************************************
* Copyright 2015, The IKANOW Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.ikanow.aleph2.data_model.interfaces.data_access.samples;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
public class SampleModule extends AbstractModule {
@Override
protected void configure() {
bind(IDependency.class).annotatedWith(Names.named("SampleDepOne")).to(SampleDependencyOne.class);
}
}
| apache-2.0 |
rterp/GMapsFX | GMapsFX/src/main/java/com/dlsc/gmapsfx/service/geocoding/GeocoderUtils.java | 2216 | /*
* Copyright 2015 Andre.
*
* 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.dlsc.gmapsfx.service.geocoding;
/**
*
* @author Andre
*/
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import netscape.javascript.JSObject;
/**
*
* @author jlstephens89
*/
public class GeocoderUtils {
public static List<JSObject> getJSObjectsFromArray(JSObject jsArray) {
final List<JSObject> result = new ArrayList<>();
boolean keepLooking = true;
int index = 0;
while (keepLooking) {
try {
JSObject jsGeocoderResult = (JSObject) ((JSObject) jsArray).getSlot(index++);
if (jsGeocoderResult != null) {
result.add(jsGeocoderResult);
} else {
keepLooking = false;
}
} catch (Exception e) {
keepLooking = false;
}
}
return result;
}
public static <T extends Enum> List<T> convertJSObjectToListOfEnum(JSObject jsObject, Class<T> enumClass) {
List<T> result = new ArrayList<>();
if (jsObject != null) {
try {
String jsTypesString = jsObject.toString();
for (T value : enumClass.getEnumConstants()) {
if (jsTypesString.toLowerCase().contains(value.name().toLowerCase())) {
result.add(value);
}
}
} catch (Exception e) {
Logger.getLogger(GeocoderUtils.class.getName()).log(Level.SEVERE, "", e);
}
}
return result;
}
} | apache-2.0 |
smabotics/5493Steamworks | 5493-CTRE-Steamworks/src/org/usfirst/frc/team5493/robot/commands/DriveStraightForDist.java | 1702 | package org.usfirst.frc.team5493.robot.commands;
import org.usfirst.frc.team5493.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
public class DriveStraightForDist extends Command {
private double targetDist;
private double leftDist;
private double rightDist;
private double speed;
private boolean leftForward;
private boolean rightForward;
public DriveStraightForDist(double distance, boolean forward) {
requires(Robot.driveBase);
if(leftDist < targetDist)
leftForward = true;
if(rightDist < targetDist)
rightForward = true;
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if(leftForward && rightForward){
Robot.driveBase.drive(speed, speed, 0, 0);
} else if(leftForward){
Robot.driveBase.drive(speed, speed, speed * 0.25, 0);
} else if(rightForward){
Robot.driveBase.drive(speed, speed, speed * -0.25, 0);
} else{
Robot.driveBase.drive(0, 0, 0, 0);
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
//if(goForward)
//return (Robot.distance.calculateDistance() >= targetDist);
//else
//return (Robot.distance.calculateDistance() <= targetDist);
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
| apache-2.0 |
zhanhb/thymeleaf-layout-dialect | thymeleaf-layout-dialect/source/nz/net/ultraq/thymeleaf/layoutdialect/models/extensions/ICloseElementTagExtensions.java | 1398 | /*
* Copyright 2016, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* 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 nz.net.ultraq.thymeleaf.layoutdialect.models.extensions;
import org.thymeleaf.model.ICloseElementTag;
import org.thymeleaf.model.IElementTag;
import java.util.Objects;
/**
* Meta-programming extensions to the {@link ICloseElementTag} class.
*
* @author zhanhb
* @author Emanuel Rabina
*/
public class ICloseElementTagExtensions {
/**
* Compares this close tag with another.
*
* @param self
* @param other
* @return {@code true} if this tag has the same name as the other element.
*/
@SuppressWarnings("EqualsOverloaded")
public static boolean equals(ICloseElementTag self, Object other) {
return other instanceof ICloseElementTag
&& Objects.equals(self.getElementCompleteName(), ((IElementTag) other).getElementCompleteName());
}
}
| apache-2.0 |
mread/buck | src/com/facebook/buck/ocaml/OCamlLibraryDescription.java | 2526 | /*
* Copyright 2013-present Facebook, 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.facebook.buck.ocaml;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.coercer.OCamlSource;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
public class OCamlLibraryDescription implements Description<OCamlLibraryDescription.Arg> {
public static final BuildRuleType TYPE = new BuildRuleType("ocaml_library");
private final OCamlBuckConfig ocamlBuckConfig;
public OCamlLibraryDescription(OCamlBuckConfig ocamlBuckConfig) {
this.ocamlBuckConfig = Preconditions.checkNotNull(ocamlBuckConfig);
}
@Override
public Arg createUnpopulatedConstructorArg() {
return new Arg();
}
@Override
public <A extends Arg> AbstractBuildRule createBuildRule(
BuildRuleParams params,
BuildRuleResolver resolver,
A args) {
ImmutableList<OCamlSource> srcs = args.srcs.get();
ImmutableList<String> flags = args.compilerFlags.get();
ImmutableList<String> linkerflags = args.linkerFlags.get();
return OCamlRuleBuilder.createBuildRule(
ocamlBuckConfig, params, resolver, srcs, /*isLibrary*/ true, flags, linkerflags);
}
@Override
public BuildRuleType getBuildRuleType() {
return TYPE;
}
@SuppressFieldNotInitialized
public static class Arg {
public Optional<ImmutableList<OCamlSource>> srcs;
public Optional<ImmutableSortedSet<BuildTarget>> deps;
public Optional<ImmutableList<String>> compilerFlags;
public Optional<ImmutableList<String>> linkerFlags;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/model/transform/GetCachePolicyConfigRequestMarshaller.java | 1947 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloudfront.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudfront.model.*;
import com.amazonaws.transform.Marshaller;
/**
* GetCachePolicyConfigRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetCachePolicyConfigRequestMarshaller implements Marshaller<Request<GetCachePolicyConfigRequest>, GetCachePolicyConfigRequest> {
public Request<GetCachePolicyConfigRequest> marshall(GetCachePolicyConfigRequest getCachePolicyConfigRequest) {
if (getCachePolicyConfigRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<GetCachePolicyConfigRequest> request = new DefaultRequest<GetCachePolicyConfigRequest>(getCachePolicyConfigRequest, "AmazonCloudFront");
request.setHttpMethod(HttpMethodName.GET);
String uriResourcePath = "/2020-05-31/cache-policy/{Id}/config";
uriResourcePath = com.amazonaws.transform.PathMarshallers.NON_GREEDY.marshall(uriResourcePath, "Id", getCachePolicyConfigRequest.getId());
request.setResourcePath(uriResourcePath);
return request;
}
}
| apache-2.0 |
pac4j/pac4j | pac4j-saml/src/test/java/org/pac4j/saml/metadata/keystore/SAML2HttpUrlKeystoreGeneratorTests.java | 2840 | package org.pac4j.saml.metadata.keystore;
import com.github.tomakehurst.wiremock.WireMockServer;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.ContentType;
import org.junit.Test;
import org.pac4j.saml.config.SAML2Configuration;
import org.pac4j.saml.crypto.CredentialProvider;
import org.pac4j.saml.crypto.KeyStoreCredentialProvider;
import org.pac4j.saml.util.ConfigurationManager;
import org.pac4j.saml.util.DefaultConfigurationManager;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import java.nio.charset.StandardCharsets;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.*;
/**
* This is {@link SAML2HttpUrlKeystoreGeneratorTests}.
*
* @author Misagh Moayyed
*/
public class SAML2HttpUrlKeystoreGeneratorTests {
@Test
public void verifyKeystoreGeneration() throws Exception {
final ConfigurationManager mgr = new DefaultConfigurationManager();
mgr.configure();
final var wireMockServer = new WireMockServer(8085);
try {
wireMockServer.stubFor(
post(urlPathEqualTo("/keystore"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", ContentType.TEXT_PLAIN.getMimeType())));
final var restBody = IOUtils.toString(
new ClassPathResource("dummy-keystore.txt").getInputStream(), StandardCharsets.UTF_8);
wireMockServer.stubFor(
get(urlPathEqualTo("/keystore"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", ContentType.TEXT_PLAIN.getMimeType())
.withBody(restBody)));
wireMockServer.start();
final var configuration = new SAML2Configuration();
configuration.setCertificateSignatureAlg("SHA256withRSA");
configuration.setForceKeystoreGeneration(true);
configuration.setKeystoreResourceUrl("http://localhost:8085/keystore");
configuration.setKeystorePassword("pac4j");
configuration.setPrivateKeyPassword("pac4j");
configuration.setServiceProviderMetadataResource(new FileSystemResource("target/out.xml"));
configuration.setIdentityProviderMetadataResource(new ClassPathResource("idp-metadata.xml"));
configuration.init();
final CredentialProvider provider = new KeyStoreCredentialProvider(configuration);
assertNotNull(provider.getCredentialResolver());
assertNotNull(provider.getCredential());
assertNotNull(provider.getKeyInfo());
} finally {
wireMockServer.stop();
}
}
}
| apache-2.0 |
stanford-futuredata/macrobase | sql/src/main/java/edu/stanford/futuredata/macrobase/sql/tree/JoinCriteria.java | 966 | /*
* 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.stanford.futuredata.macrobase.sql.tree;
import java.util.List;
public abstract class JoinCriteria {
// Force subclasses to have a proper equals and hashcode implementation
@Override
public abstract boolean equals(Object obj);
@Override
public abstract int hashCode();
@Override
public abstract String toString();
public abstract List<Node> getNodes();
}
| apache-2.0 |
mikkokar/styx | components/proxy/src/main/java/com/hotels/styx/proxy/plugin/PluginFactoryLoader.java | 902 | /*
Copyright (C) 2013-2018 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.proxy.plugin;
import com.hotels.styx.api.plugins.spi.PluginFactory;
import com.hotels.styx.spi.config.SpiExtension;
/**
* An interface for loading PluginFactory objects from various sources.
*
*/
public interface PluginFactoryLoader {
PluginFactory load(SpiExtension spiExtension);
}
| apache-2.0 |
TaoXiao/Scala | lang/src/main/java/cn/gridx/java/lang/context/CalculationContext.java | 2649 | package cn.gridx.java.lang.context;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Ping on 9/21/2014.
*/
public class CalculationContext implements Serializable {
public static final ThreadLocal userThreadLocal = new ThreadLocal();
public static void setCurrentContext(CalculationContext context) {
userThreadLocal.set(context);
DateTimeZone.setDefault(context.getTimeZone());
}
public static void unset() {
userThreadLocal.remove();
}
public static CalculationContext getCurrentContext() {
return (CalculationContext) userThreadLocal.get();
}
/////////////////////////////////////////////////////////////////////////////
private DateTimeZone timeZone;
private boolean redisCache;
private HashMap<String,Object> option; //may need String, DateTime
public CalculationContext(DateTimeZone zone, HashMap<String,Object> option, boolean redis) {
setTimeZone(zone);
setRedisCache(redis);
setOptionMap(option);
}
public DateTimeZone getTimeZone() {
return timeZone;
}
public void setTimeZone(DateTimeZone timeZone) {
this.timeZone = timeZone;
}
public boolean isRedisCache() {
return redisCache;
}
public void setRedisCache(boolean redisCache) {
this.redisCache = redisCache;
}
private Map<String,Object> getOption() {
if (option != null)
return option;
else {
setOptionMap(new HashMap<String,Object>());
return getOption();
}
}
private void setOptionMap(HashMap<String,Object> option) {
if (option == null)
setOptionMap(new HashMap<String,Object>());
else
this.option = option;
}
public void setOption(String key, Object value){
Map map = getOption();
if (value==null)
map.remove(key);
else
map.put(key, value);
}
public Object getOption(String key) {
Map map = getOption();
Object o = map.get(key);
return o;
}
public String getOptionString(String key) {
Map map = getOption();
Object o = map.get(key);
if (o != null)
return o.toString();
else return null;
}
public DateTime getOptionDateTime(String key) {
Map map = getOption();
Object o =map.get(key);
if (o!=null && o instanceof DateTime)
return ((DateTime)o);
else return null;
}
}
| apache-2.0 |
evandor/skysail | skysail.server.app.ref.one2one/test/io/skysail/server/app/ref/one2one/test/RunCucumberTests.java | 327 | package io.skysail.server.app.ref.one2one.test;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
//features
plugin = {"pretty", "json:generated/cucumber.json"}
)
public class RunCucumberTests { // NOSONAR
}
| apache-2.0 |
OpenUniversity/ovirt-engine | backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/memory/sdcomparators/StorageDomainNumberOfVmDisksComparatorTest.java | 2062 | package org.ovirt.engine.core.bll.memory.sdcomparators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
public class StorageDomainNumberOfVmDisksComparatorTest extends StorageDomainComparatorAbstractTest {
private List<StorageDomain> storageDomains;
private DiskImage vmDisk1;
private DiskImage vmDisk2;
private DiskImage vmDisk3;
@Before
@Override
public void setUp() {
super.setUp();
storageDomains = Arrays.asList(storageDomain1, storageDomain2);
vmDisk1 = new DiskImage();
vmDisk2 = new DiskImage();
vmDisk3 = new DiskImage();
}
@Test
public void compareWhenStorageDomainsHaveNoDisks() {
initComparator();
assertEqualsTo(storageDomain1, storageDomain2);
}
@Test
public void compareWhenSizesAreEqual() {
attachVmDisksToStorageDomain(storageDomain1, vmDisk1);
attachVmDisksToStorageDomain(storageDomain2, vmDisk2);
initComparator(vmDisk1, vmDisk2);
assertEqualsTo(storageDomain1, storageDomain2);
}
@Test
public void compareWhenSizesAreNotEqual() {
attachVmDisksToStorageDomain(storageDomain1, vmDisk1, vmDisk2);
attachVmDisksToStorageDomain(storageDomain2, vmDisk3);
initComparator(vmDisk1, vmDisk2, vmDisk3);
assertBiggerThan(storageDomain1, storageDomain2);
assertSmallerThan(storageDomain2, storageDomain1);
}
private void attachVmDisksToStorageDomain(StorageDomain storageDomain, DiskImage... vmDisks) {
for (DiskImage diskImage : vmDisks) {
diskImage.setStorageIds(new ArrayList<>(Arrays.asList(storageDomain.getId())));
}
}
private void initComparator(DiskImage... vmDisks) {
comparator = new StorageDomainNumberOfVmDisksComparator(storageDomains, Arrays.asList(vmDisks));
}
}
| apache-2.0 |
andrew-sumner/cubano | src/main/java/org/concordion/cubano/utils/ActionTimer.java | 3595 | package org.concordion.cubano.utils;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Logs the duration of an action.
*
* @author Andrew Sumner
*/
public class ActionTimer {
private final ZonedDateTime startwait;
private final Logger logger;
private ActionTimer(Logger logger) {
this.logger = logger;
this.startwait = now();
}
/**
* Start a new timer using, no logging will be performed.
*
* @return new ActionTimer
*/
public static ActionTimer start() {
return new ActionTimer(LoggerFactory.getLogger(ActionTimer.class.getName()));
}
/**
* Start a new timer, providing a logger to use.
*
* @param logger Logger to use for any logging
* @return new ActionTimer
*/
public static ActionTimer start(Logger logger) {
return new ActionTimer(logger);
}
/**
* Start a new timer, logging the supplied message.
* <p>
* Example:
* <p>
* <pre>ActionTimer timer = ActionTimer.start(LOGGER, "Starting action");</pre>
*
* @param logger Logger to use for any logging
* @param format Formatted message string, argument place holders can be embedded with {} marker
* @param args List of arguments for the message format string
* @return new ActionTimer
*/
public static ActionTimer start(Logger logger, String format, Object... args) {
logger.debug(format, args);
return new ActionTimer(logger);
}
/**
* The duration between the time the start method was called and now.
*
* @return Duration
*/
public Duration duration() {
return Duration.between(startwait, now());
}
/**
* Log supplied message.
* <p>
* Example:
* <p>
* <pre>timer.stop("Action completed in {} seconds", timer.duration().getSeconds());</pre>
*
* @param format Formatted message string, argument place holders can be embedded with {} marker
* @param args List of arguments for the message format string
*/
public void stop(String format, Object... args) {
stop(LogLevel.DEBUG, format, args);
}
/**
* Log the supplied message at the specified level.
*
* @param level Log level
* @param format Formatted message string, argument place holders can be embedded with {} marker
* @param args List of arguments for the message format string
*/
public void stop(LogLevel level, String format, Object... args) {
switch (level) {
case INFO:
logger.info(format, args);
break;
case DEBUG:
logger.debug(format, args);
break;
case TRACE:
logger.trace(format, args);
break;
default:
throw new IllegalArgumentException("Unknown LogLevel");
}
}
private static ZonedDateTime now() {
return ZonedDateTime.now();
}
/**
* Allowed log levels.
*/
public enum LogLevel {
INFO, DEBUG, TRACE;
}
/**
* Check if timer has passed supplied duration.
*
* @param unit Unit of time
* @param duration Duration
* @return True if time since timer was started is more that supplied value
*/
public boolean hasPassed(TimeUnit unit, long duration) {
return startwait.plusSeconds(unit.toSeconds(duration)).isAfter(now());
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/waf_regional/transform/TimeWindowMarshaller.java | 2289 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.waf.model.waf_regional.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.waf.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* TimeWindowMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class TimeWindowMarshaller {
private static final MarshallingInfo<java.util.Date> STARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StartTime").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<java.util.Date> ENDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EndTime").timestampFormat("unixTimestamp").build();
private static final TimeWindowMarshaller instance = new TimeWindowMarshaller();
public static TimeWindowMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(TimeWindow timeWindow, ProtocolMarshaller protocolMarshaller) {
if (timeWindow == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(timeWindow.getStartTime(), STARTTIME_BINDING);
protocolMarshaller.marshall(timeWindow.getEndTime(), ENDTIME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
iservport/helianto-spring | src/main/scala/org/helianto/user/service/UserPostInstallService.java | 200 | package org.helianto.user.service;
import org.helianto.user.domain.User;
public interface UserPostInstallService {
User systemPostInstall(User group);
User userPostInstall(User user);
}
| apache-2.0 |
halober/ovirt-engine | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/RemoveStoragePoolCommand.java | 17408 | package org.ovirt.engine.core.bll.storage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.LockMessagesMatchUtil;
import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute;
import org.ovirt.engine.core.bll.network.ExternalNetworkManager;
import org.ovirt.engine.core.bll.network.MacPoolManager;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.DetachStorageDomainFromPoolParameters;
import org.ovirt.engine.core.common.action.RemoveStorageDomainParameters;
import org.ovirt.engine.core.common.action.StoragePoolParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.VmNic;
import org.ovirt.engine.core.common.businessentities.network.VnicProfile;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.FormatStorageDomainVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.ISingleAsyncOperation;
import org.ovirt.engine.core.utils.SyncronizeNumberOfAsyncOperations;
import org.ovirt.engine.core.utils.linq.LinqUtils;
import org.ovirt.engine.core.utils.linq.Predicate;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
import org.ovirt.engine.core.vdsbroker.irsbroker.SpmStopOnIrsVDSCommandParameters;
@NonTransactiveCommandAttribute(forceCompensation = true)
public class RemoveStoragePoolCommand<T extends StoragePoolParametersBase> extends StorageHandlingCommandBase<T> {
private Map<String, Pair<String, String>> sharedLocks;
public RemoveStoragePoolCommand(T parameters) {
super(parameters);
}
protected RemoveStoragePoolCommand(Guid commandId) {
super(commandId);
}
@Override
protected void executeCommand() {
List<String> macsToRemove = getVmNicDao().getAllMacsByDataCenter(getStoragePool().getId());
removeNetworks();
/**
* Detach master storage domain last.
*/
List<StorageDomain> storageDomains = getStorageDomainDAO().getAllForStoragePool(getStoragePool().getId());
Collections.sort(storageDomains, new Comparator<StorageDomain>() {
@Override
public int compare(StorageDomain o1, StorageDomain o2) {
return o1.getStorageDomainType().compareTo(o2.getStorageDomainType());
}
});
if (storageDomains.size() > 0) {
if (!getParameters().getForceDelete() && getAllRunningVdssInPool().size() > 0) {
if(!regularRemoveStorageDomains(storageDomains)) {
setSucceeded(false);
return;
}
} else if (getParameters().getForceDelete()) {
forceRemoveStorageDomains(storageDomains);
} else {
return;
}
}
removeDataCenter();
MacPoolManager.getInstance().freeMacs(macsToRemove);
setSucceeded(true);
}
private void removeDataCenter() {
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
getCompensationContext().snapshotEntity(getStoragePool());
getStoragePoolDAO().remove(getStoragePool().getId());
getCompensationContext().stateChanged();
return null;
}
});
}
private void removeNetworks() {
final List<Network> networks = getNetworkDAO().getAllForDataCenter(getStoragePoolId());
for (Network network : networks) {
if (network.isExternal()) {
for (VmNic nic : getVmNicDao().getAllForNetwork(network.getId())) {
new ExternalNetworkManager(nic, network).deallocateIfExternal();
}
}
}
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
for (final Network net : networks) {
List<VnicProfile> profiles = getDbFacade().getVnicProfileDao().getAllForNetwork(net.getId());
for (VnicProfile vnicProfile : profiles) {
getCompensationContext().snapshotEntity(vnicProfile);
getDbFacade().getVnicProfileDao().remove(vnicProfile.getId());
}
getCompensationContext().snapshotEntity(net);
getNetworkDAO().remove(net.getId());
}
getCompensationContext().stateChanged();
return null;
}
});
}
private void forceRemoveStorageDomains(List<StorageDomain> storageDomains) {
StorageDomain masterDomain = null;
for (StorageDomain storageDomain : storageDomains) {
if (storageDomain.getStorageDomainType() != StorageDomainType.Master) {
if (storageDomain.getStorageDomainType() != StorageDomainType.ISO) {
removeDomainFromDb(storageDomain);
}
} else {
masterDomain = storageDomain;
}
}
if (masterDomain != null) {
removeDomainFromDb(masterDomain);
}
}
private boolean regularRemoveStorageDomains(List<StorageDomain> storageDomains) {
boolean retVal = true;
List<StorageDomain> temp = LinqUtils.filter(storageDomains, new Predicate<StorageDomain>() {
@Override
public boolean eval(StorageDomain storage_domain) {
return storage_domain.getStorageDomainType() == StorageDomainType.Master;
}
});
final StorageDomain masterDomain = LinqUtils.first(temp);
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
getCompensationContext().snapshotEntity(masterDomain.getStoragePoolIsoMapData());
masterDomain.setStatus(StorageDomainStatus.Locked);
getDbFacade().getStoragePoolIsoMapDao().update(masterDomain.getStoragePoolIsoMapData());
getCompensationContext().stateChanged();
return null;
}
});
// destroying a pool is an SPM action. We need to connect all hosts
// to the pool. Later on, during spm election, one of the hosts will
// lock the pool
// and the spm status will be FREE. Only then we can invoke the
// destroy verb.
connectAllHostToPoolAndDomain(masterDomain);
List<VDS> vdss = getAllRunningVdssInPool();
for (StorageDomain storageDomain : storageDomains) {
if (storageDomain.getStorageDomainType() != StorageDomainType.Master) {
if (!removeDomainFromPool(storageDomain, vdss.get(0))) {
log.errorFormat("Unable to detach storage domain {0} {1}",
storageDomain.getStorageName(),
storageDomain.getId());
retVal = false;
}
}
}
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
detachStorageDomainWithEntities(masterDomain);
getCompensationContext().snapshotEntity(masterDomain.getStorageStaticData());
masterDomain.setStorageDomainType(StorageDomainType.Data);
getDbFacade().getStorageDomainStaticDao().update(masterDomain.getStorageStaticData());
getCompensationContext().stateChanged();
return null;
}
});
handleDestroyStoragePoolCommand();
setSucceeded(true);
if (!getStoragePool().isLocal()) {
for (VDS vds : vdss) {
StorageHelperDirector.getInstance().getItem(masterDomain.getStorageType())
.disconnectStorageFromDomainByVdsId(masterDomain, vds.getId());
}
} else {
try {
runVdsCommand(VDSCommandType.FormatStorageDomain,
new FormatStorageDomainVDSCommandParameters(vdss.get(0).getId(),
masterDomain.getId()));
} catch (VdcBLLException e) {
// Do nothing, exception already printed at logs
}
StorageHelperDirector.getInstance().getItem(masterDomain.getStorageType())
.disconnectStorageFromDomainByVdsId(masterDomain, vdss.get(0).getId());
removeDomainFromDb(masterDomain);
}
runSynchronizeOperation(new DisconnectStoragePoolAsyncOperationFactory());
return retVal;
}
private void handleDestroyStoragePoolCommand() {
try {
runVdsCommand(VDSCommandType.DestroyStoragePool,
new IrsBaseVDSCommandParameters(getStoragePool().getId()));
} catch (VdcBLLException e) {
try {
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
runVdsCommand(VDSCommandType.SpmStopOnIrs,
new SpmStopOnIrsVDSCommandParameters(getStoragePool().getId()));
return null;
}
});
} catch (Exception e1) {
log.errorFormat("Failed destroy storage pool with id {0} and after that failed to stop spm because of {1}",
getStoragePoolId(),
e1);
}
throw e;
}
}
private void removeDomainFromDb(final StorageDomain domain) {
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
// Not compensation for remove domain as we don't want
// to rollback a deleted domain - it will only cause more
// problems if a domain got deleted in VDSM and not in backend
// as it will be impossible to remove it.
StorageHelperDirector.getInstance().getItem(domain.getStorageType())
.storageDomainRemoved(domain.getStorageStaticData());
getStorageDomainDAO().remove(domain.getId());
return null;
}
});
}
protected boolean removeDomainFromPool(StorageDomain storageDomain, VDS vds) {
if (storageDomain.getStorageType() != StorageType.LOCALFS
|| storageDomain.getStorageDomainType() == StorageDomainType.ISO) {
DetachStorageDomainFromPoolParameters tempVar = new DetachStorageDomainFromPoolParameters(
storageDomain.getId(), getStoragePool().getId());
tempVar.setRemoveLast(true);
tempVar.setDestroyingPool(true);
// Compensation context is not passed, as we do not want to compensate in case of failure
// in detach of one of storage domains
if (!Backend.getInstance()
.runInternalAction(VdcActionType.DetachStorageDomainFromPool, tempVar)
.getSucceeded()) {
return false;
}
} else {
RemoveStorageDomainParameters tempVar = new RemoveStorageDomainParameters(storageDomain.getId());
tempVar.setDestroyingPool(true);
tempVar.setDoFormat(true);
tempVar.setVdsId(vds.getId());
if (!runInternalAction(VdcActionType.RemoveStorageDomain, tempVar, cloneContext().withoutLock().withoutExecutionContext())
.getSucceeded()) {
return false;
}
}
return true;
}
@Override
protected boolean canDoAction() {
if (!super.canDoAction() ||
!checkStoragePool() ||
!checkStoragePoolStatusNotEqual(StoragePoolStatus.Up,
VdcBllMessages.ERROR_CANNOT_REMOVE_ACTIVE_STORAGE_POOL)) {
return false;
}
if (getStoragePool().getStatus() != StoragePoolStatus.Uninitialized && !getParameters().getForceDelete()
&& !initializeVds()) {
return false;
}
final List<StorageDomain> poolDomains =
getStorageDomainDAO().getAllForStoragePool(getStoragePool().getId());
final List<StorageDomain> activeOrLockedDomains = getActiveOrLockedDomainList(poolDomains);
if (!activeOrLockedDomains.isEmpty()) {
return failCanDoAction(VdcBllMessages.ERROR_CANNOT_REMOVE_POOL_WITH_ACTIVE_DOMAINS);
}
if (!getParameters().getForceDelete()) {
if(poolDomains.size() > 1) {
return failCanDoAction(VdcBllMessages.ERROR_CANNOT_REMOVE_STORAGE_POOL_WITH_NONMASTER_DOMAINS);
}
if (!poolDomains.isEmpty() && !canDetachStorageDomainWithVmsAndDisks(poolDomains.get(0))) {
return false;
}
} else {
List<VDS> poolHosts = getVdsDAO().getAllForStoragePool(getParameters().getStoragePoolId());
sharedLocks = new HashMap<String, Pair<String, String>>();
for (VDS host : poolHosts) {
sharedLocks.put(host.getId().toString(),
LockMessagesMatchUtil.makeLockingPair(LockingGroup.VDS, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED));
}
if (!poolHosts.isEmpty() && acquireLockInternal()) {
for (VDS host : poolHosts) {
if (host.getStatus() != VDSStatus.Maintenance) {
return failCanDoAction(VdcBllMessages.ERROR_CANNOT_FORCE_REMOVE_STORAGE_POOL_WITH_VDS_NOT_IN_MAINTENANCE);
}
}
}
}
return true;
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(VdcBllMessages.VAR__TYPE__STORAGE__POOL);
addCanDoActionMessage(VdcBllMessages.VAR__ACTION__REMOVE);
}
protected List<StorageDomain> getActiveOrLockedDomainList(List<StorageDomain> domainsList) {
domainsList = LinqUtils.filter(domainsList, new Predicate<StorageDomain>() {
@Override
public boolean eval(StorageDomain dom) {
return (dom.getStatus() == StorageDomainStatus.Active || dom.getStatus().isStorageDomainInProcess());
}
});
return domainsList;
}
@Override
public AuditLogType getAuditLogTypeValue() {
if (getParameters().getForceDelete()){
return getSucceeded() ? AuditLogType.USER_FORCE_REMOVE_STORAGE_POOL : AuditLogType.USER_FORCE_REMOVE_STORAGE_POOL_FAILED;
}
return getSucceeded() ? AuditLogType.USER_REMOVE_STORAGE_POOL : AuditLogType.USER_REMOVE_STORAGE_POOL_FAILED;
}
/**
* @param masterDomain
* Connect all hosts to the pool and to the domains
*/
protected void connectAllHostToPoolAndDomain(final StorageDomain masterDomain) {
final List<VDS> vdsList = getAllRunningVdssInPool();
final StoragePool storagePool = getStoragePool();
SyncronizeNumberOfAsyncOperations sync = new SyncronizeNumberOfAsyncOperations(vdsList.size(),
null, new ActivateDeactivateSingleAsyncOperationFactory() {
@Override
public ISingleAsyncOperation createSingleAsyncOperation() {
return new ConntectVDSToPoolAndDomains((ArrayList<VDS>) vdsList, masterDomain, storagePool);
}
@Override
public void initialize(ArrayList parameters) {
// no need to initilalize params
}
});
sync.execute();
}
@Override
protected Map<String, Pair<String, String>> getSharedLocks() {
return sharedLocks;
}
}
| apache-2.0 |
aaronanderson/ode | axis2-war/src/test/java/org/apache/ode/axis2/rampart/policy/SecuredProcessesTest.java | 5738 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.axis2.rampart.policy;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.client.Options;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.ode.utils.DOMUtils;
import org.apache.ode.il.OMUtils;
import org.apache.ode.axis2.Axis2TestBase;
import org.apache.neethi.PolicyEngine;
import org.apache.neethi.Policy;
import org.apache.rampart.RampartMessageData;
import java.io.File;
import java.io.FileFilter;
/**
*
*
*/
public class SecuredProcessesTest extends Axis2TestBase {
private String testDir = "TestRampartPolicy/secured-processes";
private String clientRepo = getClass().getClassLoader().getResource(testDir).getFile();
@DataProvider(name = "secured-processes-bundles")
public Object[][] testPolicySamples() throws Exception {
File[] samples = new File(getClass().getClassLoader().getResource(testDir).getFile()).listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() && pathname.getName().matches("process-sample0\\d");
}
});
Object[][] bundles = new Object[samples.length][];
for (int i = 0; i < samples.length; i++) {
String sampleIndex = samples[i].getName().replace("process-", "");
String policyFile = clientRepo + "/" + sampleIndex + "-policy.xml";
bundles[i] = new Object[]{testDir + "/" + samples[i].getName(), clientRepo, policyFile};
}
// bundles = new Object[][]{new Object[]{testDir+"/process-sample04", clientRepo, clientRepo+"/sample04-policy.xml"}};
return bundles;
}
@BeforeMethod
protected void setUp() throws Exception {
// mind the annotation above: start the server only once for all tests
startServer(testDir, "webapp/WEB-INF/conf/axis2.xml");
}
@AfterMethod
protected void tearDown() throws Exception {
// mind the annotation above: start the server only once for all tests
super.tearDown();
}
@Test(dataProvider = "secured-processes-bundles")
public void invokeSecuredProcesses(String bundleName, String clientRepo, String policyFile) throws Exception {
if (server.isDeployed(new File(bundleName).getName())) {
server.undeployProcess(bundleName);
}
server.deployProcess(bundleName);
try {
ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(clientRepo, null);
ServiceClient client = new ServiceClient(ctx, null);
Options options = new Options();
// Rampart SymetricBinding (sample04) blows up if not provided with a soap action
options.setAction("");
options.setTo(new EndpointReference("http://localhost:8888/processes/helloWorld"));
options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy(policyFile));
client.setOptions(options);
client.engageModule("rampart");
client.engageModule("rahas");
OMElement responseElement = client.sendReceive(getPayload(bundleName));
String response = DOMUtils.domToString(OMUtils.toDOM(responseElement));
System.out.println(response);
System.out.println(response);
assertTrue(response.contains("<helloResponse") && response.contains("Hello " + bundleName + "!"));
} finally {
server.undeployProcess(bundleName);
}
}
@Test
public void standAlonePolicy() throws Exception {
invokeSecuredProcesses(testDir+"/process-sample02_standalone_policy", clientRepo, clientRepo+"/sample02-policy.xml");
}
private static Policy loadPolicy(String xmlPath) throws Exception {
StAXOMBuilder builder = new StAXOMBuilder(xmlPath);
return PolicyEngine.getPolicy(builder.getDocumentElement());
}
private static OMElement getPayload(String value) {
OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace ns = factory.createOMNamespace("http://ode/bpel/unit-test.wsdl", "ns1");
OMElement elem = factory.createOMElement("hello", ns);
OMElement childElem = factory.createOMElement("TestPart", null);
childElem.setText(value);
elem.addChild(childElem);
return elem;
}
}
| apache-2.0 |
marianpavel/snAIke-android | app/src/main/java/ro/marianpavel/snaike/MainActivity.java | 468 | package ro.marianpavel.snaike;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| apache-2.0 |
hortonworks/cloudbreak | cloud-template/src/main/java/com/sequenceiq/cloudbreak/cloud/template/group/GroupResourceService.java | 8947 | package com.sequenceiq.cloudbreak.cloud.template.group;
import static com.sequenceiq.cloudbreak.cloud.scheduler.PollGroup.CANCELLED;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.context.CloudContext;
import com.sequenceiq.cloudbreak.cloud.model.CloudResource;
import com.sequenceiq.cloudbreak.cloud.model.CloudResourceStatus;
import com.sequenceiq.cloudbreak.cloud.model.Group;
import com.sequenceiq.cloudbreak.cloud.model.Network;
import com.sequenceiq.cloudbreak.cloud.model.Security;
import com.sequenceiq.cloudbreak.cloud.model.Variant;
import com.sequenceiq.cloudbreak.cloud.notification.PersistenceNotifier;
import com.sequenceiq.cloudbreak.cloud.scheduler.PollGroup;
import com.sequenceiq.cloudbreak.cloud.scheduler.SyncPollingScheduler;
import com.sequenceiq.cloudbreak.cloud.store.InMemoryStateStore;
import com.sequenceiq.cloudbreak.cloud.task.PollTask;
import com.sequenceiq.cloudbreak.cloud.template.GroupResourceBuilder;
import com.sequenceiq.cloudbreak.cloud.template.NetworkResourceBuilder;
import com.sequenceiq.cloudbreak.cloud.template.ResourceNotNeededException;
import com.sequenceiq.cloudbreak.cloud.template.context.ResourceBuilderContext;
import com.sequenceiq.cloudbreak.cloud.template.init.ResourceBuilders;
import com.sequenceiq.cloudbreak.cloud.template.task.ResourcePollTaskFactory;
import com.sequenceiq.common.api.type.ResourceType;
@Service
public class GroupResourceService {
private static final Logger LOGGER = LoggerFactory.getLogger(GroupResourceService.class);
@Inject
private ResourceBuilders resourceBuilders;
@Inject
private SyncPollingScheduler<List<CloudResourceStatus>> syncPollingScheduler;
@Inject
private ResourcePollTaskFactory statusCheckFactory;
@Inject
private PersistenceNotifier resourceNotifier;
public List<CloudResourceStatus> buildResources(ResourceBuilderContext context,
AuthenticatedContext auth, Iterable<Group> groups, Network network, Security security) throws Exception {
CloudContext cloudContext = auth.getCloudContext();
List<CloudResourceStatus> results = new ArrayList<>();
for (GroupResourceBuilder<ResourceBuilderContext> builder : resourceBuilders.group(cloudContext.getVariant())) {
PollGroup pollGroup = InMemoryStateStore.getStack(auth.getCloudContext().getId());
if (CANCELLED.equals(pollGroup)) {
break;
}
for (Group group : getOrderedCopy(groups)) {
try {
CloudResource buildableResource = builder.create(context, auth, group, network);
if (buildableResource != null) {
buildableResource = CloudResource.builder().cloudResource(buildableResource).group(group.getName()).build();
createResource(auth, buildableResource);
CloudResource resource = builder.build(context, auth, group, network, group.getSecurity(), buildableResource);
updateResource(auth, resource);
PollTask<List<CloudResourceStatus>> task = statusCheckFactory.newPollResourceTask(builder, auth, Collections.singletonList(resource),
context, true);
List<CloudResourceStatus> pollerResult = syncPollingScheduler.schedule(task);
context.addGroupResources(group.getName(), Collections.singletonList(resource));
results.addAll(pollerResult);
} else {
LOGGER.debug("CloudResource is null for {} with resourceType: {} and builder: {}, build is skipped.",
group.getName(), builder.resourceType(), builder.getClass().getSimpleName());
}
} catch (ResourceNotNeededException e) {
LOGGER.debug("Skipping resource creation: {}", e.getMessage());
}
}
}
return results;
}
public List<CloudResourceStatus> deleteResources(ResourceBuilderContext context,
AuthenticatedContext auth, Collection<CloudResource> resources, Network network, boolean cancellable) throws Exception {
CloudContext cloudContext = auth.getCloudContext();
List<CloudResourceStatus> results = new ArrayList<>();
List<GroupResourceBuilder<ResourceBuilderContext>> builderChain = resourceBuilders.group(cloudContext.getVariant());
for (int i = builderChain.size() - 1; i >= 0; i--) {
GroupResourceBuilder<ResourceBuilderContext> builder = builderChain.get(i);
List<CloudResource> specificResources = getResources(resources, builder.resourceType());
for (CloudResource resource : specificResources) {
if (resource.getStatus().resourceExists()) {
CloudResource deletedResource = builder.delete(context, auth, resource, network);
if (deletedResource != null) {
PollTask<List<CloudResourceStatus>> task = statusCheckFactory.newPollResourceTask(
builder, auth, Collections.singletonList(deletedResource), context, cancellable);
List<CloudResourceStatus> pollerResult = syncPollingScheduler.schedule(task);
results.addAll(pollerResult);
}
}
resourceNotifier.notifyDeletion(resource, cloudContext);
}
}
return results;
}
public List<CloudResourceStatus> update(ResourceBuilderContext context, AuthenticatedContext auth,
Network network, Security security, Collection<CloudResource> groupResources) throws Exception {
List<CloudResourceStatus> results = new ArrayList<>();
CloudContext cloudContext = auth.getCloudContext();
for (NetworkResourceBuilder<ResourceBuilderContext> builder : resourceBuilders.network(cloudContext.getVariant())) {
List<CloudResource> resources = getResources(groupResources, builder.resourceType());
for (CloudResource resource : resources) {
CloudResourceStatus status = builder.update(context, auth, network, security, resource);
if (status != null) {
PollTask<List<CloudResourceStatus>> task = statusCheckFactory.newPollResourceTask(
builder, auth, Collections.singletonList(status.getCloudResource()), context, true);
List<CloudResourceStatus> pollerResult = syncPollingScheduler.schedule(task);
results.addAll(pollerResult);
}
}
}
return results;
}
public List<CloudResource> getGroupResources(Variant variant, Collection<CloudResource> resources) {
Collection<ResourceType> types = new ArrayList<>();
for (GroupResourceBuilder<?> builder : resourceBuilders.group(variant)) {
types.add(builder.resourceType());
}
return getResources(resources, types);
}
protected void createResource(AuthenticatedContext auth, CloudResource buildableResource) {
if (buildableResource.isPersistent()) {
resourceNotifier.notifyAllocation(buildableResource, auth.getCloudContext());
}
}
protected void updateResource(AuthenticatedContext auth, CloudResource buildableResource) {
if (buildableResource.isPersistent()) {
resourceNotifier.notifyUpdate(buildableResource, auth.getCloudContext());
}
}
private List<CloudResource> getResources(Collection<CloudResource> resources, ResourceType type) {
return getResources(resources, Collections.singletonList(type));
}
private List<CloudResource> getResources(Collection<CloudResource> resources, Collection<ResourceType> types) {
List<CloudResource> filtered = new ArrayList<>(resources.size());
for (CloudResource resource : resources) {
if (types.contains(resource.getType())) {
filtered.add(resource);
}
}
return filtered;
}
private Iterable<Group> getOrderedCopy(Iterable<Group> groups) {
Ordering<Group> byLengthOrdering = new Ordering<>() {
@Override
public int compare(Group left, Group right) {
return Ints.compare(left.getInstancesSize(), right.getInstancesSize());
}
};
return byLengthOrdering.sortedCopy(groups);
}
}
| apache-2.0 |
stagraqubole/presto | presto-hive/src/test/java/com/facebook/presto/hive/AbstractTestHiveClientS3.java | 12914 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.hive;
import com.facebook.presto.hive.metastore.CachingHiveMetastore;
import com.facebook.presto.hive.shaded.org.apache.thrift.TException;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.ConnectorColumnHandle;
import com.facebook.presto.spi.ConnectorPartitionResult;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.ConnectorSplitSource;
import com.facebook.presto.spi.ConnectorTableHandle;
import com.facebook.presto.spi.ConnectorTableMetadata;
import com.facebook.presto.spi.RecordCursor;
import com.facebook.presto.spi.RecordSink;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.TupleDomain;
import com.facebook.presto.type.TypeRegistry;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.HostAndPort;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Table;
import org.testng.annotations.Test;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import static com.facebook.presto.hadoop.HadoopFileStatus.isDirectory;
import static com.facebook.presto.hive.util.Types.checkType;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.TimeZoneKey.UTC_KEY;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
@Test(groups = "hive-s3")
public abstract class AbstractTestHiveClientS3
{
private static final ConnectorSession SESSION = new ConnectorSession("user", "test", "default", "default", UTC_KEY, Locale.ENGLISH, null, null);
protected String database;
protected SchemaTableName tableS3;
protected SchemaTableName temporaryCreateTable;
protected HdfsEnvironment hdfsEnvironment;
protected TestingHiveMetastore metastoreClient;
protected HiveClient client;
protected void setupHive(String databaseName)
{
database = databaseName;
tableS3 = new SchemaTableName(database, "presto_test_s3");
String random = UUID.randomUUID().toString().toLowerCase().replace("-", "");
temporaryCreateTable = new SchemaTableName(database, "tmp_presto_test_create_s3_" + random);
}
protected void setup(String host, int port, String databaseName, String awsAccessKey, String awsSecretKey, String writableBucket)
{
setupHive(databaseName);
HiveClientConfig hiveClientConfig = new HiveClientConfig()
.setS3AwsAccessKey(awsAccessKey)
.setS3AwsSecretKey(awsSecretKey);
String proxy = System.getProperty("hive.metastore.thrift.client.socks-proxy");
if (proxy != null) {
hiveClientConfig.setMetastoreSocksProxy(HostAndPort.fromString(proxy));
}
HiveCluster hiveCluster = new TestingHiveCluster(hiveClientConfig, host, port);
ExecutorService executor = newCachedThreadPool(daemonThreadsNamed("hive-s3-%s"));
hdfsEnvironment = new HdfsEnvironment(new HdfsConfiguration(hiveClientConfig));
metastoreClient = new TestingHiveMetastore(hiveCluster, executor, hiveClientConfig, writableBucket);
client = new HiveClient(
new HiveConnectorId("hive-test"),
hiveClientConfig,
metastoreClient,
new NamenodeStats(),
new HdfsEnvironment(new HdfsConfiguration(hiveClientConfig)),
new HadoopDirectoryLister(),
sameThreadExecutor(),
new TypeRegistry());
}
@Test
public void testGetRecordsS3()
throws Exception
{
ConnectorTableHandle table = getTableHandle(tableS3);
List<ConnectorColumnHandle> columnHandles = ImmutableList.copyOf(client.getColumnHandles(table).values());
Map<String, Integer> columnIndex = indexColumns(columnHandles);
ConnectorPartitionResult partitionResult = client.getPartitions(table, TupleDomain.<ConnectorColumnHandle>all());
assertEquals(partitionResult.getPartitions().size(), 1);
ConnectorSplitSource splitSource = client.getPartitionSplits(table, partitionResult.getPartitions());
long sum = 0;
for (ConnectorSplit split : getAllSplits(splitSource)) {
try (RecordCursor cursor = client.getRecordSet(split, columnHandles).cursor()) {
while (cursor.advanceNextPosition()) {
sum += cursor.getLong(columnIndex.get("t_bigint"));
}
}
}
assertEquals(sum, 78300);
}
@Test
public void testGetFileStatus()
throws Exception
{
Path basePath = new Path("s3://presto-test-hive/");
Path tablePath = new Path(basePath, "presto_test_s3");
Path filePath = new Path(tablePath, "test1.csv");
FileSystem fs = hdfsEnvironment.getFileSystem(basePath);
assertTrue(isDirectory(fs.getFileStatus(basePath)));
assertTrue(isDirectory(fs.getFileStatus(tablePath)));
assertFalse(isDirectory(fs.getFileStatus(filePath)));
assertFalse(fs.exists(new Path(basePath, "foo")));
}
@Test
public void testTableCreation()
throws Exception
{
try {
doCreateTable(temporaryCreateTable, "presto_test");
}
finally {
dropTable(temporaryCreateTable);
}
}
private void doCreateTable(SchemaTableName tableName, String tableOwner)
throws InterruptedException
{
// begin creating the table
List<ColumnMetadata> columns = ImmutableList.<ColumnMetadata>builder()
.add(new ColumnMetadata("id", BIGINT, 1, false))
.build();
ConnectorTableMetadata tableMetadata = new ConnectorTableMetadata(tableName, columns, tableOwner);
HiveOutputTableHandle outputHandle = client.beginCreateTable(SESSION, tableMetadata);
// write the records
RecordSink sink = client.getRecordSink(outputHandle);
sink.beginRecord(1);
sink.appendLong(1);
sink.finishRecord();
sink.beginRecord(1);
sink.appendLong(3);
sink.finishRecord();
sink.beginRecord(1);
sink.appendLong(2);
sink.finishRecord();
String fragment = sink.commit();
// commit the table
client.commitCreateTable(outputHandle, ImmutableList.of(fragment));
// Hack to work around the metastore not being configured for S3.
// The metastore tries to validate the location when creating the
// table, which fails without explicit configuration for S3.
// We work around that by using a dummy location when creating the
// table and update it here to the correct S3 location.
metastoreClient.updateTableLocation(database, tableName.getTableName(), outputHandle.getTargetPath());
// load the new table
ConnectorTableHandle tableHandle = getTableHandle(tableName);
List<ConnectorColumnHandle> columnHandles = ImmutableList.copyOf(client.getColumnHandles(tableHandle).values());
// verify the data
ConnectorPartitionResult partitionResult = client.getPartitions(tableHandle, TupleDomain.<ConnectorColumnHandle>all());
assertEquals(partitionResult.getPartitions().size(), 1);
ConnectorSplitSource splitSource = client.getPartitionSplits(tableHandle, partitionResult.getPartitions());
ConnectorSplit split = getOnlyElement(getAllSplits(splitSource));
try (RecordCursor cursor = client.getRecordSet(split, columnHandles).cursor()) {
assertTrue(cursor.advanceNextPosition());
assertEquals(cursor.getLong(0), 1);
assertTrue(cursor.advanceNextPosition());
assertEquals(cursor.getLong(0), 3);
assertTrue(cursor.advanceNextPosition());
assertEquals(cursor.getLong(0), 2);
assertFalse(cursor.advanceNextPosition());
}
}
private void dropTable(SchemaTableName table)
{
try {
metastoreClient.dropTable(table.getSchemaName(), table.getTableName());
}
catch (RuntimeException e) {
// this usually occurs because the table was not created
}
}
private ConnectorTableHandle getTableHandle(SchemaTableName tableName)
{
ConnectorTableHandle handle = client.getTableHandle(SESSION, tableName);
checkArgument(handle != null, "table not found: %s", tableName);
return handle;
}
private static List<ConnectorSplit> getAllSplits(ConnectorSplitSource source)
throws InterruptedException
{
ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder();
while (!source.isFinished()) {
splits.addAll(source.getNextBatch(1000));
}
return splits.build();
}
private static ImmutableMap<String, Integer> indexColumns(List<ConnectorColumnHandle> columnHandles)
{
ImmutableMap.Builder<String, Integer> index = ImmutableMap.builder();
int i = 0;
for (ConnectorColumnHandle columnHandle : columnHandles) {
HiveColumnHandle hiveColumnHandle = checkType(columnHandle, HiveColumnHandle.class, "columnHandle");
index.put(hiveColumnHandle.getName(), i);
i++;
}
return index.build();
}
private static class TestingHiveMetastore
extends CachingHiveMetastore
{
private final String writableBucket;
public TestingHiveMetastore(HiveCluster hiveCluster, ExecutorService executor, HiveClientConfig hiveClientConfig, String writableBucket)
{
super(hiveCluster, executor, hiveClientConfig);
this.writableBucket = writableBucket;
}
@Override
public Database getDatabase(String databaseName)
throws NoSuchObjectException
{
Database database = super.getDatabase(databaseName);
database.setLocationUri("s3://" + writableBucket + "/");
return database;
}
@Override
public void createTable(Table table)
{
// hack to work around the metastore not being configured for S3
table.getSd().setLocation("/");
super.createTable(table);
}
@Override
public void dropTable(String databaseName, String tableName)
{
try {
// hack to work around the metastore not being configured for S3
Table table = getTable(databaseName, tableName);
table.getSd().setLocation("/");
try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) {
client.alter_table(databaseName, tableName, table);
client.drop_table(databaseName, tableName, false);
}
}
catch (TException e) {
throw Throwables.propagate(e);
}
}
public void updateTableLocation(String databaseName, String tableName, String location)
{
try {
Table table = getTable(databaseName, tableName);
table.getSd().setLocation(location);
try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) {
client.alter_table(databaseName, tableName, table);
}
}
catch (TException e) {
throw Throwables.propagate(e);
}
}
}
}
| apache-2.0 |
KRMAssociatesInc/eHMP | lib/mvi/org/hl7/v3/SubmucosalRoute.java | 793 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SubmucosalRoute.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="SubmucosalRoute">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="SUBMUCINJ"/>
* <enumeration value="SMUCMAB"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "SubmucosalRoute")
@XmlEnum
public enum SubmucosalRoute {
SUBMUCINJ,
SMUCMAB;
public String value() {
return name();
}
public static SubmucosalRoute fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
uddhavgautam/dynamic-resourceUpdateCheck | app/src/main/java/edu/ualr/cpsc7398/updatechecker/controller/recyclerviewadapter/utils/EditTextLocker.java | 9889 | package edu.ualr.cpsc7398.updatechecker.controller.recyclerviewadapter.utils;
/**
* Created by uddhav on 2/14/17.
*/
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.Toast;
import edu.ualr.cpsc7398.updatechecker.controller.service.utils.DataBean;
import edu.ualr.cpsc7398.updatechecker.controller.service.utils.HttpRequestRunnable;
import edu.ualr.cpsc7398.updatechecker.view.activity.MainActivity;
public class EditTextLocker {
private EditText editText;
private int charactersLimit;
private int fractionLimit;
private MainActivity mainActivity = new MainActivity();
private OnKeyListener editTextOnKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
startStopEditing(false);
}
return false;
}
};
private TextWatcher editTextWatcherForCharacterLimits = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!editText.getText().toString().equalsIgnoreCase("")) {
int editTextLength = editText.getText().toString().trim().length();
if (editTextLength >= charactersLimit) {
startStopEditing(true);
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
private TextWatcher editTextWatcherForFractionLimit = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!editText.getText().toString().equalsIgnoreCase("")) {
String editTextString = editText.getText().toString().trim();
int decimalIndexOf = editTextString.indexOf(".");
if (decimalIndexOf >= 0) {
if (editTextString.substring(decimalIndexOf).length() > fractionLimit) {
startStopEditing(true);
}
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
public EditTextLocker(EditText editText) {
this.editText = editText;
editText.setOnKeyListener(editTextOnKeyListener);
}
public void limitCharacters(final int limit) {
this.charactersLimit = limit;
editText.addTextChangedListener(editTextWatcherForCharacterLimits);
}
public void limitFractionDigitsinDecimal(int fractionLimit) {
this.fractionLimit = fractionLimit;
editText.addTextChangedListener(editTextWatcherForFractionLimit);
}
public void unlockEditText() {
startStopEditing(false);
}
public void startStopEditing(boolean isLock) {
if (isLock) {
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
}
}});
} else {
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
return null;
}
}});
}
}
public void range1to600NoLeading01(int i) {
this.charactersLimit = i; //I already got the editText from the constructor
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!editText.getText().toString().equalsIgnoreCase("")) {
int editTextLength = editText.getText().toString().trim().length();
if (editTextLength >= charactersLimit) {
startStopEditing(true);
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (!editText.getText().toString().equalsIgnoreCase("")) { //if not null
int length = editText.length();
if (length == 1 && editText.getText().toString().equals("0"))
editText.setText("");
DataBean.setTotalUpdates(Integer.parseInt(editText.getText().toString()));
}
}
});
}
public void range1to600NoLeading02(int i) {
this.charactersLimit = i; //I already got the editText from the constructor
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!editText.getText().toString().equalsIgnoreCase("")) {
int editTextLength = editText.getText().toString().trim().length();
if (editTextLength >= charactersLimit) {
startStopEditing(true);
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (!editText.getText().toString().equalsIgnoreCase("")) { //if not null
int length = editText.length();
if (length == 1 && editText.getText().toString().equals("0"))
editText.setText("");
DataBean.setSeed(Integer.parseInt(editText.getText().toString()));
}
}
});
}
public void updateBeanUrl(final Context context) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!(editText.getText().equals(null) || editText.getText().equals(""))) { //if not null
//check if the URL resource is not dynamic. If last-modifed is more than 10 minutes, treat that as static
String urlChanging = editText.getText().toString();
String url = null;
if (urlChanging.contains(" ")) {
url = urlChanging.substring(0, urlChanging.indexOf(" "));
if (!url.equals(null)) {
Log.i("urlchecked: ", url);
if (HttpRequestRunnable.isUrlResourceStatic(url)) {
//Toast should be in UI thread
/*
Why use Runnable over Thread?
Runnable separates code that needs to run asynchronously, from how the code is run. This keeps your code flexible. For instance, asynchronous code in a runnable can run on a threadpool, or a dedicated thread.
A Thread has state your runnable probably doesn't need access to. Having access to more state than necessary is poor design.
Threads occupy a lot of memory. Creating a new thread for every small actions takes processing time to allocate and deallocate this memory.
What is runOnUiThread actually doing?
Android's runOnUiThread queues a Runnable to execute on the UI thread. This is important because you should never update UI from multiple threads. runOnUiThread uses a Handler.
Be aware if the UI thread's queue is full, or the items needing execution are lengthy, it may be some time before your queued Runnable actually runs.
What is a Handler?
A handler allows you to post runnables to execute on a specific thread. Behind the scenes, runOnUi Thread queues your Runnable up with Android's Ui Handler so your runnable can execute safely on the UI thread.
*/
Log.i("Inside toast", "inside toast");
DataBean.setUrl(null);
mainActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast toast = Toast.makeText(context, "This is the static resource, plz. use dynamic resource!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
} else {
DataBean.setUrl(editText.getText().toString());
}
}
}
}
}
});
}
}
| apache-2.0 |
bshp/midPoint | infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/ListXNodeImpl.java | 4435 | /*
* Copyright (c) 2010-2018 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.prism.impl.xnode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import com.evolveum.midpoint.prism.Visitor;
import com.evolveum.midpoint.prism.xnode.ListXNode;
import com.evolveum.midpoint.prism.xnode.XNode;
import com.evolveum.midpoint.util.DebugUtil;
public class ListXNodeImpl extends XNodeImpl implements List<XNodeImpl>, ListXNode {
private final List<XNodeImpl> subnodes = new ArrayList<>();
@Override
public int size() {
return subnodes.size();
}
@Override
public boolean isEmpty() {
return subnodes.isEmpty();
}
@Override
public boolean contains(Object o) {
return subnodes.contains(o);
}
@Override
public Iterator<XNodeImpl> iterator() {
return subnodes.iterator();
}
@Override
public Object[] toArray() {
return subnodes.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return subnodes.toArray(a);
}
@Override
public boolean add(XNodeImpl e) {
return subnodes.add(e);
}
@Override
public boolean remove(Object o) {
return subnodes.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return subnodes.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends XNodeImpl> c) {
return subnodes.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends XNodeImpl> c) {
return subnodes.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
return subnodes.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return subnodes.retainAll(c);
}
@Override
public void clear() {
subnodes.clear();
}
@Override
public XNodeImpl get(int index) {
return subnodes.get(index);
}
@Override
public XNodeImpl set(int index, XNodeImpl element) {
return subnodes.set(index, element);
}
@Override
public void add(int index, XNodeImpl element) {
subnodes.add(index, element);
}
@Override
public XNodeImpl remove(int index) {
return subnodes.remove(index);
}
@Override
public int indexOf(Object o) {
return subnodes.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return subnodes.lastIndexOf(o);
}
@Override
public ListIterator<XNodeImpl> listIterator() {
return subnodes.listIterator();
}
@Override
public ListIterator<XNodeImpl> listIterator(int index) {
return subnodes.listIterator(index);
}
@Override
public List<XNodeImpl> subList(int fromIndex, int toIndex) {
return subnodes.subList(fromIndex, toIndex);
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
for (XNodeImpl subnode: subnodes) {
if (subnode != null) {
subnode.accept(visitor);
} else {
// !!!!! TODO
}
}
}
@Override
public String debugDump(int indent) {
StringBuilder sb = new StringBuilder();
DebugUtil.debugDump(sb, this, indent, true, dumpSuffix());
return sb.toString();
}
@Override
public String getDesc() {
return "list";
}
@Override
public String toString() {
return "XNode(list:"+subnodes.size()+" elements)";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ListXNodeImpl xNodes = (ListXNodeImpl) o;
if (!subnodes.equals(xNodes.subnodes)) return false;
return true;
}
@Override
public int hashCode() {
return subnodes.hashCode();
}
@Override
public boolean isHeterogeneousList() {
return subnodes.stream().anyMatch(n -> n != null && n.getElementName() != null); // TODO - or allMatch?
}
@Override
public List<? extends XNode> asList() {
return this;
}
}
| apache-2.0 |
ElecEntertainment/EEUtils | src/main/java/net/larry1123/elec/util/config/fieldhanders/doubles/DoubleArrayWrapFieldHandler.java | 2143 | /*
* Copyright 2014 ElecEntertainment
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.larry1123.elec.util.config.fieldhanders.doubles;
import net.larry1123.elec.util.config.ConfigBase;
import net.larry1123.elec.util.config.fieldhanders.ArrayFieldHandler;
import org.apache.commons.lang3.ArrayUtils;
import java.lang.reflect.Field;
/**
* @author Larry1123
* @since 4/30/2014 - 2:34 AM
*/
public class DoubleArrayWrapFieldHandler extends ArrayFieldHandler<Double[]> {
public DoubleArrayWrapFieldHandler(Field field, ConfigBase configBase, String fieldName) {
super(field, configBase, fieldName);
}
public DoubleArrayWrapFieldHandler(Field field, ConfigBase configBase) {
super(field, configBase);
}
/**
* {@inheritDoc}
*/
@Override
public void setToFile(Double[] value) {
if (ArrayUtils.isNotEmpty(value)) {
getPropertiesFile().setDoubleArray(getKey(), ArrayUtils.toPrimitive(value), getSpacer());
}
}
/**
* {@inheritDoc}
*/
@Override
public Double[] getFromFile() {
if (getPropertiesFile().containsKey(getKey())) {
double[] temp = getPropertiesFile().getDoubleArray(getKey(), getSpacer());
return ArrayUtils.toObject(temp);
}
else {
return new Double[0];
}
}
/**
* {@inheritDoc}
*/
@Override
public Double[] getFromField() {
try {
return (Double[]) getField().get(getConfig());
}
catch (IllegalAccessException e) {
return new Double[0];
}
}
}
| apache-2.0 |
aljoscha/giraph | src/main/java/org/apache/giraph/examples/SimpleShortestPathsVertex.java | 2915 | /*
* 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.giraph.examples;
import org.apache.giraph.graph.Edge;
import org.apache.giraph.graph.EdgeListVertex;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.log4j.Logger;
/**
* Demonstrates the basic Pregel shortest paths implementation.
*/
@Algorithm(
name = "Shortest paths",
description = "Finds all shortest paths from a selected vertex"
)
public class SimpleShortestPathsVertex extends
EdgeListVertex<LongWritable, DoubleWritable,
FloatWritable, DoubleWritable> {
/** The shortest paths id */
public static final String SOURCE_ID = "SimpleShortestPathsVertex.sourceId";
/** Default shortest paths id */
public static final long SOURCE_ID_DEFAULT = 1;
/** Class logger */
private static final Logger LOG =
Logger.getLogger(SimpleShortestPathsVertex.class);
/**
* Is this vertex the source id?
*
* @return True if the source id
*/
private boolean isSource() {
return getId().get() ==
getContext().getConfiguration().getLong(SOURCE_ID,
SOURCE_ID_DEFAULT);
}
@Override
public void compute(Iterable<DoubleWritable> messages) {
if (getSuperstep() == 0) {
setValue(new DoubleWritable(Double.MAX_VALUE));
}
double minDist = isSource() ? 0d : Double.MAX_VALUE;
for (DoubleWritable message : messages) {
minDist = Math.min(minDist, message.get());
}
if (LOG.isDebugEnabled()) {
LOG.debug("Vertex " + getId() + " got minDist = " + minDist +
" vertex value = " + getValue());
}
if (minDist < getValue().get()) {
setValue(new DoubleWritable(minDist));
for (Edge<LongWritable, FloatWritable> edge : getEdges()) {
double distance = minDist + edge.getValue().get();
if (LOG.isDebugEnabled()) {
LOG.debug("Vertex " + getId() + " sent to " +
edge.getTargetVertexId() + " = " + distance);
}
sendMessage(edge.getTargetVertexId(), new DoubleWritable(distance));
}
}
voteToHalt();
}
}
| apache-2.0 |
java110/MicroCommunity | service-community/src/main/java/com/java110/community/listener/inspectionTaskDetail/AbstractInspectionTaskDetailBusinessServiceDataFlowListener.java | 5205 | package com.java110.community.listener.inspectionTaskDetail;
import com.alibaba.fastjson.JSONObject;
import com.java110.community.dao.IInspectionTaskDetailServiceDao;
import com.java110.entity.center.Business;
import com.java110.core.event.service.AbstractBusinessServiceDataFlowListener;
import com.java110.utils.constant.ResponseConstant;
import com.java110.utils.constant.StatusConstant;
import com.java110.utils.exception.ListenerExecuteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 巡检任务明细 服务侦听 父类
* Created by wuxw on 2018/7/4.
*/
public abstract class AbstractInspectionTaskDetailBusinessServiceDataFlowListener extends AbstractBusinessServiceDataFlowListener {
private static Logger logger = LoggerFactory.getLogger(AbstractInspectionTaskDetailBusinessServiceDataFlowListener.class);
/**
* 获取 DAO工具类
*
* @return
*/
public abstract IInspectionTaskDetailServiceDao getInspectionTaskDetailServiceDaoImpl();
/**
* 刷新 businessInspectionTaskDetailInfo 数据
* 主要将 数据库 中字段和 接口传递字段建立关系
*
* @param businessInspectionTaskDetailInfo
*/
protected void flushBusinessInspectionTaskDetailInfo(Map businessInspectionTaskDetailInfo, String statusCd) {
businessInspectionTaskDetailInfo.put("newBId", businessInspectionTaskDetailInfo.get("b_id"));
businessInspectionTaskDetailInfo.put("inspectionId", businessInspectionTaskDetailInfo.get("inspection_id"));
businessInspectionTaskDetailInfo.put("operate", businessInspectionTaskDetailInfo.get("operate"));
businessInspectionTaskDetailInfo.put("inspectionName", businessInspectionTaskDetailInfo.get("inspection_name"));
businessInspectionTaskDetailInfo.put("state", businessInspectionTaskDetailInfo.get("state"));
businessInspectionTaskDetailInfo.put("communityId", businessInspectionTaskDetailInfo.get("community_id"));
businessInspectionTaskDetailInfo.put("taskId", businessInspectionTaskDetailInfo.get("task_id"));
businessInspectionTaskDetailInfo.put("taskDetailId", businessInspectionTaskDetailInfo.get("task_detail_id"));
businessInspectionTaskDetailInfo.put("patrolType", businessInspectionTaskDetailInfo.get("patrol_type"));
businessInspectionTaskDetailInfo.put("description", businessInspectionTaskDetailInfo.get("description"));
businessInspectionTaskDetailInfo.remove("bId");
businessInspectionTaskDetailInfo.put("statusCd", statusCd);
}
/**
* 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
*
* @param businessInspectionTaskDetail 巡检任务明细信息
*/
protected void autoSaveDelBusinessInspectionTaskDetail(Business business, JSONObject businessInspectionTaskDetail) {
//自动插入DEL
Map info = new HashMap();
info.put("taskDetailId", businessInspectionTaskDetail.getString("taskDetailId"));
info.put("statusCd", StatusConstant.STATUS_CD_VALID);
List<Map> currentInspectionTaskDetailInfos = getInspectionTaskDetailServiceDaoImpl().getInspectionTaskDetailInfo(info);
if (currentInspectionTaskDetailInfos == null || currentInspectionTaskDetailInfos.size() != 1) {
throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
}
Map currentInspectionTaskDetailInfo = currentInspectionTaskDetailInfos.get(0);
currentInspectionTaskDetailInfo.put("bId", business.getbId());
currentInspectionTaskDetailInfo.put("inspectionId", currentInspectionTaskDetailInfo.get("inspection_id"));
currentInspectionTaskDetailInfo.put("operate", currentInspectionTaskDetailInfo.get("operate"));
currentInspectionTaskDetailInfo.put("inspectionName", currentInspectionTaskDetailInfo.get("inspection_name"));
currentInspectionTaskDetailInfo.put("state", currentInspectionTaskDetailInfo.get("state"));
currentInspectionTaskDetailInfo.put("communityId", currentInspectionTaskDetailInfo.get("community_id"));
currentInspectionTaskDetailInfo.put("taskId", currentInspectionTaskDetailInfo.get("task_id"));
currentInspectionTaskDetailInfo.put("taskDetailId", currentInspectionTaskDetailInfo.get("task_detail_id"));
currentInspectionTaskDetailInfo.put("patrolType", currentInspectionTaskDetailInfo.get("patrol_type"));
currentInspectionTaskDetailInfo.put("description", currentInspectionTaskDetailInfo.get("description"));
currentInspectionTaskDetailInfo.put("operate", StatusConstant.OPERATE_DEL);
getInspectionTaskDetailServiceDaoImpl().saveBusinessInspectionTaskDetailInfo(currentInspectionTaskDetailInfo);
for (Object key : currentInspectionTaskDetailInfo.keySet()) {
if (businessInspectionTaskDetail.get(key) == null) {
businessInspectionTaskDetail.put(key.toString(), currentInspectionTaskDetailInfo.get(key));
}
}
}
}
| apache-2.0 |
wangsongpeng/jdk-src | src/main/java/org/omg/PortableInterceptor/NON_EXISTENT.java | 503 | package org.omg.PortableInterceptor;
/**
* org/omg/PortableInterceptor/NON_EXISTENT.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl
* Monday, December 12, 2016 4:37:46 PM PST
*/
public interface NON_EXISTENT
{
/** Object adapter state indicating that the adapter has been destroyed.
*/
public static final short value = (short)(4);
}
| apache-2.0 |
ontop/ontop | core/optimization/src/main/java/it/unibz/inf/ontop/iq/transformer/impl/ExplicitEqualityTransformerImpl.java | 25293 | package it.unibz.inf.ontop.iq.transformer.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.exception.MinorOntopInternalBugException;
import it.unibz.inf.ontop.exception.OntopInternalBugException;
import it.unibz.inf.ontop.injection.IntermediateQueryFactory;
import it.unibz.inf.ontop.iq.IQTree;
import it.unibz.inf.ontop.iq.UnaryIQTree;
import it.unibz.inf.ontop.iq.node.*;
import it.unibz.inf.ontop.iq.transform.IQTreeTransformer;
import it.unibz.inf.ontop.iq.transform.impl.ChildTransformer;
import it.unibz.inf.ontop.iq.transform.impl.CompositeIQTreeTransformer;
import it.unibz.inf.ontop.iq.transform.impl.DefaultNonRecursiveIQTreeTransformer;
import it.unibz.inf.ontop.iq.transformer.ExplicitEqualityTransformer;
import it.unibz.inf.ontop.model.atom.AtomFactory;
import it.unibz.inf.ontop.model.atom.AtomPredicate;
import it.unibz.inf.ontop.model.atom.DataAtom;
import it.unibz.inf.ontop.model.term.*;
import it.unibz.inf.ontop.substitution.ImmutableSubstitution;
import it.unibz.inf.ontop.substitution.InjectiveVar2VarSubstitution;
import it.unibz.inf.ontop.substitution.SubstitutionFactory;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import it.unibz.inf.ontop.utils.VariableGenerator;
import java.util.*;
import java.util.stream.Stream;
public class ExplicitEqualityTransformerImpl implements ExplicitEqualityTransformer {
private final IntermediateQueryFactory iqFactory;
private final AtomFactory atomFactory;
private final TermFactory termFactory;
private final VariableGenerator variableGenerator;
private final SubstitutionFactory substitutionFactory;
private final CompositeIQTreeTransformer compositeTransformer;
@AssistedInject
public ExplicitEqualityTransformerImpl(@Assisted VariableGenerator variableGenerator,
IntermediateQueryFactory iqFactory,
AtomFactory atomFactory,
TermFactory termFactory,
SubstitutionFactory substitutionFactory) {
this.iqFactory = iqFactory;
this.atomFactory = atomFactory;
this.termFactory = termFactory;
this.variableGenerator = variableGenerator;
this.substitutionFactory = substitutionFactory;
ImmutableList<IQTreeTransformer> preTransformers = ImmutableList.of(new LocalExplicitEqualityEnforcer());
ImmutableList<IQTreeTransformer> postTransformers = ImmutableList.of(new CnLifter(), new FilterChildNormalizer(iqFactory));
this.compositeTransformer = new CompositeIQTreeTransformer(preTransformers, postTransformers, iqFactory);
}
@Override
public IQTree transform(IQTree tree) {
return compositeTransformer.transform(tree);
}
/**
* Affects (left) joins and data nodes.
* - left join: if the same variable is returned by both operands (implicit equality),
* rename it (with a fresh variable each time) in each branch but the left one,
* and make the corresponding equalities explicit.
* - inner join: identical to left join, but renaming is performed in each branch but the first where the variable appears
* - data node: if the data node contains a ground term, create a variable and make the equality explicit (create a filter).
*
* If needed, creates a root projection to ensure that the transformed query has the same signature as the input one
*/
class LocalExplicitEqualityEnforcer extends DefaultNonRecursiveIQTreeTransformer {
@Override
public IQTree transformIntensionalData(IntensionalDataNode dn) {
return transformIntensionalDataNode(dn);
}
@Override
public IQTree transformExtensionalData(ExtensionalDataNode dn) {
return transformExtensionalDataNode(dn);
}
@Override
public IQTree transformInnerJoin(IQTree tree, InnerJoinNode rootNode, ImmutableList<IQTree> children) {
ImmutableList<InjectiveVar2VarSubstitution> substitutions = computeSubstitutions(children);
if (substitutions.stream().allMatch(ImmutableSubstitution::isEmpty))
return tree;
ImmutableList<IQTree> updatedChildren = updateJoinChildren(substitutions, children);
return iqFactory.createUnaryIQTree(
iqFactory.createConstructionNode(tree.getVariables()),
iqFactory.createNaryIQTree(
iqFactory.createInnerJoinNode(
Optional.of(updateJoinCondition(
rootNode.getOptionalFilterCondition(),
substitutions ))),
updatedChildren
));
}
@Override
public IQTree transformLeftJoin(IQTree tree, LeftJoinNode rootNode, IQTree leftChild, IQTree rightChild) {
ImmutableList<IQTree> children = ImmutableList.of(leftChild, rightChild);
ImmutableList<InjectiveVar2VarSubstitution> substitutions = computeSubstitutions(children);
if (substitutions.stream().allMatch(ImmutableSubstitution::isEmpty))
return tree;
ImmutableList<IQTree> updatedChildren = updateJoinChildren(substitutions, children);
return iqFactory.createUnaryIQTree(
iqFactory.createConstructionNode(tree.getVariables()),
iqFactory.createBinaryNonCommutativeIQTree(
iqFactory.createLeftJoinNode(
Optional.of(
updateJoinCondition(
rootNode.getOptionalFilterCondition(),
substitutions
))),
updatedChildren.get(0),
updatedChildren.get(1)
));
}
private ImmutableList<InjectiveVar2VarSubstitution> computeSubstitutions(ImmutableList<IQTree> children) {
if (children.size() < 2) {
throw new ExplicitEqualityTransformerInternalException("At least 2 children are expected");
}
ImmutableSet<Variable> repeatedVariables = children.stream()
.flatMap(t -> t.getVariables().stream())
.collect(ImmutableCollectors.toMultiset()).entrySet().stream()
.filter(e -> e.getCount() > 1)
.map(Multiset.Entry::getElement)
.collect(ImmutableCollectors.toSet());
return children.stream().sequential()
.map(t -> substitutionFactory.getInjectiveVar2VarSubstitution(
t.getVariables().stream()
.filter(repeatedVariables::contains)
.filter(v -> !isFirstOcc(v, children, t)),
variableGenerator::generateNewVariableFromVar))
.collect(ImmutableCollectors.toList());
}
private ImmutableList<IQTree> updateJoinChildren(ImmutableList<InjectiveVar2VarSubstitution> substitutions, ImmutableList<IQTree> children) {
Iterator<IQTree> it = children.iterator();
return substitutions.stream().sequential()
.map(s -> it.next().applyDescendingSubstitutionWithoutOptimizing(s))
.collect(ImmutableCollectors.toList());
}
private boolean isFirstOcc(Variable variable, ImmutableList<IQTree> children, IQTree tree) {
return children.stream().sequential()
.filter(t -> t.getVariables().contains(variable))
.findFirst()
.orElseThrow(() -> new MinorOntopInternalBugException("Should be present"))
== tree;
}
private ImmutableExpression updateJoinCondition(Optional<ImmutableExpression> optionalFilterCondition, ImmutableList<InjectiveVar2VarSubstitution> substitutions) {
Stream<ImmutableExpression> varEqualities = substitutions.stream()
.flatMap(s -> s.getImmutableMap().entrySet().stream())
.map(e -> termFactory.getStrictEquality(e.getKey(), e.getValue()));
return termFactory.getConjunction(optionalFilterCondition, varEqualities).get();
}
private IQTree transformIntensionalDataNode(IntensionalDataNode dn) {
ImmutableList<Optional<Variable>> replacementVars = getArgumentReplacement(dn.getProjectionAtom());
if (empt(replacementVars))
return dn;
FilterNode filter = createFilter(dn.getProjectionAtom(), replacementVars);
DataAtom<AtomPredicate> atom = replaceVars(dn.getProjectionAtom(), replacementVars);
return iqFactory.createUnaryIQTree(
iqFactory.createConstructionNode(dn.getVariables()),
iqFactory.createUnaryIQTree(
filter,
dn.newAtom(atom))
);
}
private IQTree transformExtensionalDataNode(ExtensionalDataNode dn) {
ImmutableMap<Integer, ? extends VariableOrGroundTerm> initialArgumentMap = dn.getArgumentMap();
ImmutableMap<Integer, Variable> replacementVars = getArgumentReplacement(initialArgumentMap);
if (replacementVars.isEmpty())
return dn;
FilterNode filter = createFilter(initialArgumentMap, replacementVars);
ImmutableMap<Integer, ? extends VariableOrGroundTerm> newArgumentMap = replaceVars(initialArgumentMap, replacementVars);
return iqFactory.createUnaryIQTree(
iqFactory.createConstructionNode(dn.getVariables()),
iqFactory.createUnaryIQTree(
filter,
iqFactory.createExtensionalDataNode(dn.getRelationDefinition(), newArgumentMap))
);
}
private boolean empt(ImmutableList<Optional<Variable>> replacementVars) {
return replacementVars.stream()
.noneMatch(Optional::isPresent);
}
private <P extends AtomPredicate> DataAtom<P> replaceVars(DataAtom<P> projectionAtom, ImmutableList<Optional<Variable>> replacements) {
Iterator<Optional<Variable>> it = replacements.iterator();
return atomFactory.getDataAtom(
projectionAtom.getPredicate(),
projectionAtom.getArguments().stream()
.map(a -> {
Optional<Variable> r = it.next();
return r.isPresent() ?
r.get() :
a;
})
.collect(ImmutableCollectors.toList())
);
}
private ImmutableMap<Integer, ? extends VariableOrGroundTerm> replaceVars(
ImmutableMap<Integer, ? extends VariableOrGroundTerm> argumentMap,
ImmutableMap<Integer, Variable> replacements) {
return argumentMap.entrySet().stream()
.collect(ImmutableCollectors.toMap(
Map.Entry::getKey,
e -> Optional.ofNullable((VariableOrGroundTerm)replacements.get(e.getKey()))
.orElseGet(e::getValue)));
}
private ImmutableList<Optional<Variable>> getArgumentReplacement(DataAtom<AtomPredicate> dataAtom) {
Set<Variable> vars = new HashSet<>();
List<Optional<Variable>> replacements = new ArrayList<>();
for (VariableOrGroundTerm term: dataAtom.getArguments()) {
if (term instanceof GroundTerm) {
replacements.add(Optional.of(variableGenerator.generateNewVariable()));
} else if (term instanceof Variable) {
Variable var = (Variable) term;
if (vars.contains(var)) {
replacements.add(Optional.of(variableGenerator.generateNewVariableFromVar(var)));
} else {
replacements.add(Optional.empty());
vars.add(var);
}
}
}
return ImmutableList.copyOf(replacements);
}
private ImmutableMap<Integer, Variable> getArgumentReplacement(
ImmutableMap<Integer, ? extends VariableOrGroundTerm> argumentMap) {
Set<Variable> vars = new HashSet<>();
Map<Integer, Variable> replacementMap = new HashMap<>();
for (Map.Entry<Integer, ? extends VariableOrGroundTerm> entry : argumentMap.entrySet()) {
VariableOrGroundTerm term = entry.getValue();
if (term instanceof GroundTerm) {
replacementMap.put(entry.getKey(), variableGenerator.generateNewVariable());
} else if (term instanceof Variable) {
Variable var = (Variable) term;
if (vars.contains(var)) {
replacementMap.put(entry.getKey(), variableGenerator.generateNewVariableFromVar(var));
} else {
vars.add(var);
}
}
}
return ImmutableMap.copyOf(replacementMap);
}
private FilterNode createFilter(DataAtom<AtomPredicate> da, ImmutableList<Optional<Variable>> replacementVars) {
Iterator<Optional<Variable>> it = replacementVars.iterator();
return iqFactory.createFilterNode(
termFactory.getConjunction(da.getArguments().stream()
.map(a -> getEquality(a, it.next()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableCollectors.toList())));
}
private FilterNode createFilter(ImmutableMap<Integer, ? extends VariableOrGroundTerm> initialArgumentMap,
ImmutableMap<Integer, Variable> replacementVars) {
return iqFactory.createFilterNode(
termFactory.getConjunction(replacementVars.entrySet().stream()
.map(e -> termFactory.getStrictEquality(initialArgumentMap.get(e.getKey()), e.getValue()))
.collect(ImmutableCollectors.toList())));
}
private Optional<ImmutableExpression> getEquality(VariableOrGroundTerm t, Optional<Variable> replacement) {
return replacement
.map(variable -> termFactory.getStrictEquality(t, variable));
}
}
/**
* Affects each outermost filter or (left) join n in the tree.
* For each child of n, deletes its root if it is a filter node.
* Then:
* - if n is a join or filter: merge the boolean expressions
* - if n is a left join: merge boolean expressions coming from the right, and lift the ones coming from the left.
* This lift is only performed for optimization purposes: may save a subquery during SQL generation.
*/
class FilterChildNormalizer extends DefaultNonRecursiveIQTreeTransformer {
private final ChildTransformer childTransformer;
public FilterChildNormalizer(IntermediateQueryFactory iqFactory) {
this.childTransformer = new ChildTransformer(iqFactory, this);
}
@Override
public IQTree transformLeftJoin(IQTree tree, LeftJoinNode rootNode, IQTree leftChild, IQTree rightChild) {
Optional<ImmutableExpression> leftChildChildExpression = getOptionalChildExpression(leftChild);
Optional<ImmutableExpression> rightChildExpression = getOptionalChildExpression(rightChild);
if(leftChildChildExpression.isPresent() || rightChildExpression.isPresent()) {
IQTree leftJoinTree = iqFactory.createBinaryNonCommutativeIQTree(
rightChildExpression.isPresent() ?
iqFactory.createLeftJoinNode(
Optional.of(
updateJoinCondition(
rootNode.getOptionalFilterCondition(),
ImmutableList.of(rightChildExpression.get())
))) :
rootNode,
trimRootFilter(leftChild),
trimRootFilter(rightChild)
);
return leftChildChildExpression.isPresent() ?
iqFactory.createUnaryIQTree(iqFactory.createFilterNode(leftChildChildExpression.get()), leftJoinTree) :
leftJoinTree;
}
return tree;
}
@Override
public IQTree transformInnerJoin(IQTree tree, InnerJoinNode rootNode, ImmutableList<IQTree> children) {
ImmutableList<ImmutableExpression> filterChildExpressions = getChildExpressions(children);
if (filterChildExpressions.isEmpty())
return tree;
return iqFactory.createNaryIQTree(
iqFactory.createInnerJoinNode(
Optional.of(
updateJoinCondition(
rootNode.getOptionalFilterCondition(),
filterChildExpressions
))),
children.stream()
.map(this::trimRootFilter)
.collect(ImmutableCollectors.toList())
);
}
@Override
public IQTree transformFilter(IQTree tree, FilterNode rootNode, IQTree child) {
ImmutableList<ImmutableExpression> filterChildExpressions = getChildExpressions(ImmutableList.of(child));
if (filterChildExpressions.isEmpty())
return tree;
return iqFactory.createUnaryIQTree(
iqFactory.createFilterNode(
updateJoinCondition(
Optional.of(rootNode.getFilterCondition()),
filterChildExpressions
)),
trimRootFilter(child)
);
}
private ImmutableList<ImmutableExpression> getChildExpressions(ImmutableList<IQTree> children) {
return children.stream()
.filter(t -> t.getRootNode() instanceof FilterNode)
.map(t -> ((FilterNode) t.getRootNode()).getFilterCondition())
.collect(ImmutableCollectors.toList());
}
private Optional<ImmutableExpression> getOptionalChildExpression(IQTree child) {
QueryNode root = child.getRootNode();
return root instanceof FilterNode?
Optional.of(((FilterNode) root).getFilterCondition()):
Optional.empty();
}
private IQTree trimRootFilter(IQTree tree) {
return tree.getRootNode() instanceof FilterNode ?
((UnaryIQTree) tree).getChild() :
tree;
}
private ImmutableExpression updateJoinCondition(Optional<ImmutableExpression> joinCondition, ImmutableList<ImmutableExpression> additionalConditions) {
if (additionalConditions.isEmpty())
throw new ExplicitEqualityTransformerInternalException("Nonempty list of filters expected");
return termFactory.getConjunction(joinCondition, additionalConditions.stream()).get();
}
protected IQTree transformUnaryNode(IQTree tree, UnaryOperatorNode rootNode, IQTree child) {
return childTransformer.transform(tree);
}
protected IQTree transformNaryCommutativeNode(IQTree tree, NaryOperatorNode rootNode, ImmutableList<IQTree> children) {
return childTransformer.transform(tree);
}
protected IQTree transformBinaryNonCommutativeNode(IQTree tree, BinaryNonCommutativeOperatorNode rootNode, IQTree leftChild, IQTree rightChild) {
return childTransformer.transform(tree);
}
}
/**
* - Default behavior: for each child, deletes its root if it is a substitution-free construction node (i.e. a simple projection),
* and lift the projection if needed
* - Distinct or slice nodes: does not apply
*/
class CnLifter extends DefaultNonRecursiveIQTreeTransformer {
@Override
public IQTree transformDistinct(IQTree tree, DistinctNode rootNode, IQTree child) {
return tree;
}
@Override
public IQTree transformSlice(IQTree tree, SliceNode rootNode, IQTree child) {
return tree;
}
@Override
public IQTree transformUnaryNode(IQTree tree, UnaryOperatorNode rootNode, IQTree child) {
ImmutableList<ConstructionNode> idleCns = getIdleCns(Stream.of(child));
return idleCns.isEmpty() ?
tree :
getProjection(
tree.getVariables(),
iqFactory.createUnaryIQTree(
rootNode,
trimIdleCn(child)
));
}
@Override
public IQTree transformInnerJoin(IQTree tree, InnerJoinNode rootNode, ImmutableList<IQTree> children) {
ImmutableList<ConstructionNode> idleCns = getIdleCns(children.stream());
return idleCns.isEmpty() ?
tree :
getProjection(
tree.getVariables(),
iqFactory.createNaryIQTree(
rootNode,
children.stream()
.map(this::trimIdleCn)
.collect(ImmutableCollectors.toList())
));
}
@Override
protected IQTree transformBinaryNonCommutativeNode(IQTree tree, BinaryNonCommutativeOperatorNode rootNode, IQTree leftChild, IQTree rightChild) {
ImmutableList<ConstructionNode> idleCns = getIdleCns(Stream.of(leftChild, rightChild));
return idleCns.isEmpty() ?
tree :
getProjection(
tree.getVariables(),
iqFactory.createBinaryNonCommutativeIQTree(
rootNode,
trimIdleCn(leftChild),
trimIdleCn(rightChild)
));
}
private ImmutableList<ConstructionNode> getIdleCns(Stream<IQTree> trees) {
return trees
.map(this::getIdleCn)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableCollectors.toList());
}
private Optional<ConstructionNode> getIdleCn(IQTree tree) {
QueryNode root = tree.getRootNode();
if (root instanceof ConstructionNode) {
ConstructionNode cn = ((ConstructionNode) root);
if (cn.getSubstitution().isEmpty()) {
return Optional.of(cn);
}
}
return Optional.empty();
}
private IQTree trimIdleCn(IQTree tree) {
return getIdleCn(tree).isPresent() ?
((UnaryIQTree) tree).getChild() :
tree;
}
private IQTree getProjection(ImmutableSet<Variable> signature, IQTree tree) {
QueryNode root = tree.getRootNode();
if (root instanceof ConstructionNode){
return iqFactory.createUnaryIQTree(
iqFactory.createConstructionNode(signature, ((ConstructionNode)root).getSubstitution()),
((UnaryIQTree)tree).getChild()
);
}
return iqFactory.createUnaryIQTree(
iqFactory.createConstructionNode(signature),
tree
);
}
}
private static class ExplicitEqualityTransformerInternalException extends OntopInternalBugException {
ExplicitEqualityTransformerInternalException(String message) {
super(message);
}
}
}
| apache-2.0 |
ReactiveX/RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDefer.java | 1732 | /*
* Copyright (c) 2016-present, RxJava Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.rxjava3.internal.operators.maybe;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.functions.Supplier;
import io.reactivex.rxjava3.internal.disposables.EmptyDisposable;
import java.util.Objects;
/**
* Defers the creation of the actual Maybe the incoming MaybeObserver is subscribed to.
*
* @param <T> the value type
*/
public final class MaybeDefer<T> extends Maybe<T> {
final Supplier<? extends MaybeSource<? extends T>> maybeSupplier;
public MaybeDefer(Supplier<? extends MaybeSource<? extends T>> maybeSupplier) {
this.maybeSupplier = maybeSupplier;
}
@Override
protected void subscribeActual(MaybeObserver<? super T> observer) {
MaybeSource<? extends T> source;
try {
source = Objects.requireNonNull(maybeSupplier.get(), "The maybeSupplier returned a null MaybeSource");
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
EmptyDisposable.error(ex, observer);
return;
}
source.subscribe(observer);
}
}
| apache-2.0 |
ben-manes/guava | guava/src/com/google/common/collect/RegularImmutableMultiset.java | 5230 | /*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Objects;
import com.google.common.collect.Multisets.ImmutableEntry;
import com.google.common.primitives.Ints;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableMultiset} with zero or more elements.
*
* @author Jared Levy
* @author Louis Wasserman
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
class RegularImmutableMultiset<E> extends ImmutableMultiset<E> {
static final RegularImmutableMultiset<Object> EMPTY =
new RegularImmutableMultiset<Object>(ImmutableList.<Entry<Object>>of());
private final transient Multisets.ImmutableEntry<E>[] entries;
private final transient Multisets.ImmutableEntry<E>[] hashTable;
private final transient int size;
private final transient int hashCode;
private transient ImmutableSet<E> elementSet;
RegularImmutableMultiset(Collection<? extends Entry<? extends E>> entries) {
int distinct = entries.size();
@SuppressWarnings("unchecked")
Multisets.ImmutableEntry<E>[] entryArray = new Multisets.ImmutableEntry[distinct];
if (distinct == 0) {
this.entries = entryArray;
this.hashTable = null;
this.size = 0;
this.hashCode = 0;
this.elementSet = ImmutableSet.of();
} else {
int tableSize = Hashing.closedTableSize(distinct, 1.0);
int mask = tableSize - 1;
@SuppressWarnings("unchecked")
Multisets.ImmutableEntry<E>[] hashTable = new Multisets.ImmutableEntry[tableSize];
int index = 0;
int hashCode = 0;
long size = 0;
for (Entry<? extends E> entry : entries) {
E element = checkNotNull(entry.getElement());
int count = entry.getCount();
int hash = element.hashCode();
int bucket = Hashing.smear(hash) & mask;
Multisets.ImmutableEntry<E> bucketHead = hashTable[bucket];
Multisets.ImmutableEntry<E> newEntry;
if (bucketHead == null) {
boolean canReuseEntry = entry instanceof Multisets.ImmutableEntry
&& !(entry instanceof NonTerminalEntry);
newEntry = canReuseEntry
? (Multisets.ImmutableEntry<E>) entry
: new Multisets.ImmutableEntry<E>(element, count);
} else {
newEntry = new NonTerminalEntry<E>(element, count, bucketHead);
}
hashCode += hash ^ count;
entryArray[index++] = newEntry;
hashTable[bucket] = newEntry;
size += count;
}
this.entries = entryArray;
this.hashTable = hashTable;
this.size = Ints.saturatedCast(size);
this.hashCode = hashCode;
}
}
private static final class NonTerminalEntry<E> extends Multisets.ImmutableEntry<E> {
private final Multisets.ImmutableEntry<E> nextInBucket;
NonTerminalEntry(E element, int count, ImmutableEntry<E> nextInBucket) {
super(element, count);
this.nextInBucket = nextInBucket;
}
@Override
public ImmutableEntry<E> nextInBucket() {
return nextInBucket;
}
}
@Override
boolean isPartialView() {
return false;
}
@Override
public int count(@Nullable Object element) {
Multisets.ImmutableEntry<E>[] hashTable = this.hashTable;
if (element == null || hashTable == null) {
return 0;
}
int hash = Hashing.smearedHash(element);
int mask = hashTable.length - 1;
for (Multisets.ImmutableEntry<E> entry = hashTable[hash & mask]; entry != null;
entry = entry.nextInBucket()) {
if (Objects.equal(element, entry.getElement())) {
return entry.getCount();
}
}
return 0;
}
@Override
public int size() {
return size;
}
@Override
public ImmutableSet<E> elementSet() {
ImmutableSet<E> result = elementSet;
return (result == null) ? elementSet = new ElementSet() : result;
}
private final class ElementSet extends ImmutableSet.Indexed<E> {
@Override
E get(int index) {
return entries[index].getElement();
}
@Override
public boolean contains(@Nullable Object object) {
return RegularImmutableMultiset.this.contains(object);
}
@Override
boolean isPartialView() {
return true;
}
@Override
public int size() {
return entries.length;
}
}
@Override
Entry<E> getEntry(int index) {
return entries[index];
}
@Override
public int hashCode() {
return hashCode;
}
}
| apache-2.0 |
crnk-project/crnk-framework | crnk-integration-examples/spring-boot-example/src/main/java/io/crnk/example/springboot/domain/repository/TaskRepositoryImpl.java | 1834 | package io.crnk.example.springboot.domain.repository;
import io.crnk.core.exception.BadRequestException;
import io.crnk.core.exception.ResourceNotFoundException;
import io.crnk.core.queryspec.QuerySpec;
import io.crnk.core.repository.ResourceRepositoryBase;
import io.crnk.core.resource.list.ResourceList;
import io.crnk.example.springboot.domain.model.Task;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
// tag::doc[]
@Component
public class TaskRepositoryImpl extends ResourceRepositoryBase<Task, Long> implements TaskRepository {
// for simplicity we make use of static, should not be used in real applications
private static final Map<Long, Task> tasks = new ConcurrentHashMap<>();
private static final AtomicLong ID_GENERATOR = new AtomicLong(4);
public TaskRepositoryImpl() {
super(Task.class);
}
@Override
public <S extends Task> S save(S entity) {
if (entity.getId() == null) {
entity.setId(ID_GENERATOR.getAndIncrement());
}
tasks.put(entity.getId(), entity);
return entity;
}
@Override
public <S extends Task> S create(S entity) {
if (entity.getId() != null && tasks.containsKey(entity.getId())) {
throw new BadRequestException("Task already exists");
}
return save(entity);
}
@Override
public Class<Task> getResourceClass() {
return Task.class;
}
@Override
public Task findOne(Long taskId, QuerySpec querySpec) {
Task task = tasks.get(taskId);
if (task == null) {
throw new ResourceNotFoundException("Task not found!");
}
return task;
}
@Override
public ResourceList<Task> findAll(QuerySpec querySpec) {
return querySpec.apply(tasks.values());
}
@Override
public void delete(Long taskId) {
tasks.remove(taskId);
}
}
// end::doc[] | apache-2.0 |
Wazzymandias/RainOrShine | app/src/main/java/com/example/android/sunshine/app/MainActivity.java | 3221 | package com.example.android.sunshine.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today - Sunny - 88 / 63",
"Tomorrow - Foggy - 70 / 40",
"Weds - Cloudy - 72 / 63",
"Thurs - Asteroids - 75 / 65",
"Fri - Heavy Rain - 65 / 56",
"Sat - HELP TRAPPED IN WEATHER STATION - 60 / 51",
"Sun - Sunny - 80 / 68"
};
ArrayList<String> weatherForecastList = new ArrayList<>(Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<>(
//The current context (this fragment's parent activity)
getActivity(),
// ID of list item layout
R.layout.list_item_forecast,
// ID of text view to populate
R.id.list_item_forecast_textview,
// Forecast data
weatherForecastList);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
}
}
| apache-2.0 |
lauriewu1/AndroidSunshineApp | app/src/main/java/com/example/android/sunshine/app/DetailActivity.java | 1957 | package com.example.android.sunshine.app;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class DetailActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
return rootView;
}
}
}
| apache-2.0 |
hazendaz/assertj-core | src/test/java/org/assertj/core/error/ShouldContainCharSequence_create_Test.java | 6831 | /*
* 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-2021 the original author or authors.
*/
package org.assertj.core.error;
import static java.lang.String.format;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.error.ShouldContainCharSequence.shouldContain;
import static org.assertj.core.error.ShouldContainCharSequence.shouldContainIgnoringCase;
import static org.assertj.core.error.ShouldContainCharSequence.shouldContainIgnoringWhitespaces;
import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION;
import static org.assertj.core.util.Arrays.array;
import static org.mockito.internal.util.collections.Sets.newSet;
import org.assertj.core.description.TextDescription;
import org.assertj.core.internal.ComparatorBasedComparisonStrategy;
import org.assertj.core.internal.StandardComparisonStrategy;
import org.assertj.core.util.CaseInsensitiveStringComparator;
import org.junit.jupiter.api.Test;
/**
* Tests for <code>{@link ShouldContainCharSequence#create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation)}</code>.
*
* @author Alex Ruiz
* @author Yvonne Wang
* @author Joel Costigliola
*/
class ShouldContainCharSequence_create_Test {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = shouldContain("Yoda", "Luke");
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \"Yoda\"%n" +
"to contain:%n" +
" \"Luke\" "));
}
@Test
void should_create_error_message_with_custom_comparison_strategy() {
// GIVEN
ErrorMessageFactory factory = shouldContain("Yoda", "Luke",
new ComparatorBasedComparisonStrategy(CaseInsensitiveStringComparator.instance));
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \"Yoda\"%n" +
"to contain:%n" +
" \"Luke\" when comparing values using CaseInsensitiveStringComparator"));
}
@Test
void should_create_error_message_when_ignoring_whitespaces() {
// GIVEN
ErrorMessageFactory factory = shouldContainIgnoringWhitespaces("Yoda", "Luke", StandardComparisonStrategy.instance());
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \"Yoda\"%n" +
"to contain (ignoring whitespaces):%n" +
" \"Luke\" "));
}
@Test
void should_create_error_message_with_custom_comparison_strategy_when_ignoring_whitespaces() {
// GIVEN
ErrorMessageFactory factory = shouldContainIgnoringWhitespaces("Yoda", "Luke",
new ComparatorBasedComparisonStrategy(CaseInsensitiveStringComparator.instance));
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \"Yoda\"%n" +
"to contain (ignoring whitespaces):%n" +
" \"Luke\" when comparing values using CaseInsensitiveStringComparator"));
}
@Test
void should_create_error_message_when_ignoring_case() {
// GIVEN
ErrorMessageFactory factory = shouldContainIgnoringCase("Yoda", "Luke");
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \"Yoda\"%n" +
"to contain:%n" +
" \"Luke\"%n" +
" (ignoring case)"));
}
@Test
void should_create_error_message_with_several_CharSequence_values() {
// GIVEN
CharSequence[] charSequences = array("Luke", "Vador", "Solo");
ErrorMessageFactory factory = shouldContain("Yoda, Luke", charSequences, newSet("Vador", "Solo"));
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \"Yoda, Luke\"%n" +
"to contain:%n" +
" [\"Luke\", \"Vador\", \"Solo\"]%n" +
"but could not find:%n" +
" [\"Vador\", \"Solo\"]%n "));
}
@Test
void should_create_error_message_with_several_CharSequence_values_when_ignoring_whitespaces() {
// GIVEN
CharSequence[] charSequences = array("Luke", "Vador", "Solo");
ErrorMessageFactory factory = shouldContainIgnoringWhitespaces("Yoda, Luke", charSequences, newSet("Vador", "Solo"),
StandardComparisonStrategy.instance());
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" \"Yoda, Luke\"%n" +
"to contain (ignoring whitespaces):%n" +
" [\"Luke\", \"Vador\", \"Solo\"]%n" +
"but could not find:%n" +
" [\"Vador\", \"Solo\"]%n "));
}
}
| apache-2.0 |
watson-developer-cloud/java-sdk | personality-insights/src/main/java/com/ibm/watson/personality_insights/v3/model/Behavior.java | 1961 | /*
* (C) Copyright IBM Corp. 2016, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.personality_insights.v3.model;
import com.google.gson.annotations.SerializedName;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/** The temporal behavior for the input content. */
public class Behavior extends GenericModel {
@SerializedName("trait_id")
protected String traitId;
protected String name;
protected String category;
protected Double percentage;
/**
* Gets the traitId.
*
* <p>The unique, non-localized identifier of the characteristic to which the results pertain. IDs
* have the form `behavior_{value}`.
*
* @return the traitId
*/
public String getTraitId() {
return traitId;
}
/**
* Gets the name.
*
* <p>The user-visible, localized name of the characteristic.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the category.
*
* <p>The category of the characteristic: `behavior` for temporal data.
*
* @return the category
*/
public String getCategory() {
return category;
}
/**
* Gets the percentage.
*
* <p>For JSON content that is timestamped, the percentage of timestamped input data that occurred
* during that day of the week or hour of the day. The range is 0 to 1.
*
* @return the percentage
*/
public Double getPercentage() {
return percentage;
}
}
| apache-2.0 |
remibergsma/cosmic | cosmic-core/api/src/main/java/com/cloud/agent/api/storage/PrepareOVAPackingAnswer.java | 290 | package com.cloud.agent.api.storage;
import com.cloud.agent.api.Answer;
public class PrepareOVAPackingAnswer extends Answer {
public PrepareOVAPackingAnswer(final PrepareOVAPackingCommand cmd, final boolean result, final String details) {
super(cmd, result, details);
}
}
| apache-2.0 |
google/supl-client | src/main/java/com/google/location/suplclient/asn1/supl2/supl_response/SUPLRESPONSE.java | 13246 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.location.suplclient.asn1.supl2.supl_response;
// Copyright 2008 Google Inc. All Rights Reserved.
/*
* This class is AUTOMATICALLY GENERATED. Do NOT EDIT.
*/
//
//
import com.google.location.suplclient.asn1.base.Asn1Object;
import com.google.location.suplclient.asn1.base.Asn1Sequence;
import com.google.location.suplclient.asn1.base.Asn1Tag;
import com.google.location.suplclient.asn1.base.BitStream;
import com.google.location.suplclient.asn1.base.BitStreamReader;
import com.google.location.suplclient.asn1.base.SequenceComponent;
import com.google.location.suplclient.asn1.supl2.ulp_components.PosMethod;
import com.google.location.suplclient.asn1.supl2.ulp_components.SLPAddress;
import com.google.location.suplclient.asn1.supl2.ulp_version_2_message_extensions.Ver2_SUPL_RESPONSE_extension;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import javax.annotation.Nullable;
/**
*
*/
public class SUPLRESPONSE extends Asn1Sequence {
//
private static final Asn1Tag TAG_SUPLRESPONSE
= Asn1Tag.fromClassAndNumber(-1, -1);
public SUPLRESPONSE() {
super();
}
@Override
@Nullable
protected Asn1Tag getTag() {
return TAG_SUPLRESPONSE;
}
@Override
protected boolean isTagImplicit() {
return true;
}
public static Collection<Asn1Tag> getPossibleFirstTags() {
if (TAG_SUPLRESPONSE != null) {
return ImmutableList.of(TAG_SUPLRESPONSE);
} else {
return Asn1Sequence.getPossibleFirstTags();
}
}
/**
* Creates a new SUPLRESPONSE from encoded stream.
*/
public static SUPLRESPONSE fromPerUnaligned(byte[] encodedBytes) {
SUPLRESPONSE result = new SUPLRESPONSE();
result.decodePerUnaligned(new BitStreamReader(encodedBytes));
return result;
}
/**
* Creates a new SUPLRESPONSE from encoded stream.
*/
public static SUPLRESPONSE fromPerAligned(byte[] encodedBytes) {
SUPLRESPONSE result = new SUPLRESPONSE();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
}
@Override protected boolean isExtensible() {
return true;
}
@Override public boolean containsExtensionValues() {
for (SequenceComponent extensionComponent : getExtensionComponents()) {
if (extensionComponent.isExplicitlySet()) return true;
}
return false;
}
private PosMethod posMethod_;
public PosMethod getPosMethod() {
return posMethod_;
}
/**
* @throws ClassCastException if value is not a PosMethod
*/
public void setPosMethod(Asn1Object value) {
this.posMethod_ = (PosMethod) value;
}
public PosMethod setPosMethodToNewInstance() {
posMethod_ = new PosMethod();
return posMethod_;
}
private SLPAddress sLPAddress_;
public SLPAddress getSLPAddress() {
return sLPAddress_;
}
/**
* @throws ClassCastException if value is not a SLPAddress
*/
public void setSLPAddress(Asn1Object value) {
this.sLPAddress_ = (SLPAddress) value;
}
public SLPAddress setSLPAddressToNewInstance() {
sLPAddress_ = new SLPAddress();
return sLPAddress_;
}
private SETAuthKey sETAuthKey_;
public SETAuthKey getSETAuthKey() {
return sETAuthKey_;
}
/**
* @throws ClassCastException if value is not a SETAuthKey
*/
public void setSETAuthKey(Asn1Object value) {
this.sETAuthKey_ = (SETAuthKey) value;
}
public SETAuthKey setSETAuthKeyToNewInstance() {
sETAuthKey_ = new SETAuthKey();
return sETAuthKey_;
}
private KeyIdentity4 keyIdentity4_;
public KeyIdentity4 getKeyIdentity4() {
return keyIdentity4_;
}
/**
* @throws ClassCastException if value is not a KeyIdentity4
*/
public void setKeyIdentity4(Asn1Object value) {
this.keyIdentity4_ = (KeyIdentity4) value;
}
public KeyIdentity4 setKeyIdentity4ToNewInstance() {
keyIdentity4_ = new KeyIdentity4();
return keyIdentity4_;
}
private Ver2_SUPL_RESPONSE_extension extensionVer2_SUPL_RESPONSE_extension;
public Ver2_SUPL_RESPONSE_extension getExtensionVer2_SUPL_RESPONSE_extension() {
return extensionVer2_SUPL_RESPONSE_extension;
}
/**
* @throws ClassCastException if value is not a Ver2_SUPL_RESPONSE_extension
*/
public void setExtensionVer2_SUPL_RESPONSE_extension(Asn1Object value) {
extensionVer2_SUPL_RESPONSE_extension = (Ver2_SUPL_RESPONSE_extension) value;
}
public void setExtensionVer2_SUPL_RESPONSE_extensionToNewInstance() {
extensionVer2_SUPL_RESPONSE_extension = new Ver2_SUPL_RESPONSE_extension();
}
@Override public Iterable<? extends SequenceComponent> getComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
builder.add(new SequenceComponent() {
Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 0);
@Override public boolean isExplicitlySet() {
return getPosMethod() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return false;
}
@Override public Asn1Object getComponentValue() {
return getPosMethod();
}
@Override public void setToNewInstance() {
setPosMethodToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
return tag == null ? PosMethod.getPossibleFirstTags() : ImmutableList.of(tag);
}
@Override
public Asn1Tag getTag() {
return tag;
}
@Override
public boolean isImplicitTagging() {
return true;
}
@Override public String toIndentedString(String indent) {
return "posMethod : "
+ getPosMethod().toIndentedString(indent);
}
});
builder.add(new SequenceComponent() {
Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 1);
@Override public boolean isExplicitlySet() {
return getSLPAddress() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return true;
}
@Override public Asn1Object getComponentValue() {
return getSLPAddress();
}
@Override public void setToNewInstance() {
setSLPAddressToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
return tag == null ? SLPAddress.getPossibleFirstTags() : ImmutableList.of(tag);
}
@Override
public Asn1Tag getTag() {
return tag;
}
@Override
public boolean isImplicitTagging() {
return true;
}
@Override public String toIndentedString(String indent) {
return "sLPAddress : "
+ getSLPAddress().toIndentedString(indent);
}
});
builder.add(new SequenceComponent() {
Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 2);
@Override public boolean isExplicitlySet() {
return getSETAuthKey() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return true;
}
@Override public Asn1Object getComponentValue() {
return getSETAuthKey();
}
@Override public void setToNewInstance() {
setSETAuthKeyToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
return tag == null ? SETAuthKey.getPossibleFirstTags() : ImmutableList.of(tag);
}
@Override
public Asn1Tag getTag() {
return tag;
}
@Override
public boolean isImplicitTagging() {
return true;
}
@Override public String toIndentedString(String indent) {
return "sETAuthKey : "
+ getSETAuthKey().toIndentedString(indent);
}
});
builder.add(new SequenceComponent() {
Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 3);
@Override public boolean isExplicitlySet() {
return getKeyIdentity4() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return true;
}
@Override public Asn1Object getComponentValue() {
return getKeyIdentity4();
}
@Override public void setToNewInstance() {
setKeyIdentity4ToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
return tag == null ? KeyIdentity4.getPossibleFirstTags() : ImmutableList.of(tag);
}
@Override
public Asn1Tag getTag() {
return tag;
}
@Override
public boolean isImplicitTagging() {
return true;
}
@Override public String toIndentedString(String indent) {
return "keyIdentity4 : "
+ getKeyIdentity4().toIndentedString(indent);
}
});
return builder.build();
}
@Override public Iterable<? extends SequenceComponent>
getExtensionComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
builder.add(new SequenceComponent() {
@Override public boolean isExplicitlySet() {
return getExtensionVer2_SUPL_RESPONSE_extension() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return true;
}
@Override public Asn1Object getComponentValue() {
return getExtensionVer2_SUPL_RESPONSE_extension();
}
@Override public void setToNewInstance() {
setExtensionVer2_SUPL_RESPONSE_extensionToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
throw new UnsupportedOperationException(
"BER decoding not supported for extension elements");
}
@Override
public Asn1Tag getTag() {
throw new UnsupportedOperationException(
"BER is not supported for extension elements");
}
@Override
public boolean isImplicitTagging() {
throw new UnsupportedOperationException(
"BER is not supported for extension elements");
}
@Override public String toIndentedString(String indent) {
return "ver2_SUPL_RESPONSE_extension : "
+ getExtensionVer2_SUPL_RESPONSE_extension().toIndentedString(indent);
}
});
return builder.build();
}
@Override public Iterable<BitStream> encodePerUnaligned() {
return super.encodePerUnaligned();
}
@Override public Iterable<BitStream> encodePerAligned() {
return super.encodePerAligned();
}
@Override public void decodePerUnaligned(BitStreamReader reader) {
super.decodePerUnaligned(reader);
}
@Override public void decodePerAligned(BitStreamReader reader) {
super.decodePerAligned(reader);
}
@Override public String toString() {
return toIndentedString("");
}
public String toIndentedString(String indent) {
StringBuilder builder = new StringBuilder();
builder.append("SUPLRESPONSE = {\n");
final String internalIndent = indent + " ";
for (SequenceComponent component : getComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
if (isExtensible()) {
builder.append(internalIndent).append("...\n");
for (SequenceComponent component : getExtensionComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
}
builder.append(indent).append("};\n");
return builder.toString();
}
}
| apache-2.0 |
awslabs/aws-mobile-self-paced-labs-samples | spl-48/Snake Game - AWS/src/com/amazon/example/snake/SplashScreenActivity.java | 1781 | package com.amazon.example.snake;
import com.amazon.example.snake.aws.S3DownloadTask;
import com.amazon.example.snake.aws.S3DownloadTask.DownloadTaskFinishedListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
public class SplashScreenActivity extends Activity implements
DownloadTaskFinishedListener {
private ProgressBar progressBar;
private TextView progressBarText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the splash screen
setContentView(R.layout.activity_splash_screen);
// Find the progress bar
progressBar = (ProgressBar) findViewById(R.id.activity_splash_progress_bar);
progressBarText = (TextView) findViewById(R.id.activity_splash_progress_bar_text);
boolean withIdentity = getIntent().getBooleanExtra("withIdentity",
false);
if (withIdentity) {
// Start your loading
new S3DownloadTask(progressBar, progressBarText, this)
.execute("Archive.zip"); // Pass in whatever you need a url
// is just an example we don't
// use it in this tutorial
}
else
completeSplash(false);
}
private void completeSplash(boolean success) {
startApp(success);
finish(); // Don't forget to finish this Splash Activity so the user
// can't return to it!
}
private void startApp(boolean success) {
Intent intent = new Intent(SplashScreenActivity.this,
SnakeGameActivity.class);
if (success)
intent.putExtra("resourceDirectory", getApplicationContext()
.getExternalFilesDir(null) + "/downloads");
startActivity(intent);
}
@Override
public void onTaskFinished(boolean success) {
completeSplash(success);
}
} | apache-2.0 |
youngor/openclouddb | MyCat-web/rainbow-common/src/main/java/org/hx/rainbow/common/core/service/SoaInvoker.java | 1333 | /*
* Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software;Designed and Developed mainly by many Chinese
* opensource volunteers. you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 2 only, as published by the
* Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Any questions about this component can be directed to it's project Web address
* https://code.google.com/p/opencloudb/.
*
*/
package org.hx.rainbow.common.core.service;
import org.hx.rainbow.common.context.RainbowContext;
public abstract interface SoaInvoker {
public abstract RainbowContext invoke(RainbowContext context);
} | apache-2.0 |
googleinterns/calcite | core/src/main/java/org/apache/calcite/runtime/Matcher.java | 11850 | /*
* 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.runtime;
import org.apache.calcite.linq4j.MemoryFactory;
import org.apache.calcite.util.ImmutableBitSet;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Workspace that partialMatches patterns against an automaton.
* @param <E> Type of rows matched by this automaton
*/
public class Matcher<E> {
private final DeterministicAutomaton dfa;
private final ImmutableMap<String, Predicate<MemoryFactory.Memory<E>>> predicates;
// The following members are work space. They can be shared among partitions,
// but only one thread can use them at a time. Putting them here saves the
// expense of creating a fresh object each call to "match".
private final ImmutableList<Tuple<Integer>> emptyStateSet = ImmutableList.of();
private final ImmutableBitSet startSet;
private final List<Integer> rowSymbols = new ArrayList<>();
/**
* Creates a Matcher; use {@link #builder}.
*/
private Matcher(Automaton automaton,
ImmutableMap<String, Predicate<MemoryFactory.Memory<E>>> predicates) {
this.predicates = Objects.requireNonNull(predicates);
final ImmutableBitSet.Builder startSetBuilder =
ImmutableBitSet.builder();
startSetBuilder.set(automaton.startState.id);
automaton.epsilonSuccessors(automaton.startState.id, startSetBuilder);
startSet = startSetBuilder.build();
// Build the DFA
dfa = new DeterministicAutomaton(automaton);
}
public static <E> Builder<E> builder(Automaton automaton) {
return new Builder<>(automaton);
}
public List<PartialMatch<E>> match(E... rows) {
return match(Arrays.asList(rows));
}
public List<PartialMatch<E>> match(Iterable<E> rows) {
final ImmutableList.Builder<PartialMatch<E>> resultMatchBuilder =
ImmutableList.builder();
final Consumer<PartialMatch<E>> resultMatchConsumer = resultMatchBuilder::add;
final PartitionState<E> partitionState = createPartitionState(0, 0);
for (E row : rows) {
partitionState.getMemoryFactory().add(row);
matchOne(partitionState.getRows(), partitionState, resultMatchConsumer);
}
return resultMatchBuilder.build();
}
public PartitionState<E> createPartitionState(int history, int future) {
return new PartitionState<>(history, future);
}
/**
* Feeds a single input row into the given partition state,
* and writes the resulting output rows (if any).
* This method ignores the symbols that caused a transition.
*/
protected void matchOne(MemoryFactory.Memory<E> rows,
PartitionState<E> partitionState, Consumer<PartialMatch<E>> resultMatches) {
List<PartialMatch<E>> matches = matchOneWithSymbols(rows, partitionState);
for (PartialMatch<E> pm : matches) {
resultMatches.accept(pm);
}
}
protected List<PartialMatch<E>> matchOneWithSymbols(MemoryFactory.Memory<E> rows,
PartitionState<E> partitionState) {
final HashSet<PartialMatch<E>> newMatches = new HashSet<>();
for (Map.Entry<String, Predicate<MemoryFactory.Memory<E>>> predicate
: predicates.entrySet()) {
for (PartialMatch<E> pm : partitionState.getPartialMatches()) {
// Remove this match
if (predicate.getValue().test(rows)) {
// Check if we have transitions from here
final List<DeterministicAutomaton.Transition> transitions =
dfa.getTransitions().stream()
.filter(t -> predicate.getKey().equals(t.symbol))
.filter(t -> pm.currentState.equals(t.fromState))
.collect(Collectors.toList());
for (DeterministicAutomaton.Transition transition : transitions) {
// System.out.println("Append new transition to ");
final PartialMatch<E> newMatch = pm.append(transition.symbol,
rows.get(), transition.toState);
newMatches.add(newMatch);
}
}
}
// Check if a new Match starts here
if (predicate.getValue().test(rows)) {
final List<DeterministicAutomaton.Transition> transitions =
dfa.getTransitions().stream()
.filter(t -> predicate.getKey().equals(t.symbol))
.filter(t -> dfa.startState.equals(t.fromState))
.collect(Collectors.toList());
for (DeterministicAutomaton.Transition transition : transitions) {
final PartialMatch<E> newMatch = new PartialMatch<>(-1L,
ImmutableList.of(transition.symbol), ImmutableList.of(rows.get()),
transition.toState);
newMatches.add(newMatch);
}
}
}
// Remove all current partitions
partitionState.clearPartitions();
// Add all partial matches
partitionState.addPartialMatches(newMatches);
// Check if one of the new Matches is in a final state, otherwise add them
// and go on
final ImmutableList.Builder<PartialMatch<E>> builder =
ImmutableList.builder();
for (PartialMatch<E> match : newMatches) {
if (dfa.getEndStates().contains(match.currentState)) {
// This is the match, handle all "open" partial matches with a suitable
// strategy
// TODO add strategy
// Return it!
builder.add(match);
}
}
return builder.build();
}
/**
* State for each partition.
*
* @param <E> Row type
*/
static class PartitionState<E> {
private final Set<PartialMatch<E>> partialMatches = new HashSet<>();
private final MemoryFactory<E> memoryFactory;
PartitionState(int history, int future) {
this.memoryFactory = new MemoryFactory<>(history, future);
}
public void addPartialMatches(Collection<PartialMatch<E>> matches) {
partialMatches.addAll(matches);
}
public Set<PartialMatch<E>> getPartialMatches() {
return ImmutableSet.copyOf(partialMatches);
}
public void removePartialMatch(PartialMatch<E> pm) {
partialMatches.remove(pm);
}
public void clearPartitions() {
partialMatches.clear();
}
public MemoryFactory.Memory<E> getRows() {
return memoryFactory.create();
}
public MemoryFactory<E> getMemoryFactory() {
return this.memoryFactory;
}
}
/**
* Partial match of the NFA.
*
* <p>This class is immutable; the {@link #copy()} and
* {@link #append(String, Object, DeterministicAutomaton.MultiState)}
* methods generate new instances.
*
* @param <E> Row type
*/
static class PartialMatch<E> {
final long startRow;
final ImmutableList<String> symbols;
final ImmutableList<E> rows;
final DeterministicAutomaton.MultiState currentState;
PartialMatch(long startRow, ImmutableList<String> symbols,
ImmutableList<E> rows, DeterministicAutomaton.MultiState currentState) {
this.startRow = startRow;
this.symbols = symbols;
this.rows = rows;
this.currentState = currentState;
}
public PartialMatch<E> copy() {
return new PartialMatch<>(startRow, symbols, rows, currentState);
}
public PartialMatch<E> append(String symbol, E row,
DeterministicAutomaton.MultiState toState) {
ImmutableList<String> symbols = ImmutableList.<String>builder()
.addAll(this.symbols)
.add(symbol)
.build();
ImmutableList<E> rows = ImmutableList.<E>builder()
.addAll(this.rows)
.add(row)
.build();
return new PartialMatch<>(startRow, symbols, rows, toState);
}
@Override public boolean equals(Object o) {
return o == this
|| o instanceof PartialMatch
&& startRow == ((PartialMatch) o).startRow
&& Objects.equals(symbols, ((PartialMatch) o).symbols)
&& Objects.equals(rows, ((PartialMatch) o).rows)
&& Objects.equals(currentState, ((PartialMatch) o).currentState);
}
@Override public int hashCode() {
return Objects.hash(startRow, symbols, rows, currentState);
}
@Override public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < rows.size(); i++) {
if (i > 0) {
sb.append(", ");
}
sb.append("(");
sb.append(symbols.get(i));
sb.append(", ");
sb.append(rows.get(i));
sb.append(")");
}
sb.append("]");
return sb.toString();
}
}
/**
* Builds a Matcher.
*
* @param <E> Type of rows matched by this automaton
*/
public static class Builder<E> {
final Automaton automaton;
final Map<String, Predicate<MemoryFactory.Memory<E>>> symbolPredicates =
new HashMap<>();
Builder(Automaton automaton) {
this.automaton = automaton;
}
/**
* Associates a predicate with a symbol.
*/
public Builder<E> add(String symbolName,
Predicate<MemoryFactory.Memory<E>> predicate) {
symbolPredicates.put(symbolName, predicate);
return this;
}
public Matcher<E> build() {
final Set<String> predicateSymbolsNotInGraph =
Sets.newTreeSet(symbolPredicates.keySet());
predicateSymbolsNotInGraph.removeAll(automaton.symbolNames);
if (!predicateSymbolsNotInGraph.isEmpty()) {
throw new IllegalArgumentException("not all predicate symbols ["
+ predicateSymbolsNotInGraph + "] are in graph ["
+ automaton.symbolNames + "]");
}
final ImmutableMap.Builder<String, Predicate<MemoryFactory.Memory<E>>> builder =
ImmutableMap.builder();
for (String symbolName : automaton.symbolNames) {
// If a symbol does not have a predicate, it defaults to true.
// By convention, "STRT" is used for the start symbol, but it could be
// anything.
builder.put(symbolName,
symbolPredicates.getOrDefault(symbolName, e -> true));
}
return new Matcher<>(automaton, builder.build());
}
}
/**
* Represents a Tuple of a symbol and a row
*
* @param <E> Type of Row
*/
static class Tuple<E> {
final String symbol;
final E row;
Tuple(String symbol, E row) {
this.symbol = symbol;
this.row = row;
}
@Override public boolean equals(Object o) {
return o == this
|| o instanceof Tuple
&& ((Tuple) o).symbol.equals(symbol)
&& Objects.equals(row, ((Tuple) o).row);
}
@Override public int hashCode() {
return Objects.hash(symbol, row);
}
@Override public String toString() {
return "(" + symbol + ", " + row + ")";
}
}
}
| apache-2.0 |
dizitart/nitrite-database | nitrite-datagate/src/test/java/org/dizitart/no2/datagate/SyncIntegrationTest.java | 14424 | /*
*
* Copyright 2017-2018 Nitrite 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.dizitart.no2.datagate;
import lombok.extern.slf4j.Slf4j;
import org.dizitart.no2.*;
import org.dizitart.no2.objects.ObjectRepository;
import org.dizitart.no2.sync.*;
import org.dizitart.no2.sync.data.UserAccount;
import org.dizitart.no2.util.ExecutorUtils;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.dizitart.no2.Document.createDocument;
import static org.dizitart.no2.objects.filters.ObjectFilters.eq;
import static org.dizitart.no2.sync.TimeSpan.timeSpan;
import static org.dizitart.no2.datagate.Constants.*;
import static org.dizitart.no2.datagate.DbTestOperations.getRandomTempDbFile;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author Anindya Chatterjee.
*/
@Slf4j
@DirtiesContext
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SyncIntegrationTest {
@LocalServerPort
private int serverPort;
@Autowired
private Jongo jongo;
private NitriteCollection primary;
private NitriteCollection secondary;
private ObjectRepository<Employee> primaryEmployeeRepository;
private ObjectRepository<Employee> secondaryEmployeeRepository;
private Nitrite primaryDb;
private Nitrite secondaryDb;
private String primaryFile;
private String secondaryFile;
private String clientId = "junit";
private String clientSecret = "jun1t";
private String userId = "user";
private String password = "password";
private String remoteCollection = "test-collection@" + userId;
private DataGateSyncTemplate syncTemplate;
@Rule
public Retry retry = new Retry(3);
@Before
public void setUp() {
primaryFile = getRandomTempDbFile();
secondaryFile = getRandomTempDbFile();
primaryDb = Nitrite.builder()
.filePath(primaryFile)
.openOrCreate();
secondaryDb = Nitrite.builder()
.filePath(secondaryFile)
.openOrCreate();
primary = primaryDb.getCollection("primary");
secondary = secondaryDb.getCollection("secondary");
primaryEmployeeRepository = primaryDb.getRepository(Employee.class);
secondaryEmployeeRepository = secondaryDb.getRepository(Employee.class);
prepareClientAuth();
prepareUserAuth();
DataGateClient dataGateClient = new DataGateClient("http://localhost:" + serverPort)
.withAuth(userId, password);
syncTemplate = new DataGateSyncTemplate(dataGateClient, remoteCollection);
}
private void prepareClientAuth() {
UserAccount clientAccount = new UserAccount();
clientAccount.setUserName(clientId);
clientAccount.setPassword(clientSecret);
clientAccount.setAuthorities(new String[]{AUTH_CLIENT});
MongoCollection collection = jongo.getCollection(USER_REPO);
collection.insert(clientAccount);
}
private void prepareUserAuth() {
UserAccount userAccount = new UserAccount();
userAccount.setUserName(userId);
userAccount.setPassword(password);
userAccount.setAuthorities(new String[]{AUTH_USER});
userAccount.setCollections(new ArrayList<String>() {{
add(remoteCollection);
}});
DataGateClient dataGateClient = new DataGateClient("http://localhost:" + serverPort)
.withAuth(clientId, clientSecret);
DataGateUserTemplate userTemplate = new DataGateUserTemplate(dataGateClient);
userTemplate.createRemoteUser(userAccount);
}
@After
public void clear() throws IOException {
primaryDb.close();
secondaryDb.close();
Files.delete(Paths.get(primaryFile));
Files.delete(Paths.get(secondaryFile));
jongo.getCollection(remoteCollection).drop();
jongo.getCollection(USER_REPO).remove();
}
@Test
public void testDocumentSync() throws InterruptedException {
ExecutorService worker = ExecutorUtils.daemonExecutor();
final CountDownLatch latch = new CountDownLatch(2);
SyncHandle syncHandlePrimary = Replicator.of(primaryDb)
.forLocal(primary)
.withSyncTemplate(syncTemplate)
.delay(timeSpan(1, TimeUnit.SECONDS))
.ofType(ReplicationType.BOTH_WAY)
.withListener(new SyncEventListener() {
@Override
public void onSyncEvent(SyncEventData eventInfo) {
Throwable syncError = eventInfo.getError();
EventType syncEventType = eventInfo.getEventType();
assertEquals(eventInfo.getCollectionName(), "primary");
if (syncError != null) {
log.error("Sync error in " + syncEventType, syncError);
}
}
})
.configure();
syncHandlePrimary.startSync();
SyncHandle syncHandleSecondary = Replicator.of(primaryDb)
.forLocal(secondary)
.withSyncTemplate(syncTemplate)
.delay(timeSpan(1, TimeUnit.SECONDS))
.ofType(ReplicationType.BOTH_WAY)
.withListener(new SyncEventListener() {
@Override
public void onSyncEvent(SyncEventData eventInfo) {
Throwable syncError = eventInfo.getError();
EventType syncEventType = eventInfo.getEventType();
assertEquals(eventInfo.getCollectionName(), "secondary");
if (syncError != null) {
log.error("Sync error in " + syncEventType, syncError);
}
}
})
.configure();
syncHandleSecondary.startSync();
worker.submit(() -> {
// insert some data
log.info("****************** Inserting data to primary **********************");
for (int i = 0; i < 7; i++) {
Document document = createDocument("pkey1", i)
.put("pkey2", "primary value");
primary.insert(document);
}
Cursor cursor = primary.find();
log.info("****************** Updating data to primary **********************");
int i = 0;
for (Document document : cursor) {
if (i == 5) {
document.put("pkey2", "new primary value");
primary.update(document);
}
i++;
}
await().atMost(5, TimeUnit.SECONDS).until(() -> {
Thread.sleep(2000);
return true;
});
latch.countDown();
});
worker.submit(() -> {
// insert some data
log.info("****************** Inserting data to secondary **********************");
for (int i = 0; i < 5; i++) {
Document document = createDocument("skey1", i)
.put("skey2", "secondary value");
secondary.insert(document);
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("****************** Removing data from secondary **********************");
secondary.remove(secondary.find().firstOrDefault());
latch.countDown();
});
latch.await();
// wait for 4 sec to sync it all up
try {
await().atMost(5, TimeUnit.SECONDS).until(() -> primary.size() == 11 && secondary.size() == 11);
} catch (Throwable t) {
log.error("Primary Size = " + primary.size() + " & Secondary Size = " + secondary.size());
log.error("\nPrimary - " + primary.find().toList() + "\nSecondary - "
+ secondary.find().toList(), t);
throw t;
}
assertEquals(primary.size(), secondary.size());
List<Document> secondaryList = secondary.find().toList();
List<Document> primaryList = primary.find().toList();
for (Document document : primaryList) {
if (!secondaryList.contains(document)) {
fail(document + " does not exists in secondary");
}
}
}
@Test
public void testObjectSync() throws InterruptedException {
ExecutorService worker = ExecutorUtils.daemonExecutor();
final CountDownLatch latch = new CountDownLatch(2);
SyncHandle syncHandlePrimary = Replicator.of(primaryDb)
.forLocal(primaryEmployeeRepository)
.withSyncTemplate(syncTemplate)
.delay(timeSpan(1, TimeUnit.SECONDS))
.ofType(ReplicationType.BOTH_WAY)
.withListener(new SyncEventListener() {
@Override
public void onSyncEvent(SyncEventData eventInfo) {
Throwable syncError = eventInfo.getError();
EventType syncEventType = eventInfo.getEventType();
if (syncError != null) {
log.error("Sync error in " + syncEventType, syncError);
}
}
})
.configure();
syncHandlePrimary.startSync();
SyncHandle syncHandleSecondary = Replicator.of(primaryDb)
.forLocal(secondaryEmployeeRepository)
.withSyncTemplate(syncTemplate)
.delay(timeSpan(1, TimeUnit.SECONDS))
.ofType(ReplicationType.BOTH_WAY)
.withListener(new SyncEventListener() {
@Override
public void onSyncEvent(SyncEventData eventInfo) {
Throwable syncError = eventInfo.getError();
EventType syncEventType = eventInfo.getEventType();
if (syncError != null) {
log.error("Sync error in " + syncEventType, syncError);
}
}
})
.configure();
syncHandleSecondary.startSync();
worker.submit(() -> {
// insert some data
for (int i = 0; i < 7; i++) {
Employee employee = DataGenerator.generateEmployee(0);
employee.setEmpId(employee.getEmpId() + i + 10000);
primaryEmployeeRepository.insert(employee);
}
org.dizitart.no2.objects.Cursor<Employee> cursor = primaryEmployeeRepository.find();
int i = 0;
for (Employee employee : cursor) {
if (i == 5) {
employee.setAddress("New Address");
primaryEmployeeRepository.update(eq("empId", employee.getEmpId()), employee);
}
i++;
}
await().atMost(5, TimeUnit.SECONDS).until(() -> {
Thread.sleep(2000);
return true;
});
latch.countDown();
});
worker.submit(() -> {
// insert some data
for (int i = 0; i < 5; i++) {
Employee employee = DataGenerator.generateEmployee(0);
employee.setEmpId(employee.getEmpId() + i + 50000);
secondaryEmployeeRepository.insert(employee);
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
secondaryEmployeeRepository.remove(eq("empId", secondaryEmployeeRepository.find()
.firstOrDefault().getEmpId()));
latch.countDown();
});
latch.await();
// wait for 4 sec to sync it all up
try {
await().atMost(5, TimeUnit.SECONDS).until(() -> primaryEmployeeRepository.size() == 11
&& secondaryEmployeeRepository.size() == 11);
} catch (Throwable t) {
log.error("Primary Size = " + primaryEmployeeRepository.size() + " & Secondary Size = " + secondaryEmployeeRepository.size());
log.error("\nPrimary - " + primaryEmployeeRepository.find().toList() + "\nSecondary - "
+ secondaryEmployeeRepository.find().toList(), t);
throw t;
}
assertEquals(primaryEmployeeRepository.size(), secondaryEmployeeRepository.size());
List<Employee> secondaryList = secondaryEmployeeRepository.find().toList();
List<Employee> primaryList = primaryEmployeeRepository.find().toList();
for (Employee employee : primaryList) {
if (!secondaryList.contains(employee)) {
fail(employee + " does not exists in secondary");
}
}
}
}
| apache-2.0 |
tkurz/sparql-mm | src/main/java/com/github/tkurz/sparqlmm/doc/ExtensionDescriptionBuilder.java | 1686 | package com.github.tkurz.sparqlmm.doc;
import com.github.tkurz.sparqlmm.Constants;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
/**
* ...
* <p/>
* Author: Thomas Kurz (tkurz@apache.org)
*/
public class ExtensionDescriptionBuilder {
public static final String FUNCTION_NAMES = "META-INF/services/org.openrdf.query.algebra.evaluation.function.Function";
public static void main(String [] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, RDFHandlerException {
List<String> functionNames = Resources.readLines(Resources.getResource(FUNCTION_NAMES), Charset.forName("UTF-8"));
FunctionSet functionSet = new FunctionSet(functionNames);
String baseString = "sparql-mm/ns/" + Constants.VERSION + "/function/";
File ttl = new File(baseString + "index.ttl");
Files.createParentDirs(ttl);
functionSet.toRDF(ttl, RDFFormat.TURTLE);
File rdf = new File(baseString + "index.rdf");
Files.createParentDirs(rdf);
functionSet.toRDF(rdf, RDFFormat.RDFXML);
File md = new File(baseString + "index.md");
Files.createParentDirs(md);
functionSet.toMD(md);
File html = new File(baseString + "index.html");
Files.createParentDirs(html);
functionSet.toHTML(html);
File latex = new File(baseString + "index.tex");
Files.createParentDirs(latex);
functionSet.toLatex(latex);
}
}
| apache-2.0 |
openbakery/timetracker | src/main/java/org/openbakery/timetracker/web/timesheet/DayEntryListView.java | 1578 | package org.openbakery.timetracker.web.timesheet;
import org.apache.commons.lang.time.DateUtils;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.openbakery.timetracker.util.DateHelper;
import org.openbakery.timetracker.util.DurationHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: rene
* Date: 25.02.13
* Time: 17:00
* To change this template use File | Settings | File Templates.
*/
public class DayEntryListView extends ListView<DayEntry> {
private static final long serialVersionUID = 1L;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(DateHelper.DATE_PATTERN_WITH_DAYNAME);
public DayEntryListView(String id, List<DayEntry> dayEntryList) {
super(id, dayEntryList);
}
@Override
protected void populateItem(ListItem<DayEntry> item) {
DayEntry dayEntry = item.getModelObject();
String dayString = dateFormat.format(dayEntry.getDate());
if (DateUtils.isSameDay(dayEntry.getDate(), new Date())) {
dayString += " <span class=\"label label-important\">Today</span>";
}
Label dayLabel = new Label("day", dayString);
dayLabel.setEscapeModelStrings(false);
item.add(dayLabel);
item.add(new Label("sumDuration", DurationHelper.toTimeString(DurationHelper.calculateDurationSum(dayEntry.getTimeEntryList()))));
item.add(new TimeEntryListView("timeEntries", dayEntry.getTimeEntryList()));
}
}
| apache-2.0 |
kgeriiie/android-start-r | app/src/main/java/com/fps/starter/ui/fragment/TestFragment.java | 711 | package com.fps.starter.ui.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.fps.starter.R;
import butterknife.Bind;
import butterknife.ButterKnife;
public class TestFragment extends BaseFragment {
protected String TAG = TestFragment.class.getName();
@Bind(R.id.title)TextView mTitleTv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_test, container, false);
ButterKnife.bind(this, v);
return v;
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/DescribeAccountAttributesResult.java | 5414 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceResult;
/**
* <p>
* Contains the output of DescribeAccountAttributes.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAccountAttributesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Information about one or more account attributes.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<AccountAttribute> accountAttributes;
/**
* <p>
* Information about one or more account attributes.
* </p>
*
* @return Information about one or more account attributes.
*/
public java.util.List<AccountAttribute> getAccountAttributes() {
if (accountAttributes == null) {
accountAttributes = new com.amazonaws.internal.SdkInternalList<AccountAttribute>();
}
return accountAttributes;
}
/**
* <p>
* Information about one or more account attributes.
* </p>
*
* @param accountAttributes
* Information about one or more account attributes.
*/
public void setAccountAttributes(java.util.Collection<AccountAttribute> accountAttributes) {
if (accountAttributes == null) {
this.accountAttributes = null;
return;
}
this.accountAttributes = new com.amazonaws.internal.SdkInternalList<AccountAttribute>(accountAttributes);
}
/**
* <p>
* Information about one or more account attributes.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setAccountAttributes(java.util.Collection)} or {@link #withAccountAttributes(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param accountAttributes
* Information about one or more account attributes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeAccountAttributesResult withAccountAttributes(AccountAttribute... accountAttributes) {
if (this.accountAttributes == null) {
setAccountAttributes(new com.amazonaws.internal.SdkInternalList<AccountAttribute>(accountAttributes.length));
}
for (AccountAttribute ele : accountAttributes) {
this.accountAttributes.add(ele);
}
return this;
}
/**
* <p>
* Information about one or more account attributes.
* </p>
*
* @param accountAttributes
* Information about one or more account attributes.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeAccountAttributesResult withAccountAttributes(java.util.Collection<AccountAttribute> accountAttributes) {
setAccountAttributes(accountAttributes);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAccountAttributes() != null)
sb.append("AccountAttributes: ").append(getAccountAttributes());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeAccountAttributesResult == false)
return false;
DescribeAccountAttributesResult other = (DescribeAccountAttributesResult) obj;
if (other.getAccountAttributes() == null ^ this.getAccountAttributes() == null)
return false;
if (other.getAccountAttributes() != null && other.getAccountAttributes().equals(this.getAccountAttributes()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAccountAttributes() == null) ? 0 : getAccountAttributes().hashCode());
return hashCode;
}
@Override
public DescribeAccountAttributesResult clone() {
try {
return (DescribeAccountAttributesResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
Ccook/gtk-java-bindings | src/main/java/com/github/ccook/gtk/model/object/widget/container/bin/GtkButton.java | 213 | package com.github.ccook.gtk.model.object.widget.container.bin;
import com.github.ccook.gtk.model.object.widget.container.GtkBin;
/**
* Created by cam on 10/22/16.
*/
public class GtkButton extends GtkBin {
}
| apache-2.0 |
bounswe/bounswe2016group11 | coco-android/Coco/app/src/main/java/com/cocomap/coco/pojo/SearchResponse.java | 352 | package com.cocomap.coco.pojo;
import java.util.List;
/**
* Created by Emrah on 21/12/2016.
*/
public class SearchResponse {
List<PostRetrieveResponse> topics;
public List<PostRetrieveResponse> getTopics() {
return topics;
}
public void setTopics(List<PostRetrieveResponse> topics) {
this.topics = topics;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-groundstation/src/main/java/com/amazonaws/services/groundstation/model/transform/GroundStationDataMarshaller.java | 2650 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.groundstation.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.groundstation.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GroundStationDataMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GroundStationDataMarshaller {
private static final MarshallingInfo<String> GROUNDSTATIONID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("groundStationId").build();
private static final MarshallingInfo<String> GROUNDSTATIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("groundStationName").build();
private static final MarshallingInfo<String> REGION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("region").build();
private static final GroundStationDataMarshaller instance = new GroundStationDataMarshaller();
public static GroundStationDataMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(GroundStationData groundStationData, ProtocolMarshaller protocolMarshaller) {
if (groundStationData == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(groundStationData.getGroundStationId(), GROUNDSTATIONID_BINDING);
protocolMarshaller.marshall(groundStationData.getGroundStationName(), GROUNDSTATIONNAME_BINDING);
protocolMarshaller.marshall(groundStationData.getRegion(), REGION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
Radlermo/Monikajava_pft | addressbook-web-tests/src/test/java/pl/stqa/pft/addressbook/model/Groups.java | 1455 | package pl.stqa.pft.addressbook.model;
import com.google.common.collect.ForwardingSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Groups extends ForwardingSet<GroupData> {
private Set<GroupData> delegate;//delegujemy metode
public Groups(Groups groups) {
this.delegate = new HashSet<GroupData>(groups.delegate);// bierzemy zbiór z istniejącego objektu, który jest przekazywany jako parametr, budujemy nowy zbiór zawierający
//te same elementy (new HashSet...) i przypisujemy go jako atrybut w objekt
}
//pusty konstruktor dla zbioru public Groups all() z klasy Group Helper
public Groups() {
this.delegate= new HashSet<GroupData>();
}
public Groups(Collection<GroupData> groups) {
this.delegate = new HashSet<GroupData>(groups);
}
@Override
protected Set<GroupData> delegate() {
return delegate; //zwracamy metode delegate
}
//dodajemy swoje metody które będą używane w testach
//metoda na dodanie grupy
public Groups withAdded(GroupData group) {
Groups groups = new Groups(this);//buduje kopie istniejącego objektu
groups.add(group);
return groups;
}
//metoda na usunięcie grupy
public Groups without(GroupData group) {
Groups groups = new Groups(this);//buduje kopie istniejącego objektu
groups.remove(group);
return groups;
}
}
| apache-2.0 |
eug48/hapi-fhir | hapi-fhir-utilities/src/main/java/org/hl7/fhir/utilities/graphql/Argument.java | 3078 | package org.hl7.fhir.utilities.graphql;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class Argument {
String name;
private List<Value> values = new ArrayList<Value>();
boolean list;
public Argument() {
super();
}
public Argument(String name, Value value) {
super();
this.name = name;
this.values.add(value);
}
public Argument(String name, JsonElement json) throws EGraphQLException {
super();
this.name = name;
valuesFromNode(json);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isList() {
return list;
}
public void setList(boolean list) {
this.list = list;
}
public List<Value> getValues() {
return values;
}
public void addValue(Value value){
values.add(value);
}
public boolean hasValue(String value) {
for (Value v : values )
if (v.isValue(value))
return true;
return false;
}
public void valuesFromNode(JsonElement json) throws EGraphQLException {
if (json instanceof JsonPrimitive && ((JsonPrimitive) json).isString())
values.add(new StringValue(((JsonPrimitive)json).getAsString()));
else if (json instanceof JsonPrimitive && ((JsonPrimitive) json).isNumber())
values.add(new NumberValue(((JsonPrimitive)json).getAsString()));
else if (json instanceof JsonPrimitive && ((JsonPrimitive) json).isBoolean())
values.add(new NameValue(((JsonPrimitive)json).getAsBoolean()));
else if (json instanceof JsonObject)
values.add(new ObjectValue((JsonObject) json));
else if (json instanceof JsonArray) {
for (JsonElement v : (JsonArray) json)
valuesFromNode(v);
} else
throw new EGraphQLException("Unexpected JSON type for \""+name+"\": "+json.getClass().getName());
}
public void write(StringBuilder b, int indent) throws EGraphQLException, EGraphEngine {
b.append("\"");
for (char ch : name.toCharArray()) {
if (ch == '"') b.append("\"");
else if (ch == '\\') b.append("\\");
else if (ch == '\r') b.append("\\r");
else if (ch == '\n') b.append("\\n");
else if (ch == '\t') b.append("\\t");
else if (ch < 32)
b.append("\\u"+Integer.toHexString(ch));
else
b.append(ch);
}
b.append("\":");
if (list) {
b.append("[");
boolean first = true;
for (Value v : values) {
if (first) first = false; else b.append(",");
v.write(b, indent);
}
b.append("]");
} else {
if (values.size() > 1)
throw new EGraphQLException("Internal error: non list \""+name+"\" has "+Integer.toString(values.size())+" values");
if (values.size() == 0)
b.append("null");
else
values.get(0).write(b, indent);
}
}
} | apache-2.0 |
Salaboy/wires | wires-core/wires-core-client/src/main/java/org/kie/wires/core/client/util/GeometryUtil.java | 4253 | /*
* Copyright 2014 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.wires.core.client.util;
/**
* Useful geometry functions taken from Java's Line2D class
*/
public class GeometryUtil {
/**
* Returns the square of the distance from a point to a line segment.
* The distance measured is the distance between the specified
* point and the closest point between the specified end points.
* If the specified point intersects the line segment in between the
* end points, this method returns 0.0.
* <p/>
* See http://docs.oracle.com/javase/6/docs/api/java/awt/geom/Line2D.html#ptSegDist%28double,%20double,%20double,%20double,%20double,%20double%29
* @param x1 the X coordinate of the start point of the
* specified line segment
* @param y1 the Y coordinate of the start point of the
* specified line segment
* @param x2 the X coordinate of the end point of the
* specified line segment
* @param y2 the Y coordinate of the end point of the
* specified line segment
* @param px the X coordinate of the specified point being
* measured against the specified line segment
* @param py the Y coordinate of the specified point being
* measured against the specified line segment
* @return a double value that is the square of the distance from the
* specified point to the specified line segment.
*/
public static double ptSegDistSq( double x1,
double y1,
double x2,
double y2,
double px,
double py ) {
// Adjust vectors relative to x1,y1
// x2,y2 becomes relative vector from x1,y1 to end of segment
x2 -= x1;
y2 -= y1;
// px,py becomes relative vector from x1,y1 to test point
px -= x1;
py -= y1;
double dotprod = px * x2 + py * y2;
double projlenSq;
if ( dotprod <= 0.0 ) {
// px,py is on the side of x1,y1 away from x2,y2
// distance to segment is length of px,py vector
// "length of its (clipped) projection" is now 0.0
projlenSq = 0.0;
} else {
// switch to backwards vectors relative to x2,y2
// x2,y2 are already the negative of x1,y1=>x2,y2
// to get px,py to be the negative of px,py=>x2,y2
// the dot product of two negated vectors is the same
// as the dot product of the two normal vectors
px = x2 - px;
py = y2 - py;
dotprod = px * x2 + py * y2;
if ( dotprod <= 0.0 ) {
// px,py is on the side of x2,y2 away from x1,y1
// distance to segment is length of (backwards) px,py vector
// "length of its (clipped) projection" is now 0.0
projlenSq = 0.0;
} else {
// px,py is between x1,y1 and x2,y2
// dotprod is the length of the px,py vector
// projected on the x2,y2=>x1,y1 vector times the
// length of the x2,y2=>x1,y1 vector
projlenSq = dotprod * dotprod / ( x2 * x2 + y2 * y2 );
}
}
// Distance to line is now the length of the relative point
// vector minus the length of its projection onto the line
// (which is zero if the projection falls outside the range
// of the line segment).
double lenSq = px * px + py * py - projlenSq;
if ( lenSq < 0 ) {
lenSq = 0;
}
return lenSq;
}
}
| apache-2.0 |
SecUSo/EasyVote | vcd_votedevice/src/main/java/de/tud/vcd/votedevice/multielection/VCDModel.java | 1051 | /*******************************************************************************
* # Copyright 2015 SecUSo.org / Jurlind Budurushi / Roman Jöris
* #
* # 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.tud.vcd.votedevice.multielection;
import java.util.Observer;
public interface VCDModel {
public void addObserver(Observer o);
public void updateObserver();
public void resetBallotCard();
}
| apache-2.0 |
sburba/Tvdb-Api-Android | TvdbApi/src/main/java/com/sburba/tvdbapi/xml/XmlException.java | 258 | package com.sburba.tvdbapi.xml;
public class XmlException extends Exception {
public XmlException(String message) {
super(message);
}
public XmlException(String message, Throwable throwable) {
super(message, throwable);
}
} | apache-2.0 |
mrfrag/wreckan-server | src/main/java/com/github/wreckan/admin/client/mvp/presenters/RootPresenter.java | 746 | package com.github.wreckan.admin.client.mvp.presenters;
import com.github.wreckan.admin.client.WreckanEventBus;
import com.github.wreckan.admin.client.mvp.IRootView;
import com.github.wreckan.admin.client.mvp.IRootView.IRootPresenter;
import com.github.wreckan.admin.client.mvp.views.RootView;
import com.google.gwt.user.client.ui.IsWidget;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;
@Presenter(view = RootView.class)
public class RootPresenter extends BasePresenter<IRootView, WreckanEventBus> implements IRootPresenter {
@Override
public void onSetBody(IsWidget body) {
view.setBody(body);
}
@Override
public void onSetToolBar(IsWidget toolbar) {
view.setToolbar(toolbar);
}
}
| apache-2.0 |
kimkr/AndroidArchitecture | presentation/src/main/java/io/github/kimkr/presentation/view/ViewBinding.java | 367 | package io.github.kimkr.presentation.view;
import android.databinding.BindingAdapter;
import android.view.View;
/**
* Created by kkr on 2017. 10. 26..
*/
public class ViewBinding {
@BindingAdapter(value = {"binding:selected"}, requireAll = false)
public static void setSelected(View view, boolean selected) {
view.setSelected(selected);
}
}
| apache-2.0 |
ljl1988com/pig | src/org/apache/pig/backend/hadoop/executionengine/tez/plan/operator/POSimpleTezLoad.java | 5187 | /**
* 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.pig.backend.hadoop.executionengine.tez.plan.operator;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.pig.LoadFunc;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapReduce;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POLoad;
import org.apache.pig.backend.hadoop.executionengine.tez.runtime.TezInput;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.PigImplConstants;
import org.apache.pig.impl.plan.OperatorKey;
import org.apache.tez.mapreduce.input.MRInput;
import org.apache.tez.mapreduce.lib.MRReader;
import org.apache.tez.runtime.api.LogicalInput;
import org.apache.tez.runtime.library.api.KeyValueReader;
/**
* POSimpleTezLoad is used on the backend to read tuples from a Tez MRInput
*/
public class POSimpleTezLoad extends POLoad implements TezInput {
private static final long serialVersionUID = 1L;
private String inputKey;
private MRInput input;
private KeyValueReader reader;
private transient Configuration conf;
private transient boolean finished = false;
public POSimpleTezLoad(OperatorKey k, LoadFunc loader) {
super(k, loader);
}
@Override
public String[] getTezInputs() {
return new String[] { inputKey };
}
@Override
public void replaceInput(String oldInputKey, String newInputKey) {
if (oldInputKey.equals(inputKey)) {
inputKey = newInputKey;
}
}
@Override
public void addInputsToSkip(Set<String> inputsToSkip) {
}
@Override
public void attachInputs(Map<String, LogicalInput> inputs,
Configuration conf)
throws ExecException {
this.conf = conf;
LogicalInput logInput = inputs.get(inputKey);
if (logInput == null || !(logInput instanceof MRInput)) {
throw new ExecException("POSimpleTezLoad only accepts MRInputs");
}
input = (MRInput) logInput;
try {
reader = input.getReader();
// Set split index, MergeCoGroup need it. And this input is the only input of the
// MergeCoGroup vertex.
if (reader instanceof MRReader) {
int splitIndex = ((PigSplit)((MRReader)reader).getSplit()).getSplitIndex();
PigMapReduce.sJobContext.getConfiguration().setInt(PigImplConstants.PIG_SPLIT_INDEX, splitIndex);
}
} catch (IOException e) {
throw new ExecException(e);
}
}
/**
* Previously, we reused the same Result object for all results, but we found
* certain operators (e.g. POStream) save references to the Result object and
* expect it to be constant.
*/
@Override
public Result getNextTuple() throws ExecException {
try {
if (finished) {
return RESULT_EOP;
}
Result res = new Result();
if (!reader.next()) {
res.result = null;
res.returnStatus = POStatus.STATUS_EOP;
// For certain operators (such as STREAM), we could still have some work
// to do even after seeing the last input. These operators set a flag that
// says all input has been sent and to run the pipeline one more time.
if (Boolean.valueOf(conf.get(JobControlCompiler.END_OF_INP_IN_MAP, "false"))) {
this.parentPlan.endOfAllInput = true;
}
finished = true;
} else {
Tuple next = (Tuple) reader.getCurrentValue();
res.result = next;
res.returnStatus = POStatus.STATUS_OK;
}
return res;
} catch (IOException e) {
throw new ExecException(e);
}
}
public void setInputKey(String inputKey) {
this.inputKey = inputKey;
}
}
| apache-2.0 |
ty1er/incubator-asterixdb | hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/physical/PreSortedDistinctByPOperator.java | 4015 | /*
* 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.hyracks.algebricks.core.algebra.operators.physical;
import java.util.List;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.IHyracksJobBuilder;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.base.PhysicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractLogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.IOperatorSchema;
import org.apache.hyracks.algebricks.core.jobgen.impl.JobGenContext;
import org.apache.hyracks.algebricks.core.jobgen.impl.JobGenHelper;
import org.apache.hyracks.algebricks.runtime.base.IAggregateEvaluatorFactory;
import org.apache.hyracks.algebricks.runtime.operators.aggreg.SimpleAlgebricksAccumulatingAggregatorFactory;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.RecordDescriptor;
import org.apache.hyracks.api.job.IOperatorDescriptorRegistry;
import org.apache.hyracks.dataflow.std.group.IAggregatorDescriptorFactory;
import org.apache.hyracks.dataflow.std.group.preclustered.PreclusteredGroupOperatorDescriptor;
public class PreSortedDistinctByPOperator extends AbstractPreSortedDistinctByPOperator {
public PreSortedDistinctByPOperator(List<LogicalVariable> columnList) {
super(columnList);
}
@Override
public PhysicalOperatorTag getOperatorTag() {
return PhysicalOperatorTag.PRE_SORTED_DISTINCT_BY;
}
@Override
public boolean isMicroOperator() {
return false;
}
@Override
public void contributeRuntimeOperator(IHyracksJobBuilder builder, JobGenContext context, ILogicalOperator op,
IOperatorSchema opSchema, IOperatorSchema[] inputSchemas, IOperatorSchema outerPlanSchema)
throws AlgebricksException {
IOperatorDescriptorRegistry spec = builder.getJobSpec();
int[] keysAndDecs = getKeysAndDecs(inputSchemas[0]);
IBinaryComparatorFactory[] comparatorFactories = JobGenHelper
.variablesToAscBinaryComparatorFactories(columnList, context.getTypeEnvironment(op), context);
IAggregateEvaluatorFactory[] aggFactories = new IAggregateEvaluatorFactory[] {};
IAggregatorDescriptorFactory aggregatorFactory =
new SimpleAlgebricksAccumulatingAggregatorFactory(aggFactories, keysAndDecs);
RecordDescriptor recordDescriptor =
JobGenHelper.mkRecordDescriptor(context.getTypeEnvironment(op), opSchema, context);
/* make fd columns part of the key but the comparator only compares the distinct key columns */
PreclusteredGroupOperatorDescriptor opDesc = new PreclusteredGroupOperatorDescriptor(spec, keysAndDecs,
comparatorFactories, aggregatorFactory, recordDescriptor);
contributeOpDesc(builder, (AbstractLogicalOperator) op, opDesc);
ILogicalOperator src = op.getInputs().get(0).getValue();
builder.contributeGraphEdge(src, 0, op, 0);
}
}
| apache-2.0 |
Padepokan79/PUBTeam | ManipulateDatabase/src/com/padepokan79/model/MdJabatanFungsi.java | 603 | package com.padepokan79.model;
public interface MdJabatanFungsi {
public final String querySearchNamaBerdasarkanKdFungsi =
"select KDFUNGSI,NMFUNGSI from jabatan_fungsi where KDFUNGSI=?";
public final String querySelectData =
"select KDFUNGSI,NMFUNGSI from jabatan_fungsi;";
public final String queryInsertData=
"insert into jabatan_fungsi values (?,?);";
public final String queryUpdateNamaBerdasarkanKodeFungsi=
"update jabatan_fungsi set nmfungsi=? where kdfungsi=?;";
public final String queryDeleteDataBerdasarkanKodeFungsi=
"delete from jabatan_fungsi where kdfungsi=?;";
}
| apache-2.0 |
brunoalvarez89/Visu | src/com/ufavaloro/android/visu/userinterface/MainActivity.java | 10883 | /*****************************************************************************************
* MainActivity.java *
* Clase que administra la interfaz de usuario. *
****************************************************************************************/
package com.ufavaloro.android.visu.userinterface;
import java.io.File;
import com.ufavaloro.android.visu.R;
import com.ufavaloro.android.visu.connection.ConnectionMode;
import com.ufavaloro.android.visu.connection.ConnectionType;
import com.ufavaloro.android.visu.main.MainInterface;
import com.ufavaloro.android.visu.main.MainInterfaceMessage;
import com.ufavaloro.android.visu.storage.StorageInterfaceMessage;
import com.ufavaloro.android.visu.storage.datatypes.StorageData;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.OpenFileActivityBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class MainActivity extends Activity {
// Estudio
private MainInterface mMainInterface;
// View para manejar Status Bar y Navigation Bar
private View mRootView;
// Dialogs Theme
private int mDialogTheme = android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar_MinWidth;
// Request code for enabling Bluetooth
private static final int REQUEST_CODE_ENABLE_BLUETOOTH = 2;
// Request código de apertura de archivo de Google Drive
private static final int REQUEST_CODE_GOOGLE_DRIVE_FILE_BROWSER = 1;
// Incoming Connection Progress Dialog
private ProgressDialog mWaitingForConnectionDialog;
// Método que se ejecuta luego de haberse creado el SurfaceView asociado
public void setupAfterSurfaceCreated() {
mMainInterface = new MainInterface(this, mMainInterfaceHandler);
//mMainInterface.getConnectionInterface().addConnection(ConnectionType.BLUETOOTH, ConnectionMode.SLAVE);
}
/*****************************************************************************************
* Dialogs
*****************************************************************************************/
// Dialog de menú principal
public void mainMenuDialog() {
MainMenuDialog dialog = new MainMenuDialog(this, this, mDialogTheme);
}
// Dialog de nuevo estudio
public void newStudyDialog() {
NewStudyDialog dialog = new NewStudyDialog(this, this, mDialogTheme);
}
// Dialog para abrir un archivo desde la memoria interna
public void loadFileFromLocalStorageDialog() {
LoadFileFromLocalStorageDialog dialog = new LoadFileFromLocalStorageDialog(this, mMainInterface);
dialog.setup();
}
// Dialog para abrir un archivo desde Google Drive
public void loadFileFromGoogleDriveDialog() {
LoadFileFromGoogleDriveDialog dialog = new LoadFileFromGoogleDriveDialog(this, mMainInterface);
dialog.setup();
}
// Dialog de parar estudio
public void stopStudyDialog() {
StopStudyDialog dialog = new StopStudyDialog(this, mDialogTheme);
dialog.setMainInterface(mMainInterface);
dialog.setup();
}
// Dialog con las opciones del canal
public void channelOptionsDialog(int channelNumber) {
ChannelOptionsDialog dialog = new ChannelOptionsDialog(this, mDialogTheme, channelNumber);
dialog.setMainActivity(this);
dialog.setMainInterface(mMainInterface);
dialog.setup();
}
// Dialog de configuración de canales ONLINE
public void onlineChannelPropertiesDialog(int channel) {
OnlineChannelPropertiesDialog dialog = new OnlineChannelPropertiesDialog(this, mDialogTheme, channel);
dialog.setStudy(mMainInterface);
dialog.setup();
dialog.show();
}
// Dialog con las propiedades del canal OFFLINE
public void offlineChannelPropertiesDialog(int channelNumber) {
OfflineChannelPropertiesDialog dialog = new OfflineChannelPropertiesDialog(this, mDialogTheme, channelNumber);
dialog.setStudy(mMainInterface);
dialog.setup();
dialog.show();
}
public void addBluetoothConnectionDialog() {
AddBluetoothConnectionDialog dialog = new AddBluetoothConnectionDialog(this, this, mDialogTheme);
}
public void connectToRemoteDeviceDialog() {
RemoteBluetoothDevicesDialog dialog = new RemoteBluetoothDevicesDialog(this, this, mDialogTheme);
}
public void waitingForConnectionDialog() {
mMainInterface.getConnectionInterface().addConnection(ConnectionType.BLUETOOTH, ConnectionMode.SLAVE);
mWaitingForConnectionDialog = ProgressDialog.show(this, "Conexión Bluetooth", "Esperando...");
}
private final Handler mMainInterfaceHandler = new Handler() {
// Método para manejar el mensaje
@Override
public void handleMessage(Message msg) {
// Tipo de mensaje recibido
MainInterfaceMessage mainInterfaceMessage = MainInterfaceMessage.values(msg.what);
switch (mainInterfaceMessage) {
case NOTHING:
break;
case BLUETOOTH_CONNECTED:
mWaitingForConnectionDialog.cancel();
shortToast("Conectado");
break;
case BLUETOOTH_DISCONNECTED:
shortToast("Desconectado");
break;
default:
break;
}
}
};
/*****************************************************************************************
* Visibilidad de Status Bar y Navigation Bar *
*****************************************************************************************/
// Método que muestra Status y Navigation bars
private void showSystemUi(boolean visible) {
int flag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE;
if (!visible) {
// We used the deprecated "STATUS_BAR_HIDDEN" for unbundling
flag |= View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
mRootView.setSystemUiVisibility(flag);
}
// Método que escucha la pantalla para decidir cuando mostrar la UI
private void setOnSystemUiVisibilityChangeListener() {
mRootView.setOnSystemUiVisibilityChangeListener(
new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
// Note that system bars will only be "visible" if none of the
// LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
// The system bars are visible. Make any desired
// adjustments to your UI, such as showing the action bar or
// other navigational controls.
if(mMainInterface.getDrawInterface() != null) mMainInterface.getDrawInterface().setUiVisibility(true);
} else {
// The system bars are NOT visible. Make any desired
// adjustments to your UI, such as hiding the action bar or
// other navigational controls.
if(mMainInterface.getDrawInterface() != null) mMainInterface.getDrawInterface().setUiVisibility(false);
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
showSystemUi(false);
}
}, 4000);
}
});
}
/*****************************************************************************************
* Otros métodos *
*****************************************************************************************/
// Getter de la carpeta de estudios
public static File getStudiesFolder() {
return StorageData.studiesFolder;
}
// Toast corto
public void shortToast(String toToast) {
Toast.makeText(getApplicationContext(), toToast, Toast.LENGTH_SHORT).show();
}
// Toast largo
public void longToast(String toToast) {
Toast.makeText(getApplicationContext(), toToast, Toast.LENGTH_LONG).show();
}
// MainInterface Getter (for Dialogs)
public MainInterface getMainInterface() {
return mMainInterface;
}
/*****************************************************************************************
* Ciclo de vida de la activity *
*****************************************************************************************/
// this.activity on create
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.activity_main);
}
// this.activity on start
@Override
public void onStart() {
super.onStart();
}
// this.activity on resume
@Override
public void onResume() {
super.onResume();
mRootView = getWindow().getDecorView();
setOnSystemUiVisibilityChangeListener();
showSystemUi(false);
}
// this.activity on pause
@Override
public void onPause() {
super.onPause();
}
// this.activity on stop
@Override
public void onStop() {
super.onStop();
}
// this.activity on destroy
@Override
public void onDestroy() {
super.onDestroy();
// Paro todos los Threads
//if(mMainInterface != null) mMainInterface.getBluetoothProtocol().stopConnections();
}
// this.activity on back pressed
public void onBackPressed() {
moveTaskToBack(true);
}
// this.activity onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_GOOGLE_DRIVE_FILE_BROWSER:
if (resultCode == RESULT_OK) {
if(!mMainInterface.isGoogleDriveConnected()) return;
DriveId driveId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
mMainInterface.getStorageInterface().loadFileFromGoogleDrive(driveId);
shortToast("Abriendo archivo...");
}
getMainInterface().getDrawInterface().startDrawing();
break;
case REQUEST_CODE_ENABLE_BLUETOOTH:
if (resultCode == Activity.RESULT_OK) {
shortToast("Bluetooth activado");
addBluetoothConnectionDialog();
}
if (resultCode == Activity.RESULT_CANCELED) {
shortToast("Por favor, active el Bluetooth");
}
break;
default:
break;
}
}
}//MainActivity
| apache-2.0 |
ben-upsilon/exp-aqr | src/com/google/zxing/qrcode/decoder/Mode.java | 3359 | /*
* Copyright 2007 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.qrcode.decoder;
/**
*
* 解码模式
* <p>See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which
* data can be encoded to bits in the QR code standard.</p>
*
* @author Sean Owen
*/
public enum Mode {
TERMINATOR(new int[]{0, 0, 0}, 0x00), // Not really a mode...
NUMERIC(new int[]{10, 12, 14}, 0x01),
ALPHANUMERIC(new int[]{9, 11, 13}, 0x02),
STRUCTURED_APPEND(new int[]{0, 0, 0}, 0x03), // Not supported
BYTE(new int[]{8, 16, 16}, 0x04),
ECI(new int[]{0, 0, 0}, 0x07), // character counts don't apply
KANJI(new int[]{8, 10, 12}, 0x08),
FNC1_FIRST_POSITION(new int[]{0, 0, 0}, 0x05),
FNC1_SECOND_POSITION(new int[]{0, 0, 0}, 0x09),
/**
* See GBT 18284-2000; "Hanzi" is a transliteration of this mode name.
*/
HANZI(new int[]{8, 10, 12}, 0x0D);
private final int[] characterCountBitsForVersions;
private final int bits;
Mode(int[] characterCountBitsForVersions, int bits) {
this.characterCountBitsForVersions = characterCountBitsForVersions;
this.bits = bits;
}
/**
* @param bits four bits encoding a QR Code data mode
* @return Mode encoded by these bits
* @throws IllegalArgumentException if bits do not correspond to a known mode
*/
public static Mode forBits(int bits) {
switch (bits) {
case 0x0:
return TERMINATOR;
case 0x1:
return NUMERIC;
case 0x2:
return ALPHANUMERIC;
case 0x3:
return STRUCTURED_APPEND;
case 0x4:
return BYTE;
case 0x5:
return FNC1_FIRST_POSITION;
case 0x7:
return ECI;
case 0x8:
return KANJI;
case 0x9:
return FNC1_SECOND_POSITION;
case 0xD:
// 0xD is defined in GBT 18284-2000, may not be supported in foreign country
return HANZI;
default:
throw new IllegalArgumentException();
}
}
/**
* @param version version in question
* @return number of bits used, in this QR Code symbol {@link Version}, to encode the
* count of characters that will follow encoded in this Mode
*/
public int getCharacterCountBits(Version version) {
int number = version.getVersionNumber();
int offset;
if (number <= 9) {
offset = 0;
} else if (number <= 26) {
offset = 1;
} else {
offset = 2;
}
return characterCountBitsForVersions[offset];
}
public int getBits() {
return bits;
}
}
| apache-2.0 |
StrategyObject/fop | test/java/org/apache/fop/visual/BitmapComparator.java | 7596 | /*
* 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.
*/
/* $Id$ */
package org.apache.fop.visual;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.apache.batik.ext.awt.image.GraphicsUtil;
import org.apache.batik.ext.awt.image.renderable.Filter;
import org.apache.batik.ext.awt.image.spi.ImageTagRegistry;
import org.apache.batik.util.ParsedURL;
/**
* Helper class to visually compare two bitmap images.
* <p>
* This class was created by extracting reusable code from
* org.apache.batik.test.util.ImageCompareText (Apache Batik)
* into this separate class.
* <p>
* TODO Move as utility class to XML Graphics Commons when possible
*/
public final class BitmapComparator {
private BitmapComparator() {
}
/**
* Builds a new BufferedImage that is the difference between the two input images
* @param ref the reference bitmap
* @param gen the newly generated bitmap
* @return the diff bitmap
*/
public static BufferedImage buildDiffImage(BufferedImage ref,
BufferedImage gen) {
BufferedImage diff = new BufferedImage(ref.getWidth(),
ref.getHeight(),
BufferedImage.TYPE_INT_ARGB);
WritableRaster refWR = ref.getRaster();
WritableRaster genWR = gen.getRaster();
WritableRaster dstWR = diff.getRaster();
boolean refPre = ref.isAlphaPremultiplied();
if (!refPre) {
ColorModel cm = ref.getColorModel();
cm = GraphicsUtil.coerceData(refWR, cm, true);
ref = new BufferedImage(cm, refWR, true, null);
}
boolean genPre = gen.isAlphaPremultiplied();
if (!genPre) {
ColorModel cm = gen.getColorModel();
cm = GraphicsUtil.coerceData(genWR, cm, true);
gen = new BufferedImage(cm, genWR, true, null);
}
int w = ref.getWidth();
int h = ref.getHeight();
int [] refPix = null;
int [] genPix = null;
for (int y = 0; y < h; y++) {
refPix = refWR.getPixels(0, y, w, 1, refPix);
genPix = genWR.getPixels(0, y, w, 1, genPix);
for (int i = 0; i < refPix.length; i++) {
// val = ((genPix[i] - refPix[i]) * 5) + 128;
int val = ((refPix[i] - genPix[i]) * 10) + 128;
if ((val & 0xFFFFFF00) != 0) {
if ((val & 0x80000000) != 0) {
val = 0;
} else {
val = 255;
}
}
genPix[i] = val;
}
dstWR.setPixels(0, y, w, 1, genPix);
}
if (!genPre) {
ColorModel cm = gen.getColorModel();
cm = GraphicsUtil.coerceData(genWR, cm, false);
}
if (!refPre) {
ColorModel cm = ref.getColorModel();
cm = GraphicsUtil.coerceData(refWR, cm, false);
}
return diff;
}
/**
* Builds a combined image that places a number of images next to each other for
* manual, visual comparison.
* @param images the array of bitmaps
* @return the combined image
*/
public static BufferedImage buildCompareImage(BufferedImage[] images) {
BufferedImage cmp = new BufferedImage(
images[0].getWidth() * images.length,
images[0].getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = cmp.createGraphics();
g.setPaint(Color.white);
g.fillRect(0, 0, cmp.getWidth(), cmp.getHeight());
int lastWidth = 0;
for (int i = 0; i < images.length; i++) {
if (lastWidth > 0) {
g.translate(lastWidth, 0);
}
if (images[i] != null) {
g.drawImage(images[i], 0, 0, null);
lastWidth = images[i].getWidth();
} else {
lastWidth = 20; //Maybe add a special placeholder image instead later
}
}
g.dispose();
return cmp;
}
/**
* Builds a combined image that places two images next to each other for
* manual, visual comparison.
* @param ref the reference image
* @param gen the actual image
* @return the combined image
*/
public static BufferedImage buildCompareImage(BufferedImage ref,
BufferedImage gen) {
return buildCompareImage(new BufferedImage[] {ref, gen});
}
/**
* Loads an image from a URL
* @param url the URL to the image
* @return the bitmap as BufferedImage
* TODO This method doesn't close the InputStream opened by the URL.
*/
public static BufferedImage getImage(URL url) {
ImageTagRegistry reg = ImageTagRegistry.getRegistry();
Filter filt = reg.readURL(new ParsedURL(url));
if (filt == null) {
return null;
}
RenderedImage red = filt.createDefaultRendering();
if (red == null) {
return null;
}
BufferedImage img = new BufferedImage(red.getWidth(),
red.getHeight(),
BufferedImage.TYPE_INT_ARGB);
red.copyData(img.getRaster());
return img;
}
/**
* Loads an image from a URL
* @param bitmapFile the bitmap file
* @return the bitmap as BufferedImage
*/
public static BufferedImage getImage(File bitmapFile) {
try {
InputStream in = new java.io.FileInputStream(bitmapFile);
try {
in = new java.io.BufferedInputStream(in);
ImageTagRegistry reg = ImageTagRegistry.getRegistry();
Filter filt = reg.readStream(in);
if (filt == null) {
return null;
}
RenderedImage red = filt.createDefaultRendering();
if (red == null) {
return null;
}
BufferedImage img = new BufferedImage(red.getWidth(),
red.getHeight(),
BufferedImage.TYPE_INT_ARGB);
red.copyData(img.getRaster());
return img;
} finally {
IOUtils.closeQuietly(in);
}
} catch (IOException e) {
return null;
}
}
}
| apache-2.0 |
roman-kashitsyn/Gitoscope | src/main/java/gitoscope/exception/CommitNotFoundException.java | 622 | package gitoscope.exception;
public class CommitNotFoundException extends GitoscopeException {
public CommitNotFoundException(String projectName, String commitId) {
super();
this.projectName = projectName;
this.commitId = commitId;
}
public String getProjectName() {
return this.projectName;
}
public String getCommitId() {
return this.commitId;
}
public CommitNotFoundException initCause(Throwable t) {
super.initCause(t);
return this;
}
private String projectName;
private String commitId;
}
| apache-2.0 |
ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Abilities/Druid/Druid_ShapeShift4.java | 583 | package com.suscipio_solutions.consecro_mud.Abilities.Druid;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.core.CMLib;
public class Druid_ShapeShift4 extends Druid_ShapeShift
{
@Override public String ID() { return "Druid_ShapeShift4"; }
private final static String localizedName = CMLib.lang().L("Fourth Totem");
@Override public String name() { return localizedName; }
@Override public int abstractQuality(){return Ability.QUALITY_OK_SELF;}
@Override public String[] triggerStrings(){return empty;}
}
| apache-2.0 |
elasticlib/elasticlib | elasticlib-node/src/main/java/org/elasticlib/node/repository/RevisionManager.java | 6718 | /*
* Copyright 2014 Guillaume Masclet <guillaume.masclet@yahoo.fr>.
*
* 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.elasticlib.node.repository;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import java.util.Optional;
import java.util.SortedSet;
import org.elasticlib.common.exception.ConflictException;
import org.elasticlib.common.exception.UnknownContentException;
import org.elasticlib.common.exception.UnknownRevisionException;
import org.elasticlib.common.hash.Hash;
import org.elasticlib.common.model.CommandResult;
import org.elasticlib.common.model.Operation;
import org.elasticlib.common.model.Revision;
import org.elasticlib.common.model.Revision.RevisionBuilder;
import org.elasticlib.common.model.RevisionTree;
import org.elasticlib.common.model.RevisionTree.RevisionTreeBuilder;
import static org.elasticlib.node.manager.storage.DatabaseEntries.asMappable;
import static org.elasticlib.node.manager.storage.DatabaseEntries.entry;
import org.elasticlib.node.manager.storage.StorageManager;
/**
* Stores and retrieves revisions inside a repository.
*/
class RevisionManager {
private static final String REVISION = "revision";
private final StorageManager storageManager;
private final Database database;
/**
* Constructor.
*
* @param storageManager Underlying storage manager.
*/
public RevisionManager(StorageManager storageManager) {
this.storageManager = storageManager;
this.database = storageManager.openDatabase(REVISION);
}
/**
* Adds a new revision.
*
* @param revision Revision to add.
* @return Actual result.
*/
public CommandResult put(Revision revision) {
Optional<RevisionTree> existing = load(revision.getContent(), LockMode.RMW);
RevisionTree updated;
if (!existing.isPresent()) {
if (!revision.getParents().isEmpty()) {
throw new ConflictException();
}
updated = new RevisionTreeBuilder()
.add(revision)
.build();
} else {
if (existing.get().contains(revision.getRevision())) {
updated = existing.get();
} else if (!existing.get().getHead().equals(revision.getParents())) {
throw new ConflictException();
} else {
updated = existing.get()
.add(revision)
.merge();
}
}
return save(existing, updated);
}
/**
* Adds a new revision tree.
*
* @param info Revision tree to add.
* @return Actual result.
*/
public CommandResult put(RevisionTree tree) {
Optional<RevisionTree> existing = load(tree.getContent(), LockMode.RMW);
RevisionTree updated;
if (!existing.isPresent()) {
updated = tree;
} else {
updated = existing.get()
.add(tree)
.merge();
}
return save(existing, updated);
}
/**
* Marks an existing content as deleted.
*
* @param hash Content hash.
* @param head Expected associated head, for optimistic concurrency purpose.
* @return Actual result.
*/
public CommandResult delete(Hash hash, SortedSet<Hash> head) {
Optional<RevisionTree> existing = load(hash, LockMode.RMW);
if (!existing.isPresent()) {
throw new UnknownContentException();
}
if (!existing.get().getHead().equals(head)) {
throw new ConflictException();
}
RevisionTree updated;
if (existing.get().isDeleted()) {
updated = existing.get();
} else {
updated = existing.get().add(new RevisionBuilder()
.withContent(hash)
.withLength(existing.get().getLength())
.withParents(existing.get().getHead())
.withDeleted(true)
.computeRevisionAndBuild());
}
return save(existing, updated);
}
/**
* Loads revision tree of a content.
*
* @param hash Content hash.
* @return Associated revision tree, if any.
*/
public Optional<RevisionTree> get(Hash hash) {
return load(hash, LockMode.DEFAULT);
}
private Optional<RevisionTree> load(Hash hash, LockMode lockMode) {
DatabaseEntry data = new DatabaseEntry();
OperationStatus status = database.get(storageManager.currentTransaction(),
entry(hash),
data,
lockMode);
if (status == OperationStatus.NOTFOUND) {
return Optional.empty();
}
return Optional.of(asMappable(data, RevisionTree.class));
}
private CommandResult save(Optional<RevisionTree> before, RevisionTree after) {
Optional<Operation> operation = operation(before, after);
if (!operation.isPresent()) {
return CommandResult.noOp(after.getContent(), after.getHead());
}
if (!after.getUnknownParents().isEmpty()) {
throw new UnknownRevisionException();
}
database.put(storageManager.currentTransaction(), entry(after.getContent()), entry(after));
return CommandResult.of(operation.get(), after.getContent(), after.getHead());
}
private static Optional<Operation> operation(Optional<RevisionTree> before, RevisionTree after) {
boolean beforeIsDeleted = !before.isPresent() || before.get().isDeleted();
boolean afterIsDeleted = after.isDeleted();
if (before.isPresent() && before.get().equals(after)) {
return Optional.empty();
}
if (beforeIsDeleted && !afterIsDeleted) {
return Optional.of(Operation.CREATE);
}
if (!beforeIsDeleted && afterIsDeleted) {
return Optional.of(Operation.DELETE);
}
return Optional.of(Operation.UPDATE);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-devopsguru/src/main/java/com/amazonaws/services/devopsguru/model/transform/ListEventsFiltersJsonUnmarshaller.java | 4032 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.devopsguru.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.devopsguru.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ListEventsFilters JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListEventsFiltersJsonUnmarshaller implements Unmarshaller<ListEventsFilters, JsonUnmarshallerContext> {
public ListEventsFilters unmarshall(JsonUnmarshallerContext context) throws Exception {
ListEventsFilters listEventsFilters = new ListEventsFilters();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("InsightId", targetDepth)) {
context.nextToken();
listEventsFilters.setInsightId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("EventTimeRange", targetDepth)) {
context.nextToken();
listEventsFilters.setEventTimeRange(EventTimeRangeJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("EventClass", targetDepth)) {
context.nextToken();
listEventsFilters.setEventClass(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("EventSource", targetDepth)) {
context.nextToken();
listEventsFilters.setEventSource(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DataSource", targetDepth)) {
context.nextToken();
listEventsFilters.setDataSource(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ResourceCollection", targetDepth)) {
context.nextToken();
listEventsFilters.setResourceCollection(ResourceCollectionJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return listEventsFilters;
}
private static ListEventsFiltersJsonUnmarshaller instance;
public static ListEventsFiltersJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ListEventsFiltersJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-connectwisdom/src/main/java/com/amazonaws/services/connectwisdom/model/GetRecommendationsRequest.java | 11036 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.connectwisdom.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/wisdom-2020-10-19/GetRecommendations" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetRecommendationsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The identifier of the Wisdom assistant. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*/
private String assistantId;
/**
* <p>
* The maximum number of results to return per page.
* </p>
*/
private Integer maxResults;
/**
* <p>
* The identifier of the session. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*/
private String sessionId;
/**
* <p>
* The duration (in seconds) for which the call waits for a recommendation to be made available before returning. If
* a recommendation is available, the call returns sooner than <code>WaitTimeSeconds</code>. If no messages are
* available and the wait time expires, the call returns successfully with an empty list.
* </p>
*/
private Integer waitTimeSeconds;
/**
* <p>
* The identifier of the Wisdom assistant. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*
* @param assistantId
* The identifier of the Wisdom assistant. Can be either the ID or the ARN. URLs cannot contain the ARN.
*/
public void setAssistantId(String assistantId) {
this.assistantId = assistantId;
}
/**
* <p>
* The identifier of the Wisdom assistant. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*
* @return The identifier of the Wisdom assistant. Can be either the ID or the ARN. URLs cannot contain the ARN.
*/
public String getAssistantId() {
return this.assistantId;
}
/**
* <p>
* The identifier of the Wisdom assistant. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*
* @param assistantId
* The identifier of the Wisdom assistant. Can be either the ID or the ARN. URLs cannot contain the ARN.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRecommendationsRequest withAssistantId(String assistantId) {
setAssistantId(assistantId);
return this;
}
/**
* <p>
* The maximum number of results to return per page.
* </p>
*
* @param maxResults
* The maximum number of results to return per page.
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* The maximum number of results to return per page.
* </p>
*
* @return The maximum number of results to return per page.
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* <p>
* The maximum number of results to return per page.
* </p>
*
* @param maxResults
* The maximum number of results to return per page.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRecommendationsRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* <p>
* The identifier of the session. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*
* @param sessionId
* The identifier of the session. Can be either the ID or the ARN. URLs cannot contain the ARN.
*/
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
/**
* <p>
* The identifier of the session. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*
* @return The identifier of the session. Can be either the ID or the ARN. URLs cannot contain the ARN.
*/
public String getSessionId() {
return this.sessionId;
}
/**
* <p>
* The identifier of the session. Can be either the ID or the ARN. URLs cannot contain the ARN.
* </p>
*
* @param sessionId
* The identifier of the session. Can be either the ID or the ARN. URLs cannot contain the ARN.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRecommendationsRequest withSessionId(String sessionId) {
setSessionId(sessionId);
return this;
}
/**
* <p>
* The duration (in seconds) for which the call waits for a recommendation to be made available before returning. If
* a recommendation is available, the call returns sooner than <code>WaitTimeSeconds</code>. If no messages are
* available and the wait time expires, the call returns successfully with an empty list.
* </p>
*
* @param waitTimeSeconds
* The duration (in seconds) for which the call waits for a recommendation to be made available before
* returning. If a recommendation is available, the call returns sooner than <code>WaitTimeSeconds</code>. If
* no messages are available and the wait time expires, the call returns successfully with an empty list.
*/
public void setWaitTimeSeconds(Integer waitTimeSeconds) {
this.waitTimeSeconds = waitTimeSeconds;
}
/**
* <p>
* The duration (in seconds) for which the call waits for a recommendation to be made available before returning. If
* a recommendation is available, the call returns sooner than <code>WaitTimeSeconds</code>. If no messages are
* available and the wait time expires, the call returns successfully with an empty list.
* </p>
*
* @return The duration (in seconds) for which the call waits for a recommendation to be made available before
* returning. If a recommendation is available, the call returns sooner than <code>WaitTimeSeconds</code>.
* If no messages are available and the wait time expires, the call returns successfully with an empty list.
*/
public Integer getWaitTimeSeconds() {
return this.waitTimeSeconds;
}
/**
* <p>
* The duration (in seconds) for which the call waits for a recommendation to be made available before returning. If
* a recommendation is available, the call returns sooner than <code>WaitTimeSeconds</code>. If no messages are
* available and the wait time expires, the call returns successfully with an empty list.
* </p>
*
* @param waitTimeSeconds
* The duration (in seconds) for which the call waits for a recommendation to be made available before
* returning. If a recommendation is available, the call returns sooner than <code>WaitTimeSeconds</code>. If
* no messages are available and the wait time expires, the call returns successfully with an empty list.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetRecommendationsRequest withWaitTimeSeconds(Integer waitTimeSeconds) {
setWaitTimeSeconds(waitTimeSeconds);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAssistantId() != null)
sb.append("AssistantId: ").append(getAssistantId()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults()).append(",");
if (getSessionId() != null)
sb.append("SessionId: ").append(getSessionId()).append(",");
if (getWaitTimeSeconds() != null)
sb.append("WaitTimeSeconds: ").append(getWaitTimeSeconds());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetRecommendationsRequest == false)
return false;
GetRecommendationsRequest other = (GetRecommendationsRequest) obj;
if (other.getAssistantId() == null ^ this.getAssistantId() == null)
return false;
if (other.getAssistantId() != null && other.getAssistantId().equals(this.getAssistantId()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
if (other.getSessionId() == null ^ this.getSessionId() == null)
return false;
if (other.getSessionId() != null && other.getSessionId().equals(this.getSessionId()) == false)
return false;
if (other.getWaitTimeSeconds() == null ^ this.getWaitTimeSeconds() == null)
return false;
if (other.getWaitTimeSeconds() != null && other.getWaitTimeSeconds().equals(this.getWaitTimeSeconds()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAssistantId() == null) ? 0 : getAssistantId().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
hashCode = prime * hashCode + ((getSessionId() == null) ? 0 : getSessionId().hashCode());
hashCode = prime * hashCode + ((getWaitTimeSeconds() == null) ? 0 : getWaitTimeSeconds().hashCode());
return hashCode;
}
@Override
public GetRecommendationsRequest clone() {
return (GetRecommendationsRequest) super.clone();
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/transform/DescribeTasksRequestProtocolMarshaller.java | 2674 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ecs.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ecs.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeTasksRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeTasksRequestProtocolMarshaller implements Marshaller<Request<DescribeTasksRequest>, DescribeTasksRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AmazonEC2ContainerServiceV20141113.DescribeTasks").serviceName("AmazonECS").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DescribeTasksRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DescribeTasksRequest> marshall(DescribeTasksRequest describeTasksRequest) {
if (describeTasksRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DescribeTasksRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
describeTasksRequest);
protocolMarshaller.startMarshalling();
DescribeTasksRequestMarshaller.getInstance().marshall(describeTasksRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
pwendell/Avro | lang/java/src/test/java/org/apache/avro/ipc/stats/StatsPluginOverhead.java | 3425 | /**
* 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.avro.ipc.stats;
import java.io.IOException;
import java.net.URL;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRequestor;
import org.apache.avro.generic.GenericResponder;
import org.apache.avro.ipc.AvroRemoteException;
import org.apache.avro.ipc.HttpServer;
import org.apache.avro.ipc.HttpTransceiver;
import org.apache.avro.ipc.Responder;
import org.apache.avro.ipc.Transceiver;
/**
* Naively measures overhead of using the stats plugin.
*
* The API used is the generic one.
* The protocol is the "null" protocol: null is sent
* and returned.
*/
public class StatsPluginOverhead {
/** Number of RPCs per iteration. */
private static final int COUNT = 100000;
private static final Protocol NULL_PROTOCOL = Protocol.parse(
"{\"protocol\": \"null\", "
+ "\"messages\": { \"null\": {"
+ " \"request\": [], "
+ " \"response\": \"null\"} } }");
private static class IdentityResponder extends GenericResponder {
public IdentityResponder(Protocol local) {
super(local);
}
@Override
public Object respond(Message message, Object request)
throws AvroRemoteException {
return request;
}
}
public static void main(String[] args) throws Exception {
double with = sendRpcs(true)/1000000000.0;
double without = sendRpcs(false)/1000000000.0;
System.out.println(String.format(
"Overhead: %f%%. RPC/s: %f (with) vs %f (without). " +
"RPC time (ms): %f vs %f",
100*(with - without)/(without),
COUNT/with,
COUNT/without,
1000*with/COUNT,
1000*without/COUNT));
}
/** Sends RPCs and returns nanos elapsed. */
private static long sendRpcs(boolean withPlugin) throws IOException {
HttpServer server = createServer(withPlugin);
Transceiver t =
new HttpTransceiver(new URL("http://127.0.0.1:"+server.getPort()+"/"));
GenericRequestor requestor = new GenericRequestor(NULL_PROTOCOL, t);
long now = System.nanoTime();
for (int i = 0; i < COUNT; ++i) {
requestor.request("null", null);
}
long elapsed = System.nanoTime() - now;
t.close();
server.close();
return elapsed;
}
/** Starts an Avro server. */
private static HttpServer createServer(boolean withPlugin)
throws IOException {
Responder r = new IdentityResponder(NULL_PROTOCOL);
if (withPlugin) {
r.addRPCPlugin(new StatsPlugin());
}
// Start Avro server
HttpServer server = new HttpServer(r, 0);
server.start();
return server;
}
}
| apache-2.0 |
ow2-chameleon/fuchsia | bases/knx/calimero/src/main/java/tuwien/auto/calimero/mgmt/EventListeners.java | 3547 | /*
* #%L
* OW2 Chameleon - Fuchsia Framework
* %%
* Copyright (C) 2009 - 2014 OW2 Chameleon
* %%
* 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%
*/
/*
Calimero - A library for KNX network access
Copyright (C) 2006-2008 B. Malinowsky
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or at your option any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under terms
of your choice, provided that you also meet, for each linked independent
module, the terms and conditions of the license of that module. An
independent module is a module which is not derived from or based on
this library. If you modify this library, you may extend this exception
to your version of the library, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from your
version.
*/
package tuwien.auto.calimero.mgmt;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import tuwien.auto.calimero.log.LogService;
/**
* Internal container for keeping event listeners.
* <p>
*
* @author B. Malinowsky
*/
final class EventListeners
{
private final List listeners = new ArrayList();
private List listenersCopy = new ArrayList();
private final LogService logger;
EventListeners(LogService logger)
{
this.logger = logger;
}
void add(EventListener l)
{
if (l == null)
return;
synchronized (listeners) {
if (!listeners.contains(l)) {
listeners.add(l);
listenersCopy = new ArrayList(listeners);
}
else
logger.warn("event listener already registered");
}
}
void remove(EventListener l)
{
synchronized (listeners) {
if (listeners.remove(l))
listenersCopy = new ArrayList(listeners);
}
}
Iterator iterator()
{
return listenersCopy.iterator();
}
}
| apache-2.0 |
snailee/QGallery | src/com/example/android/displayingbitmaps/util/ImageWorker.java | 16483 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.example.android.displayingbitmaps.util;
import java.lang.ref.WeakReference;
import kr.qgallery.BuildConfig;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.ImageView;
import com.example.android.common.logger.Log;
/**
* This class wraps up completing some arbitrary long running work when loading a bitmap to an
* ImageView. It handles things like using a memory and disk cache, running the work in a background
* thread and setting a placeholder image.
*/
public abstract class ImageWorker {
private static final String TAG = "ImageWorker";
private static final int FADE_IN_TIME = 200;
private ImageCache mImageCache;
private ImageCache.ImageCacheParams mImageCacheParams;
private Bitmap mLoadingBitmap;
private boolean mFadeInBitmap = true;
private boolean mExitTasksEarly = false;
protected boolean mPauseWork = false;
private final Object mPauseWorkLock = new Object();
protected Resources mResources;
private static final int MESSAGE_CLEAR = 0;
private static final int MESSAGE_INIT_DISK_CACHE = 1;
private static final int MESSAGE_FLUSH = 2;
private static final int MESSAGE_CLOSE = 3;
protected ImageWorker(Context context) {
mResources = context.getResources();
}
/**
* Load an image specified by the data parameter into an ImageView (override
* {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and disk
* cache will be used if an {@link ImageCache} has been added using
* {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCache.ImageCacheParams)}
* . If the image is found in the memory cache, it is set immediately, otherwise an
* {@link AsyncTask} will be created to asynchronously load the bitmap.
*
* @param data The URL of the image to download.
* @param imageView The ImageView to bind the downloaded image to.
*/
public void loadImage(Object data, ImageView imageView) {
if (data == null) {
return;
}
BitmapDrawable value = null;
if (mImageCache != null) {
value = mImageCache.getBitmapFromMemCache(String.valueOf(data));
}
if (value != null) {
// Bitmap found in memory cache
imageView.setImageDrawable(value);
} else if (cancelPotentialWork(data, imageView)) {
// BEGIN_INCLUDE(execute_background_task)
final BitmapWorkerTask task = new BitmapWorkerTask(data, imageView);
final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap, task);
imageView.setImageDrawable(asyncDrawable);
// NOTE: This uses a custom version of AsyncTask that has been pulled from the
// framework and slightly modified. Refer to the docs at the top of the class
// for more info on what was changed.
task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR);
// END_INCLUDE(execute_background_task)
}
}
/**
* Set placeholder bitmap that shows when the the background thread is running.
*
* @param bitmap
*/
public void setLoadingImage(Bitmap bitmap) {
mLoadingBitmap = bitmap;
}
/**
* Set placeholder bitmap that shows when the the background thread is running.
*
* @param resId
*/
public void setLoadingImage(int resId) {
mLoadingBitmap = BitmapFactory.decodeResource(mResources, resId);
}
/**
* Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap
* caching.
*
* @param fragmentManager
* @param cacheParams The cache parameters to use for the image cache.
*/
public void addImageCache(FragmentManager fragmentManager, ImageCache.ImageCacheParams cacheParams) {
mImageCacheParams = cacheParams;
mImageCache = ImageCache.getInstance(fragmentManager, mImageCacheParams);
new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE);
}
/**
* Adds an {@link ImageCache} to this {@link ImageWorker} to handle disk and memory bitmap
* caching.
*
* @param activity
* @param diskCacheDirectoryName See
* {@link ImageCache.ImageCacheParams#ImageCacheParams(android.content.Context, String)}.
*/
public void addImageCache(FragmentActivity activity, String diskCacheDirectoryName) {
mImageCacheParams = new ImageCache.ImageCacheParams(activity, diskCacheDirectoryName);
mImageCache = ImageCache.getInstance(activity.getSupportFragmentManager(), mImageCacheParams);
new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE);
}
/**
* If set to true, the image will fade-in once it has been loaded by the background thread.
*/
public void setImageFadeIn(boolean fadeIn) {
mFadeInBitmap = fadeIn;
}
public void setExitTasksEarly(boolean exitTasksEarly) {
mExitTasksEarly = exitTasksEarly;
setPauseWork(false);
}
/**
* Subclasses should override this to define any processing or work that must happen to produce
* the final bitmap. This will be executed in a background thread and be long running. For
* example, you could resize a large bitmap here, or pull down an image from the network.
*
* @param data The data to identify which image to process, as provided by
* {@link ImageWorker#loadImage(Object, android.widget.ImageView)}
* @return The processed bitmap
*/
protected abstract Bitmap processBitmap(Object data);
/**
* @return The {@link ImageCache} object currently being used by this ImageWorker.
*/
protected ImageCache getImageCache() {
return mImageCache;
}
/**
* Cancels any pending work attached to the provided ImageView.
*
* @param imageView
*/
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
final Object bitmapData = bitmapWorkerTask.mData;
Log.d(TAG, "cancelWork - cancelled work for " + bitmapData);
}
}
}
/**
* Returns true if the current work has been canceled or if there was no work in progress on this
* image view. Returns false if the work in progress deals with the same data. The work is not
* stopped in that case.
*/
public static boolean cancelPotentialWork(Object data, ImageView imageView) {
// BEGIN_INCLUDE(cancel_potential_work)
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final Object bitmapData = bitmapWorkerTask.mData;
if (bitmapData == null || !bitmapData.equals(data)) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
Log.d(TAG, "cancelPotentialWork - cancelled work for " + data);
}
} else {
// The same work is already in progress.
return false;
}
}
return true;
// END_INCLUDE(cancel_potential_work)
}
/**
* @param imageView Any imageView
* @return Retrieve the currently active work task (if any) associated with this imageView. null
* if there is no such task.
*/
private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
/**
* The actual AsyncTask that will asynchronously process the image.
*/
private class BitmapWorkerTask extends AsyncTask<Void, Void, BitmapDrawable> {
private Object mData;
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(Object data, ImageView imageView) {
mData = data;
imageViewReference = new WeakReference<ImageView>(imageView);
}
/**
* Background processing.
*/
@Override
protected BitmapDrawable doInBackground(Void... params) {
// BEGIN_INCLUDE(load_bitmap_in_background)
if (BuildConfig.DEBUG) {
Log.d(TAG, "doInBackground - starting work");
}
final String dataString = String.valueOf(mData);
Bitmap bitmap = null;
BitmapDrawable drawable = null;
// Wait here if work is paused and the task is not cancelled
synchronized (mPauseWorkLock) {
while (mPauseWork && !isCancelled()) {
try {
mPauseWorkLock.wait();
} catch (InterruptedException e) {
}
}
}
// If the image cache is available and this task has not been cancelled by another
// thread and the ImageView that was originally bound to this task is still bound back
// to this task and our "exit early" flag is not set then try and fetch the bitmap from
// the cache
if (mImageCache != null && !isCancelled() && getAttachedImageView() != null
&& !mExitTasksEarly) {
bitmap = mImageCache.getBitmapFromDiskCache(dataString);
}
// If the bitmap was not found in the cache and this task has not been cancelled by
// another thread and the ImageView that was originally bound to this task is still
// bound back to this task and our "exit early" flag is not set, then call the main
// process method (as implemented by a subclass)
if (bitmap == null && !isCancelled() && getAttachedImageView() != null && !mExitTasksEarly) {
bitmap = processBitmap(mData);
}
// If the bitmap was processed and the image cache is available, then add the processed
// bitmap to the cache for future use. Note we don't check if the task was cancelled
// here, if it was, and the thread is still running, we may as well add the processed
// bitmap to our cache as it might be used again in the future
if (bitmap != null) {
if (Utils.hasHoneycomb()) {
// Running on Honeycomb or newer, so wrap in a standard BitmapDrawable
drawable = new BitmapDrawable(mResources, bitmap);
} else {
// Running on Gingerbread or older, so wrap in a RecyclingBitmapDrawable
// which will recycle automagically
drawable = new RecyclingBitmapDrawable(mResources, bitmap);
}
if (mImageCache != null) {
mImageCache.addBitmapToCache(dataString, drawable);
}
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "doInBackground - finished work");
}
return drawable;
// END_INCLUDE(load_bitmap_in_background)
}
/**
* Once the image is processed, associates it to the imageView
*/
@Override
protected void onPostExecute(BitmapDrawable value) {
// BEGIN_INCLUDE(complete_background_work)
// if cancel was called on this task or the "exit early" flag is set then we're done
if (isCancelled() || mExitTasksEarly) {
value = null;
}
final ImageView imageView = getAttachedImageView();
if (value != null && imageView != null) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "onPostExecute - setting bitmap");
}
setImageDrawable(imageView, value);
}
// END_INCLUDE(complete_background_work)
}
@Override
protected void onCancelled(BitmapDrawable value) {
super.onCancelled(value);
synchronized (mPauseWorkLock) {
mPauseWorkLock.notifyAll();
}
}
/**
* Returns the ImageView associated with this task as long as the ImageView's task still points
* to this task as well. Returns null otherwise.
*/
private ImageView getAttachedImageView() {
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask) {
return imageView;
}
return null;
}
}
/**
* A custom Drawable that will be attached to the imageView while the work is in progress.
* Contains a reference to the actual worker task, so that it can be stopped if a new binding is
* required, and makes sure that only the last started worker process can bind its result,
* independently of the finish order.
*/
private static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference = new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
/**
* Called when the processing is complete and the final drawable should be set on the ImageView.
*
* @param imageView
* @param drawable
*/
private void setImageDrawable(ImageView imageView, Drawable drawable) {
if (mFadeInBitmap) {
// Transition drawable with a transparent drawable and the final drawable
final TransitionDrawable td =
new TransitionDrawable(new Drawable[] {new ColorDrawable(android.R.color.transparent),
drawable});
// Set background to loading bitmap
imageView.setBackgroundDrawable(new BitmapDrawable(mResources, mLoadingBitmap));
imageView.setImageDrawable(td);
td.startTransition(FADE_IN_TIME);
} else {
imageView.setImageDrawable(drawable);
}
}
/**
* Pause any ongoing background work. This can be used as a temporary measure to improve
* performance. For example background work could be paused when a ListView or GridView is being
* scrolled using a {@link android.widget.AbsListView.OnScrollListener} to keep scrolling smooth.
* <p>
* If work is paused, be sure setPauseWork(false) is called again before your fragment or activity
* is destroyed (for example during {@link android.app.Activity#onPause()}), or there is a risk
* the background thread will never finish.
*/
public void setPauseWork(boolean pauseWork) {
synchronized (mPauseWorkLock) {
mPauseWork = pauseWork;
if (!mPauseWork) {
mPauseWorkLock.notifyAll();
}
}
}
protected class CacheAsyncTask extends AsyncTask<Object, Void, Void> {
@Override
protected Void doInBackground(Object... params) {
switch ((Integer) params[0]) {
case MESSAGE_CLEAR:
clearCacheInternal();
break;
case MESSAGE_INIT_DISK_CACHE:
initDiskCacheInternal();
break;
case MESSAGE_FLUSH:
flushCacheInternal();
break;
case MESSAGE_CLOSE:
closeCacheInternal();
break;
}
return null;
}
}
protected void initDiskCacheInternal() {
if (mImageCache != null) {
mImageCache.initDiskCache();
}
}
protected void clearCacheInternal() {
if (mImageCache != null) {
mImageCache.clearCache();
}
}
protected void flushCacheInternal() {
if (mImageCache != null) {
mImageCache.flush();
}
}
protected void closeCacheInternal() {
if (mImageCache != null) {
mImageCache.close();
mImageCache = null;
}
}
public void clearCache() {
new CacheAsyncTask().execute(MESSAGE_CLEAR);
}
public void flushCache() {
new CacheAsyncTask().execute(MESSAGE_FLUSH);
}
public void closeCache() {
new CacheAsyncTask().execute(MESSAGE_CLOSE);
}
}
| apache-2.0 |
tfisher1226/ARIES | nam/nam-engine/src/main/java/nam/service/src/main/java/AbstractDataUnitManagerMBeanBuilder.java | 2668 | package nam.service.src.main.java;
import java.lang.reflect.Modifier;
import java.util.List;
import nam.model.Module;
import nam.model.Project;
import nam.model.Unit;
import nam.service.ServiceLayerHelper;
import org.aries.util.NameUtil;
import aries.generation.engine.GenerationContext;
import aries.generation.model.AnnotationUtil;
import aries.generation.model.ModelAnnotation;
import aries.generation.model.ModelAttribute;
import aries.generation.model.ModelClass;
import aries.generation.model.ModelInterface;
/**
* Builds a DataUnit Manager {@link ModelClass} object given a {@link Unit} Specification as input;
*
* <h3>Properties</h3>
* The following properties can be used to configure execution of this builder:
* <ul>
* <li>generateJavadoc</li>
* </ul>
*
* <h3>Dependencies</h3>
* Execution of this builder must come after the following builders:
* <ul>
* <li>ProcessClassBuilder</li>
* </ul>
*
* @author tfisher
*/
public abstract class AbstractDataUnitManagerMBeanBuilder extends AbstractDataUnitManagerBuilder {
public AbstractDataUnitManagerMBeanBuilder(GenerationContext context) {
super(context);
}
protected void initializeImportedClasses(ModelInterface modelInterface) throws Exception {
modelInterface.addImportedClass("java.util.Collection");
modelInterface.addImportedClass("java.util.List");
modelInterface.addImportedClass("javax.management.MXBean");
}
protected void initializeInterfaceAnnotations(ModelInterface modelInterface) throws Exception {
List<ModelAnnotation> classAnnotations = modelInterface.getInterfaceAnnotations();
classAnnotations.add(AnnotationUtil.createMXBeanAnnotation());
}
protected void initializeInstanceFields(ModelInterface modelInterface, String suffix) throws Exception {
modelInterface.addInstanceAttribute(createMBeanNameConstant(suffix));
}
protected ModelAttribute createMBeanNameConstant(String suffix) {
Project project = context.getProject();
String domain = project.getDomain();
if (context != null && !context.getPropertyAsBoolean("appendProjectToGroupId"))
domain += "." + project.getName();
//domain = domain.replace("-", ".");
String name = NameUtil.capName(modelUnit.getName());
if (name.endsWith("MBean"))
name = name.replace("MBean", "");
ModelAttribute attribute = new ModelAttribute();
attribute.setModifiers(Modifier.PUBLIC + Modifier.FINAL + Modifier.STATIC);
attribute.setClassName(String.class.getName());
attribute.setName("MBEAN_NAME");
attribute.setDefault("\""+domain+"."+suffix+":name="+name+"\"");
attribute.setGenerateGetter(false);
attribute.setGenerateSetter(false);
return attribute;
}
}
| apache-2.0 |
raisercostin/lius4compass | src/main/java/lius/index/openoffice/OpenOfficeEntityResolver.java | 1382 | package lius.index.openoffice;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.StringReader;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
/**
* @author Rida Benjelloun (ridabenjelloun@gmail.com)
*/
public class OpenOfficeEntityResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) {
if (systemId.endsWith(".dtd")) {
StringReader stringInput = new StringReader(" ");
return new InputSource(stringInput);
} else {
return null;
}
}
}
| apache-2.0 |
andrenmaia/batfish | projects/batfish/src/batfish/z3/node/DeclareVarExpr.java | 591 | package batfish.z3.node;
import java.util.ArrayList;
import java.util.List;
public class DeclareVarExpr extends Statement implements ComplexExpr {
private List<Expr> _subExpressions;
public DeclareVarExpr(String name, int size) {
_subExpressions = new ArrayList<Expr>();
_subExpressions.add(new IdExpr("declare-var"));
_subExpressions.add(new IdExpr(name));
_subExpressions.add(new BitVecExpr(size));
_printer = new CollapsedComplexExprPrinter(this);
}
@Override
public List<Expr> getSubExpressions() {
return _subExpressions;
}
}
| apache-2.0 |