repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lfreneda/cepdb
api/v1/72921365.jsonp.js
168
jsonp({"cep":"72921365","logradouro":"Quadra Quadra 37A","bairro":"Jardim Am\u00e9rica I","cidade":"\u00c1guas Lindas de Goi\u00e1s","uf":"GO","estado":"Goi\u00e1s"});
cc0-1.0
lfreneda/cepdb
api/v1/08717460.jsonp.js
150
jsonp({"cep":"08717460","logradouro":"Rua Francisco Urizzi","bairro":"Mogi Moderno","cidade":"Mogi das Cruzes","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
jonnybarnes/jonnybarnes.uk
app/Http/Controllers/LikesController.php
583
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\Like; use Illuminate\View\View; class LikesController extends Controller { /** * Show the latest likes. * * @return View */ public function index(): View { $likes = Like::latest()->paginate(20); return view('likes.index', compact('likes')); } /** * Show a single like. * * @param Like $like * @return View */ public function show(Like $like): View { return view('likes.show', compact('like')); } }
cc0-1.0
lfreneda/cepdb
api/v1/40349645.jsonp.js
128
jsonp({"cep":"40349645","logradouro":"Vila Carmelita","bairro":"Alto do Peru","cidade":"Salvador","uf":"BA","estado":"Bahia"});
cc0-1.0
lfreneda/cepdb
api/v1/59626390.jsonp.js
161
jsonp({"cep":"59626390","logradouro":"Rua Jo\u00e3o Alves Cavalcante","bairro":"Rinc\u00e3o","cidade":"Mossor\u00f3","uf":"RN","estado":"Rio Grande do Norte"});
cc0-1.0
lfreneda/cepdb
api/v1/13181783.jsonp.js
178
jsonp({"cep":"13181783","logradouro":"Pra\u00e7a Vitto Franciscatto","bairro":"Parque Bandeirantes I (Nova Veneza)","cidade":"Sumar\u00e9","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/26042720.jsonp.js
155
jsonp({"cep":"26042720","logradouro":"Rua Sargento Pac\u00edfico","bairro":"Santa Rita","cidade":"Nova Igua\u00e7u","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
muten84/luigibifulco.it
www.luigibifulco.it/blog/site/snippets/bootstrap-header.php
706
<!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('<?php echo url('assets/img/home-bg.jpg') ?>')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="site-heading"> <h1><?php echo html($site->title()) ?></h1> <hr class="small"> <span class="subheading"><?php echo html($site->description()) ?></span> </div> </div> </div> </div> </header>
cc0-1.0
lfreneda/cepdb
api/v1/59022650.jsonp.js
160
jsonp({"cep":"59022650","logradouro":"Pra\u00e7a Engenheiro Abel de Menezes Lira","bairro":"Tirol","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
cc0-1.0
lfreneda/cepdb
api/v1/13083110.jsonp.js
168
jsonp({"cep":"13083110","logradouro":"Rua Gustavo Rodrigues D\u00f3ria","bairro":"Cidade Universit\u00e1ria","cidade":"Campinas","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/23065370.jsonp.js
148
jsonp({"cep":"23065370","logradouro":"Rua Trinta e Seis","bairro":"Paci\u00eancia","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
department-of-veterans-affairs/vets-website
src/applications/personalization/dashboard/utils/mocks/ERROR_400.js
271
export default { errors: [ { title: 'Bad Request', detail: 'Received a bad request response from the upstream server', code: 'EVSS400', source: 'EVSS::DisabilityCompensationForm::Service', status: '400', meta: {}, }, ], };
cc0-1.0
tarrow/wikidata-analysis
java/analyzer/src/test/java/org/wikidata/analyzer/Processor/ReferenceProcessorTest.java
3806
package test.java.org.wikidata.analyzer.Processor; import junit.framework.TestCase; import main.java.org.wikidata.analyzer.Processor.ReferenceProcessor; import org.wikidata.wdtk.datamodel.helpers.*; import org.wikidata.wdtk.datamodel.implementation.DataObjectFactoryImpl; import org.wikidata.wdtk.datamodel.implementation.ItemIdValueImpl; import org.wikidata.wdtk.datamodel.implementation.PropertyIdValueImpl; import org.wikidata.wdtk.datamodel.interfaces.ItemDocument; import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue; import java.util.HashMap; import java.util.Map; /** * @author Addshore */ public class ReferenceProcessorTest extends TestCase { private void assertCounter( Map<String, Long> counters, String counter, int expected ) { assertTrue( "Assert counter name exists '" + counter + "'", counters.containsKey( counter ) ); assertEquals( "Assert counter '" + counter + "'value correct", (long)expected, (long)counters.get( counter ) ); } public void testProcessItemDocument() throws Exception { Map<String, Long> counters = new HashMap<>(); ReferenceProcessor processor = new ReferenceProcessor(counters); ItemIdValue id = ItemIdValueImpl.create("Q42", "foo"); ItemDocument doc = ItemDocumentBuilder.forItemId(id) .withStatement( StatementBuilder .forSubjectAndProperty(id, PropertyIdValueImpl.create("P1", "bar")) .withReference(ReferenceBuilder.newInstance().withNoValue(PropertyIdValueImpl.create("P143", "Foo")).build()) .withReference(ReferenceBuilder.newInstance().withSomeValue(PropertyIdValueImpl.create("P99", "Foo")).build()) .withReference(ReferenceBuilder.newInstance().withPropertyValue( PropertyIdValueImpl.create("P2", "Foo"), new DataObjectFactoryImpl().getStringValue("") ).build()) .build() ) .withStatement( StatementBuilder .forSubjectAndProperty(id, PropertyIdValueImpl.create("P1", "bar")) .withReference( ReferenceBuilder.newInstance() .withPropertyValue( PropertyIdValueImpl.create("P55", "Foo"), new DataObjectFactoryImpl().getStringValue("") ) .withNoValue(PropertyIdValueImpl.create("P66", "Foo")) .build()) .build() ) .withStatement( StatementBuilder .forSubjectAndProperty(id, PropertyIdValueImpl.create("P100", "foo")) .build() ) .build(); processor.processItemDocument( doc ); this.assertCounter(counters, "references", 4); this.assertCounter(counters, "statements.referenced", 2 ); this.assertCounter(counters, "statements.unreferenced", 1 ); this.assertCounter(counters, "references.snaks", 5 ); this.assertCounter(counters, "references.snaks.prop.P143", 1 ); this.assertCounter(counters, "references.snaks.type.value", 2 ); this.assertCounter(counters, "references.snaks.type.somevalue", 1 ); this.assertCounter(counters, "references.snaks.type.novalue", 2 ); } }
cc0-1.0
lfreneda/cepdb
api/v1/26423280.jsonp.js
156
jsonp({"cep":"26423280","logradouro":"Avenida Senhor do Bonfim","bairro":"Cidade Senhor do Bonfim","cidade":"Japeri","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend
tests/unit/dataactcore/test_job_queue.py
7292
from collections import OrderedDict import csv import os from unittest.mock import Mock from celery.exceptions import MaxRetriesExceededError, Retry import pytest from dataactcore.interfaces.interfaceHolder import InterfaceHolder from dataactcore.models.jobModels import FileType, JobStatus, JobType from dataactcore.utils import fileE, jobQueue from tests.unit.dataactcore.factories.staging import ( AwardFinancialAssistanceFactory, AwardProcurementFactory) from tests.unit.dataactcore.factories.job import JobFactory def read_file_rows(file_path): assert os.path.isfile(file_path) with open(file_path) as f: return [row for row in csv.reader(f)] def test_generate_f_file(monkeypatch, mock_broker_config_paths): """A CSV with fields in the right order should be written to the file system""" fileF_mock = Mock() monkeypatch.setattr(jobQueue, 'fileF', fileF_mock) fileF_mock.generateFRows.return_value = [ dict(key4='a', key11='b'), dict(key4='c', key11='d') ] fileF_mock.mappings = OrderedDict( [('key4', 'mapping4'), ('key11', 'mapping11')]) file_path = str(mock_broker_config_paths['broker_files'].join('uniq1')) expected = [['key4', 'key11'], ['a', 'b'], ['c', 'd']] jobQueue.generate_f_file(1, 1, Mock(), 'uniq1', 'uniq1', is_local=True) assert read_file_rows(file_path) == expected # re-order fileF_mock.mappings = OrderedDict( [('key11', 'mapping11'), ('key4', 'mapping4')]) file_path = str(mock_broker_config_paths['broker_files'].join('uniq2')) expected = [['key11', 'key4'], ['b', 'a'], ['d', 'c']] jobQueue.generate_f_file(1, 1, Mock(), 'uniq2', 'uniq2', is_local=True) assert read_file_rows(file_path) == expected def test_generate_e_file_query(monkeypatch, mock_broker_config_paths, database): """Verify that generate_e_file makes an appropriate query (matching both D1 and D2 entries)""" # Generate several file D1 entries, largely with the same submission_id, # and with two overlapping DUNS. Generate several D2 entries with the same # submission_id as well model = AwardProcurementFactory() aps = [AwardProcurementFactory(submission_id=model.submission_id) for i in range(4)] afas = [AwardFinancialAssistanceFactory(submission_id=model.submission_id) for i in range(5)] same_duns = AwardProcurementFactory( submission_id=model.submission_id, awardee_or_recipient_uniqu=model.awardee_or_recipient_uniqu) unrelated = AwardProcurementFactory(submission_id=model.submission_id + 1) database.session.add_all(aps + afas + [model, same_duns, unrelated]) monkeypatch.setattr(jobQueue.fileE, 'retrieveRows', Mock(return_value=[])) # Mock out the interface holder class; rather nasty, as we want to _keep_ # the database session handler interface_class = Mock() interface_class.return_value.jobDb.session = database.session jobQueue.generate_e_file( model.submission_id, 1, interface_class, 'uniq', 'uniq', is_local=True) # [0][0] gives us the first, non-keyword args call_args = jobQueue.fileE.retrieveRows.call_args[0][0] expected = [ap.awardee_or_recipient_uniqu for ap in aps] expected.append(model.awardee_or_recipient_uniqu) expected.extend(afa.awardee_or_recipient_uniqu for afa in afas) assert list(sorted(call_args)) == list(sorted(expected)) def test_generate_e_file_csv(monkeypatch, mock_broker_config_paths, database): """Verify that an appropriate CSV is written, based on fileE.Row's structure""" # Create an award so that we have _a_ duns ap = AwardProcurementFactory() database.session.add(ap) database.session.commit() monkeypatch.setattr(jobQueue.fileE, 'retrieveRows', Mock()) jobQueue.fileE.retrieveRows.return_value = [ fileE.Row('a', 'b', 'c', '1a', '1b', '2a', '2b', '3a', '3b', '4a', '4b', '5a', '5b'), fileE.Row('A', 'B', 'C', '1A', '1B', '2A', '2B', '3A', '3B', '4A', '4B', '5A', '5B') ] interface_class = Mock() interface_class.return_value.jobDb.session = database.session jobQueue.generate_e_file( ap.submission_id, 1, interface_class, 'uniq', 'uniq', is_local=True) file_path = str(mock_broker_config_paths['broker_files'].join('uniq')) expected = [ ['AwardeeOrRecipientUniqueIdentifier', 'UltimateParentUniqueIdentifier', 'UltimateParentLegalEntityName', 'HighCompOfficer1FullName', 'HighCompOfficer1Amount', 'HighCompOfficer2FullName', 'HighCompOfficer2Amount', 'HighCompOfficer3FullName', 'HighCompOfficer3Amount', 'HighCompOfficer4FullName', 'HighCompOfficer4Amount', 'HighCompOfficer5FullName', 'HighCompOfficer5Amount'], ['a', 'b', 'c', '1a', '1b', '2a', '2b', '3a', '3b', '4a', '4b', '5a', '5b'], ['A', 'B', 'C', '1A', '1B', '2A', '2B', '3A', '3B', '4A', '4B', '5A', '5B'] ] assert read_file_rows(file_path) == expected def test_job_context_success(database, job_constants): """When a job successfully runs, it should be marked as "finished" """ sess = database.session job = JobFactory( job_status=sess.query(JobStatus).filter_by(name='running').one(), job_type=sess.query(JobType).filter_by(name='validation').one(), file_type=sess.query(FileType).filter_by(name='sub_award').one(), ) sess.add(job) sess.commit() with jobQueue.job_context(Mock(), InterfaceHolder, job.job_id): pass # i.e. be successful sess.refresh(job) assert job.job_status.name == 'finished' def test_job_context_fail(database, job_constants): """When a job raises an exception and has no retries left, it should be marked as failed""" sess = database.session job = JobFactory( job_status=sess.query(JobStatus).filter_by(name='running').one(), job_type=sess.query(JobType).filter_by(name='validation').one(), file_type=sess.query(FileType).filter_by(name='sub_award').one(), ) sess.add(job) sess.commit() task = Mock() task.retry.return_value = MaxRetriesExceededError() with jobQueue.job_context(task, InterfaceHolder, job.job_id): raise Exception('This failed!') sess.refresh(job) assert job.job_status.name == 'failed' assert job.error_message == 'This failed!' def test_job_context_retry(database, job_constants): """When a job raises an exception but can still retry, we should expect a particular exception (which signifies to celery that it should retry)""" sess = database.session job = JobFactory( job_status=sess.query(JobStatus).filter_by(name='running').one(), job_type=sess.query(JobType).filter_by(name='validation').one(), file_type=sess.query(FileType).filter_by(name='sub_award').one(), ) sess.add(job) sess.commit() task = Mock() task.retry.return_value = Retry() with pytest.raises(Retry): with jobQueue.job_context(task, InterfaceHolder, job.job_id): raise Exception('This failed!') sess.refresh(job) assert job.job_status.name == 'running' # still going
cc0-1.0
lfreneda/cepdb
api/v1/12246330.jsonp.js
174
jsonp({"cep":"12246330","logradouro":"Rua das Arraias","bairro":"Parque Residencial Aquarius","cidade":"S\u00e3o Jos\u00e9 dos Campos","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/24476445.jsonp.js
161
jsonp({"cep":"24476445","logradouro":"Rua Deputado Carlos Vilela","bairro":"Ita\u00fana","cidade":"S\u00e3o Gon\u00e7alo","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/81720280.jsonp.js
166
jsonp({"cep":"81720280","logradouro":"Rua Desembargador Ant\u00f4nio de Paula","bairro":"Alto Boqueir\u00e3o","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/50620660.jsonp.js
138
jsonp({"cep":"50620660","logradouro":"Rua Jornalista Luiz Teixeira","bairro":"Torre","cidade":"Recife","uf":"PE","estado":"Pernambuco"});
cc0-1.0
lfreneda/cepdb
api/v1/76803806.jsonp.js
159
jsonp({"cep":"76803806","logradouro":"Avenida dos Imigrantes","bairro":"S\u00e3o Jo\u00e3o Bosco","cidade":"Porto Velho","uf":"RO","estado":"Rond\u00f4nia"});
cc0-1.0
lfreneda/cepdb
api/v1/57018860.jsonp.js
150
jsonp({"cep":"57018860","logradouro":"Rua S\u00e3o Jos\u00e9","bairro":"Ch\u00e3 de Bebedouro","cidade":"Macei\u00f3","uf":"AL","estado":"Alagoas"});
cc0-1.0
lfreneda/cepdb
api/v1/03109001.jsonp.js
150
jsonp({"cep":"03109001","logradouro":"Avenida Henry Ford","bairro":"Parque da Mooca","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
hgcummings/DataAccessExamples
DataAccessExamples.Core.Tests/DbDapperTests.cs
1565
using Dapper; using DataAccessExamples.Core.Services.Department; using NUnit.Framework; using System.Linq; namespace DataAccessExamples.Core.Tests { public class DbDapperTests { private TestDatabase testDatabase; [TestFixtureSetUp] public void BeforeAll() { testDatabase = new TestDatabase(); testDatabase.ExecuteScript(InitialiseSchema); } [TestFixtureTearDown] public void AfterAll() { testDatabase.Dispose(); } [Test] public void ListDepartments_ReturnsDepartmentsByCode() { // Arrange using (var connection = testDatabase.CreateConnection()) { connection.Execute("INSERT INTO Department (Code, Name) Values ('d02', 'Second Department')"); connection.Execute("INSERT INTO Department (Code, Name) Values ('d01', 'First Department')"); } // Act var service = new DapperDepartmentService(testDatabase); var result = service.ListDepartments(); // Assert Assert.That(result.Departments.Select(d => d.Name), Is.EqualTo(new[] {"First Department", "Second Department"})); } private const string InitialiseSchema = @"CREATE TABLE Department ( [Code] [nchar](4) NOT NULL, [Name] [nvarchar](40) NOT NULL)"; } }
cc0-1.0
lfreneda/cepdb
api/v1/51350530.jsonp.js
130
jsonp({"cep":"51350530","logradouro":"Rua S\u00e3o Nicolau","bairro":"Ipsep","cidade":"Recife","uf":"PE","estado":"Pernambuco"});
cc0-1.0
lfreneda/cepdb
api/v1/13402015.jsonp.js
142
jsonp({"cep":"13402015","logradouro":"Rua Dois","bairro":"Jardim S\u00e3o Paulo","cidade":"Piracicaba","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/61942490.jsonp.js
152
jsonp({"cep":"61942490","logradouro":"Pra\u00e7a Raimundo Soares Ramos","bairro":"Outra Banda","cidade":"Maranguape","uf":"CE","estado":"Cear\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/31310470.jsonp.js
142
jsonp({"cep":"31310470","logradouro":"Rua Jord\u00e2nia","bairro":"Ouro Preto","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
cc0-1.0
ivayloivanof/AdvancedCSharp
AdvancedCSharp/02.MuldimentionalArraysSetsDictionaries/OtherHomeworks/MultidimensionalArraysSetsDict/PascalTriangle/PascalTriangle.cs
953
using System; using System.Collections.Generic; class PascalTriangle { static void Main() { int height = int.Parse(Console.ReadLine()); int[][] triangle = new int[height][]; triangle[0] = new int[1]; triangle[0][0] = 1; for (int row = 1; row < height; row++) { triangle[row] = new int[row + 1]; triangle[row][0] = 1; for (int col = 1; col <= row - 1; col++) { triangle[row][col] = triangle[row - 1][col - 1] + triangle[row - 1][col]; } triangle[row][row] = 1; } for (int row = 0; row < triangle.Length; row++) { Console.Write("".PadLeft((height - row) * 2)); for (int col = 0; col < triangle[row].Length; col++) { Console.Write("{0,3} ", triangle[row][col]); } Console.WriteLine(); } } }
cc0-1.0
gavineadie/Pachyderm
Frameworks/PXFoundation/Sources/org/pachyderm/foundation/PXBindingXMLValidator.java
2576
// // PXBindingXMLValidator.java // PXFoundation // // Created by King Chung Huang on 4/7/05. // Copyright (c)2005 King Chung Huang. All rights reserved. // package org.pachyderm.foundation; import org.nmc.jdom.Element; import org.pachyderm.apollo.core.CXLocalizedValue; import com.webobjects.eocontrol.EOQualifier; import com.webobjects.foundation.NSArray; import com.webobjects.foundation.NSDictionary; public class PXBindingXMLValidator extends PXBindingValidator { @SuppressWarnings("unused") private EOQualifier _qualifier; @SuppressWarnings("unused") private CXLocalizedValue _errorDescription, _failureReason, _recoverySuggestion; @SuppressWarnings("unused") private NSArray _recoveryOptions; @SuppressWarnings("unused") private Object _recoveryAttempter; @SuppressWarnings("unused") private String _domain; @SuppressWarnings("unused") private int _code; @SuppressWarnings("unused") private NSDictionary _userInfo; public PXBindingXMLValidator(Element validatorElement) { super(); Element elem; String text; elem = validatorElement.getChild("qualifier"); _qualifier = null; elem = validatorElement.getChild("error-description"); _errorDescription = PXComponentXMLDesc._parseElementWithLocalizedChildStrings(elem); elem = validatorElement.getChild("failure-reason"); _failureReason = PXComponentXMLDesc._parseElementWithLocalizedChildStrings(elem); elem = validatorElement.getChild("recovery-suggestion"); _recoverySuggestion = PXComponentXMLDesc._parseElementWithLocalizedChildStrings(elem); elem = validatorElement.getChild("recovery-options"); _recoveryOptions = NSArray.EmptyArray; _domain = validatorElement.getChildTextNormalize("domain"); text = validatorElement.getChildTextNormalize("code"); _code = Integer.parseInt(text); elem = validatorElement.getChild("user-info"); _userInfo = PXComponentXMLDesc._parseDictionaryElement(elem); } } /* Copyright 2005-2006 The New Media Consortium, Copyright 2000-2006 San Francisco Museum of Modern Art 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. */
cc0-1.0
misterbigood/doc-saemf
plugins/post-status-notifier-lite/lib/IfwPsn/Vendor/Zend/Validate/Barcode/Sscc.php
1582
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package IfwPsn_Vendor_Zend_Validate * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Sscc.php 1312339 2015-12-19 13:37:32Z worschtebrot $ */ /** * @see IfwPsn_Vendor_Zend_Validate_Barcode_AdapterAbstract */ require_once IFW_PSN_LIB_ROOT . 'IfwPsn/Vendor/Zend/Validate/Barcode/AdapterAbstract.php'; /** * @category Zend * @package IfwPsn_Vendor_Zend_Validate * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class IfwPsn_Vendor_Zend_Validate_Barcode_Sscc extends IfwPsn_Vendor_Zend_Validate_Barcode_AdapterAbstract { /** * Allowed barcode lengths * @var integer */ protected $_length = 18; /** * Allowed barcode characters * @var string */ protected $_characters = '0123456789'; /** * Checksum function * @var string */ protected $_checksum = '_gtin'; }
cc0-1.0
lfreneda/cepdb
api/v1/53210211.jsonp.js
143
jsonp({"cep":"53210211","logradouro":"Travessa da Mangueira","bairro":"Caixa D'\u00c1gua","cidade":"Olinda","uf":"PE","estado":"Pernambuco"});
cc0-1.0
Wicpar/SinkingSimulatorDevkit
src/com/yourdomain/yourpackage/Main.java
1054
package com.yourdomain.yourpackage; import com.wicpar.wicparbase.utils.plugins.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.fortsoft.pf4j.Extension; import ro.fortsoft.pf4j.Plugin; import ro.fortsoft.pf4j.PluginWrapper; /** * Created by Frederic on 25/09/2015 at 13:58. */ public class Main extends Plugin { /** * Constructor to be used by plugin manager for plugin instantiation. * Your plugins have to provide constructor with this exact signature to * be successfully loaded by manager. * * @param wrapper */ public Main(PluginWrapper wrapper) { super(wrapper); } @Extension public static class testPlugin implements Injector { Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void OnHandlerPreInit() { logger.info("Test PreInit"); } @Override public void OnHandlerPostInit() { } @Override public void OnGamePreInit() { } @Override public void OnGamePostInit() { } @Override public void OnGameFinish() { } } }
cc0-1.0
lfreneda/cepdb
api/v1/66845822.jsonp.js
158
jsonp({"cep":"66845822","logradouro":"Avenida Concei\u00e7\u00e3o","bairro":"Bras\u00edlia (Outeiro)","cidade":"Bel\u00e9m","uf":"PA","estado":"Par\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/12509660.jsonp.js
169
jsonp({"cep":"12509660","logradouro":"Rua Jos\u00e9 Lopes","bairro":"Parque S\u00e3o Francisco III","cidade":"Guaratinguet\u00e1","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/05443001.jsonp.js
142
jsonp({"cep":"05443001","logradouro":"Rua Natingui","bairro":"Vila Madalena","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
biomodels/BIOMD0000000094
setup.py
377
from setuptools import setup, find_packages setup(name='BIOMD0000000094', version=20140916, description='BIOMD0000000094 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/BIOMD0000000094', maintainer='Stanley Gu', maintainer_url='[email protected]', packages=find_packages(), package_data={'': ['*.xml', 'README.md']}, )
cc0-1.0
lfreneda/cepdb
api/v1/69055470.jsonp.js
130
jsonp({"cep":"69055470","logradouro":"Rua 29","bairro":"Parque 10 de Novembro","cidade":"Manaus","uf":"AM","estado":"Amazonas"});
cc0-1.0
lfreneda/cepdb
api/v1/06843420.jsonp.js
158
jsonp({"cep":"06843420","logradouro":"Rua Marqu\u00eas de Itu","bairro":"Vila Engenho Velho","cidade":"Embu das Artes","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/24941370.jsonp.js
161
jsonp({"cep":"24941370","logradouro":"Rua Cinco","bairro":"Ch\u00e1caras de Ino\u00e3 (Ino\u00e3)","cidade":"Maric\u00e1","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/91410001.jsonp.js
164
jsonp({"cep":"91410001","logradouro":"Rua Professor Cristiano Fischer","bairro":"Petr\u00f3polis","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
cc0-1.0
lfreneda/cepdb
api/v1/04658120.jsonp.js
160
jsonp({"cep":"04658120","logradouro":"Rua Amador Louren\u00e7o","bairro":"Vila Constan\u00e7a","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/23900901.jsonp.js
151
jsonp({"cep":"23900901","logradouro":"Pra\u00e7a Nilo Pe\u00e7anha","bairro":"Centro","cidade":"Angra dos Reis","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/13313509.jsonp.js
142
jsonp({"cep":"13313509","logradouro":"Pra\u00e7a Conselho do Povo","bairro":"Progresso","cidade":"Itu","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/86041170.jsonp.js
149
jsonp({"cep":"86041170","logradouro":"Rua Pisa","bairro":"Parque Residencial Jo\u00e3o Piza","cidade":"Londrina","uf":"PR","estado":"Paran\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/04424110.jsonp.js
157
jsonp({"cep":"04424110","logradouro":"Pra\u00e7a Paulo Klenau","bairro":"Cidade J\u00falia","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/75528068.jsonp.js
150
jsonp({"cep":"75528068","logradouro":"Rua JA 5","bairro":"Conjunto Habitacional Juca Arantes","cidade":"Itumbiara","uf":"GO","estado":"Goi\u00e1s"});
cc0-1.0
lfreneda/cepdb
api/v1/14401223.jsonp.js
157
jsonp({"cep":"14401223","logradouro":"Travessa Jovino Redondo","bairro":"Jardim Boa Esperan\u00e7a","cidade":"Franca","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/05890420.jsonp.js
173
jsonp({"cep":"05890420","logradouro":"Travessa Popul\u00f4nia","bairro":"Conjunto Habitacional Pirajussara","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/21842600.jsonp.js
152
jsonp({"cep":"21842600","logradouro":"Rua Vista Alegre","bairro":"Senador Camar\u00e1","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/74633275.jsonp.js
150
jsonp({"cep":"74633275","logradouro":"Avenida An\u00e1polis","bairro":"El\u00edsio Campos","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
cc0-1.0
lfreneda/cepdb
api/v1/94470010.jsonp.js
147
jsonp({"cep":"94470010","logradouro":"Rua Ca\u00e7ula","bairro":"Viam\u00f3polis","cidade":"Viam\u00e3o","uf":"RS","estado":"Rio Grande do Sul"});
cc0-1.0
lfreneda/cepdb
api/v1/13301210.jsonp.js
167
jsonp({"cep":"13301210","logradouro":"Rua Joaquim Galv\u00e3o de Fran\u00e7a Pacheco","bairro":"Jardim Novo Itu","cidade":"Itu","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
armandorvila/paymelater
src/main/java/com/armandorv/paymelater/web/rest/dto/PaymentDTO.java
1794
package com.armandorv.paymelater.web.rest.dto; import org.joda.time.LocalDate; import com.armandorv.paymelater.domain.util.CustomLocalDateSerializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.joda.deser.LocalDateDeserializer; public class PaymentDTO { private String subject; private String description; private String location; private String borrower; private Double amount; @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = CustomLocalDateSerializer.class) private LocalDate deadLine; public PaymentDTO() { } public PaymentDTO(String subject, String description, String location, String borrower, Double amount, LocalDate deadLine) { super(); this.subject = subject; this.description = description; this.location = location; this.borrower = borrower; this.amount = amount; this.deadLine = deadLine; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getBorrower() { return borrower; } public void setBorrower(String borrower) { this.borrower = borrower; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public LocalDate getDeadLine() { return deadLine; } public void setDeadLine(LocalDate deadLine) { this.deadLine = deadLine; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
cc0-1.0
lfreneda/cepdb
api/v1/35680521.jsonp.js
148
jsonp({"cep":"35680521","logradouro":"Rua Carla Cristina Machado","bairro":"Bela Vista","cidade":"Ita\u00fana","uf":"MG","estado":"Minas Gerais"});
cc0-1.0
lfreneda/cepdb
api/v1/15062227.jsonp.js
199
jsonp({"cep":"15062227","logradouro":"Rua Jos\u00e9 Cust\u00f3dio Corr\u00eaa","bairro":"Loteamento Recanto do Lago","cidade":"S\u00e3o Jos\u00e9 do Rio Preto","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/57072160.jsonp.js
160
jsonp({"cep":"57072160","logradouro":"Rua Doutor Carlos Br\u00eada","bairro":"Cidade Universit\u00e1ria","cidade":"Macei\u00f3","uf":"AL","estado":"Alagoas"});
cc0-1.0
lfreneda/cepdb
api/v1/15070130.jsonp.js
172
jsonp({"cep":"15070130","logradouro":"Rua Andr\u00e9 Carrazone","bairro":"Jardim Estrela","cidade":"S\u00e3o Jos\u00e9 do Rio Preto","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/80610162.jsonp.js
134
jsonp({"cep":"80610162","logradouro":"Rua Pedro Nogas","bairro":"Port\u00e3o","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/29167084.jsonp.js
155
jsonp({"cep":"29167084","logradouro":"Avenida Monte Carmelo","bairro":"Colina de Laranjeiras","cidade":"Serra","uf":"ES","estado":"Esp\u00edrito Santo"});
cc0-1.0
lfreneda/cepdb
api/v1/17209361.jsonp.js
161
jsonp({"cep":"17209361","logradouro":"Rua Roberto Pacheco de Almeida Prado","bairro":"Jardim Pires I","cidade":"Ja\u00fa","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/91787762.jsonp.js
134
jsonp({"cep":"91787762","logradouro":"Estrada Dois","bairro":"Lami","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
cc0-1.0
oomlout/oomlout-OOMP
old/OOMPpart_RESE_0805_X_O204_67.py
243
import OOMP newPart = OOMP.oompItem(9442) newPart.addTag("oompType", "RESE") newPart.addTag("oompSize", "0805") newPart.addTag("oompColor", "X") newPart.addTag("oompDesc", "O204") newPart.addTag("oompIndex", "67") OOMP.parts.append(newPart)
cc0-1.0
lfreneda/cepdb
api/v1/13601432.jsonp.js
156
jsonp({"cep":"13601432","logradouro":"Rua Rouxinol","bairro":"Conjunto Habitacional Narciso Gomes","cidade":"Araras","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
iCONEXT/SMI_Travel
src/java/com/smi/travel/datalayer/dao/StockDao.java
1551
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.smi.travel.datalayer.dao; import com.smi.travel.datalayer.entity.Product; import com.smi.travel.datalayer.entity.Stock; import com.smi.travel.datalayer.entity.StockDetail; import com.smi.travel.datalayer.view.entity.OtherTicketView; import com.smi.travel.datalayer.view.entity.StockViewSummary; import java.util.Date; import java.util.List; /** * * @author Surachai */ public interface StockDao { public String InsertStock(Stock ItemLot); public String UpdateStock(Stock ItemLot); public String DeleteStock(Stock ItemLot); public String DeleteStockDetail(String DetailID); public StockViewSummary SearchStockFromFilter(String productId,String payStatus,String itemStatus,Date createDate,Date EffecttiveFrom,Date EffectiveTo); public List<Product> getListStockProduct(); public String getStockId(Stock stock); public Stock getStock(String stockId); public List<StockDetail> checkStockDetail(String stockId); public List<Stock> searchStock(String productId,String createDate,String EffecttiveFrom,String EffectiveTo,String expire); public StockViewSummary searchStockDetail(String productId,String payStatus,String itemStatus); public List<Stock> getStockById(String stockId); public List<OtherTicketView> getStockByProductId(String productId, String otherId); }
cc0-1.0
lfreneda/cepdb
api/v1/35502852.jsonp.js
151
jsonp({"cep":"35502852","logradouro":"Rua Joana Daldegan","bairro":"Santa L\u00facia","cidade":"Divin\u00f3polis","uf":"MG","estado":"Minas Gerais"});
cc0-1.0
lfreneda/cepdb
api/v1/51345325.jsonp.js
140
jsonp({"cep":"51345325","logradouro":"Rua Ant\u00f4nio Barros Soares","bairro":"COHAB","cidade":"Recife","uf":"PE","estado":"Pernambuco"});
cc0-1.0
lfreneda/cepdb
api/v1/81540225.jsonp.js
175
jsonp({"cep":"81540225","logradouro":"Jardinete Raquel Carneiro do Amaral e Silva","bairro":"Jardim das Am\u00e9ricas","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/03961050.jsonp.js
157
jsonp({"cep":"03961050","logradouro":"Rua Felipe Cordeli","bairro":"Cidade S\u00e3o Mateus","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/35171524.jsonp.js
143
jsonp({"cep":"35171524","logradouro":"Rua Quatro","bairro":"Aldeia do Lago","cidade":"Coronel Fabriciano","uf":"MG","estado":"Minas Gerais"});
cc0-1.0
lfreneda/cepdb
api/v1/04859015.jsonp.js
178
jsonp({"cep":"04859015","logradouro":"Pra\u00e7a Ant\u00f4nio Molina","bairro":"Jardim Santa F\u00e9 (Zona Sul)","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
gvsmirnov/java-perv
labs-8/src/main/java/ru/gvsmirnov/perv/labs/jit/DeadCode.java
857
package ru.gvsmirnov.perv.labs.jit; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.RunnerException; /** * TODO: link to the blog post */ @State(Scope.Benchmark) public class DeadCode extends ComparingBenchmark { private double value= Math.random() * Integer.MAX_VALUE; @Benchmark public double measureA() { double previous; double current = value / 2; do { previous = current; current = (previous + (value / previous)) / 2; } while ((previous - current) > 1e-15); return current; } @Benchmark public double measureB() { for (int i = 0; i < 1_000_000; i++); return Math.sqrt(value); } public static void main(String[] args) throws RunnerException { runBenchmarks_JIT_vs_Interpreter(DeadCode.class); } }
cc0-1.0
lfreneda/cepdb
api/v1/21815320.jsonp.js
141
jsonp({"cep":"21815320","logradouro":"Rua Washington Lima","bairro":"Bangu","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/30220265.jsonp.js
143
jsonp({"cep":"30220265","logradouro":"Rua Mangabeira da Serra","bairro":"Serra","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
cc0-1.0
lfreneda/cepdb
api/v1/29123080.jsonp.js
141
jsonp({"cep":"29123080","logradouro":"Rua Vosso Reino","bairro":"Jaburuna","cidade":"Vila Velha","uf":"ES","estado":"Esp\u00edrito Santo"});
cc0-1.0
lfreneda/cepdb
api/v1/17022480.jsonp.js
177
jsonp({"cep":"17022480","logradouro":"Rua dos Mec\u00e2nicos","bairro":"N\u00facleo Residencial Edison Bastos Gasparini","cidade":"Bauru","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/59115688.jsonp.js
175
jsonp({"cep":"59115688","logradouro":"Rua S\u00e3o F\u00e9lix","bairro":"Nossa Senhora da Apresenta\u00e7\u00e3o","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
cc0-1.0
CloudScale-Project/Examples
Minimal/project/src/eu/cloudscale/examples/minimal/app/problems/OLB.java
1174
/** * Copyright 2014 SAP AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.cloudscale.examples.minimal.app.problems; /** * Represents the One Lane Bridge problem. * * @author C5170547 * */ public final class OLB { private static final int TIME_TO_SLEEP = 100; private static OLB instance = new OLB(); /** * * @return singleton instance */ public static OLB getInstance() { return instance; } private OLB() { } /** * Method leading to a One Lane Bridge. */ public synchronized void call() { try { Thread.sleep(TIME_TO_SLEEP); } catch (final InterruptedException e) { throw new RuntimeException(e); } } }
epl-1.0
opendaylight/ovsdb
southbound/southbound-impl/src/main/java/org/opendaylight/ovsdb/southbound/OvsdbDataTreeChangeListener.java
15932
/* * Copyright © 2016 Red Hat, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.ovsdb.southbound; import java.net.ConnectException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.eclipse.jdt.annotation.NonNull; import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener; import org.opendaylight.mdsal.binding.api.DataBroker; import org.opendaylight.mdsal.binding.api.DataObjectModification; import org.opendaylight.mdsal.binding.api.DataTreeChangeListener; import org.opendaylight.mdsal.binding.api.DataTreeIdentifier; import org.opendaylight.mdsal.binding.api.DataTreeModification; import org.opendaylight.mdsal.common.api.LogicalDatastoreType; import org.opendaylight.ovsdb.lib.OvsdbClient; import org.opendaylight.ovsdb.southbound.ovsdb.transact.BridgeOperationalState; import org.opendaylight.ovsdb.southbound.ovsdb.transact.TransactCommandAggregator; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ConnectionInfo; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Data-tree change listener for OVSDB. */ public class OvsdbDataTreeChangeListener implements ClusteredDataTreeChangeListener<Node>, AutoCloseable { /** Our registration. */ private final ListenerRegistration<DataTreeChangeListener<Node>> registration; /** The connection manager. */ private final OvsdbConnectionManager cm; /** The data broker. */ private final DataBroker db; /** The instance identifier codec. */ private final InstanceIdentifierCodec instanceIdentifierCodec; /** Logger. */ private static final Logger LOG = LoggerFactory.getLogger(OvsdbDataTreeChangeListener.class); /** * Create an instance and register the listener. * * @param db The data broker. * @param cm The connection manager. */ OvsdbDataTreeChangeListener(DataBroker db, OvsdbConnectionManager cm, InstanceIdentifierCodec instanceIdentifierCodec) { this.cm = cm; this.db = db; this.instanceIdentifierCodec = instanceIdentifierCodec; InstanceIdentifier<Node> path = InstanceIdentifier .create(NetworkTopology.class) .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID)) .child(Node.class); DataTreeIdentifier<Node> dataTreeIdentifier = DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, path); registration = db.registerDataTreeChangeListener(dataTreeIdentifier, this); LOG.info("OVSDB topology listener has been registered."); } @Override public void close() { registration.close(); LOG.info("OVSDB topology listener has been closed."); } @Override public void onDataTreeChanged(@NonNull Collection<DataTreeModification<Node>> changes) { LOG.trace("onDataTreeChanged: {}", changes); // Connect first if necessary connect(changes); // Update connections if necessary updateConnections(changes); // Update the actual data updateData(changes); // Disconnect if necessary disconnect(changes); LOG.trace("onDataTreeChanged: exit"); } private void connect(@NonNull Collection<DataTreeModification<Node>> changes) { for (DataTreeModification<Node> change : changes) { if (change.getRootNode().getModificationType() == DataObjectModification.ModificationType.WRITE || change .getRootNode().getModificationType() == DataObjectModification.ModificationType.SUBTREE_MODIFIED) { DataObjectModification<OvsdbNodeAugmentation> ovsdbNodeModification = change.getRootNode().getModifiedAugmentation(OvsdbNodeAugmentation.class); if (ovsdbNodeModification != null && ovsdbNodeModification.getDataBefore() == null) { OvsdbNodeAugmentation ovsdbNode = ovsdbNodeModification.getDataAfter(); if (ovsdbNode != null) { ConnectionInfo key = ovsdbNode.getConnectionInfo(); if (key != null) { InstanceIdentifier<Node> iid = cm.getInstanceIdentifier(key); if (iid != null) { LOG.warn("Connection to device {} already exists. Plugin does not allow multiple " + "connections to same device, hence dropping the request {}", key, ovsdbNode); } else { try { cm.connect(change.getRootPath().getRootIdentifier(), ovsdbNode); LOG.info("OVSDB node has been connected: {}",ovsdbNode); } catch (UnknownHostException | ConnectException e) { LOG.warn("Failed to connect to ovsdbNode", e); } } } } } } } } private void disconnect(@NonNull Collection<DataTreeModification<Node>> changes) { for (DataTreeModification<Node> change : changes) { if (change.getRootNode().getModificationType() == DataObjectModification.ModificationType.DELETE) { DataObjectModification<OvsdbNodeAugmentation> ovsdbNodeModification = change.getRootNode().getModifiedAugmentation(OvsdbNodeAugmentation.class); if (ovsdbNodeModification != null) { OvsdbNodeAugmentation ovsdbNode = ovsdbNodeModification.getDataBefore(); if (ovsdbNode != null) { ConnectionInfo key = ovsdbNode.getConnectionInfo(); InstanceIdentifier<Node> iid = cm.getInstanceIdentifier(key); try { cm.disconnect(ovsdbNode); LOG.info("OVSDB node has been disconnected:{}", ovsdbNode); if (iid != null) { cm.stopConnectionReconciliationIfActive(iid.firstIdentifierOf(Node.class), ovsdbNode); } } catch (UnknownHostException e) { LOG.warn("Failed to disconnect ovsdbNode", e); } } } } if (change.getRootNode().getModificationType() == DataObjectModification.ModificationType.WRITE) { DataObjectModification<OvsdbNodeAugmentation> ovsdbNodeModification = change.getRootNode().getModifiedAugmentation(OvsdbNodeAugmentation.class); if (ovsdbNodeModification != null) { DataObjectModification<ConnectionInfo> connectionInfoDOM = ovsdbNodeModification.getModifiedChildContainer(ConnectionInfo.class); if (connectionInfoDOM != null) { if (connectionInfoDOM.getModificationType() == DataObjectModification.ModificationType.DELETE) { ConnectionInfo key = connectionInfoDOM.getDataBefore(); if (key != null) { InstanceIdentifier<Node> iid = cm.getInstanceIdentifier(key); try { OvsdbNodeAugmentation ovsdbNode = ovsdbNodeModification.getDataBefore(); cm.disconnect(ovsdbNode); LOG.warn("OVSDB node {} has been disconnected, because connection-info related to " + "the node is removed by user, but node still exist.", ovsdbNode); cm.stopConnectionReconciliationIfActive(iid.firstIdentifierOf(Node.class), ovsdbNode); } catch (UnknownHostException e) { LOG.warn("Failed to disconnect ovsdbNode", e); } } } } } } } } private void updateConnections(@NonNull Collection<DataTreeModification<Node>> changes) { for (DataTreeModification<Node> change : changes) { switch (change.getRootNode().getModificationType()) { case SUBTREE_MODIFIED: case WRITE: DataObjectModification<OvsdbNodeAugmentation> ovsdbNodeModification = change.getRootNode().getModifiedAugmentation(OvsdbNodeAugmentation.class); if (ovsdbNodeModification != null) { final OvsdbNodeAugmentation dataBefore = ovsdbNodeModification.getDataBefore(); if (dataBefore != null) { OvsdbNodeAugmentation dataAfter = ovsdbNodeModification.getDataAfter(); if (dataAfter != null) { ConnectionInfo connectionInfo = dataAfter.getConnectionInfo(); if (connectionInfo != null) { OvsdbClient client = cm.getClient(connectionInfo); if (client == null) { if (dataBefore != null) { try { cm.disconnect(dataBefore); cm.connect(change.getRootPath().getRootIdentifier(), dataAfter); } catch (UnknownHostException | ConnectException e) { LOG.warn("Error disconnecting from or connecting to ovsdbNode", e); } } } } } } } break; default: // FIXME: delete seems to be unhandled break; } } } private void updateData(@NonNull Collection<DataTreeModification<Node>> changes) { for (Entry<OvsdbConnectionInstance, Collection<DataTreeModification<Node>>> connectionInstanceEntry : changesPerConnectionInstance(changes).entrySet()) { OvsdbConnectionInstance connectionInstance = connectionInstanceEntry.getKey(); Collection<DataTreeModification<Node>> clientChanges = connectionInstanceEntry.getValue(); connectionInstance.transact(new TransactCommandAggregator(), new BridgeOperationalState(db, clientChanges), clientChanges, instanceIdentifierCodec); } } private Map<OvsdbConnectionInstance, Collection<DataTreeModification<Node>>> changesPerConnectionInstance( @NonNull Collection<DataTreeModification<Node>> changes) { Map<OvsdbConnectionInstance, Collection<DataTreeModification<Node>>> result = new HashMap<>(); for (DataTreeModification<Node> change : changes) { OvsdbConnectionInstance client = null; Node dataAfter = change.getRootNode().getDataAfter(); Node node = dataAfter != null ? dataAfter : change.getRootNode().getDataBefore(); if (node != null) { OvsdbNodeAugmentation ovsdbNode = node.augmentation(OvsdbNodeAugmentation.class); if (ovsdbNode != null) { if (ovsdbNode.getConnectionInfo() != null) { client = cm.getConnectionInstance(ovsdbNode.getConnectionInfo()); } else { client = cm.getConnectionInstance(SouthboundMapper.createInstanceIdentifier(node.getNodeId())); } } else { OvsdbBridgeAugmentation bridgeAugmentation = node.augmentation(OvsdbBridgeAugmentation.class); if (bridgeAugmentation != null) { OvsdbNodeRef managedBy = bridgeAugmentation.getManagedBy(); if (managedBy != null) { client = cm.getConnectionInstance((InstanceIdentifier<Node>) managedBy.getValue()); } } } if (client == null) { //Try getting from change root identifier client = cm.getConnectionInstance(change.getRootPath().getRootIdentifier()); } } else { LOG.warn("Following change don't have after/before data {}", change); } if (client != null) { LOG.debug("Found client for {}", node); /* * As of now data change sets are processed by single thread, so we can assume that device will * be connected and ownership will be decided before sending any instructions down to the device. * Note:Processing order in onDataChange() method should not change. If processing is changed to * use multiple thread, we might need to take care of corner cases, where ownership is not decided * but transaction are ready to go to switch. In that scenario, either we need to queue those task * till ownership is decided for that specific device. * Given that each DataChangeNotification is notified through separate thread, so we are already * multi threaded and i don't see any need to further parallelism per DataChange * notifications processing. */ if (cm.getHasDeviceOwnership(client.getMDConnectionInfo())) { LOG.debug("*This* instance of southbound plugin is an owner of the device {}", node); result.computeIfAbsent(client, key -> new ArrayList<>()).add(change); } else { LOG.debug("*This* instance of southbound plugin is *not* an owner of the device {}", node); } } else { LOG.debug("Did not find client for {}", node); } } return result; } }
epl-1.0
gaiandb/gaiandb
java/Asset/ClientTools/com/ibm/gaiandb/apps/DBConnector.java
10980
/* * (C) Copyright IBM Corp. 2009 * * LICENSE: Eclipse Public License v1.0 * http://www.eclipse.org/legal/epl-v10.html */ package com.ibm.gaiandb.apps; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import javax.security.auth.login.LoginException; import com.ibm.gaiandb.GaianDBConfig; import com.ibm.gaiandb.GaianNode; import com.ibm.gaiandb.apps.dashboard.Dashboard; import com.ibm.gaiandb.diags.GDBMessages; import com.ibm.gaiandb.security.common.SecurityToken; import sun.misc.BASE64Encoder; import com.ibm.gaiandb.Logger; /** * Provides a framework for applications to connect to GaianDB easily. * * @author Samir Talwar - [email protected] */ public class DBConnector { // Use PROPRIETARY notice if class contains a main() method, otherwise use COPYRIGHT notice. public static final String COPYRIGHT_NOTICE = "(c) Copyright IBM Corp. 2009"; private static final Logger logger = new Logger( "DBConnector", 30 ); /** The default connection URL. */ private static final String DEFAULT_URL = "jdbc:derby://localhost:" + GaianNode.DEFAULT_PORT + "/" + GaianDBConfig.GAIANDB_NAME; /** The default database user. */ private static final String DEFAULT_USER = GaianDBConfig.GAIAN_NODE_DEFAULT_USR; /** The default database password. */ private static final String DEFAULT_PASSWORD = GaianDBConfig.GAIAN_NODE_DEFAULT_PWD; /** * True if the Derby connection driver is loaded, as we only need to load it * once. */ private static boolean isDerbyDriverLoaded = false; /** The database connection. */ protected Connection conn; /** The JDBC URL with which we last attempted to connect. */ protected String url; /** True if we kept retrying last time we attempted to connect. */ protected boolean retry; /** A copy of the properties used to connect. */ protected Properties propsCache=null; /** The delay in seconds between connection retries. */ protected int retryDelay = 5; /* * Three methods of connection are supported: * 1. "simple", consisting of user's name and password; * 2. "asserted", where the user's identity is asserted by a trusted authority; * 3. "token", consisting of a token that represents the user's credentials. * * Each of the modes above require a set of properties, which are passed in via the Properties object. * These properties may contain two or more of the following: * 1. DB URL (e.g. jdbc:derby:/localhost:6414/gaiandb) -- mandatory * 2. User name -- mandatory * 3. Password * 4. SecurityToken * See below for key names. */ /** Connection modes */ public static final byte MODE_SIMPLE=1; public static final byte MODE_ASSERT=2; public static final byte MODE_TOKEN=3; public static final String MODEKEY="mode"; // indicates connection mode public static final String URLKEY="url"; public static final String USERKEY="user"; public static final String DOMAINKEY="domain"; public static final String PWDKEY="password"; public static final String PROXYUIDKEY = "proxy-user"; public static final String PROXYPWDKEY = "proxy-pwd"; public static final String TOKENKEY="token"; private static final String ANONUID = "APP";; /** * Retrieves the time we delay by between connections retries. * * @return The delay time, in seconds. */ public int getRetryDelay() { return retryDelay; } /** * Sets the delay time between connection retries. * * @param retryDelay * The new delay time, in seconds. */ public void setRetryDelay(int retryDelay) { this.retryDelay = retryDelay; } /** * Creates a new connector, but does not connect to any database until the * <code>connect</code> method is called. */ public DBConnector() { this(DEFAULT_USER, DEFAULT_PASSWORD, false); } /** * Initialises the connection URL, username and password from the * <code>args</code> parameter - usually command-line arguments. * * @param args * The application's command-line arguments. * * @throws ClassNotFoundException * if the Derby client driver class cannot be found. * @throws LoginException */ public DBConnector(String[] args) { this( args.length > 0 ? args[0] : DEFAULT_URL, args.length > 1 ? args[1] : DEFAULT_USER, args.length > 2 ? args[2] : DEFAULT_PASSWORD); } /** * Initialises the connection URL, username and password using the argument * provided. * * @param url * The JDBC URL of the database. * @param user * The chosen username. * @param password * The password associated with the given username. * * @throws ClassNotFoundException * if the Derby client driver class cannot be found. * @throws LoginException */ private DBConnector(String url, String user, String password) { this(user, password, true); this.url=url; } public DBConnector(String user, String password, final boolean retry) { this.propsCache = new Properties(); this.propsCache.setProperty(USERKEY, user); this.propsCache.setProperty(PWDKEY, password); this.propsCache.put(MODEKEY, MODE_SIMPLE); this.retry = retry; } public Connection connect(String url) throws LoginException, ClassNotFoundException { this.url=url; return this.connect(); } /** * Connects to the database at the URL provided, using the provided username * and password. Will try again if it fails. * * @param url * The JDBC URL of the database in the form * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>. * @param user * The chosen username. * @param password * The password associated with the given username. * * @return The database connection. * * @throws ClassNotFoundException * if the Derby client driver class cannot be found. * @throws LoginException */ public Connection connect(String url, Properties info) throws ClassNotFoundException, LoginException { return connect(url, info, true); } /** * Connects to the database at the URL provided, using the provided properties. * * @param url * The JDBC URL of the database in the form * <code>jdbc:<em>subprotocol</em>:<em>subname</em></code>. * @param user * The chosen username. * @param password * The password associated with the given username. * @param retry * If true, this method will keep trying to connect indefinitely * until it succeeds. If false, it will return null on failure. * * @return The database connection on success, or null on failure. * * @throws ClassNotFoundException * if the Derby client driver class cannot be found. */ public Connection connect(String url, Properties info, final boolean retry) throws ClassNotFoundException, LoginException { this.url = url; this.retry = retry; if (null == info || null == url || null == info.getProperty(USERKEY) || null == info.get(MODEKEY)) return null; // mandatory values are missing byte mode = Byte.parseByte(info.get(MODEKEY).toString()); if (!isDerbyDriverLoaded) { Class.forName( GaianDBConfig.DERBY_CLIENT_DRIVER ); isDerbyDriverLoaded = true; } logger.logInfo("Attempting to connect to " + url + " using mode: " + MODEKEY); conn = null; do { try { if (mode==MODE_SIMPLE || mode==MODE_ASSERT) { conn = DriverManager.getConnection(url, info); } if (mode==MODE_TOKEN) { SecurityToken secureToken = (SecurityToken)info.get(TOKENKEY); if (null == secureToken) return null; // mandatory value is missing // initiate "anonymous" connection conn = DriverManager.getConnection(url, ANONUID, "anonymous"); if (conn!=null && !conn.isClosed()) { String sid=sendAuthToken(secureToken); // send token to server if (null != sid) { conn.close(); // build a user name (with domain) -- must conform with SQL92 naming conventions StringBuffer sb = new StringBuffer(); sb.append('\"'); sb.append(info.getProperty(USERKEY)); sb.append('@'); sb.append(info.getProperty(DOMAINKEY)); sb.append('\"'); String uid=sb.toString(); // initiate connection for "real" user conn = DriverManager.getConnection(url, uid, sid); } } } if (null != conn && !conn.isClosed()) logger.logInfo("Connected to the database at " + url); break; } catch (SQLException e) { logger.logWarning(GDBMessages.DBCONNECTOR_CANNOT_CONNECT, "Could not connect to the database with credentials: " + e); conn = null; } if (retry) { try { Thread.sleep(retryDelay * 1000); } catch (InterruptedException e) { return null; } } } while (retry); return conn; } private String sendAuthToken(SecurityToken st) { // sends a user ID (UID) and security token (st), returns a session ID (SID) String sid=null; if (null != st) { try { String query = "VALUES GAIANDB.AUTHTOKEN(?)"; PreparedStatement ps = conn.prepareStatement(query); ps.setQueryTimeout(Dashboard.QUERY_TIMEOUT); String token=""; if (st.isValid()) token = new BASE64Encoder().encodeBuffer(st.get()); // convert to a String with Base64Encoding ps.setString(1, token); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { sid = resultSet.getString(1); } // clean up resultSet.close(); resultSet = null; ps.close(); ps = null; } catch (SQLException e) { logger.logException(GDBMessages.DBCONNECTOR_CANNOT_FIND_SESSION_ID, "Could not find the session ID for this token", e); } } return sid; } /** * Connects using the pre-defined properties. * * @return The database connection. * * @throws ClassNotFoundException * if the Derby client driver class cannot be found. * @throws LoginException */ public Connection connect() throws ClassNotFoundException, LoginException { return connect(this.url, this.propsCache, this.retry); } /** * Returns the connection for use with other classes. * * @return A connection to the database, or <code>null</code> if one has not * been established yet. */ public Connection getConnection() { return conn; } /** * Displays the message you've given and a termination message, then quits * the program. Useful for a quick bailout. * * @param message * The message to display on <code>System.err</code>. */ public static void terminate(String message) { if (message != null && message.length() > 0) { logger.logWarning(GDBMessages.DBCONNECTOR_SHUTDOWN_MESSAGE, message); } logger.logInfo("This program will now terminate."); System.exit(1); // TODO replace this with a proper clean shutdown } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/mappings/querykeys/QueryKey.java
4929
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.mappings.querykeys; import java.io.*; import org.eclipse.persistence.descriptors.ClassDescriptor; /** * <p> * <b>Purpose</b>: Define a Java appropriate alias to a database field or function. * <p> * <b>Responsibilities</b>: * <ul> * <li> Define the name of the alias. * <li> Define the descriptor of the alias. * </ul> */ public class QueryKey implements Cloneable, Serializable { protected String name; protected ClassDescriptor descriptor; /** * INTERNAL: * Clones itself. */ public Object clone() { Object object = null; try { object = super.clone(); } catch (Exception exception) { throw new InternalError(exception.toString()); } return object; } /** * INTERNAL: * Convert all the class-name-based settings in this QueryKey to actual class-based * settings * Will be overridded by subclasses * @param classLoader */ public void convertClassNamesToClasses(ClassLoader classLoader){} /** * INTERNAL: * Return the descriptor. */ public ClassDescriptor getDescriptor() { return descriptor; } /** * PUBLIC: * Return the name for the query key. * This is the name that will be used in the expression. */ public String getName() { return name; } /** * INTERNAL: * Initialize any information in the receiver that requires its descriptor. * Set the receiver's descriptor back reference. * @param aDescriptor is the owner descriptor of the receiver. */ public void initialize(ClassDescriptor aDescriptor) { setDescriptor(aDescriptor); } /** * INTERNAL: * return whether this query key is abstract * @return boolean */ public boolean isAbstractQueryKey() { return (this.getClass().equals(org.eclipse.persistence.internal.helper.ClassConstants.QueryKey_Class)); } /** * PUBLIC:: * Related query key should implement this method to return true. */ public boolean isCollectionQueryKey() { return false; } /** * PUBLIC:: * Related query key should implement this method to return true. */ public boolean isDirectCollectionQueryKey() { return false; } /** * PUBLIC:: * Related query key should implement this method to return true. */ public boolean isDirectQueryKey() { return false; } /** * PUBLIC:: * Related query key should implement this method to return true. */ public boolean isForeignReferenceQueryKey() { return false; } /** * PUBLIC:: * Related query key should implement this method to return true. */ public boolean isManyToManyQueryKey() { return false; } /** * PUBLIC:: * Related query key should implement this method to return true. */ public boolean isOneToManyQueryKey() { return false; } /** * PUBLIC:: * Related query key should implement this method to return true. */ public boolean isOneToOneQueryKey() { return false; } /** * INTERNAL: * This is a QueryKey. return true. * @return boolean */ public boolean isQueryKey() { return true; } /** * INTERNAL: * Set the descriptor. */ public void setDescriptor(ClassDescriptor descriptor) { this.descriptor = descriptor; } /** * PUBLIC: * Set the name for the query key. * This is the name that will be used in the expression. */ public void setName(String name) { this.name = name; } /** * INTERNAL: * return a string representation of this instance of QueryKey */ public String toString() { return org.eclipse.persistence.internal.helper.Helper.getShortClassName(this) + "(" + getName() + ")"; } }
epl-1.0
edgarmueller/emfstore-rest
bundles/org.eclipse.emf.emfstore.examplemodel/src/org/eclipse/emf/emfstore/bowling/impl/MerchandiseImpl.java
8470
/** */ package org.eclipse.emf.emfstore.bowling.impl; import java.math.BigDecimal; import java.math.BigInteger; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.emfstore.bowling.BowlingPackage; import org.eclipse.emf.emfstore.bowling.Merchandise; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Merchandise</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.emf.emfstore.bowling.impl.MerchandiseImpl#getName <em>Name</em>}</li> * <li>{@link org.eclipse.emf.emfstore.bowling.impl.MerchandiseImpl#getPrice <em>Price</em>}</li> * <li>{@link org.eclipse.emf.emfstore.bowling.impl.MerchandiseImpl#getSerialNumber <em>Serial Number</em>}</li> * </ul> * </p> * * @generated */ public class MerchandiseImpl extends EObjectImpl implements Merchandise { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getPrice() <em>Price</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPrice() * @generated * @ordered */ protected static final BigDecimal PRICE_EDEFAULT = null; /** * The cached value of the '{@link #getPrice() <em>Price</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getPrice() * @generated * @ordered */ protected BigDecimal price = PRICE_EDEFAULT; /** * This is true if the Price attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated * @ordered */ protected boolean priceESet; /** * The default value of the '{@link #getSerialNumber() <em>Serial Number</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSerialNumber() * @generated * @ordered */ protected static final BigInteger SERIAL_NUMBER_EDEFAULT = null; /** * The cached value of the '{@link #getSerialNumber() <em>Serial Number</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @see #getSerialNumber() * @generated * @ordered */ protected BigInteger serialNumber = SERIAL_NUMBER_EDEFAULT; /** * This is true if the Serial Number attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated * @ordered */ protected boolean serialNumberESet; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ protected MerchandiseImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override protected EClass eStaticClass() { return BowlingPackage.Literals.MERCHANDISE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BowlingPackage.MERCHANDISE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public BigDecimal getPrice() { return price; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void setPrice(BigDecimal newPrice) { BigDecimal oldPrice = price; price = newPrice; boolean oldPriceESet = priceESet; priceESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BowlingPackage.MERCHANDISE__PRICE, oldPrice, price, !oldPriceESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void unsetPrice() { BigDecimal oldPrice = price; boolean oldPriceESet = priceESet; price = PRICE_EDEFAULT; priceESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, BowlingPackage.MERCHANDISE__PRICE, oldPrice, PRICE_EDEFAULT, oldPriceESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public boolean isSetPrice() { return priceESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public BigInteger getSerialNumber() { return serialNumber; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void setSerialNumber(BigInteger newSerialNumber) { BigInteger oldSerialNumber = serialNumber; serialNumber = newSerialNumber; boolean oldSerialNumberESet = serialNumberESet; serialNumberESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BowlingPackage.MERCHANDISE__SERIAL_NUMBER, oldSerialNumber, serialNumber, !oldSerialNumberESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public void unsetSerialNumber() { BigInteger oldSerialNumber = serialNumber; boolean oldSerialNumberESet = serialNumberESet; serialNumber = SERIAL_NUMBER_EDEFAULT; serialNumberESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, BowlingPackage.MERCHANDISE__SERIAL_NUMBER, oldSerialNumber, SERIAL_NUMBER_EDEFAULT, oldSerialNumberESet)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ public boolean isSetSerialNumber() { return serialNumberESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BowlingPackage.MERCHANDISE__NAME: return getName(); case BowlingPackage.MERCHANDISE__PRICE: return getPrice(); case BowlingPackage.MERCHANDISE__SERIAL_NUMBER: return getSerialNumber(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case BowlingPackage.MERCHANDISE__NAME: setName((String) newValue); return; case BowlingPackage.MERCHANDISE__PRICE: setPrice((BigDecimal) newValue); return; case BowlingPackage.MERCHANDISE__SERIAL_NUMBER: setSerialNumber((BigInteger) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case BowlingPackage.MERCHANDISE__NAME: setName(NAME_EDEFAULT); return; case BowlingPackage.MERCHANDISE__PRICE: unsetPrice(); return; case BowlingPackage.MERCHANDISE__SERIAL_NUMBER: unsetSerialNumber(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case BowlingPackage.MERCHANDISE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case BowlingPackage.MERCHANDISE__PRICE: return isSetPrice(); case BowlingPackage.MERCHANDISE__SERIAL_NUMBER: return isSetSerialNumber(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (name: "); result.append(name); result.append(", price: "); if (priceESet) result.append(price); else result.append("<unset>"); result.append(", serialNumber: "); if (serialNumberESet) result.append(serialNumber); else result.append("<unset>"); result.append(')'); return result.toString(); } } // MerchandiseImpl
epl-1.0
junli007/vone
WebRoot/dep/angular/i18n/angular-locale_shi.js
3298
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u2d5c\u2d49\u2d3c\u2d30\u2d61\u2d5c", "\u2d5c\u2d30\u2d37\u2d33\u2d33\u2d6f\u2d30\u2d5c" ], "DAY": [ "\u2d30\u2d59\u2d30\u2d4e\u2d30\u2d59", "\u2d30\u2d62\u2d4f\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d4f\u2d30\u2d59", "\u2d30\u2d3d\u2d55\u2d30\u2d59", "\u2d30\u2d3d\u2d61\u2d30\u2d59", "\u2d59\u2d49\u2d4e\u2d61\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d39\u2d62\u2d30\u2d59" ], "MONTH": [ "\u2d49\u2d4f\u2d4f\u2d30\u2d62\u2d54", "\u2d31\u2d55\u2d30\u2d62\u2d55", "\u2d4e\u2d30\u2d55\u2d5a", "\u2d49\u2d31\u2d54\u2d49\u2d54", "\u2d4e\u2d30\u2d62\u2d62\u2d53", "\u2d62\u2d53\u2d4f\u2d62\u2d53", "\u2d62\u2d53\u2d4d\u2d62\u2d53\u2d63", "\u2d56\u2d53\u2d5b\u2d5c", "\u2d5b\u2d53\u2d5c\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d3d\u2d5c\u2d53\u2d31\u2d54", "\u2d4f\u2d53\u2d61\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d37\u2d53\u2d4a\u2d30\u2d4f\u2d31\u2d49\u2d54" ], "SHORTDAY": [ "\u2d30\u2d59\u2d30", "\u2d30\u2d62\u2d4f", "\u2d30\u2d59\u2d49", "\u2d30\u2d3d\u2d55", "\u2d30\u2d3d\u2d61", "\u2d30\u2d59\u2d49\u2d4e", "\u2d30\u2d59\u2d49\u2d39" ], "SHORTMONTH": [ "\u2d49\u2d4f\u2d4f", "\u2d31\u2d55\u2d30", "\u2d4e\u2d30\u2d55", "\u2d49\u2d31\u2d54", "\u2d4e\u2d30\u2d62", "\u2d62\u2d53\u2d4f", "\u2d62\u2d53\u2d4d", "\u2d56\u2d53\u2d5b", "\u2d5b\u2d53\u2d5c", "\u2d3d\u2d5c\u2d53", "\u2d4f\u2d53\u2d61", "\u2d37\u2d53\u2d4a" ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM, y HH:mm:ss", "mediumDate": "d MMM, y", "mediumTime": "HH:mm:ss", "short": "d/M/y HH:mm", "shortDate": "d/M/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "dh", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "shi", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
epl-1.0
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/testlanguages/lookaheadLang/LookAhead4.java
1409
/** * generated by Xtext */ package org.eclipse.xtext.testlanguages.lookaheadLang; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Look Ahead4</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.eclipse.xtext.testlanguages.lookaheadLang.LookAhead4#getX <em>X</em>}</li> * </ul> * * @see org.eclipse.xtext.testlanguages.lookaheadLang.LookaheadLangPackage#getLookAhead4() * @model * @generated */ public interface LookAhead4 extends EObject { /** * Returns the value of the '<em><b>X</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>X</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>X</em>' attribute. * @see #setX(String) * @see org.eclipse.xtext.testlanguages.lookaheadLang.LookaheadLangPackage#getLookAhead4_X() * @model * @generated */ String getX(); /** * Sets the value of the '{@link org.eclipse.xtext.testlanguages.lookaheadLang.LookAhead4#getX <em>X</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>X</em>' attribute. * @see #getX() * @generated */ void setX(String value); } // LookAhead4
epl-1.0
DavidGutknecht/elexis-3-base
bundles/com.hilotec.elexis.kgview/src/com/hilotec/elexis/kgview/Preferences.java
4452
package com.hilotec.elexis.kgview; import org.eclipse.jface.preference.BooleanFieldEditor; import org.eclipse.jface.preference.FieldEditorPreferencePage; import org.eclipse.jface.preference.IntegerFieldEditor; import org.eclipse.swt.SWT; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import ch.elexis.core.services.holder.ConfigServiceHolder; import ch.elexis.core.ui.preferences.ConfigServicePreferenceStore; import ch.elexis.core.ui.preferences.ConfigServicePreferenceStore.Scope; import ch.elexis.core.ui.preferences.inputs.MultilineFieldEditor; /** * Einstelllungsseite fuer kgview-Plugin. * * @author Antoine Kaufmann */ public class Preferences extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { private static ConfigServicePreferenceStore store; public static final String CFG_EVLISTE = "hilotec/kgview/einnahmevorschriften"; public static final String CFG_FLORDZ = "hilotec/kgview/ordnungszahlfavliste"; public static final String CFG_MK_INCSTOP = "hilotec/kgview/mkincludestopdate"; public static final String CFG_AKG_HEARTBEAT = "hilotec/kgview/archivkgheartbaeat"; public static final String CFG_AKG_SCROLLPERIOD = "hilotec/kgview/archivkgscrollperiod"; public static final String CFG_AKG_SCROLLDIST_UP = "hilotec/kgview/archivkgscrolldistup"; public static final String CFG_AKG_SCROLLDIST_DOWN = "hilotec/kgview/archivkgscrolldistdown"; static { store = new ConfigServicePreferenceStore(Scope.MANDATOR); // Standardwerte setzten store.setDefault(CFG_FLORDZ, false); store.setDefault(CFG_MK_INCSTOP, false); store.setDefault(CFG_AKG_HEARTBEAT, 10); store.setDefault(CFG_AKG_SCROLLPERIOD, 200); store.setDefault(CFG_AKG_SCROLLDIST_UP, 5); store.setDefault(CFG_AKG_SCROLLDIST_DOWN, 5); } public Preferences(){ super(GRID); setPreferenceStore(store); } @Override public void init(IWorkbench workbench){} @Override protected void createFieldEditors(){ addField(new MultilineFieldEditor(CFG_EVLISTE, "Einnahmevorschriften", 5, SWT.V_SCROLL, true, getFieldEditorParent())); addField(new BooleanFieldEditor(CFG_FLORDZ, "Ordnungszahl in FML anzeigen", getFieldEditorParent())); addField(new BooleanFieldEditor(CFG_MK_INCSTOP, "In Medikarte bis/mit Stoppdatum anzeigen?", getFieldEditorParent())); addField(new IntegerFieldEditor(CFG_AKG_HEARTBEAT, "Archiv KG Heartbeat", getFieldEditorParent())); addField(new IntegerFieldEditor(CFG_AKG_SCROLLPERIOD, "Archiv KG Scroll Periode [ms]", getFieldEditorParent())); addField(new IntegerFieldEditor(CFG_AKG_SCROLLDIST_UP, "Archiv KG Scroll Distanz hoch [px]", getFieldEditorParent())); addField(new IntegerFieldEditor(CFG_AKG_SCROLLDIST_DOWN, "Archiv KG Scroll Distanz runter [px]", getFieldEditorParent())); } /** * @return Konfigurierte Einnahmevorschriften im aktuellen Mandant. */ public static String[] getEinnahmevorschriften(){ String s = ConfigServiceHolder.getMandator(CFG_EVLISTE, ""); return s.split(","); } /** * @return */ public static boolean getOrdnungszahlInFML(){ boolean oz = ConfigServiceHolder.getMandator(CFG_FLORDZ, false); return oz; } /** * @return Sollen in der gefilterten Medikarteansicht auch Medikament angezeigt werden, die das * aktuelle Datum als Stoppdatum haben? */ public static boolean getMedikarteStopdatumInkl(){ return store.getBoolean(CFG_MK_INCSTOP); } /** * @return Heartbeat abstand in Sekunden, fuer die Aktualisierung der ArchivKG-Ansicht. */ public int getArchivKGHeartbeat(){ int n = store.getInt(CFG_AKG_HEARTBEAT); if (n < 1) n = 1; return n; } /** * @return Fuer automatisches Scrollen in ArchivKG, Periode in Millisekunden. */ public static int getArchivKGScrollPeriod(){ int n = store.getInt(CFG_AKG_SCROLLPERIOD); if (n < 50) n = 50; return n; } /** * @return Fuer automatisches Scrollen in ArchivKG, Scrolldistanz in Pixel */ public static int getArchivKGScrollDistUp(){ int n = store.getInt(CFG_AKG_SCROLLDIST_UP); if (n < 1) n = 1; return n; } /** * @return Fuer automatisches Scrollen in ArchivKG, Scrolldistanz in Pixel */ public static int getArchivKGScrollDistDown(){ int n = store.getInt(CFG_AKG_SCROLLDIST_DOWN); if (n < 1) n = 1; return n; } }
epl-1.0
alovassy/titan.EclipsePlug-ins
org.eclipse.titan.log.viewer/src/org/eclipse/titan/log/viewer/parsers/data/LogRecord.java
3465
/****************************************************************************** * Copyright (c) 2000-2015 Ericsson Telecom AB * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.eclipse.titan.log.viewer.parsers.data; import org.eclipse.titan.log.viewer.utils.Constants; /** * This class represents a log record * */ public class LogRecord { private String timestamp; private String eventType = Constants.EVENTTYPE_UNKNOWN; private String componentReference = ""; //$NON-NLS-1$ private String sourceInformation = ""; //$NON-NLS-1$ private String message = ""; //$NON-NLS-1$ private long recordOffset; private int recordLength; private int recordNumber; /** * Returns the component reference * @return the component reference */ public String getComponentReference() { return this.componentReference; } /** * Sets the component reference * @param componentReference the component reference */ public void setComponentReference(final String componentReference) { this.componentReference = componentReference; } /** * Returns the event type * @return the event type */ public String getEventType() { return this.eventType; } /** * Sets the event type * @param eventType the event type */ public void setEventType(final String eventType) { this.eventType = eventType; } /** * Returns the message * @return the message */ public String getMessage() { return this.message; } /** * Sets the message * @param message the message */ public void setMessage(final String message) { this.message = message; } /** * Returns the source information * @return the source information */ public String getSourceInformation() { return this.sourceInformation; } /** * Sets the source information * @param sourceInformation the source information */ public void setSourceInformation(final String sourceInformation) { this.sourceInformation = sourceInformation; } /** * Returns the time stamp * @return the time stamp */ public String getTimestamp() { return this.timestamp; } /** * Sets the time stamp * @param timestamp the time stamp */ public void setTimestamp(final String timestamp) { this.timestamp = timestamp; } /** * Returns the record length * @return the record length */ public int getRecordLength() { return this.recordLength; } /** * Sets the record length * @param recordLength the record length */ public void setRecordLength(final int recordLength) { this.recordLength = recordLength; } /** * Returns the record offset * @return the record offset */ public long getRecordOffset() { return this.recordOffset; } /** * Sets the record offset * @param recordOffset the record offset */ public void setRecordOffset(final long recordOffset) { this.recordOffset = recordOffset; } /** * Returns the record number * @return the record number */ public int getRecordNumber() { return this.recordNumber; } /** * Sets the record number * @param recordNumber the record number */ public void setRecordNumber(final int recordNumber) { this.recordNumber = recordNumber; } }
epl-1.0
mtstv/accesscontroltool
accesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/configmodel/AceBean.java
11284
/* * (C) Copyright 2015 Netcentric 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 */ package biz.netcentric.cq.tools.actool.configmodel; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.day.cq.security.util.CqActions; import biz.netcentric.cq.tools.actool.dumpservice.AcDumpElement; import biz.netcentric.cq.tools.actool.dumpservice.AcDumpElementVisitor; /** This class is used to store data of an AcessControlEntry. Objects of this class get created during the reading of the configuration file * in order to set the corresponding ACEs in the system on the one hand and to store data during the reading of existing ACEs before writing * the data back to a dump or configuration file again on the other hand. */ public class AceBean implements AcDumpElement { public static final Logger LOG = LoggerFactory.getLogger(AceBean.class); private String principalName; // as found in jcr for ACE settings private String authorizableId; // as configured in yaml file private String jcrPath; private String actionsStringFromConfig; private String privilegesString; private String permission; private String[] actions; private List<Restriction> restrictions = new ArrayList<Restriction>(); private boolean keepOrder = false; // default is to reorder denies before allows private String initialContent; public static final String RESTRICTION_NAME_GLOB = "rep:glob"; @Override public AceBean clone() { AceBean clone = new AceBean(); clone.setJcrPath(jcrPath); clone.setPrivilegesString(privilegesString); clone.setAuthorizableId(authorizableId); clone.setPrincipalName(principalName); clone.setPermission(permission); clone.setActions(actions); clone.setRestrictions(new ArrayList<Restriction>(restrictions)); clone.setInitialContent(initialContent); clone.setKeepOrder(keepOrder); return clone; } public String getPermission() { return permission; } public void setPermission(String permissionString) { permission = permissionString; } public void clearActions() { actions = null; actionsStringFromConfig = ""; } public String getPrincipalName() { return principalName; } public void setPrincipalName(String principalName) { this.principalName = principalName; } public String getAuthorizableId() { return authorizableId; } public void setAuthorizableId(String authorizableId) { this.authorizableId = authorizableId; } public String getJcrPath() { return jcrPath; } public String getJcrPathForPolicyApi() { if (StringUtils.isBlank(jcrPath)) { return null; // repository level permission } else { return jcrPath; } } public void setJcrPath(String jcrPath) { this.jcrPath = jcrPath; } public boolean isAllow() { return "allow".equalsIgnoreCase(permission); } public List<Restriction> getRestrictions() { return restrictions; } public void setRestrictions(Object restrictionsRaw, String oldStyleRepGlob) { restrictions.clear(); if (restrictionsRaw != null) { if (!(restrictionsRaw instanceof Map)) { throw new IllegalArgumentException("If 'restrictions' is provided for an AC entry, it needs to be a map."); } Map<String, ?> restrictionsMap = (Map<String, ?>) restrictionsRaw; for (final String key : restrictionsMap.keySet()) { final String value = (String) restrictionsMap.get(key); if (value == null) { LOG.debug("Could not get value from restriction map using key: {}", key); continue; } final String[] values = value.split(" *, *"); restrictions.add(new Restriction(key, values)); } } if (oldStyleRepGlob != null) { if (containsRestriction(RESTRICTION_NAME_GLOB)) { throw new IllegalArgumentException("Usage of restrictions -> rep:glob and repGlob on top level cannot be mixed."); } restrictions.add(new Restriction(RESTRICTION_NAME_GLOB, oldStyleRepGlob)); } } public boolean containsRestriction(String restrictionName) { for (Restriction currentRestriction : restrictions) { if (StringUtils.equals(currentRestriction.getName(), restrictionName)) { return true; } } return false; } public void setRestrictions(List<Restriction> restrictions) { this.restrictions = restrictions; } public String getRepGlob() { for (Restriction currentRestriction : restrictions) { if (StringUtils.equals(currentRestriction.getName(), RESTRICTION_NAME_GLOB)) { return currentRestriction.getValue(); } } return null; } public String getActionsString() { if (actions != null) { final StringBuilder sb = new StringBuilder(); for (final String action : actions) { sb.append(action).append(","); } return StringUtils.chomp(sb.toString(), ","); } return ""; } public void setActions(String[] actions) { this.actions = actions; } public String[] getActions() { return actions; } public String getPrivilegesString() { return privilegesString; } public String[] getPrivileges() { if (StringUtils.isNotBlank(privilegesString)) { return privilegesString.split(" *, *"); } return null; } public void setPrivilegesString(String privilegesString) { this.privilegesString = privilegesString; } public String getInitialContent() { return initialContent; } public void setInitialContent(String initialContent) { this.initialContent = initialContent; } public boolean isKeepOrder() { return keepOrder; } public void setKeepOrder(boolean keepOrder) { this.keepOrder = keepOrder; } @Override public String toString() { return "AceBean [jcrPath=" + jcrPath + "\n" + ", actionsStringFromConfig=" + actionsStringFromConfig + "\n" + ", privilegesString=" + privilegesString + "\n" + ", principal=" + principalName + "\n, authorizableId=" + authorizableId + "\n" + ", permission=" + permission + "\n, actions=" + Arrays.toString(actions) + "\n" + ", restrictions=" + restrictions + "\n" + ", initialContent=" + initialContent + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + Arrays.hashCode(actions); result = (prime * result) + ((actionsStringFromConfig == null) ? 0 : actionsStringFromConfig.hashCode()); result = (prime * result) + ((initialContent == null) ? 0 : initialContent.hashCode()); result = (prime * result) + ((jcrPath == null) ? 0 : jcrPath.hashCode()); result = (prime * result) + ((permission == null) ? 0 : permission.hashCode()); result = (prime * result) + ((principalName == null) ? 0 : principalName.hashCode()); result = (prime * result) + ((privilegesString == null) ? 0 : privilegesString.hashCode()); result = (prime * result) + ((restrictions == null) ? 0 : restrictions.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AceBean other = (AceBean) obj; if (!Arrays.equals(actions, other.actions)) { return false; } if (actionsStringFromConfig == null) { if (other.actionsStringFromConfig != null) { return false; } } else if (!actionsStringFromConfig.equals(other.actionsStringFromConfig)) { return false; } if (initialContent == null) { if (other.initialContent != null) { return false; } } else if (!initialContent.equals(other.initialContent)) { return false; } if (jcrPath == null) { if (other.jcrPath != null) { return false; } } else if (!jcrPath.equals(other.jcrPath)) { return false; } if (permission == null) { if (other.permission != null) { return false; } } else if (!permission.equals(other.permission)) { return false; } if (principalName == null) { if (other.principalName != null) { return false; } } else if (!principalName.equals(other.principalName)) { return false; } if (privilegesString == null) { if (other.privilegesString != null) { return false; } } else if (!privilegesString.equals(other.privilegesString)) { return false; } if (restrictions == null) { if (other.restrictions != null) { return false; } } else if (!restrictions.equals(other.restrictions)) { return false; } return true; } @Override public void accept(AcDumpElementVisitor acDumpElementVisitor) { acDumpElementVisitor.visit(this); } /** Creates an action map being used in {@link CqActions#installActions(String, Principal, Map, Collection)} out of the set actions on * this bean. * * @return a map containing actions as keys and booleans representing {@code true} for allow and {@code false} for deny. */ public Map<String, Boolean> getActionMap() { if (actions == null) { return Collections.emptyMap(); } final Map<String, Boolean> actionMap = new HashMap<String, Boolean>(); for (final String action : actions) { actionMap.put(action, isAllow()); } return actionMap; } public boolean isInitialContentOnlyConfig() { return StringUtils.isNotBlank(initialContent) && StringUtils.isBlank(permission) && StringUtils.isBlank(privilegesString) && StringUtils.isBlank(actionsStringFromConfig); } }
epl-1.0
alidugan/cekilis
src/com/dugan/cekilis/GmailSender.java
3550
package com.dugan.cekilis; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.Security; import java.util.Properties; public class GmailSender extends javax.mail.Authenticator { private String mailhost = "smtp.gmail.com"; private String user; private String password; private Session session; static { Security.addProvider(new com.dugan.cekilis.JSSEProvider()); } public GmailSender(String user, String password) { this.user = user; this.password = password; Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", mailhost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.quitwait", "false"); session = Session.getDefaultInstance(props, this); } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception { try{ MimeMessage message = new MimeMessage(session); DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); message.setSender(new InternetAddress(sender)); message.setSubject(subject); message.setDataHandler(handler); if (recipients.indexOf(',') > 0) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); Transport.send(message); }catch(Exception e){ } } public class ByteArrayDataSource implements DataSource { private byte[] data; private String type; public ByteArrayDataSource(byte[] data, String type) { super(); this.data = data; this.type = type; } public ByteArrayDataSource(byte[] data) { super(); this.data = data; } public void setType(String type) { this.type = type; } public String getContentType() { if (type == null) return "application/octet-stream"; else return type; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } public String getName() { return "ByteArrayDataSource"; } public OutputStream getOutputStream() throws IOException { throw new IOException("Not Supported"); } } }
epl-1.0
Jamstah/openhab2-addons
addons/binding/org.openhab.binding.rfxcom.test/src/test/java/org/openhab/binding/rfxcom/internal/messages/RFXComTemperatureRainMessageTest.java
1652
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.rfxcom.internal.messages; import static org.junit.Assert.assertEquals; import static org.openhab.binding.rfxcom.internal.messages.RFXComTemperatureRainMessage.SubType.WS1200; import javax.xml.bind.DatatypeConverter; import org.junit.Test; import org.openhab.binding.rfxcom.internal.exceptions.RFXComException; /** * Test for RFXCom-binding * * @author Martin van Wingerden * @since 1.9.0 */ public class RFXComTemperatureRainMessageTest { @Test public void testSomeMessages() throws RFXComException { String hexMessage = "0A4F01CCF001004F03B759"; byte[] message = DatatypeConverter.parseHexBinary(hexMessage); RFXComTemperatureRainMessage msg = (RFXComTemperatureRainMessage) RFXComMessageFactory.createMessage(message); assertEquals("SubType", WS1200, msg.subType); assertEquals("Seq Number", 204, (short) (msg.seqNbr & 0xFF)); assertEquals("Sensor Id", "61441", msg.getDeviceId()); assertEquals("Temperature", 7.9, msg.temperature, 0.001); assertEquals("Rain total", 95.1, msg.rainTotal, 0.001); assertEquals("Signal Level", (byte) 5, msg.signalLevel); byte[] decoded = msg.decodeMessage(); assertEquals("Message converted back", hexMessage, DatatypeConverter.printHexBinary(decoded)); } }
epl-1.0
alovassy/titan.EclipsePlug-ins
org.eclipse.titan.codegenerator/src/org/eclipse/titan/codegenerator/TTCN3JavaAPI/STRING.java
2681
/****************************************************************************** * Copyright (c) 2000-2016 Ericsson Telecom AB * 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: * * Keremi, Andras * Eros, Levente * Kovacs, Gabor * ******************************************************************************/ package org.eclipse.titan.codegenerator.TTCN3JavaAPI; import java.math.BigInteger; public class STRING extends Comparable<STRING>{ public byte[] value; public STRING() { value = null; } public STRING(String s) { this.value = s.getBytes(); } public STRING concatenate(STRING other){ return new STRING(this.value.toString() + other.value.toString()); } public BOOLEAN equalsWith(STRING string) { return new BOOLEAN(this.value.equals(string.value)); } //converts the input from INTEGER to int!!! public STRING rotateLeft(INTEGER by){ byte[] copy = new byte[value.length]; int byValue = by.value.intValue() % value.length; System.arraycopy(value,byValue,copy,0,value.length-byValue); System.arraycopy(value,0,copy,value.length-byValue,byValue); return new STRING(new String(copy)); } //converts the input from INTEGER to int!!! public STRING rotateRight(INTEGER by) { int byValue = by.value.intValue() % value.length; return rotateLeft(new INTEGER(BigInteger.valueOf(value.length-byValue))); } public static boolean match(STRING pattern, Object message){ if(!(message instanceof STRING)) return false; if(pattern.omitField&&((STRING)message).omitField) return true; if(pattern.anyOrOmitField) return true; if(pattern.anyField&&!((STRING)message).omitField) return true; if(pattern.omitField&&!((STRING)message).omitField) return false; if(pattern.anyField&&((STRING)message).omitField) return false; return (pattern.equals(((STRING)message))).getValue(); } public BOOLEAN equals(STRING v){ for(int i=0;i<value.length;i++) if(this.value[i]!=v.value[i]) return new BOOLEAN(false); return new BOOLEAN(true); } /* these are never used, only needed because STRING cannot be an abstract class due to its operator methods * the results of which on the other hand, will always be cast to the corresponding child classes */ public String toString(String tabs) { return null; } public String toString() { return null; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/choicecollection/converter/EmployeeProject.java
3280
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * bdoughan - August 7/2009 - 2.0 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings.choicecollection.converter; import org.eclipse.persistence.oxm.XMLDescriptor; import org.eclipse.persistence.oxm.mappings.XMLChoiceCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLChoiceObjectMapping; import org.eclipse.persistence.oxm.mappings.XMLDirectMapping; import org.eclipse.persistence.sessions.Project; import org.eclipse.persistence.testing.oxm.mappings.choicecollection.Address; import org.eclipse.persistence.testing.oxm.mappings.choicecollection.Employee; public class EmployeeProject extends Project { public EmployeeProject() { addDescriptor(getEmployeeDescriptor()); addDescriptor(getAddressDescriptor()); } private XMLDescriptor getEmployeeDescriptor() { XMLDescriptor descriptor = new XMLDescriptor(); descriptor.setJavaClass(Employee.class); descriptor.setDefaultRootElement("employee"); XMLDirectMapping nameMapping = new XMLDirectMapping(); nameMapping.setAttributeName("name"); nameMapping.setXPath("name/text()"); descriptor.addMapping(nameMapping); XMLChoiceCollectionMapping choiceMapping = new XMLChoiceCollectionMapping(); choiceMapping.setAttributeName("choice"); choiceMapping.addChoiceElement("street/text()", String.class); choiceMapping.addChoiceElement("address", Address.class); choiceMapping.addChoiceElement("integer/text()", Integer.class); choiceMapping.addChoiceElement("simpleAddress", Object.class); choiceMapping.setConverter(new WrapperConverter()); descriptor.addMapping(choiceMapping); XMLDirectMapping phoneMapping = new XMLDirectMapping(); phoneMapping.setAttributeName("phone"); phoneMapping.setXPath("phone/text()"); descriptor.addMapping(phoneMapping); return descriptor; } private XMLDescriptor getAddressDescriptor() { XMLDescriptor descriptor = new XMLDescriptor(); descriptor.setJavaClass(Address.class); XMLDirectMapping streetMapping = new XMLDirectMapping(); streetMapping.setAttributeName("street"); streetMapping.setXPath("street/text()"); descriptor.addMapping(streetMapping); XMLDirectMapping cityMapping = new XMLDirectMapping(); cityMapping.setAttributeName("city"); cityMapping.setXPath("city/text()"); descriptor.addMapping(cityMapping); return descriptor; } }
epl-1.0
dhuebner/che
wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/shared/dto/MachineConfigDto.java
2345
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * 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: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.api.machine.shared.dto; import org.eclipse.che.api.core.factory.FactoryParameter; import org.eclipse.che.api.core.model.machine.MachineConfig; import org.eclipse.che.api.core.rest.shared.dto.Hyperlinks; import org.eclipse.che.api.core.rest.shared.dto.Link; import org.eclipse.che.dto.shared.DTO; import java.util.List; import java.util.Map; import static org.eclipse.che.api.core.factory.FactoryParameter.Obligation.MANDATORY; import static org.eclipse.che.api.core.factory.FactoryParameter.Obligation.OPTIONAL; /** * @author Alexander Garagatyi */ @DTO public interface MachineConfigDto extends MachineConfig, Hyperlinks { @Override @FactoryParameter(obligation = OPTIONAL) String getName(); void setName(String name); MachineConfigDto withName(String name); @Override @FactoryParameter(obligation = MANDATORY) MachineSourceDto getSource(); void setSource(MachineSourceDto source); MachineConfigDto withSource(MachineSourceDto source); @Override @FactoryParameter(obligation = MANDATORY) boolean isDev(); void setDev(boolean dev); MachineConfigDto withDev(boolean dev); @Override @FactoryParameter(obligation = MANDATORY) String getType(); void setType(String type); MachineConfigDto withType(String type); @Override @FactoryParameter(obligation = OPTIONAL) LimitsDto getLimits(); void setLimits(LimitsDto limits); MachineConfigDto withLimits(LimitsDto limits); @Override List<ServerConfDto> getServers(); MachineConfigDto withServers(List<ServerConfDto> servers); @Override Map<String, String> getEnvVariables(); MachineConfigDto withEnvVariables(Map<String, String> envVariables); @Override MachineConfigDto withLinks(List<Link> links); }
epl-1.0
xored/q7.quality.mockups
plugins/com.xored.q7.quality.mockups.issues/src/com/xored/q7/quality/mockups/issues/parts/RCPTT351_DragAndDropAtTable.java
6609
package com.xored.q7.quality.mockups.issues.parts; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.viewers.BaseLabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerDropAdapter; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.dnd.TransferData; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Text; import com.xored.q7.quality.mockups.issues.BaseMockupPart; public class RCPTT351_DragAndDropAtTable extends BaseMockupPart { public class TableLabelProvider extends BaseLabelProvider implements ITableLabelProvider { @Override public void addListener(ILabelProviderListener listener) { } @Override public void dispose() { } @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public void removeListener(ILabelProviderListener listener) { } @Override public Image getColumnImage(Object element, int columnIndex) { return null; } @Override public String getColumnText(Object element, int columnIndex) { return element.toString(); } } public class TableContentProvider implements IStructuredContentProvider { @Override public void dispose() { } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } @Override public Object[] getElements(Object inputElement) { @SuppressWarnings("unchecked") List<String> list = (List<String>) inputElement; return list.toArray(); } } public class MyDragListener implements DragSourceListener { private final TableViewer viewer; public MyDragListener(TableViewer viewer) { this.viewer = viewer; } @Override public void dragFinished(DragSourceEvent event) { } @Override public void dragSetData(DragSourceEvent event) { IStructuredSelection selection = (IStructuredSelection) viewer .getSelection(); String firstElement = (String) selection.getFirstElement(); if (TextTransfer.getInstance().isSupportedType(event.dataType)) { event.data = firstElement; } } @Override public void dragStart(DragSourceEvent event) { } } public class MyDropListener extends ViewerDropAdapter { private int location = 2; private final Viewer viewer; private String current = ""; public MyDropListener(Viewer viewer) { super(viewer); this.viewer = viewer; } @Override public void drop(DropTargetEvent event) { location = this.determineLocation(event); if (event.item != null) { current = event.item.getData().toString(); } super.drop(event); } @Override public boolean performDrop(Object data) { @SuppressWarnings("unchecked") List<String> input = (List<String>) viewer.getInput(); switch (location) { case 1: log(data.toString() + " > Dropped before the target"); input.add(0, data.toString()); break; case 2: log(data.toString() + " > Dropped after the target"); input.add(data.toString()); break; case 3: log(data.toString() + " > Dropped on the target"); int k = 0; for (int i = 0; i < input.size(); i++) { if (input.get(i).equals(current)) { k = i; break; } } input.remove(k); input.add(k, data.toString()); break; case 4: log(data.toString() + " > Dropped into nothing"); input.add(0, data.toString()); break; } viewer.setInput(input); return false; } @Override public boolean validateDrop(Object target, int operation, TransferData transferType) { return true; } } private Composite composite = null; private Text text = null; @Override public Control construct(Composite parent) { composite = createComposit(parent); TableViewer tableA = createTable(composite, getItemsForA()); TableViewer tableB = createTable(composite, getItemsForB()); TableViewer tableC = createTable(composite, getItemsForC()); int operations = DND.DROP_COPY | DND.DROP_MOVE; Transfer[] transferTypes = new Transfer[] { TextTransfer.getInstance() }; tableA.addDragSupport(operations, transferTypes, new MyDragListener(tableA)); tableC.addDragSupport(operations, transferTypes, new MyDragListener(tableC)); tableB.addDropSupport(operations, transferTypes, new MyDropListener(tableB)); text = new Text(parent, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); text.setLayoutData(new GridData(GridData.FILL_BOTH)); return null; } private Composite createComposit(Composite parent) { composite = new Composite(parent, SWT.FILL); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.FILL) .grab(true, true).applyTo(composite); GridLayoutFactory.swtDefaults().numColumns(4).applyTo(composite); return composite; } private TableViewer createTable(Composite shell, List<String> items) { TableViewer viewer = new TableViewer(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new TableContentProvider()); viewer.setLabelProvider(new TableLabelProvider()); viewer.setInput(items); GridDataFactory.swtDefaults().align(SWT.FILL, SWT.FILL) .grab(true, true).applyTo(viewer.getControl()); return viewer; } private List<String> getItemsForA() { List<String> itemsA = new ArrayList<String>(); itemsA.add("Indigo"); itemsA.add("Juno"); itemsA.add("Kepler"); itemsA.add("Luna"); itemsA.add("Mars"); return itemsA; } private List<String> getItemsForB() { List<String> itemsB = new ArrayList<String>(); itemsB.add("Default"); return itemsB; } private List<String> getItemsForC() { List<String> itemsC = new ArrayList<String>(); itemsC.add("Callisto"); itemsC.add("Europa"); itemsC.add("Ganymede"); itemsC.add("Galileo"); itemsC.add("Helios"); return itemsC; } public void log(String string) { text.setText(text.getText() + string + "\n"); } }
epl-1.0
eroslevi/titan.EclipsePlug-ins
org.eclipse.titan.designer/src/org/eclipse/titan/designer/AST/ASN1/definitions/ImportModule.java
9402
/****************************************************************************** * Copyright (c) 2000-2016 Ericsson Telecom AB * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.eclipse.titan.designer.AST.ASN1.definitions; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.eclipse.titan.designer.AST.ASTVisitor; import org.eclipse.titan.designer.AST.Assignment; import org.eclipse.titan.designer.AST.Assignments; import org.eclipse.titan.designer.AST.FieldSubReference; import org.eclipse.titan.designer.AST.ISubReference; import org.eclipse.titan.designer.AST.Identifier; import org.eclipse.titan.designer.AST.Module; import org.eclipse.titan.designer.AST.ModuleImportation; import org.eclipse.titan.designer.AST.ModuleImportationChain; import org.eclipse.titan.designer.AST.Reference; import org.eclipse.titan.designer.AST.Scope; import org.eclipse.titan.designer.AST.ASN1.Defined_Reference; import org.eclipse.titan.designer.editors.ProposalCollector; import org.eclipse.titan.designer.editors.actions.DeclarationCollector; import org.eclipse.titan.designer.graphics.ImageCache; import org.eclipse.titan.designer.parsers.CompilationTimeStamp; import org.eclipse.titan.designer.parsers.GlobalParser; import org.eclipse.titan.designer.parsers.ProjectSourceParser; /** * Import module. * Models an asn.1 module of the section IMPORTS in the parent asn1.module * * @author Kristof Szabados */ public final class ImportModule extends ModuleImportation { public static final String MISSINGMODULE = "There is no ASN.1 module with name `{0}''"; private static final String NOTASN1MODULE = "The module referred by `{0}'' is not an ASN.1 module"; private static final String SYMBOLNOTEXPORTED = "Symbol `{0}'' is not exported from module `{1}''"; /** imported symbols FROM this module */ private final Symbols symbols; public ImportModule(final Identifier identifier, final Symbols symbols) { super(identifier); this.identifier = identifier; this.symbols = (null == symbols) ? new Symbols() : symbols; } @Override public String chainedDescription() { return (null != identifier) ? identifier.getDisplayName() : null; } /** @return the symbols to be imported from this imported module */ public Symbols getSymbols() { return symbols; } /** * Checks if a given symbol is imported through this importation. * * @param identifier * the identifier to search for. * * @return true if a symbol with this identifier is imported, false * otherwise. * */ public boolean hasSymbol(final Identifier identifier) { return symbols.hasSymbol(identifier.getName()); } @Override public void checkImports(final CompilationTimeStamp timestamp, final ModuleImportationChain referenceChain, final List<Module> moduleStack) { if (null != lastImportCheckTimeStamp && !lastImportCheckTimeStamp.isLess(timestamp)) { return; } Module temp = referredModule; referredModule = null; symbols.checkUniqueness(timestamp); final ProjectSourceParser parser = GlobalParser.getProjectSourceParser(project); if (null == parser || null == identifier) { lastImportCheckTimeStamp = timestamp; //FIXME: is it correct? lastImportCheckTimeStamp will be set in extreme case only - very early running return; } referredModule = parser.getModuleByName(identifier.getName()); if (temp != referredModule) { setUnhandledChange(true); } if (referredModule == null) { identifier.getLocation().reportSemanticError(MessageFormat.format(MISSINGMODULE, identifier.getDisplayName())); } else { if (!(referredModule instanceof ASN1Module)) { identifier.getLocation().reportSemanticError(MessageFormat.format(NOTASN1MODULE, identifier.getDisplayName())); lastImportCheckTimeStamp = timestamp; referredModule = null; return; } moduleStack.add(referredModule); if (!referenceChain.add(this)) { moduleStack.remove(moduleStack.size() - 1); lastImportCheckTimeStamp = timestamp; return; } referredModule.checkImports(timestamp, referenceChain, moduleStack); for (int i = 0; i < symbols.size(); i++) { Identifier id = symbols.getNthElement(i); List<ISubReference> list = new ArrayList<ISubReference>(); list.add(new FieldSubReference(id)); Defined_Reference reference = new Defined_Reference(null, list); reference.setLocation(identifier.getLocation()); if (null != referredModule.getAssBySRef(timestamp, reference)) { if (!((ASN1Module) referredModule).exportsSymbol(timestamp, id)) { identifier.getLocation().reportSemanticError( MessageFormat.format(SYMBOLNOTEXPORTED, id.getDisplayName(), referredModule .getIdentifier().getDisplayName())); } } } moduleStack.remove(moduleStack.size() - 1); } lastImportCheckTimeStamp = timestamp; } @Override public void check(final CompilationTimeStamp timestamp) { if (lastImportCheckTimeStamp != null && !lastImportCheckTimeStamp.isLess(timestamp)) { return; } usedForImportation = false; } @Override public boolean hasImportedAssignmentWithID(final CompilationTimeStamp timestamp, final Identifier identifier) { if (referredModule == null) { return false; } final Assignments assignments = referredModule.getAssignments(); if (assignments != null && assignments.hasLocalAssignmentWithID(timestamp, identifier)) { return true; } return false; } @Override public Assignment importAssignment(final CompilationTimeStamp timestamp, final ModuleImportationChain referenceChain, final Identifier moduleId, final Reference reference, final List<ModuleImportation> usedImports) { // referenceChain is not used since this can only be the // endpoint of an importation chain. if (referredModule == null) { return null; } final Assignment result = referredModule.importAssignment(timestamp, moduleId, reference); if (result != null) { usedImports.add(this); setUsedForImportation(); } return result; } /** * Adds the imported module or definitions contained in it, to the list * completion proposals. * * @param propCollector * the proposal collector. * @param targetModuleId * the identifier of the module where the definition will * be inserted. It is used to check if it is visible * there or not. * */ @Override public void addProposal(final ProposalCollector propCollector, final Identifier targetModuleId) { List<ISubReference> subrefs = propCollector.getReference().getSubreferences(); if (propCollector.getReference().getModuleIdentifier() == null && subrefs.size() == 1) { propCollector.addProposal(identifier, ImageCache.getImage(getOutlineIcon()), KIND); } final Module savedReferredModule = referredModule; if (savedReferredModule != null) { Assignments assignments = savedReferredModule.getAssignments(); for (int i = 0, size = assignments.getNofAssignments(); i < size; i++) { Assignment temporalAssignment = assignments.getAssignmentByIndex(i); if (savedReferredModule.isVisible(CompilationTimeStamp.getBaseTimestamp(), targetModuleId, temporalAssignment)) { temporalAssignment.addProposal(propCollector, 0); } } } } /** * Adds the imported module or definitions contained in it, to the list * declaration proposals. * * @param declarationCollector * the declaration collector. * @param targetModuleId * the identifier of the module where the declaration * should be inserted into. * */ @Override public void addDeclaration(final DeclarationCollector declarationCollector, final Identifier targetModuleId) { final Module savedReferredModule = referredModule; if (savedReferredModule != null) { Assignments assignments = savedReferredModule.getAssignments(); for (int i = 0; i < assignments.getNofAssignments(); i++) { Assignment temporalAssignment = assignments.getAssignmentByIndex(i); if (savedReferredModule.isVisible(CompilationTimeStamp.getBaseTimestamp(), targetModuleId, temporalAssignment)) { temporalAssignment.addDeclaration(declarationCollector, 0); } } Identifier moduleId = declarationCollector.getReference().getModuleIdentifier(); List<ISubReference> subrefs = declarationCollector.getReference().getSubreferences(); if (moduleId == null && subrefs.size() == 1 && identifier.getName().equals(subrefs.get(0).getId().getName())) { declarationCollector.addDeclaration(savedReferredModule.getIdentifier().getDisplayName(), savedReferredModule .getIdentifier().getLocation(), (Scope) null); } } } @Override public boolean accept(final ASTVisitor v) { switch (v.visit(this)) { case ASTVisitor.V_ABORT: return false; case ASTVisitor.V_SKIP: return true; } if (identifier != null && !identifier.accept(v)) { return false; } if (symbols != null && !symbols.accept(v)) { return false; } if (v.leave(this) == ASTVisitor.V_ABORT) { return false; } return true; } }
epl-1.0
collaborative-modeling/egit
org.eclipse.egit.core/src/org/eclipse/egit/core/project/GitProjectData.java
23134
/******************************************************************************* * Copyright (C) 2008, Robin Rosenberg <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * Copyright (C) 2008, Google Inc. * Copyright (C) 2015, IBM Corporation (Dani Megert <[email protected]>) * Copyright (C) 2016, Thomas Wolf <[email protected]> * Copyright (C) 2016, Andre Bossert <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.core.project; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.preferences.DefaultScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.egit.core.Activator; import org.eclipse.egit.core.GitCorePreferences; import org.eclipse.egit.core.JobFamilies; import org.eclipse.egit.core.internal.CoreText; import org.eclipse.egit.core.internal.Utils; import org.eclipse.egit.core.internal.trace.GitTraceLocation; import org.eclipse.egit.core.internal.util.ResourceUtil; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.annotations.Nullable; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryCache; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.storage.file.WindowCacheConfig; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.FileUtils; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.TeamException; /** * This class keeps information about how a project is mapped to * a Git repository. */ public class GitProjectData { private static final Map<IProject, GitProjectData> projectDataCache = new HashMap<IProject, GitProjectData>(); private static Set<RepositoryMappingChangeListener> repositoryChangeListeners = new HashSet<RepositoryMappingChangeListener>(); @SuppressWarnings("synthetic-access") private static final IResourceChangeListener rcl = new RCL(); private static class RCL implements IResourceChangeListener { @Override @SuppressWarnings("synthetic-access") public void resourceChanged(final IResourceChangeEvent event) { switch (event.getType()) { case IResourceChangeEvent.PRE_CLOSE: uncache((IProject) event.getResource()); break; case IResourceChangeEvent.PRE_DELETE: try { delete((IProject) event.getResource()); } catch (IOException e) { Activator.logError(e.getMessage(), e); } break; case IResourceChangeEvent.POST_CHANGE: update(event); break; default: break; } } } private static QualifiedName MAPPING_KEY = new QualifiedName( GitProjectData.class.getName(), "RepositoryMapping"); //$NON-NLS-1$ /** * Start listening for resource changes. */ public static void attachToWorkspace() { trace("attachToWorkspace - addResourceChangeListener"); //$NON-NLS-1$ ResourcesPlugin.getWorkspace().addResourceChangeListener( rcl, IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE); } /** * Stop listening to resource changes */ public static void detachFromWorkspace() { trace("detachFromWorkspace - removeResourceChangeListener"); //$NON-NLS-1$ ResourcesPlugin.getWorkspace().removeResourceChangeListener(rcl); } /** * Register a new listener for repository modification events. * <p> * This is a no-op if <code>objectThatCares</code> has already been * registered. * </p> * * @param objectThatCares * the new listener to register. Must not be null. */ public static synchronized void addRepositoryChangeListener( final RepositoryMappingChangeListener objectThatCares) { if (objectThatCares == null) throw new NullPointerException(); repositoryChangeListeners.add(objectThatCares); } /** * Remove a registered {@link RepositoryMappingChangeListener} * * @param objectThatCares * The listener to remove */ public static synchronized void removeRepositoryChangeListener( final RepositoryMappingChangeListener objectThatCares) { repositoryChangeListeners.remove(objectThatCares); } /** * Notify registered {@link RepositoryMappingChangeListener}s of a change. * * @param which * the repository which has had changes occur within it. */ static void fireRepositoryChanged(final RepositoryMapping which) { Job job = new Job(CoreText.GitProjectData_repositoryChangedJobName) { @Override protected IStatus run(IProgressMonitor monitor) { RepositoryMappingChangeListener[] listeners = getRepositoryChangeListeners(); monitor.beginTask( CoreText.GitProjectData_repositoryChangedTaskName, listeners.length); for (RepositoryMappingChangeListener listener : listeners) { listener.repositoryChanged(which); monitor.worked(1); } monitor.done(); return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { if (JobFamilies.REPOSITORY_CHANGED.equals(family)) return true; return super.belongsTo(family); } }; job.schedule(); } /** * Get a copy of the current set of repository change listeners * <p> * The array has no references, so is safe for iteration and modification * * @return a copy of the current repository change listeners */ private static synchronized RepositoryMappingChangeListener[] getRepositoryChangeListeners() { return repositoryChangeListeners .toArray(new RepositoryMappingChangeListener[repositoryChangeListeners .size()]); } /** * @param p * @return {@link GitProjectData} for the specified project, or null if the * Git provider is not associated with the project or an exception * occurred */ @Nullable public synchronized static GitProjectData get(final @NonNull IProject p) { try { GitProjectData d = lookup(p); if (d == null && ResourceUtil.isSharedWithGit(p)) { d = new GitProjectData(p).load(); cache(p, d); } return d; } catch (IOException err) { Activator.logError(CoreText.GitProjectData_missing, err); return null; } } /** * Drop the Eclipse project from our association of projects/repositories * * @param p * Eclipse project * @throws IOException * if deletion of property files failed */ public static void delete(final IProject p) throws IOException { trace("delete(" + p.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ GitProjectData d = lookup(p); if (d == null) deletePropertyFiles(p); else d.deletePropertyFilesAndUncache(); } /** * Drop the Eclipse project from our association of projects/repositories * and remove all RepositoryMappings. * * @param p * to deconfigure * @throws IOException * if the property file cannot be removed. */ public static void deconfigure(final IProject p) throws IOException { trace("deconfigure(" + p.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ GitProjectData d = lookup(p); if (d == null) { deletePropertyFiles(p); } else { d.deletePropertyFilesAndUncache(); unmap(d); } } /** * Add the Eclipse project to our association of projects/repositories * * @param p * Eclipse project * @param d * {@link GitProjectData} associated with this project */ public static void add(final IProject p, final GitProjectData d) { trace("add(" + p.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ cache(p, d); } /** * Update mappings of EGit-managed projects in response to new DOT_GIT * repositories appearing. * * @param event * A {@link IResourceChangeEvent#POST_CHANGE} event */ public static void update(IResourceChangeEvent event) { // If the project is EGit-managed, let's see if this added any DOT_GIT // files or folders. If so, update the project's RepositoryMappings // and then mark as team private, if anything added. We won't get // deletions of DOT_GIT directories or files here, those are // "protected" and the GitMoveDeleteHook will prevent their deletion -- // the project has to be disconnected first. final Set<GitProjectData> modified = new HashSet<>(); try { event.getDelta().accept(new IResourceDeltaVisitor() { @Override public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); int type = resource.getType(); if (type == IResource.ROOT) { return true; } else if (type == IResource.PROJECT) { return (delta.getKind() & (IResourceDelta.ADDED | IResourceDelta.CHANGED)) != 0 && ResourceUtil.isSharedWithGit(resource); } // Files & folders if ((delta.getKind() & (IResourceDelta.ADDED | IResourceDelta.CHANGED)) == 0 || resource.isLinked()) { return false; } IPath location = resource.getLocation(); if (location == null) { return false; } if (!Constants.DOT_GIT.equals(resource.getName())) { return type == IResource.FOLDER; } // A file or folder named .git File gitCandidate = location.toFile().getParentFile(); File git = new FileRepositoryBuilder() .addCeilingDirectory(gitCandidate) .findGitDir(gitCandidate).getGitDir(); if (git == null) { return false; } // Yes, indeed a valid git directory. GitProjectData data = get(resource.getProject()); if (data == null) { return false; } RepositoryMapping m = RepositoryMapping .create(resource.getParent(), git); // Is its working directory really here? If not, // a submodule folder may have been copied. try { Repository r = Activator.getDefault() .getRepositoryCache().lookupRepository(git); if (m != null && r != null && !r.isBare() && gitCandidate.equals(r.getWorkTree())) { if (data.map(m)) { data.mappings.put(m.getContainerPath(), m); modified.add(data); } } } catch (IOException e) { Activator.logError(e.getMessage(), e); } return false; } }); } catch (CoreException e) { Activator.logError(e.getMessage(), e); } finally { for (GitProjectData data : modified) { try { data.store(); } catch (CoreException e) { Activator.logError(e.getMessage(), e); } } } } static void trace(final String m) { // TODO is this the right location? if (GitTraceLocation.CORE.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.CORE.getLocation(), "(GitProjectData) " + m); //$NON-NLS-1$ } private synchronized static void cache(final IProject p, final GitProjectData d) { projectDataCache.put(p, d); } private synchronized static void uncache(final IProject p) { if (projectDataCache.remove(p) != null) { trace("uncacheDataFor(" //$NON-NLS-1$ + p.getName() + ")"); //$NON-NLS-1$ } } private static void unmap(GitProjectData data) { for (RepositoryMapping m : data.mappings.values()) { IContainer c = m.getContainer(); if (c != null && c.isAccessible()) { try { c.setSessionProperty(MAPPING_KEY, null); // Team private members are re-set in // DisconnectProviderOperation } catch (CoreException e) { Activator.logWarning(MessageFormat.format( CoreText.GitProjectData_failedToUnmapRepoMapping, c.getFullPath()), e); } } } } private synchronized static GitProjectData lookup(final IProject p) { return projectDataCache.get(p); } /** * Update the settings for the global window cache of the workspace. */ public static void reconfigureWindowCache() { final WindowCacheConfig c = new WindowCacheConfig(); IEclipsePreferences d = DefaultScope.INSTANCE.getNode(Activator.getPluginId()); IEclipsePreferences p = InstanceScope.INSTANCE.getNode(Activator.getPluginId()); c.setPackedGitLimit(p.getInt(GitCorePreferences.core_packedGitLimit, d.getInt(GitCorePreferences.core_packedGitLimit, 0))); c.setPackedGitWindowSize(p.getInt(GitCorePreferences.core_packedGitWindowSize, d.getInt(GitCorePreferences.core_packedGitWindowSize, 0))); c.setPackedGitMMAP(p.getBoolean(GitCorePreferences.core_packedGitMMAP, d.getBoolean(GitCorePreferences.core_packedGitMMAP, false))); c.setDeltaBaseCacheLimit(p.getInt(GitCorePreferences.core_deltaBaseCacheLimit, d.getInt(GitCorePreferences.core_deltaBaseCacheLimit, 0))); c.setStreamFileThreshold(p.getInt(GitCorePreferences.core_streamFileThreshold, d.getInt(GitCorePreferences.core_streamFileThreshold, 0))); c.install(); } private final IProject project; private final Map<IPath, RepositoryMapping> mappings = new HashMap<>(); private final Set<IResource> protectedResources = new HashSet<IResource>(); /** * Construct a {@link GitProjectData} for the mapping * of a project. * * @param p Eclipse project */ public GitProjectData(final IProject p) { project = p; } /** * @return the Eclipse project mapped through this resource. */ public IProject getProject() { return project; } /** * Set repository mappings * * @param newMappings */ public void setRepositoryMappings(final Collection<RepositoryMapping> newMappings) { mappings.clear(); for (RepositoryMapping mapping : newMappings) { mappings.put(mapping.getContainerPath(), mapping); } remapAll(); } /** * Get repository mappings * * @return the repository mappings for a project */ public final Map<IPath, RepositoryMapping> getRepositoryMappings() { return mappings; } /** * Hide our private parts from the navigators other browsers. * * @throws CoreException */ public void markTeamPrivateResources() throws CoreException { for (final RepositoryMapping rm : mappings.values()) { final IContainer c = rm.getContainer(); if (c == null) continue; // Not fully mapped yet? final IResource dotGit = c.findMember(Constants.DOT_GIT); if (dotGit != null) { try { final Repository r = rm.getRepository(); final File dotGitDir = dotGit.getLocation().toFile() .getCanonicalFile(); // TODO: .git *files* with gitdir: "redirect" // TODO: check whether Repository.getDirectory() is // canonicalized! If not, this check will fail anyway. if (dotGitDir.equals(r.getDirectory())) { trace("teamPrivate " + dotGit); //$NON-NLS-1$ dotGit.setTeamPrivateMember(true); } } catch (IOException err) { throw new CoreException(Activator.error(CoreText.Error_CanonicalFile, err)); } } } } /** * Determines whether the project this instance belongs to has any inner * repositories like submodules or nested repositories. * * @return {@code true} if the project has inner repositories; {@code false} * otherwise. */ public boolean hasInnerRepositories() { return !protectedResources.isEmpty(); } /** * @param f * @return true if a resource is protected in this repository */ public boolean isProtected(final IResource f) { return protectedResources.contains(f); } /** * @param resource any workbench resource contained within this project. * @return the mapping for the specified project */ @Nullable public /* TODO static */ RepositoryMapping getRepositoryMapping( @Nullable IResource resource) { IResource r = resource; try { for (; r != null; r = r.getParent()) { final RepositoryMapping m; if (!r.isAccessible()) continue; m = (RepositoryMapping) r.getSessionProperty(MAPPING_KEY); if (m != null) return m; } } catch (CoreException err) { Activator.logError( CoreText.GitProjectData_failedFindingRepoMapping, err); } return null; } private void deletePropertyFilesAndUncache() throws IOException { deletePropertyFiles(getProject()); uncache(getProject()); } private static void deletePropertyFiles(IProject project) throws IOException { final File dir = propertyFile(project).getParentFile(); FileUtils.delete(dir, FileUtils.RECURSIVE); trace("deleteDataFor(" //$NON-NLS-1$ + project.getName() + ")"); //$NON-NLS-1$ } /** * Store information about the repository connection in the workspace * * @throws CoreException */ public void store() throws CoreException { final File dat = propertyFile(); final File tmp; boolean ok = false; try { trace("save " + dat); //$NON-NLS-1$ tmp = File.createTempFile( "gpd_", //$NON-NLS-1$ ".prop", //$NON-NLS-1$ dat.getParentFile()); final FileOutputStream o = new FileOutputStream(tmp); try { final Properties p = new Properties(); for (final RepositoryMapping repoMapping : mappings.values()) { repoMapping.store(p); } p.store(o, "GitProjectData"); //$NON-NLS-1$ ok = true; } finally { o.close(); if (!ok && tmp.exists()) { FileUtils.delete(tmp); } } if (dat.exists()) FileUtils.delete(dat); if (!tmp.renameTo(dat)) { if (tmp.exists()) FileUtils.delete(tmp); throw new CoreException( Activator.error(NLS.bind( CoreText.GitProjectData_saveFailed, dat), null)); } } catch (IOException ioe) { throw new CoreException(Activator.error( NLS.bind(CoreText.GitProjectData_saveFailed, dat), ioe)); } } private File propertyFile() { return propertyFile(getProject()); } private static File propertyFile(IProject project) { return new File(project.getWorkingLocation(Activator.getPluginId()) .toFile(), "GitProjectData.properties"); //$NON-NLS-1$ } private GitProjectData load() throws IOException { final File dat = propertyFile(); trace("load " + dat); //$NON-NLS-1$ final FileInputStream o = new FileInputStream(dat); try { final Properties p = new Properties(); p.load(o); mappings.clear(); for (final Object keyObj : p.keySet()) { final String key = keyObj.toString(); if (RepositoryMapping.isInitialKey(key)) { RepositoryMapping mapping = new RepositoryMapping(p, key); mappings.put(mapping.getContainerPath(), mapping); } } } finally { o.close(); } if (!remapAll()) { try { store(); } catch (CoreException e) { IStatus status = e.getStatus(); Activator.logError(status.getMessage(), status.getException()); } } return this; } private boolean remapAll() { protectedResources.clear(); boolean allMapped = true; Iterator<RepositoryMapping> iterator = mappings.values().iterator(); while (iterator.hasNext()) { RepositoryMapping m = iterator.next(); if (!map(m)) { iterator.remove(); allMapped = false; } } return allMapped; } private boolean map(final RepositoryMapping m) { final IResource r; final File git; final IResource dotGit; IContainer c = null; m.clear(); r = getProject().findMember(m.getContainerPath()); if (r instanceof IContainer) { c = (IContainer) r; } else if (r != null) { c = Utils.getAdapter(r, IContainer.class); } if (c == null) { logAndUnmapGoneMappedResource(m, null); return false; } m.setContainer(c); IPath absolutePath = m.getGitDirAbsolutePath(); if (absolutePath == null) { logAndUnmapGoneMappedResource(m, c); return false; } git = absolutePath.toFile(); if (!RepositoryCache.FileKey.isGitRepository(git, FS.DETECTED)) { logAndUnmapGoneMappedResource(m, c); return false; } try { m.setRepository(Activator.getDefault().getRepositoryCache() .lookupRepository(git)); } catch (IOException ioe) { logAndUnmapGoneMappedResource(m, c); return false; } trace("map " //$NON-NLS-1$ + c + " -> " //$NON-NLS-1$ + m.getRepository()); try { c.setSessionProperty(MAPPING_KEY, m); } catch (CoreException err) { Activator.logError( CoreText.GitProjectData_failedToCacheRepoMapping, err); } dotGit = c.findMember(Constants.DOT_GIT); if (dotGit != null) { protect(dotGit); } fireRepositoryChanged(m); return true; } private void logAndUnmapGoneMappedResource(final RepositoryMapping m, final IContainer c) { Activator.logError(MessageFormat.format( CoreText.GitProjectData_mappedResourceGone, m.toString()), new FileNotFoundException(m.getContainerPath().toString())); m.clear(); if (c instanceof IProject) { UnmapJob unmapJob = new UnmapJob((IProject) c); unmapJob.schedule(); } else if (c != null) { try { c.setSessionProperty(MAPPING_KEY, null); } catch (CoreException e) { Activator.logWarning(MessageFormat.format( CoreText.GitProjectData_failedToUnmapRepoMapping, c.getFullPath()), e); } } } private void protect(IResource resource) { IResource c = resource; try { c.setTeamPrivateMember(true); } catch (CoreException e) { Activator.logError(MessageFormat.format( CoreText.GitProjectData_FailedToMarkTeamPrivate, c.getFullPath()), e); } while (c != null && !c.equals(getProject())) { trace("protect " + c); //$NON-NLS-1$ protectedResources.add(c); c = c.getParent(); } } private static class UnmapJob extends Job { private final IProject project; private UnmapJob(IProject project) { super(MessageFormat.format(CoreText.GitProjectData_UnmapJobName, project.getName())); this.project = project; } @Override protected IStatus run(IProgressMonitor monitor) { try { RepositoryProvider.unmap(project); return Status.OK_STATUS; } catch (TeamException e) { return new Status(IStatus.ERROR, Activator.getPluginId(), MessageFormat.format( CoreText.GitProjectData_UnmappingGoneResourceFailed, project.getName()), e); } } } }
epl-1.0
paulianttila/openhab
bundles/binding/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/communication/Device.java
1585
/** * Copyright (c) 2010-2014, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.pilight.internal.communication; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; /** * Class describing a device in pilight * * @author Jeroen Idserda * @since 1.0 */ @JsonIgnoreProperties(ignoreUnknown=true) public class Device { private String name; private String state; private Integer dimlevel; private Integer dimlevelMaximum; private Integer dimlevelMinimum; public Device() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Integer getDimlevel() { return dimlevel; } public void setDimlevel(Integer dimlevel) { this.dimlevel = dimlevel; } public Integer getDimlevelMaximum() { return dimlevelMaximum; } @JsonProperty("dimlevel-maximum") public void setDimlevelMaximum(Integer dimlevelMaximum) { this.dimlevelMaximum = dimlevelMaximum; } public Integer getDimlevelMinimum() { return dimlevelMinimum; } @JsonProperty("dimlevel-minimum") public void setDimlevelMinimum(Integer dimlevelMinimum) { this.dimlevelMinimum = dimlevelMinimum; } }
epl-1.0
boniatillo-com/PhaserEditor
source/v2/phasereditor/phasereditor.project.core/src/phasereditor/project/core/codegen/JSClassGenerator.java
1942
// The MIT License (MIT) // // Copyright (c) 2015, 2017 Arian Fornaris // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: The above copyright notice and this permission // notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. package phasereditor.project.core.codegen; /** * @author arian * */ public class JSClassGenerator extends BaseCodeGenerator { private String _clsname; private String _baseClass; private boolean _hasBaseClass; public JSClassGenerator(String clsname, String baseClass) { this._clsname = clsname; this._baseClass = baseClass; _hasBaseClass = baseClass != null && baseClass.trim().length() > 0; } @Override protected void internalGenerate() { line("/**"); line(" *"); line(" */"); openIndent("class " + _clsname + (_hasBaseClass ? " extends " + _baseClass : " ") + "{"); line(); openIndent("constructor() {"); if (_hasBaseClass) { line("super();"); } closeIndent("}"); closeIndent("}"); line(); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.legacy_fat/test-applications/EJB2XRemoteSpecWeb.war/src/com/ibm/ejb2x/base/spec/slr/web/SLRemoteHomeCreateServlet.java
3897
/******************************************************************************* * Copyright (c) 2002, 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ejb2x.base.spec.slr.web; import static org.junit.Assert.assertNotNull; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.naming.NamingException; import javax.servlet.annotation.WebServlet; import org.junit.Test; import com.ibm.ejb2x.base.spec.slr.ejb.SLRa; import com.ibm.ejb2x.base.spec.slr.ejb.SLRaHome; import com.ibm.websphere.ejbcontainer.test.tools.FATHelper; import componenttest.app.FATServlet; /** * <dl> * <dt>Test Name: * <dd>SLRemoteHomeCreateTest (formerly WSTestSLR_HCTest) * * <dt>Test Descriptions: * <dd>EJB Container basic function tests: * <ul> * <li>H____ - Home Interface / EJBHome / EJBLocalHome; * <li>HCS__ - Home create( short-arg ); * <li>HCL__ - Home create( long-arg ). * </ul> * * <dt>Command options: * <dd> * <TABLE width="100%"> * <COL span="1" width="25%" align="left"> <COL span="1" align="left"> * <TBODY> * <TR> <TH>Option</TH> <TH>Description</TH> </TR> * <TR> <TD>None</TD> * <TD></TD> * </TR> * </TBODY> * </TABLE> * * <dt>Test Matrix: * <dd> * <br>Sub-tests * <ul> * <li>hcs01 - testHomeCreate - create() * <li>hcs02 - testHomeCreateWithKey - create( pk ) * <li>hcs03 - testHomeCreateWithDuplicateKey - create( pk ) - Duplicate key * <li>hcl01 - testHomeCreateWithMultiArgs - create( long-args ) * <li>hcl02 - testHomeCreateWithDuplicateMultiArgs - create( long-args ) - Duplicate key * </ul> * <br>Data Sources * </dl> */ @SuppressWarnings("serial") @WebServlet("/SLRemoteHomeCreateServlet") public class SLRemoteHomeCreateServlet extends FATServlet { private final static String CLASS_NAME = SLRemoteHomeCreateServlet.class.getName(); private final static Logger svLogger = Logger.getLogger(CLASS_NAME); private final static String ejbJndiName1 = "com/ibm/ejb2x/base/spec/slr/ejb/SLRaBMTHome"; private static SLRaHome fhome1; @PostConstruct private void initializeHomes() { try { fhome1 = FATHelper.lookupRemoteHomeBinding(ejbJndiName1, SLRaHome.class); } catch (NamingException e) { throw new RuntimeException(e); } } /** * (hcs01) Test Stateless remote home create (no parameters) */ @Test public void testSLRemoteHomeCreate() throws Exception { SLRa ejb1 = fhome1.create(); assertNotNull("Create EJB was null.", ejb1); ejb1.remove(); } /** * (hcs02) Test Stateless remote home create (with primary key) */ //@Test public void testSLRemoteHomeCreateWithKey() { svLogger.info("This test does not apply to Stateless beans."); } /** * (hcs03) Test Stateless remote home create (with duplicate primary key) */ //@Test public void testSLRemoteHomeCreateWithDuplicateKey() { svLogger.info("This test does not apply to Stateless beans."); } /** * (hcl01) Test Stateless remote home create (with multiple args) */ //@Test public void testSLRemoteHomeCreateWithMultiArgs() { svLogger.info("This test does not apply to Stateless beans."); } /** * (hcl02) Test Stateless remote home create (with duplicate multiple args) */ //@Test public void testSLRemoteHomeCreateWithDuplicateMultiArgs() { svLogger.info("This test does not apply to Stateless beans."); } }
epl-1.0
opendaylight/packetcable
packetcable-driver/src/main/java/org/pcmm/objects/PCMMResource.java
486
/* * Copyright (c) 2014 Cable Television Laboratories, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.pcmm.objects; /** * * This class is a holder for PCMM objects. This class is intended to be * sub-classed * */ public class PCMMResource { }
epl-1.0
aschmois/ForgeEssentialsMain
src/main/java/com/forgeessentials/backup/AutoWorldSave.java
564
package com.forgeessentials.backup; import net.minecraftforge.common.DimensionManager; import java.util.TimerTask; public class AutoWorldSave extends TimerTask { @Override public void run() { while (AutoBackup.isBackingUp) { try { Thread.sleep(1000); } catch (InterruptedException e) { return; } } for (int i : DimensionManager.getIDs()) { WorldSaver.addWorldNeedsSave(i); } } }
epl-1.0
FTSRG/trainbenchmark
trainbenchmark-tool-viatra-patterns/src-gen/hu/bme/mit/trainbenchmark/benchmark/viatra/util/SwitchMonitoredInjectProcessor.java
1076
/** * Generated from platform:/resource/trainbenchmark-tool-viatra-patterns/src/hu/bme/mit/trainbenchmark/benchmark/viatra/SwitchMonitoredInject.vql */ package hu.bme.mit.trainbenchmark.benchmark.viatra.util; import hu.bme.mit.trainbenchmark.benchmark.viatra.SwitchMonitoredInjectMatch; import hu.bme.mit.trainbenchmark.railway.Switch; import org.eclipse.viatra.query.runtime.api.IMatchProcessor; /** * A match processor tailored for the hu.bme.mit.trainbenchmark.benchmark.viatra.switchMonitoredInject pattern. * * Clients should derive an (anonymous) class that implements the abstract process(). * */ @SuppressWarnings("all") public abstract class SwitchMonitoredInjectProcessor implements IMatchProcessor<SwitchMonitoredInjectMatch> { /** * Defines the action that is to be executed on each match. * @param pSw the value of pattern parameter sw in the currently processed match * */ public abstract void process(final Switch pSw); @Override public void process(final SwitchMonitoredInjectMatch match) { process(match.getSw()); } }
epl-1.0