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/23071240.jsonp.js
150
jsonp({"cep":"23071240","logradouro":"Rua Jo\u00e3o Menezes","bairro":"Campo Grande","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/18271270.jsonp.js
155
jsonp({"cep":"18271270","logradouro":"Rua Martinho Machado","bairro":"Ch\u00e1cara Junqueira","cidade":"Tatu\u00ed","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/14164015.jsonp.js
157
jsonp({"cep":"14164015","logradouro":"Rua Anna Magro Soldera","bairro":"Jardim Liberdade","cidade":"Sert\u00e3ozinho","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/91720480.jsonp.js
138
jsonp({"cep":"91720480","logradouro":"Rua Costa Lima","bairro":"Nonoai","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
cc0-1.0
nobelprize-org/nomination-visualization-1
app/modules/settings/global-settings.js
3328
define(function (require) { var jquery = require('jquery'); var d3 = require('d3'); var active = d3.select(null); var width = 1000; var height = 500; var projectionScale = 200; var svg = buildSVG(width,height); var zoom = buildZoom(); var g = svg.append("g"); var projection = d3.geo.equirectangular().scale(projectionScale).translate([width / 2, height / 2]);; var path = d3.geo.path().projection(projection); svg.call(zoom) // delete this line to disable free zooming .call(zoom.event); var dc = require('dc'); var worldChart = dc.bubbleOverlay("#world-map").svg(d3.select("#world-map svg g")); var bubbleOverlay = require('bubbleOverlay'); var bubbleOverlayData = {}; var currentState = ""; function stopped() { if (d3.event.defaultPrevented) d3.event.stopPropagation(); }; function reset() { active.classed("active", false); active = d3.select(null); svg.transition() .duration(750) .call(zoom.translate([0, 0]).scale(1).event); }; function buildSVG(width,height){ var svg = d3.select("#map-container").append("div") .attr("id", "world-map") .append("svg") .attr("width", width) .attr("height", height) .on("click", stopped, true); svg.append("rect") .attr("class", "background") .attr("width", width) .attr("height", height) .on("click", reset); return svg; }; function buildZoom(){ var zoom = d3.behavior.zoom() .translate([0, 0]) .scale(1) .scaleExtent([1, 6]) .on("zoom", zoomed); return zoom; }; function zoomed() { g.style("stroke-width", 1.5 / d3.event.scale + "px"); g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); if(bubbleOverlayData){ var overlay = new bubbleOverlay(worldChart,bubbleOverlayData); overlay.render(d3.event.scale,currentState); } }; function clicked(d) { if (active.node() === this) return reset(); active.classed("active", false); active = d3.select(this).classed("active", true); var bounds = path.bounds(d), dx = bounds[1][0] - bounds[0][0], dy = bounds[1][1] - bounds[0][1], x = (bounds[0][0] + bounds[1][0]) / 2, y = (bounds[0][1] + bounds[1][1]) / 2, scale = 0.5 / Math.max(dx / width, dy / height), translate = [width / 2 - scale * x, height / 2 - scale * y]; svg.transition() .duration(750) .call(zoom.translate(translate).scale(scale).event); }; function GlobalSettings(){ }; GlobalSettings.prototype = { width : function(){ return width; }, height : function(){ return height; }, projectionScale : function(){ return projectionScale; }, projection : function(){ return projection; }, geoPathProjection : function(){ return path; }, svg : function(){ return svg; }, bubbleOverlayData : function(){ return bubbleOverlayData; }, setBubbleOverlayData : function(bubbles){ bubbleOverlayData = bubbles; }, worldChart : function(){ return worldChart; }, g : function(){ return g; }, clicked : function(){ return clicked; }, setState : function(state){ currentState = state; } }; return new GlobalSettings(); });
cc0-1.0
lfreneda/cepdb
api/v1/49025230.jsonp.js
133
jsonp({"cep":"49025230","logradouro":"Avenida Francisco Porto","bairro":"Jardins","cidade":"Aracaju","uf":"SE","estado":"Sergipe"});
cc0-1.0
lfreneda/cepdb
api/v1/29146690.jsonp.js
142
jsonp({"cep":"29146690","logradouro":"Rua Paiva","bairro":"S\u00e3o Geraldo","cidade":"Cariacica","uf":"ES","estado":"Esp\u00edrito Santo"});
cc0-1.0
lfreneda/cepdb
api/v1/83221570.jsonp.js
148
jsonp({"cep":"83221570","logradouro":"Avenida Portu\u00e1ria","bairro":"Dom Pedro II","cidade":"Paranagu\u00e1","uf":"PR","estado":"Paran\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/14402302.jsonp.js
142
jsonp({"cep":"14402302","logradouro":"Rua Manaus","bairro":"Jardim Brasil\u00e2ndia","cidade":"Franca","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/86801637.jsonp.js
156
jsonp({"cep":"86801637","logradouro":"Rua Jos\u00e9 Rezende","bairro":"Loteamento Jardim Gramados","cidade":"Apucarana","uf":"PR","estado":"Paran\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/20230026.jsonp.js
147
jsonp({"cep":"20230026","logradouro":"Rua Washington Lu\u00eds","bairro":"Centro","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/57055900.jsonp.js
156
jsonp({"cep":"57055900","logradouro":"Rua Professor Jos\u00e9 da Silveira Camerino","bairro":"Farol","cidade":"Macei\u00f3","uf":"AL","estado":"Alagoas"});
cc0-1.0
lfreneda/cepdb
api/v1/13059093.jsonp.js
168
jsonp({"cep":"13059093","logradouro":"Rua Pedro Alexandrino de Oliveira Filho","bairro":"Residencial Cosmos","cidade":"Campinas","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/74920490.jsonp.js
176
jsonp({"cep":"74920490","logradouro":"Rua Vasco dos Reis","bairro":"Cidade Sat\u00e9lite S\u00e3o Luiz","cidade":"Aparecida de Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
cc0-1.0
lfreneda/cepdb
api/v1/05532030.jsonp.js
165
jsonp({"cep":"05532030","logradouro":"Rua Pedro Peccinini","bairro":"Instituto de Previd\u00eancia","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/29312529.jsonp.js
161
jsonp({"cep":"29312529","logradouro":"Rua Hugo Zago","bairro":"Alto Monte Cristo","cidade":"Cachoeiro de Itapemirim","uf":"ES","estado":"Esp\u00edrito Santo"});
cc0-1.0
lfreneda/cepdb
api/v1/89204075.jsonp.js
141
jsonp({"cep":"89204075","logradouro":"Rua Augusto Urban","bairro":"Am\u00e9rica","cidade":"Joinville","uf":"SC","estado":"Santa Catarina"});
cc0-1.0
lfreneda/cepdb
api/v1/97507092.jsonp.js
133
jsonp({"cep":"97507092","logradouro":"Quadra V","bairro":"Rui Ramos","cidade":"Uruguaiana","uf":"RS","estado":"Rio Grande do Sul"});
cc0-1.0
lfreneda/cepdb
api/v1/40711072.jsonp.js
146
jsonp({"cep":"40711072","logradouro":"Avenida Get\u00falio Vargas","bairro":"Alto da Terezinha","cidade":"Salvador","uf":"BA","estado":"Bahia"});
cc0-1.0
lfreneda/cepdb
api/v1/27260400.jsonp.js
174
jsonp({"cep":"27260400","logradouro":"Pra\u00e7a dos Expedicion\u00e1rios","bairro":"Vila Santa Cec\u00edlia","cidade":"Volta Redonda","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/60543322.jsonp.js
147
jsonp({"cep":"60543322","logradouro":"Rua Coronel Jo\u00e3o Correia","bairro":"Bom Jardim","cidade":"Fortaleza","uf":"CE","estado":"Cear\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/69402513.jsonp.js
137
jsonp({"cep":"69402513","logradouro":"Travessa Uirapuru","bairro":"Morada do Sol","cidade":"Manacapuru","uf":"AM","estado":"Amazonas"});
cc0-1.0
lfreneda/cepdb
api/v1/57074080.jsonp.js
144
jsonp({"cep":"57074080","logradouro":"Rua Cajueiro","bairro":"Cidade Universit\u00e1ria","cidade":"Macei\u00f3","uf":"AL","estado":"Alagoas"});
cc0-1.0
lfreneda/cepdb
api/v1/53402123.jsonp.js
147
jsonp({"cep":"53402123","logradouro":"3\u00aa Travessa Marcos Benevides","bairro":"Fragoso","cidade":"Paulista","uf":"PE","estado":"Pernambuco"});
cc0-1.0
lfreneda/cepdb
api/v1/27340300.jsonp.js
138
jsonp({"cep":"27340300","logradouro":"Rua Nove","bairro":"Santa L\u00facia","cidade":"Barra Mansa","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
lfreneda/cepdb
api/v1/68746471.jsonp.js
130
jsonp({"cep":"68746471","logradouro":"Rua L-5","bairro":"Jaderl\u00e2ndia","cidade":"Castanhal","uf":"PA","estado":"Par\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/29100031.jsonp.js
146
jsonp({"cep":"29100031","logradouro":"Rua Quinze de Novembro","bairro":"Centro","cidade":"Vila Velha","uf":"ES","estado":"Esp\u00edrito Santo"});
cc0-1.0
lfreneda/cepdb
api/v1/18303460.jsonp.js
161
jsonp({"cep":"18303460","logradouro":"Rua S\u00e9rgio de Oliveira","bairro":"Vila Aparecida","cidade":"Cap\u00e3o Bonito","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
lfreneda/cepdb
api/v1/23836750.jsonp.js
150
jsonp({"cep":"23836750","logradouro":"Rua Pedro Firmino Barbosa","bairro":"Seropedica","cidade":"Itagua\u00ed","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
department-of-veterans-affairs/vets-website
src/applications/check-in/api/local-mock-api/mocks/v2/pre-check-in-data/get.js
3288
const defaultUUID = '0429dda5-4165-46be-9ed1-1e652a8dfd83'; const createMockSuccessResponse = ( token, demographicsNeedsUpdate = false, demographicsConfirmedAt = null, nextOfKinNeedsUpdate = false, nextOfKinConfirmedAt = null, emergencyContactNeedsUpdate = false, emergencyContactConfirmedAt = null, ) => { const mockTime = new Date(); return { id: token || defaultUUID, payload: { demographics: { emergencyContact: { name: 'Bugs Bunny', workPhone: '', relationship: 'Estranged Uncle', phone: '5558675309', address: { zip: '87102', country: 'USA', street3: '', city: 'Albuquerque', county: null, street1: '123 fake street', zip4: '', street2: '', state: 'New Mexico', }, }, nextOfKin1: { name: 'VETERAN,JONAH', relationship: 'BROTHER', phone: '1112223333', workPhone: '4445556666', address: { street1: '123 Main St', street2: 'Ste 234', street3: '', city: 'Los Angeles', county: 'Los Angeles', state: 'CA', zip: '90089', zip4: '', country: 'USA', }, }, mailingAddress: { street1: '123 Turtle Trail', street2: '', street3: '', city: 'Treetopper', state: 'Tennessee', zip: '101010', }, homeAddress: { street1: '445 Fine Finch Fairway', street2: 'Apt 201', city: 'Fairfence', state: 'Florida', zip: '445545', }, homePhone: '5552223333', mobilePhone: '5553334444', workPhone: '5554445555', emailAddress: 'kermit.frog@sesameenterprises.us', }, appointments: [ { facility: 'LOMA LINDA VA CLINIC', clinicPhoneNumber: '5551234567', clinicFriendlyName: 'TEST CLINIC', clinicName: 'LOM ACC CLINIC TEST', appointmentIen: 'some-ien', startTime: mockTime, eligibility: 'ELIGIBLE', facilityId: 'some-facility', checkInWindowStart: mockTime, checkInWindowEnd: mockTime, checkedInTime: '', }, { facility: 'LOMA LINDA VA CLINIC', clinicPhoneNumber: '5551234567', clinicFriendlyName: 'TEST CLINIC', clinicName: 'LOM ACC CLINIC TEST', appointmentIen: 'some-other-ien', startTime: mockTime, eligibility: 'ELIGIBLE', facilityId: 'some-facility', checkInWindowStart: mockTime, checkInWindowEnd: mockTime, checkedInTime: '', }, ], patientDemographicsStatus: { demographicsNeedsUpdate, demographicsConfirmedAt, nextOfKinNeedsUpdate, nextOfKinConfirmedAt, emergencyContactNeedsUpdate, emergencyContactConfirmedAt, }, }, }; }; const createMockFailedResponse = _data => { return { error: true, }; }; module.exports = { createMockSuccessResponse, createMockFailedResponse, defaultUUID, };
cc0-1.0
lfreneda/cepdb
api/v1/32611144.jsonp.js
126
jsonp({"cep":"32611144","logradouro":"Rua Arapagua","bairro":"Icaivera","cidade":"Betim","uf":"MG","estado":"Minas Gerais"});
cc0-1.0
lfreneda/cepdb
api/v1/78705307.jsonp.js
163
jsonp({"cep":"78705307","logradouro":"Rua Jer\u00f4nimo Jacob Chagas","bairro":"Loteamento Alves","cidade":"Rondon\u00f3polis","uf":"MT","estado":"Mato Grosso"});
cc0-1.0
lfreneda/cepdb
api/v1/13905485.jsonp.js
166
jsonp({"cep":"13905485","logradouro":"Rua Albertina Aparecida Lopes","bairro":"Loteamento Panorama Tropical","cidade":"Amparo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
hamizmz/Junk-Draw
electron/shia/index.js
1412
var _vid = document.getElementById('vid'); var _canvas = document.getElementById('canvas'); var _context = _canvas.getContext("2d"); var _canvas_out = document.getElementById('output'); var _context_out = _canvas_out.getContext("2d"); var _timer = null; var TARGET = [255, 255, 255]; var RANGE = 120; _vid.controls = false; _vid.autoplay = true; _vid.preload = true; _canvas_out.width = _canvas.width = 1280; _canvas_out.height = _canvas.height = 720; function draw() { draw_frame(_vid, _context, _context_out, 1280, 720, TARGET, RANGE); _timer = setTimeout(draw, 60); }; function in_range(src, targ, range) { var r1 = src[0]; var g1 = src[1]; var b1 = src[2]; var r2 = targ[0]; var g2 = targ[1]; var b2 = targ[2]; return ( r1 >= r2 - range && // r1 < r2 + range && g1 >= g2 - range && // g1 < g2 + range && b1 >= b2 - range // && b1 < b2 + range ); }; function draw_frame(vid, cxt, out, w, h, target, range) { cxt.drawImage(vid, 0, 0, w, h); var frame = cxt.getImageData(0, 0, w, h); for (var x = 0, pixels = frame.data, s = 4, l = pixels.length; x < l; x += s) { if (in_range([pixels[x], pixels[x + 1], pixels[x + 2]], target, range)) pixels[x + 3] = 0; } out.putImageData(frame, 0, 0); }; _vid.addEventListener('play', draw, false); _vid.addEventListener('ended', function() { clearTimeout(_timer); alert('TEST: done!'); }, false); _vid.src = "assets/video.ogg"
cc0-1.0
lfreneda/cepdb
api/v1/16011220.jsonp.js
149
jsonp({"cep":"16011220","logradouro":"Rua Valpara\u00edso","bairro":"Novo Umuarama","cidade":"Ara\u00e7atuba","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
Programmica/pygtk-tutorial
examples/actiongroup.py
1440
#!/usr/bin/env python import gtk class ActionGroup(gtk.Window): def __init__(self): gtk.Window.__init__(self) self.set_title("ActionGroup") self.set_default_size(200, -1) self.connect("destroy", gtk.main_quit) accelgroup = gtk.AccelGroup() self.add_accel_group(accelgroup) actiongroup = gtk.ActionGroup("actiongroup") actiongroup.add_actions([("new", gtk.STOCK_NEW, "New", None, "Create a dew document", self.on_button_clicked), ("open", gtk.STOCK_OPEN, "Open", None, "Open an existing document", self.on_button_clicked), ("save", gtk.STOCK_SAVE, "Save", None, "Save the current document", self.on_button_clicked) ]) toolbar = gtk.Toolbar() self.add(toolbar) actionNew = actiongroup.get_action("new") toolitemNew = actionNew.create_tool_item() toolbar.insert(toolitemNew, 0) actionOpen = actiongroup.get_action("open") toolitemOpen = actionOpen.create_tool_item() toolbar.insert(toolitemOpen, 1) actionSave = actiongroup.get_action("save") toolitemSave = actionSave.create_tool_item() toolbar.insert(toolitemSave, 2) def on_button_clicked(self, item): print "%s ToolItem Clicked" % (item.get_property("label")) window = ActionGroup() window.show_all() gtk.main()
cc0-1.0
lfreneda/cepdb
api/v1/89281144.jsonp.js
159
jsonp({"cep":"89281144","logradouro":"Rua Elvira Richter Virmond","bairro":"Progresso","cidade":"S\u00e3o Bento do Sul","uf":"SC","estado":"Santa Catarina"});
cc0-1.0
lfreneda/cepdb
api/v1/02863060.jsonp.js
160
jsonp({"cep":"02863060","logradouro":"Rua Jos\u00e9 da Mota Verde","bairro":"Brasil\u00e2ndia","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
cc0-1.0
nathanjameshill/ReefWatchPrototype
__tests__/DisplaySelectedFieldDay-test.js
2210
/* eslint-disable */ jest .unmock('../js/components/DisplaySelectedFieldDay') .unmock('jquery'); import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import $ from 'jquery' import DisplaySelectedFieldDay from '../js/components/DisplaySelectedFieldDay'; describe('DisplaySelectedFieldDay', () => { var fieldDay = {"location": "Hallet Cove", "date": "2016-01-01"}; var result = "Hallet Cove (2016-01-01)"; it('subscribes to selectFieldDay', () => { // Render a checkbox with label in the document const displaySelectedFieldDay = TestUtils.renderIntoDocument( <DisplaySelectedFieldDay /> ); $.publish("selectFieldDay", fieldDay); const displaySelectedFieldDayContent = ReactDOM.findDOMNode(displaySelectedFieldDay); // Verify that it's Off by default expect(displaySelectedFieldDayContent.textContent).toEqual(result); }); it('displays correctly when no data present', () => { // Render a checkbox with label in the document const displaySelectedFieldDay = TestUtils.renderIntoDocument( <DisplaySelectedFieldDay /> ); const displaySelectedFieldDayContent = ReactDOM.findDOMNode(displaySelectedFieldDay); // Verify that it's Off by default expect(displaySelectedFieldDayContent.textContent).toEqual(''); }); it('displays correctly when calling updateSelectedFieldDay', () => { // Render a checkbox with label in the document const displaySelectedFieldDay = TestUtils.renderIntoDocument( <DisplaySelectedFieldDay /> ); displaySelectedFieldDay.updateSelectedFieldDay(this, fieldDay); const displaySelectedFieldDayContent = ReactDOM.findDOMNode(displaySelectedFieldDay); // Verify that it's Off by default expect(displaySelectedFieldDayContent.textContent).toEqual(result); }); }); {/* Not sure why I needed to include this in here but if not present if can find jquery */} (function($) { var o = $({}); $.subscribe = function() { o.on.apply(o, arguments); }; $.unsubscribe = function() { o.off.apply(o, arguments); }; $.publish = function() { o.trigger.apply(o, arguments); }; }($));
cc0-1.0
lfreneda/cepdb
api/v1/45604515.jsonp.js
130
jsonp({"cep":"45604515","logradouro":"Rua Bela Vista","bairro":"Calif\u00f3rnia","cidade":"Itabuna","uf":"BA","estado":"Bahia"});
cc0-1.0
lfreneda/cepdb
api/v1/33825057.jsonp.js
149
jsonp({"cep":"33825057","logradouro":"Rua Sessenta","bairro":"Floren\u00e7a","cidade":"Ribeir\u00e3o das Neves","uf":"MG","estado":"Minas Gerais"});
cc0-1.0
lfreneda/cepdb
api/v1/72317303.jsonp.js
167
jsonp({"cep":"72317303","logradouro":"Quadra QR 527 Conjunto 3","bairro":"Samambaia Sul (Samambaia)","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
cc0-1.0
lfreneda/cepdb
api/v1/57309172.jsonp.js
144
jsonp({"cep":"57309172","logradouro":"Rua Joanita Gomes dos Santos","bairro":"Bom Sucesso","cidade":"Arapiraca","uf":"AL","estado":"Alagoas"});
cc0-1.0
lfreneda/cepdb
api/v1/83324442.jsonp.js
143
jsonp({"cep":"83324442","logradouro":"Avenida Maring\u00e1","bairro":"Emiliano Perneta","cidade":"Pinhais","uf":"PR","estado":"Paran\u00e1"});
cc0-1.0
lfreneda/cepdb
api/v1/25560080.jsonp.js
168
jsonp({"cep":"25560080","logradouro":"Pra\u00e7a da Bandeira","bairro":"Coelho da Rocha","cidade":"S\u00e3o Jo\u00e3o de Meriti","uf":"RJ","estado":"Rio de Janeiro"});
cc0-1.0
memoryliang/junit
src/test/java/junit/tests/framework/AssertTest.java
3087
package junit.tests.framework; import junit.framework.AssertionFailedError; import junit.framework.ComparisonFailure; import junit.framework.TestCase; public class AssertTest extends TestCase { /* In the tests that follow, we can't use standard formatting * for exception tests: * try { * somethingThatShouldThrow(); * fail(); * catch (AssertionFailedError e) { * } * because fail() would never be reported. */ public void testFail() { // Also, we are testing fail, so we can't rely on fail() working. // We have to throw the exception manually, . try { fail(); } catch (AssertionFailedError e) { return; } throw new AssertionFailedError(); } public void testAssertEquals() { Object o = new Object(); assertEquals(o, o); try { assertEquals(new Object(), new Object()); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertEqualsNull() { assertEquals((Object) null, (Object) null); } public void testAssertStringEquals() { assertEquals("a", "a"); } public void testAssertNullNotEqualsString() { try { assertEquals(null, "foo"); fail(); } catch (ComparisonFailure e) { } } public void testAssertStringNotEqualsNull() { try { assertEquals("foo", null); fail(); } catch (ComparisonFailure e) { e.getMessage(); // why no assertion? } } public void testAssertNullNotEqualsNull() { try { assertEquals(null, new Object()); } catch (AssertionFailedError e) { e.getMessage(); // why no assertion? return; } fail(); } public void testAssertNull() { assertNull(null); try { assertNull(new Object()); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotNull() { assertNotNull(new Object()); try { assertNotNull(null); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertTrue() { assertTrue(true); try { assertTrue(false); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertFalse() { assertFalse(false); try { assertFalse(true); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertSame() { Object o = new Object(); assertSame(o, o); try { assertSame(new Integer(1), new Integer(1)); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotSame() { assertNotSame(new Integer(1), null); assertNotSame(null, new Integer(1)); assertNotSame(new Integer(1), new Integer(1)); try { Integer obj = new Integer(1); assertNotSame(obj, obj); } catch (AssertionFailedError e) { return; } fail(); } public void testAssertNotSameFailsNull() { try { assertNotSame(null, null); } catch (AssertionFailedError e) { return; } fail(); } }
epl-1.0
lunifera/lunifera-dsl
org.lunifera.dsl.semantic.common/src-gen/org/lunifera/dsl/semantic/common/types/util/LunTypesSwitch.java
20224
/** * Copyright (c) 2011 - 2014, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg) * 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 * * Based on ideas from Xtext, Xtend, Xcore * * Contributors: * Florian Pirchner - Initial implementation * */ package org.lunifera.dsl.semantic.common.types.util; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; import org.lunifera.dsl.semantic.common.types.*; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see org.lunifera.dsl.semantic.common.types.LunTypesPackage * @generated */ public class LunTypesSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static LunTypesPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LunTypesSwitch() { if (modelPackage == null) { modelPackage = LunTypesPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @parameter ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case LunTypesPackage.LCOMMON_MODEL: { LCommonModel lCommonModel = (LCommonModel)theEObject; T result = caseLCommonModel(lCommonModel); if (result == null) result = caseLLazyResolver(lCommonModel); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LLAZY_RESOLVER: { LLazyResolver lLazyResolver = (LLazyResolver)theEObject; T result = caseLLazyResolver(lLazyResolver); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LPACKAGE: { LPackage lPackage = (LPackage)theEObject; T result = caseLPackage(lPackage); if (result == null) result = caseLLazyResolver(lPackage); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LTYPED_PACKAGE: { LTypedPackage lTypedPackage = (LTypedPackage)theEObject; T result = caseLTypedPackage(lTypedPackage); if (result == null) result = caseLPackage(lTypedPackage); if (result == null) result = caseLLazyResolver(lTypedPackage); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LIMPORT: { LImport lImport = (LImport)theEObject; T result = caseLImport(lImport); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LTYPE: { LType lType = (LType)theEObject; T result = caseLType(lType); if (result == null) result = caseLAnnotationTarget(lType); if (result == null) result = caseLLazyResolver(lType); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LANNOTATION_DEF: { LAnnotationDef lAnnotationDef = (LAnnotationDef)theEObject; T result = caseLAnnotationDef(lAnnotationDef); if (result == null) result = caseLLazyResolver(lAnnotationDef); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LANNOTATION_TARGET: { LAnnotationTarget lAnnotationTarget = (LAnnotationTarget)theEObject; T result = caseLAnnotationTarget(lAnnotationTarget); if (result == null) result = caseLLazyResolver(lAnnotationTarget); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LSCALAR_TYPE: { LScalarType lScalarType = (LScalarType)theEObject; T result = caseLScalarType(lScalarType); if (result == null) result = caseLType(lScalarType); if (result == null) result = caseLAnnotationTarget(lScalarType); if (result == null) result = caseLLazyResolver(lScalarType); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LDATA_TYPE: { LDataType lDataType = (LDataType)theEObject; T result = caseLDataType(lDataType); if (result == null) result = caseLScalarType(lDataType); if (result == null) result = caseLType(lDataType); if (result == null) result = caseLAnnotationTarget(lDataType); if (result == null) result = caseLLazyResolver(lDataType); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LENUM: { LEnum lEnum = (LEnum)theEObject; T result = caseLEnum(lEnum); if (result == null) result = caseLScalarType(lEnum); if (result == null) result = caseLType(lEnum); if (result == null) result = caseLAnnotationTarget(lEnum); if (result == null) result = caseLLazyResolver(lEnum); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LENUM_LITERAL: { LEnumLiteral lEnumLiteral = (LEnumLiteral)theEObject; T result = caseLEnumLiteral(lEnumLiteral); if (result == null) result = caseLLazyResolver(lEnumLiteral); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LCLASS: { LClass lClass = (LClass)theEObject; T result = caseLClass(lClass); if (result == null) result = caseLType(lClass); if (result == null) result = caseLAnnotationTarget(lClass); if (result == null) result = caseLLazyResolver(lClass); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LFEATURES_HOLDER: { LFeaturesHolder lFeaturesHolder = (LFeaturesHolder)theEObject; T result = caseLFeaturesHolder(lFeaturesHolder); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LFEATURE: { LFeature lFeature = (LFeature)theEObject; T result = caseLFeature(lFeature); if (result == null) result = caseLAnnotationTarget(lFeature); if (result == null) result = caseLLazyResolver(lFeature); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LREFERENCE: { LReference lReference = (LReference)theEObject; T result = caseLReference(lReference); if (result == null) result = caseLFeature(lReference); if (result == null) result = caseLAnnotationTarget(lReference); if (result == null) result = caseLLazyResolver(lReference); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LATTRIBUTE: { LAttribute lAttribute = (LAttribute)theEObject; T result = caseLAttribute(lAttribute); if (result == null) result = caseLFeature(lAttribute); if (result == null) result = caseLAnnotationTarget(lAttribute); if (result == null) result = caseLLazyResolver(lAttribute); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LOPERATION: { LOperation lOperation = (LOperation)theEObject; T result = caseLOperation(lOperation); if (result == null) result = caseLAnnotationTarget(lOperation); if (result == null) result = caseLLazyResolver(lOperation); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LMODIFIER: { LModifier lModifier = (LModifier)theEObject; T result = caseLModifier(lModifier); if (result == null) result = caseLLazyResolver(lModifier); if (result == null) result = defaultCase(theEObject); return result; } case LunTypesPackage.LMULTIPLICITY: { LMultiplicity lMultiplicity = (LMultiplicity)theEObject; T result = caseLMultiplicity(lMultiplicity); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>LCommon Model</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LCommon Model</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLCommonModel(LCommonModel object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LLazy Resolver</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LLazy Resolver</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLLazyResolver(LLazyResolver object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LPackage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LPackage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLPackage(LPackage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LTyped Package</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LTyped Package</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLTypedPackage(LTypedPackage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LImport</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LImport</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLImport(LImport object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LType</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LType</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLType(LType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LAnnotation Def</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LAnnotation Def</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLAnnotationDef(LAnnotationDef object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LAnnotation Target</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LAnnotation Target</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLAnnotationTarget(LAnnotationTarget object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LScalar Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LScalar Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLScalarType(LScalarType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LData Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LData Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLDataType(LDataType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LEnum</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LEnum</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLEnum(LEnum object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LEnum Literal</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LEnum Literal</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLEnumLiteral(LEnumLiteral object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LClass</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LClass</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLClass(LClass object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LFeatures Holder</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LFeatures Holder</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLFeaturesHolder(LFeaturesHolder object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LFeature</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LFeature</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLFeature(LFeature object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LReference</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LReference</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLReference(LReference object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LAttribute</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LAttribute</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLAttribute(LAttribute object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LOperation</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LOperation</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLOperation(LOperation object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LModifier</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LModifier</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLModifier(LModifier object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>LMultiplicity</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>LMultiplicity</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseLMultiplicity(LMultiplicity object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //LunTypesSwitch
epl-1.0
memoryliang/junit
src/test/java/junit/tests/framework/TestListenerTest.java
1491
package junit.tests.framework; /** * Test class used in SuiteTest */ import junit.framework.*; public class TestListenerTest extends TestCase implements TestListener { private TestResult fResult; private int fStartCount; private int fEndCount; private int fFailureCount; private int fErrorCount; public void addError(Test test, Throwable t) { fErrorCount++; } public void addFailure(Test test, AssertionFailedError t) { fFailureCount++; } public void endTest(Test test) { fEndCount++; } @Override protected void setUp() { fResult = new TestResult(); fResult.addListener(this); fStartCount = 0; fEndCount = 0; fFailureCount = 0; } public void startTest(Test test) { fStartCount++; } public void testError() { TestCase test = new TestCase("noop") { @Override public void runTest() { throw new Error(); } }; test.run(fResult); assertEquals(1, fErrorCount); assertEquals(1, fEndCount); } public void testFailure() { TestCase test = new TestCase("noop") { @Override public void runTest() { fail(); } }; test.run(fResult); assertEquals(1, fFailureCount); assertEquals(1, fEndCount); } public void testStartStop() { TestCase test = new TestCase("noop") { @Override public void runTest() { } }; test.run(fResult); assertEquals(1, fStartCount); assertEquals(1, fEndCount); } }
epl-1.0
kopl/SPLevo
Diffing/org.splevo.diffing/src/org/splevo/diffing/DiffingException.java
1601
/******************************************************************************* * Copyright (c) 2013 * * 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: * Benjamin Klatt - initial API and implementation and/or initial documentation *******************************************************************************/ package org.splevo.diffing; /** * Exception identifying a problem during the diffing process. */ public class DiffingException extends Exception { /** Id identifying the serialization version of the class. */ private static final long serialVersionUID = 1L; /** * Default constructor. */ public DiffingException() { super(); } /** * Constructor providing a message. * * @param message * The informative message about the exception. */ public DiffingException(String message) { super(message); } /** * Constructor wrapping another throwable. * * @param throwable * A detailed exception to wrap. */ public DiffingException(Throwable throwable) { super(throwable); } /** * Constructor providing a message and wrapping another throwable. * * @param message * The informative message about the exception. * @param throwable * A detailed exception to wrap. */ public DiffingException(String message, Throwable throwable) { super(message, throwable); } }
epl-1.0
rohitmohan96/ceylon-ide-eclipse
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/explorer/PackageExplorerActionGroup.java
18973
package com.redhat.ceylon.eclipse.code.explorer; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IOpenable; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.actions.CollapseAllAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectAllAction; import org.eclipse.jdt.internal.ui.packageview.ClassPathContainer; import org.eclipse.jdt.internal.ui.packageview.ToggleLinkingAction; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.internal.ui.wizards.buildpaths.newsourcepage.GenerateBuildPathActionGroup; import org.eclipse.jdt.internal.ui.workingsets.ViewActionGroup; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.BuildActionGroup; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.ImportActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.JdtActionConstants; import org.eclipse.jdt.ui.actions.OpenProjectAction; import org.eclipse.jdt.ui.actions.ProjectActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.commands.ActionHandler; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.OpenStrategy; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchCommandConstants; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetManager; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.OpenInNewWindowAction; import org.eclipse.ui.handlers.CollapseAllHandler; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.views.framelist.BackAction; import org.eclipse.ui.views.framelist.ForwardAction; import org.eclipse.ui.views.framelist.Frame; import org.eclipse.ui.views.framelist.FrameAction; import org.eclipse.ui.views.framelist.FrameList; import org.eclipse.ui.views.framelist.GoIntoAction; import org.eclipse.ui.views.framelist.TreeFrame; import org.eclipse.ui.views.framelist.UpAction; public class PackageExplorerActionGroup extends CompositeActionGroup { private static final String FRAME_ACTION_SEPARATOR_ID= "FRAME_ACTION_SEPARATOR_ID"; //$NON-NLS-1$ private static final String FRAME_ACTION_GROUP_ID= "FRAME_ACTION_GROUP_ID"; //$NON-NLS-1$ private PackageExplorerPart fPart; private FrameList fFrameList; private GoIntoAction fZoomInAction; private BackAction fBackAction; private ForwardAction fForwardAction; private UpAction fUpAction; private boolean fFrameActionsShown; private GotoTypeAction fGotoTypeAction; private GotoPackageAction fGotoPackageAction; private GotoResourceAction fGotoResourceAction; private CollapseAllAction fCollapseAllAction; private SelectAllAction fSelectAllAction; private ToggleLinkingAction fToggleLinkingAction; private RefactorActionGroup fRefactorActionGroup; private NavigateActionGroup fNavigateActionGroup; private ViewActionGroup fViewActionGroup; private CustomFiltersActionGroup fCustomFiltersActionGroup; private IAction fGotoRequiredProjectAction; private ProjectActionGroup fProjectActionGroup; public PackageExplorerActionGroup(PackageExplorerPart part) { super(); fPart= part; fFrameActionsShown= false; TreeViewer viewer= part.getTreeViewer(); IPropertyChangeListener workingSetListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doWorkingSetChanged(event); } }; IWorkbenchPartSite site = fPart.getSite(); setGroups(new ActionGroup[] { new NewWizardsActionGroup(site), fNavigateActionGroup= new NavigateActionGroup(fPart), new CCPActionGroup(fPart), new GenerateBuildPathActionGroup(fPart), new GenerateActionGroup(fPart), fRefactorActionGroup= new RefactorActionGroup(fPart), new ImportActionGroup(fPart), new BuildActionGroup(fPart), new JavaSearchActionGroup(fPart), fProjectActionGroup= new ProjectActionGroup(fPart), fViewActionGroup= new ViewActionGroup(fPart.getRootMode(), workingSetListener, site), fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, viewer), new LayoutActionGroup(fPart) }); fViewActionGroup.fillFilters(viewer); PackagesFrameSource frameSource= new PackagesFrameSource(fPart); fFrameList= new FrameList(frameSource); frameSource.connectTo(fFrameList); fZoomInAction= new GoIntoAction(fFrameList); fPart.getSite().getSelectionProvider().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { fZoomInAction.update(); } }); fBackAction= new BackAction(fFrameList); fForwardAction= new ForwardAction(fFrameList); fUpAction= new UpAction(fFrameList); fFrameList.addPropertyChangeListener(new IPropertyChangeListener() { // connect after the actions (order of property listener) public void propertyChange(PropertyChangeEvent event) { fPart.updateTitle(); fPart.updateToolbar(); } }); fGotoTypeAction= new GotoTypeAction(fPart); fGotoPackageAction= new GotoPackageAction(fPart); fGotoResourceAction= new GotoResourceAction(fPart); fCollapseAllAction= new CollapseAllAction(fPart.getTreeViewer()); fCollapseAllAction.setActionDefinitionId(CollapseAllHandler.COMMAND_ID); fToggleLinkingAction = new ToggleLinkingAction(fPart); fToggleLinkingAction.setActionDefinitionId(IWorkbenchCommandConstants.NAVIGATE_TOGGLE_LINK_WITH_EDITOR); fGotoRequiredProjectAction= new GotoRequiredProjectAction(fPart); fSelectAllAction= new SelectAllAction(fPart.getTreeViewer()); } @Override public void dispose() { super.dispose(); } //---- Persistent state ----------------------------------------------------------------------- /* package */ void restoreFilterAndSorterState(IMemento memento) { fViewActionGroup.restoreState(memento); fCustomFiltersActionGroup.restoreState(memento); } /* package */ void saveFilterAndSorterState(IMemento memento) { fViewActionGroup.saveState(memento); fCustomFiltersActionGroup.saveState(memento); } //---- Action Bars ---------------------------------------------------------------------------- @Override public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); setGlobalActionHandlers(actionBars); fillToolBar(actionBars.getToolBarManager()); fillViewMenu(actionBars.getMenuManager()); } private void setGlobalActionHandlers(IActionBars actionBars) { // Navigate Go Into and Go To actions. actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction); actionBars.setGlobalActionHandler(ActionFactory.BACK.getId(), fBackAction); actionBars.setGlobalActionHandler(ActionFactory.FORWARD.getId(), fForwardAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction); actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction); fRefactorActionGroup.retargetFileMenuActions(actionBars); IHandlerService handlerService= (IHandlerService) fPart.getViewSite().getService(IHandlerService.class); handlerService.activateHandler(IWorkbenchCommandConstants.NAVIGATE_TOGGLE_LINK_WITH_EDITOR, new ActionHandler(fToggleLinkingAction)); handlerService.activateHandler(CollapseAllHandler.COMMAND_ID, new ActionHandler(fCollapseAllAction)); } /* package */ void fillToolBar(IToolBarManager toolBar) { if (fBackAction.isEnabled() || fUpAction.isEnabled() || fForwardAction.isEnabled()) { toolBar.add(fBackAction); toolBar.add(fForwardAction); toolBar.add(fUpAction); toolBar.add(new Separator(FRAME_ACTION_SEPARATOR_ID)); fFrameActionsShown= true; } toolBar.add(new GroupMarker(FRAME_ACTION_GROUP_ID)); toolBar.add(fCollapseAllAction); toolBar.add(fToggleLinkingAction); toolBar.update(true); } public void updateToolBar(IToolBarManager toolBar) { boolean hasBeenFrameActionsShown= fFrameActionsShown; fFrameActionsShown= fBackAction.isEnabled() || fUpAction.isEnabled() || fForwardAction.isEnabled(); if (fFrameActionsShown != hasBeenFrameActionsShown) { if (hasBeenFrameActionsShown) { toolBar.remove(fBackAction.getId()); toolBar.remove(fForwardAction.getId()); toolBar.remove(fUpAction.getId()); toolBar.remove(FRAME_ACTION_SEPARATOR_ID); } else { toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, new Separator(FRAME_ACTION_SEPARATOR_ID)); toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fUpAction); toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fForwardAction); toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fBackAction); } toolBar.update(true); } } /* package */ void fillViewMenu(IMenuManager menu) { menu.add(new Separator()); menu.add(fToggleLinkingAction); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$ } //---- Context menu ------------------------------------------------------------------------- @Override public void fillContextMenu(IMenuManager menu) { IStructuredSelection selection= (IStructuredSelection)getContext().getSelection(); int size= selection.size(); Object element= selection.getFirstElement(); if (element instanceof ClassPathContainer.RequiredProjectWrapper) menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fGotoRequiredProjectAction); addGotoMenu(menu, element, size); addOpenNewWindowAction(menu, element); super.fillContextMenu(menu); } private void addGotoMenu(IMenuManager menu, Object element, int size) { boolean enabled= size == 1 && fPart.getTreeViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer); fZoomInAction.setEnabled(enabled); if (enabled) menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction); } private boolean isGoIntoTarget(Object element) { if (element == null) return false; if (element instanceof IJavaElement) { int type= ((IJavaElement)element).getElementType(); return type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT; } if (element instanceof IWorkingSet) { return true; } return false; } private void addOpenNewWindowAction(IMenuManager menu, Object element) { if (element instanceof IJavaElement) { element= ((IJavaElement)element).getResource(); } // fix for 64890 Package explorer out of sync when open/closing projects [package explorer] 64890 if (element instanceof IProject && !((IProject)element).isOpen()) return; if (!(element instanceof IContainer)) return; menu.appendToGroup( IContextMenuConstants.GROUP_OPEN, new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element)); } //---- Key board and mouse handling ------------------------------------------------------------ /* package*/ void handleDoubleClick(DoubleClickEvent event) { TreeViewer viewer= fPart.getTreeViewer(); IStructuredSelection selection= (IStructuredSelection)event.getSelection(); Object element= selection.getFirstElement(); if (viewer.isExpandable(element)) { if (doubleClickGoesInto()) { // don't zoom into compilation units and class files if (element instanceof ICompilationUnit || element instanceof IClassFile) return; if (element instanceof IOpenable || element instanceof IContainer || element instanceof IWorkingSet) { fZoomInAction.run(); } } else { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled() && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK) return; if (selection instanceof ITreeSelection) { TreePath[] paths= ((ITreeSelection)selection).getPathsFor(element); for (int i= 0; i < paths.length; i++) { viewer.setExpandedState(paths[i], !viewer.getExpandedState(paths[i])); } } else { viewer.setExpandedState(element, !viewer.getExpandedState(element)); } } } else if (element instanceof IProject && !((IProject) element).isOpen()) { OpenProjectAction openProjectAction= fProjectActionGroup.getOpenProjectAction(); if (openProjectAction.isEnabled()) { openProjectAction.run(); } } } /** * Called by Package Explorer. * * @param event the open event * @param activate <code>true</code> if the opened editor should be activated */ /* package */void handleOpen(ISelection event, boolean activate) { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled()) { // XXX: should use the given arguments instead of using org.eclipse.jface.util.OpenStrategy.activateOnOpen() openAction.run(); return; } } /* package */ void handleKeyEvent(KeyEvent event) { if (event.stateMask != 0) return; if (event.keyCode == SWT.BS) { if (fUpAction != null && fUpAction.isEnabled()) { fUpAction.run(); event.doit= false; } } } private void doWorkingSetChanged(PropertyChangeEvent event) { if (ViewActionGroup.MODE_CHANGED.equals(event.getProperty())) { fPart.rootModeChanged(((Integer)event.getNewValue()).intValue()); Object oldInput= null; Object newInput= null; if (fPart.getRootMode() == PackageExplorerPart.PROJECTS_AS_ROOTS) { oldInput= fPart.getWorkingSetModel(); newInput= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); } else { oldInput= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); newInput= fPart.getWorkingSetModel(); } if (oldInput != null && newInput != null) { Frame frame; for (int i= 0; (frame= fFrameList.getFrame(i)) != null; i++) { if (frame instanceof TreeFrame) { TreeFrame treeFrame= (TreeFrame)frame; if (oldInput.equals(treeFrame.getInput())) treeFrame.setInput(newInput); } } } } else { IWorkingSet workingSet= (IWorkingSet) event.getNewValue(); String workingSetLabel= null; if (workingSet != null) workingSetLabel= BasicElementLabels.getWorkingSetLabel(workingSet); fPart.setWorkingSetLabel(workingSetLabel); fPart.updateTitle(); String property= event.getProperty(); if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) { TreeViewer viewer= fPart.getTreeViewer(); viewer.getControl().setRedraw(false); viewer.refresh(); viewer.getControl().setRedraw(true); } } } private boolean doubleClickGoesInto() { return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK)); } public FrameAction getUpAction() { return fUpAction; } public FrameAction getBackAction() { return fBackAction; } public FrameAction getForwardAction() { return fForwardAction; } public ViewActionGroup getWorkingSetActionGroup() { return fViewActionGroup; } public CustomFiltersActionGroup getCustomFilterActionGroup() { return fCustomFiltersActionGroup; } public FrameList getFrameList() { return fFrameList; } }
epl-1.0
Yakindu/statecharts
plugins/org.yakindu.sct.refactoring/src/org/yakindu/sct/refactoring/refactor/impl/FoldIncomingActionsRefactoring.java
5994
/** * Copyright (c) 2013 committers of YAKINDU 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: * committers of YAKINDU - initial API and implementation * */ package org.yakindu.sct.refactoring.refactor.impl; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.yakindu.base.types.Expression; import org.yakindu.sct.model.sgraph.Effect; import org.yakindu.sct.model.sgraph.Scope; import org.yakindu.sct.model.sgraph.State; import org.yakindu.sct.model.sgraph.Transition; import org.yakindu.sct.model.stext.stext.EntryEvent; import org.yakindu.sct.model.stext.stext.LocalReaction; import org.yakindu.sct.model.stext.stext.ReactionEffect; import org.yakindu.sct.model.stext.stext.ReactionTrigger; import org.yakindu.sct.model.stext.stext.StextFactory; import org.yakindu.sct.refactoring.refactor.AbstractRefactoring; /** * Implementation for 'fold incoming actions' refactoring. This refactoring * moves actions of incoming transitions to the entry block of a state. Actions * can only be moved if they are used at all incoming transitions in the same * order (checked from back to front). * <br><br> * Context: * <ul> * <li>Exactly one state.</li> * </ul> * Preconditions: * <ul> * <li>At least one action is foldable.</li> * <li>No incoming transition enters a composite state which has entry actions.</li> * </ul> * @author thomas kutz - Initial contribution and API * */ public class FoldIncomingActionsRefactoring extends AbstractRefactoring<State> { @Override protected void internalExecute() { List<Expression> actionsToFold = getFoldableActions(); addActionsToEntryReaction(actionsToFold); } /** * {@inheritDoc} */ @Override public boolean isExecutable() { return super.isExecutable() && atLeastOneActionIsFoldable() && noIncomingTransitionEntersCompositeWithEntryActions(); } private boolean noIncomingTransitionEntersCompositeWithEntryActions() { return !helper.oneIncomingTransitionEntersCompositeWithEntryActions(getContextObject()); } private boolean atLeastOneActionIsFoldable() { EList<Transition> transitions = getContextObject().getIncomingTransitions(); return getLastFoldableAction(helper.getAllActions(transitions), 0) != null; } private List<Expression> getFoldableActions() { EList<Transition> transitions = getContextObject() .getIncomingTransitions(); List<Expression> foldableActions = new ArrayList<Expression>(); Expression lastFoldableAction; int indexFromBack = 0; while ((lastFoldableAction = getLastFoldableAction( helper.getAllActions(transitions), indexFromBack)) != null) { foldableActions.add(0, lastFoldableAction); indexFromBack++; } removeLastActions(transitions, indexFromBack); return foldableActions; } private void addActionsToEntryReaction(final List<Expression> actionsToAdd) { if (actionsToAdd.isEmpty()) { return; } EList<Expression> actionsOriginal = helper .getFirstEntryActions(getContextObject()); if (actionsOriginal == null) { actionsOriginal = createEntryBlock(actionsToAdd); } else { actionsOriginal.addAll(actionsToAdd); } } private EList<Expression> createEntryBlock(List<Expression> actionsToAdd) { EList<Expression> actionsOriginal; LocalReaction newLocalReaction = StextFactory.eINSTANCE .createLocalReaction(); ReactionTrigger newReactionTrigger = StextFactory.eINSTANCE .createReactionTrigger(); EntryEvent entryEvent = StextFactory.eINSTANCE.createEntryEvent(); ReactionEffect newReactionEffect = StextFactory.eINSTANCE .createReactionEffect(); newLocalReaction.setTrigger(newReactionTrigger); newReactionTrigger.getTriggers().add(entryEvent); newReactionEffect.getActions().addAll(actionsToAdd); newLocalReaction.setEffect(newReactionEffect); Scope scope = getContextObject().getScopes().get(0); scope.getReactions().add(newLocalReaction); actionsOriginal = newReactionEffect.getActions(); return actionsOriginal; } private void removeLastActions(EList<Transition> transitions, int number) { for (Transition transition : transitions) { List<Expression> actionsToRemove = getLastActions(transition, number); Effect effect = transition.getEffect(); if (effect instanceof ReactionEffect && actionsToRemove.size() == ((ReactionEffect) effect).getActions().size()) { // we need to remove all actions, so just remove the effect // recursively which avoids serializer exceptions EcoreUtil.delete(effect, true); } else { for (Expression action : actionsToRemove) { EcoreUtil.delete(action); } } } } private List<Expression> getLastActions(Transition transition, int number) { List<Expression> lastActions = new ArrayList<Expression>(); Effect effect = transition.getEffect(); if (effect instanceof ReactionEffect) { ReactionEffect reactionEffect = (ReactionEffect) effect; List<Expression> actions = reactionEffect.getActions(); for (int i = 1; i <= number; i++) { lastActions.add(actions.get(actions.size() - i)); } } return lastActions; } private Expression getLastFoldableAction( List<List<Expression>> allActions, int indexFromBack) { Expression actionToCheck = null; for (List<Expression> actionList : allActions) { if (actionList.size() - 1 - indexFromBack < 0) { return null; } Expression lastAction = actionList.get(actionList.size() - 1 - indexFromBack); if (actionToCheck == null) { actionToCheck = lastAction; } else if (!EcoreUtil.equals(actionToCheck, lastAction)) { return null; } } return actionToCheck; } @Override protected String getCommandLabel() { return "Fold Incoming Actions"; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.classloading_test/test/com/ibm/ws/classloading/internal/ProtectionDomainTest.java
7980
/******************************************************************************* * Copyright (c) 2011, 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.ws.classloading.internal; import static com.ibm.ws.classloading.internal.TestUtil.getClassLoadingService; import static com.ibm.ws.classloading.internal.TestUtil.getTestJarURL; import static com.ibm.wsspi.classloading.ApiType.API; import static com.ibm.wsspi.classloading.ApiType.SPEC; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.security.CodeSource; import java.security.Permissions; import java.security.ProtectionDomain; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.ibm.ws.classloading.configuration.GlobalClassloadingConfiguration; import com.ibm.wsspi.adaptable.module.Container; import com.ibm.wsspi.classloading.ApiType; import com.ibm.wsspi.classloading.ClassLoaderConfiguration; import com.ibm.wsspi.classloading.ClassLoaderIdentity; import com.ibm.wsspi.library.Library; public class ProtectionDomainTest { private final Mockery mockery = new JUnit4Mockery(); private static final ClassLoader BOOTSTRAP_CLASS_LOADER = Object.class.getClassLoader(); private ClassLoadingServiceImpl service; @Before public void setUp() throws Exception { service = getClassLoadingService(BOOTSTRAP_CLASS_LOADER); } @After public void tearDown() { mockery.assertIsSatisfied(); } @Test public void testGetCodeSourceGetLocation() throws Exception { ClassLoaderIdentity id = service.createIdentity("UnitTest", this.getClass().getName()); ClassLoaderConfiguration config = service.createClassLoaderConfiguration(); config.setId(id); config.setProtectionDomain(new ProtectionDomain(new CodeSource(new File(".").toURI().toURL(), (Certificate[]) null), null)); List<Container> containers = new ArrayList<Container>(); MockContainer testJarContainer = new MockContainer("testJar", getTestJarURL()); containers.add(testJarContainer); URL thisClassURL = this.getClass().getProtectionDomain().getCodeSource().getLocation(); MockContainer unittestClassDir = new MockContainer("unittestClassDir", thisClassURL); containers.add(unittestClassDir); DeclaredApiAccess access = new DeclaredApiAccess() { @Override public EnumSet<ApiType> getApiTypeVisibility() { return null; } }; AppClassLoader appClassLoader = new AppClassLoader(BOOTSTRAP_CLASS_LOADER, config, containers, access, null, null, new GlobalClassloadingConfiguration(), Collections.emptyList()); Class<?> testJarClass = appClassLoader.loadClass("test.StringReturner"); String location = testJarClass.getProtectionDomain().getCodeSource().getLocation().toString(); assertTrue("Test class's protection domain's code source location is incorrect - expecting file://**/test.jar, found: " + location, location.contains("test.jar")); Class<?> thisClass = appClassLoader.loadClass(this.getClass().getName()); location = thisClass.getProtectionDomain().getCodeSource().getLocation().toString(); assertEquals("This class's protection domain's code source location is incorrect", thisClassURL.toString(), location); } /** * This tests cases like common shared libraries where the config uses a default ProtectionDomain. * Currently, non-default PDs for common libraries are only specified if the user has specified a * <code>&lt;javaPermission .../&gt;</code> element in their config that specifies the common library's * path in it's <em>codebase</em> attribute. This test will verify that we can get an accurate codebase * location even if the javaPermission is not set in the config. */ @Test public void testGetCodeSourceGetLocationWhenConfigDoesNotSpecifyPD() throws Exception { ClassLoaderIdentity id = service.createIdentity("UnitTest", this.getClass().getName()); ClassLoaderConfiguration config = service.createClassLoaderConfiguration(); config.setId(id); List<Container> containers = new ArrayList<Container>(); MockContainer testJarContainer = new MockContainer("testJar", getTestJarURL()); containers.add(testJarContainer); URL thisClassURL = this.getClass().getProtectionDomain().getCodeSource().getLocation(); MockContainer unittestClassDir = new MockContainer("unittestClassDir", thisClassURL); containers.add(unittestClassDir); DeclaredApiAccess access = new DeclaredApiAccess() { @Override public EnumSet<ApiType> getApiTypeVisibility() { return null; } }; AppClassLoader appClassLoader = new AppClassLoader(BOOTSTRAP_CLASS_LOADER, config, containers, access, null, null, new GlobalClassloadingConfiguration(), Collections.emptyList()); Class<?> testJarClass = appClassLoader.loadClass("test.StringReturner"); String location = testJarClass.getProtectionDomain().getCodeSource().getLocation().toString(); assertTrue("Test class's protection domain's code source location is incorrect - expecting file://**/test.jar, found: " + location, location.contains("test.jar")); Class<?> thisClass = appClassLoader.loadClass(this.getClass().getName()); location = thisClass.getProtectionDomain().getCodeSource().getLocation().toString(); assertEquals("This class's protection domain's code source location is incorrect", thisClassURL.toString(), location); } @Test public void testGetSharedLibraryClassLoaderWhenLibraryUsesFilesInsteadOfFileset() throws Exception { final Collection<File> files = new ArrayList<File>(); File testJar = new File("test.jar"); files.add(testJar); final Library lib = mockery.mock(Library.class); mockery.checking(new Expectations() { { allowing(lib).id(); will(returnValue("testSharedLibrary")); allowing(lib).getApiTypeVisibility(); will(returnValue(EnumSet.of(API, SPEC))); allowing(lib).getFilesets(); will(returnValue(Collections.emptyList())); one(lib).getFiles(); will(returnValue(files)); } }); Map<String, ProtectionDomain> protectionDomainMap = new HashMap<String, ProtectionDomain>(); CodeSource codesource = new CodeSource(new URL("file://test.jar"), (Certificate[]) null); protectionDomainMap.put(testJar.getPath(), new ProtectionDomain(codesource, new Permissions())); service.setSharedLibraryProtectionDomains(protectionDomainMap); AppClassLoader appClassLoader = service.getSharedLibraryClassLoader(lib); String location = appClassLoader.config.getProtectionDomain().getCodeSource().getLocation().toString(); assertTrue("Test protection domain's code source location is incorrect - expecting file://**/test.jar, found: " + location, location.contains("test.jar")); } }
epl-1.0
debabratahazra/DS
designstudio/components/workbench/tests/com.odcgroup.translation.core.tests/src/com/odcgroup/translation/core/internal/migration/SaveMigrationErrorToExternalFileTest.java
2174
package com.odcgroup.translation.core.internal.migration; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.odcgroup.translation.core.migration.TranslationVO; import com.odcgroup.workbench.core.tests.util.AbstractDSUnitTest; /** * Validate that file are properly written to an external error file * if something goes wrong during migration * @author yan */ public class SaveMigrationErrorToExternalFileTest extends AbstractDSUnitTest { @Before public void setUp() { createModelsProject(); } @After public void tearDown() { deleteModelsProjects(); } @Test public void testWriteNotProcessTranslations() throws IOException { List<TranslationVO> translations = new LinkedList<TranslationVO>(); for (int i=0;i<5;i++) { translations.add(new TranslationVO("some.key"+i, "some.lang"+i, "some text"+i, "some error message"+i)); } String migrationFile = new MessageRepositoryMigration().writeNotProcessTranslations(getOfsProject(), translations); Assert.assertTrue("The file should exist", new File(migrationFile).exists()); List<String> fileContents = getContents(migrationFile); Assert.assertEquals(6, fileContents.size()); // 1 header + 5 lines Assert.assertEquals("project;key;language;value;problem", fileContents.get(0)); Assert.assertEquals(getProject().getName() + MessageRepositoryMigration.SEPARATOR + "some.key3" + MessageRepositoryMigration.SEPARATOR + "some.lang3" + MessageRepositoryMigration.SEPARATOR + "some text3" + MessageRepositoryMigration.SEPARATOR + "some error message3", fileContents.get(4)); } private List<String> getContents(String filename) throws IOException { List<String> contents = new LinkedList<String>(); BufferedReader input = new BufferedReader(new FileReader(new File(filename))); try { String line = null; while ((line = input.readLine()) != null) { contents.add(line); } } finally { input.close(); } return contents; } }
epl-1.0
miklossy/xtext-core
org.eclipse.xtext/src/org/eclipse/xtext/resource/ISelectable.java
2268
/******************************************************************************* * Copyright (c) 2010 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.resource; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.naming.QualifiedName; /** * An {@link ISelectable} is something that can be queried for exported object. * Thereby it serves as a common abstract super concept for {@link IContainer} and * {@link IResourceDescription}. * Furthermore there is an implementation of the {@link org.eclipse.xtext.scoping.IScope IScope} * interface that is based on {@link ISelectable} and vice versa. * All implementations of {@link ISelectable} can deal with ignore case and case sensitive queries. * @author Sebastian Zarnekow - Initial contribution and API */ public interface ISelectable { /** * Clients may want to check the selectable to skip its processing in case it is empty. * Implementations should be fast and not require expensive precalculation. Selectable may * return <code>false</code> if it is too expensive to compute the actual result. * @return <code>true</code> if the selectable does not provide any descriptions. */ boolean isEmpty(); /** * @return all exported elements. May not be <code>null</code>. */ Iterable<IEObjectDescription> getExportedObjects(); /** * @return all elements which match the given qualified name and type. May not be <code>null</code>. */ Iterable<IEObjectDescription> getExportedObjects(EClass type, QualifiedName name, boolean ignoreCase); /** * @return all elements which match the given type. May not be <code>null</code>. */ Iterable<IEObjectDescription> getExportedObjectsByType(EClass type); /** * @return all elements which match the given instance. May not be <code>null</code>. */ Iterable<IEObjectDescription> getExportedObjectsByObject(EObject object); }
epl-1.0
bhurlow/graf
out/cljs/core/async/impl/buffers.js
16349
// Compiled by ClojureScript 1.7.228 {} goog.provide('cljs.core.async.impl.buffers'); goog.require('cljs.core'); goog.require('cljs.core.async.impl.protocols'); cljs.core.async.impl.buffers.acopy = (function cljs$core$async$impl$buffers$acopy(src,src_start,dest,dest_start,len){ var cnt = (0); while(true){ if((cnt < len)){ (dest[(dest_start + cnt)] = (src[(src_start + cnt)])); var G__33829 = (cnt + (1)); cnt = G__33829; continue; } else { return null; } break; } }); /** * @constructor * @implements {cljs.core.async.impl.buffers.Object} */ cljs.core.async.impl.buffers.RingBuffer = (function (head,tail,length,arr){ this.head = head; this.tail = tail; this.length = length; this.arr = arr; }) cljs.core.async.impl.buffers.RingBuffer.prototype.pop = (function (){ var self__ = this; var _ = this; if((self__.length === (0))){ return null; } else { var x = (self__.arr[self__.tail]); (self__.arr[self__.tail] = null); self__.tail = ((self__.tail + (1)) % self__.arr.length); self__.length = (self__.length - (1)); return x; } }); cljs.core.async.impl.buffers.RingBuffer.prototype.unshift = (function (x){ var self__ = this; var _ = this; (self__.arr[self__.head] = x); self__.head = ((self__.head + (1)) % self__.arr.length); self__.length = (self__.length + (1)); return null; }); cljs.core.async.impl.buffers.RingBuffer.prototype.unbounded_unshift = (function (x){ var self__ = this; var this$ = this; if(((self__.length + (1)) === self__.arr.length)){ this$.resize(); } else { } return this$.unshift(x); }); cljs.core.async.impl.buffers.RingBuffer.prototype.resize = (function (){ var self__ = this; var _ = this; var new_arr_size = (self__.arr.length * (2)); var new_arr = (new Array(new_arr_size)); if((self__.tail < self__.head)){ cljs.core.async.impl.buffers.acopy.call(null,self__.arr,self__.tail,new_arr,(0),self__.length); self__.tail = (0); self__.head = self__.length; return self__.arr = new_arr; } else { if((self__.tail > self__.head)){ cljs.core.async.impl.buffers.acopy.call(null,self__.arr,self__.tail,new_arr,(0),(self__.arr.length - self__.tail)); cljs.core.async.impl.buffers.acopy.call(null,self__.arr,(0),new_arr,(self__.arr.length - self__.tail),self__.head); self__.tail = (0); self__.head = self__.length; return self__.arr = new_arr; } else { if((self__.tail === self__.head)){ self__.tail = (0); self__.head = (0); return self__.arr = new_arr; } else { return null; } } } }); cljs.core.async.impl.buffers.RingBuffer.prototype.cleanup = (function (keep_QMARK_){ var self__ = this; var this$ = this; var n__22113__auto__ = self__.length; var x = (0); while(true){ if((x < n__22113__auto__)){ var v_33830 = this$.pop(); if(keep_QMARK_.call(null,v_33830)){ this$.unshift(v_33830); } else { } var G__33831 = (x + (1)); x = G__33831; continue; } else { return null; } break; } }); cljs.core.async.impl.buffers.RingBuffer.getBasis = (function (){ return new cljs.core.PersistentVector(null, 4, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.with_meta(new cljs.core.Symbol(null,"head","head",869147608,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null)),cljs.core.with_meta(new cljs.core.Symbol(null,"tail","tail",494507963,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null)),cljs.core.with_meta(new cljs.core.Symbol(null,"length","length",-2065447907,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null)),cljs.core.with_meta(new cljs.core.Symbol(null,"arr","arr",2115492975,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null))], null); }); cljs.core.async.impl.buffers.RingBuffer.cljs$lang$type = true; cljs.core.async.impl.buffers.RingBuffer.cljs$lang$ctorStr = "cljs.core.async.impl.buffers/RingBuffer"; cljs.core.async.impl.buffers.RingBuffer.cljs$lang$ctorPrWriter = (function (this__21808__auto__,writer__21809__auto__,opt__21810__auto__){ return cljs.core._write.call(null,writer__21809__auto__,"cljs.core.async.impl.buffers/RingBuffer"); }); cljs.core.async.impl.buffers.__GT_RingBuffer = (function cljs$core$async$impl$buffers$__GT_RingBuffer(head,tail,length,arr){ return (new cljs.core.async.impl.buffers.RingBuffer(head,tail,length,arr)); }); cljs.core.async.impl.buffers.ring_buffer = (function cljs$core$async$impl$buffers$ring_buffer(n){ if((n > (0))){ } else { throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str("Can't create a ring buffer of size 0"),cljs.core.str("\n"),cljs.core.str(cljs.core.pr_str.call(null,cljs.core.list(new cljs.core.Symbol(null,">",">",1085014381,null),new cljs.core.Symbol(null,"n","n",-2092305744,null),(0))))].join(''))); } return (new cljs.core.async.impl.buffers.RingBuffer((0),(0),(0),(new Array(n)))); }); /** * @constructor * @implements {cljs.core.ICounted} * @implements {cljs.core.async.impl.protocols.Buffer} */ cljs.core.async.impl.buffers.FixedBuffer = (function (buf,n){ this.buf = buf; this.n = n; this.cljs$lang$protocol_mask$partition0$ = 2; this.cljs$lang$protocol_mask$partition1$ = 0; }) cljs.core.async.impl.buffers.FixedBuffer.prototype.cljs$core$async$impl$protocols$Buffer$ = true; cljs.core.async.impl.buffers.FixedBuffer.prototype.cljs$core$async$impl$protocols$Buffer$full_QMARK_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return (self__.buf.length === self__.n); }); cljs.core.async.impl.buffers.FixedBuffer.prototype.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return self__.buf.pop(); }); cljs.core.async.impl.buffers.FixedBuffer.prototype.cljs$core$async$impl$protocols$Buffer$add_BANG__STAR_$arity$2 = (function (this$,itm){ var self__ = this; var this$__$1 = this; self__.buf.unbounded_unshift(itm); return this$__$1; }); cljs.core.async.impl.buffers.FixedBuffer.prototype.cljs$core$async$impl$protocols$Buffer$close_buf_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return null; }); cljs.core.async.impl.buffers.FixedBuffer.prototype.cljs$core$ICounted$_count$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return self__.buf.length; }); cljs.core.async.impl.buffers.FixedBuffer.getBasis = (function (){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"buf","buf",1426618187,null),new cljs.core.Symbol(null,"n","n",-2092305744,null)], null); }); cljs.core.async.impl.buffers.FixedBuffer.cljs$lang$type = true; cljs.core.async.impl.buffers.FixedBuffer.cljs$lang$ctorStr = "cljs.core.async.impl.buffers/FixedBuffer"; cljs.core.async.impl.buffers.FixedBuffer.cljs$lang$ctorPrWriter = (function (this__21808__auto__,writer__21809__auto__,opt__21810__auto__){ return cljs.core._write.call(null,writer__21809__auto__,"cljs.core.async.impl.buffers/FixedBuffer"); }); cljs.core.async.impl.buffers.__GT_FixedBuffer = (function cljs$core$async$impl$buffers$__GT_FixedBuffer(buf,n){ return (new cljs.core.async.impl.buffers.FixedBuffer(buf,n)); }); cljs.core.async.impl.buffers.fixed_buffer = (function cljs$core$async$impl$buffers$fixed_buffer(n){ return (new cljs.core.async.impl.buffers.FixedBuffer(cljs.core.async.impl.buffers.ring_buffer.call(null,n),n)); }); /** * @constructor * @implements {cljs.core.ICounted} * @implements {cljs.core.async.impl.protocols.UnblockingBuffer} * @implements {cljs.core.async.impl.protocols.Buffer} */ cljs.core.async.impl.buffers.DroppingBuffer = (function (buf,n){ this.buf = buf; this.n = n; this.cljs$lang$protocol_mask$partition0$ = 2; this.cljs$lang$protocol_mask$partition1$ = 0; }) cljs.core.async.impl.buffers.DroppingBuffer.prototype.cljs$core$async$impl$protocols$UnblockingBuffer$ = true; cljs.core.async.impl.buffers.DroppingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$ = true; cljs.core.async.impl.buffers.DroppingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$full_QMARK_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return false; }); cljs.core.async.impl.buffers.DroppingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return self__.buf.pop(); }); cljs.core.async.impl.buffers.DroppingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$add_BANG__STAR_$arity$2 = (function (this$,itm){ var self__ = this; var this$__$1 = this; if((self__.buf.length === self__.n)){ } else { self__.buf.unshift(itm); } return this$__$1; }); cljs.core.async.impl.buffers.DroppingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$close_buf_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return null; }); cljs.core.async.impl.buffers.DroppingBuffer.prototype.cljs$core$ICounted$_count$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return self__.buf.length; }); cljs.core.async.impl.buffers.DroppingBuffer.getBasis = (function (){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"buf","buf",1426618187,null),new cljs.core.Symbol(null,"n","n",-2092305744,null)], null); }); cljs.core.async.impl.buffers.DroppingBuffer.cljs$lang$type = true; cljs.core.async.impl.buffers.DroppingBuffer.cljs$lang$ctorStr = "cljs.core.async.impl.buffers/DroppingBuffer"; cljs.core.async.impl.buffers.DroppingBuffer.cljs$lang$ctorPrWriter = (function (this__21808__auto__,writer__21809__auto__,opt__21810__auto__){ return cljs.core._write.call(null,writer__21809__auto__,"cljs.core.async.impl.buffers/DroppingBuffer"); }); cljs.core.async.impl.buffers.__GT_DroppingBuffer = (function cljs$core$async$impl$buffers$__GT_DroppingBuffer(buf,n){ return (new cljs.core.async.impl.buffers.DroppingBuffer(buf,n)); }); cljs.core.async.impl.buffers.dropping_buffer = (function cljs$core$async$impl$buffers$dropping_buffer(n){ return (new cljs.core.async.impl.buffers.DroppingBuffer(cljs.core.async.impl.buffers.ring_buffer.call(null,n),n)); }); /** * @constructor * @implements {cljs.core.ICounted} * @implements {cljs.core.async.impl.protocols.UnblockingBuffer} * @implements {cljs.core.async.impl.protocols.Buffer} */ cljs.core.async.impl.buffers.SlidingBuffer = (function (buf,n){ this.buf = buf; this.n = n; this.cljs$lang$protocol_mask$partition0$ = 2; this.cljs$lang$protocol_mask$partition1$ = 0; }) cljs.core.async.impl.buffers.SlidingBuffer.prototype.cljs$core$async$impl$protocols$UnblockingBuffer$ = true; cljs.core.async.impl.buffers.SlidingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$ = true; cljs.core.async.impl.buffers.SlidingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$full_QMARK_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return false; }); cljs.core.async.impl.buffers.SlidingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return self__.buf.pop(); }); cljs.core.async.impl.buffers.SlidingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$add_BANG__STAR_$arity$2 = (function (this$,itm){ var self__ = this; var this$__$1 = this; if((self__.buf.length === self__.n)){ cljs.core.async.impl.protocols.remove_BANG_.call(null,this$__$1); } else { } self__.buf.unshift(itm); return this$__$1; }); cljs.core.async.impl.buffers.SlidingBuffer.prototype.cljs$core$async$impl$protocols$Buffer$close_buf_BANG_$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return null; }); cljs.core.async.impl.buffers.SlidingBuffer.prototype.cljs$core$ICounted$_count$arity$1 = (function (this$){ var self__ = this; var this$__$1 = this; return self__.buf.length; }); cljs.core.async.impl.buffers.SlidingBuffer.getBasis = (function (){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"buf","buf",1426618187,null),new cljs.core.Symbol(null,"n","n",-2092305744,null)], null); }); cljs.core.async.impl.buffers.SlidingBuffer.cljs$lang$type = true; cljs.core.async.impl.buffers.SlidingBuffer.cljs$lang$ctorStr = "cljs.core.async.impl.buffers/SlidingBuffer"; cljs.core.async.impl.buffers.SlidingBuffer.cljs$lang$ctorPrWriter = (function (this__21808__auto__,writer__21809__auto__,opt__21810__auto__){ return cljs.core._write.call(null,writer__21809__auto__,"cljs.core.async.impl.buffers/SlidingBuffer"); }); cljs.core.async.impl.buffers.__GT_SlidingBuffer = (function cljs$core$async$impl$buffers$__GT_SlidingBuffer(buf,n){ return (new cljs.core.async.impl.buffers.SlidingBuffer(buf,n)); }); cljs.core.async.impl.buffers.sliding_buffer = (function cljs$core$async$impl$buffers$sliding_buffer(n){ return (new cljs.core.async.impl.buffers.SlidingBuffer(cljs.core.async.impl.buffers.ring_buffer.call(null,n),n)); }); if(typeof cljs.core.async.impl.buffers.NO_VAL !== 'undefined'){ } else { cljs.core.async.impl.buffers.NO_VAL = (new Object()); } cljs.core.async.impl.buffers.undelivered_QMARK_ = (function cljs$core$async$impl$buffers$undelivered_QMARK_(val){ return (cljs.core.async.impl.buffers.NO_VAL === val); }); /** * @constructor * @implements {cljs.core.ICounted} * @implements {cljs.core.async.impl.protocols.UnblockingBuffer} * @implements {cljs.core.async.impl.protocols.Buffer} */ cljs.core.async.impl.buffers.PromiseBuffer = (function (val){ this.val = val; this.cljs$lang$protocol_mask$partition0$ = 2; this.cljs$lang$protocol_mask$partition1$ = 0; }) cljs.core.async.impl.buffers.PromiseBuffer.prototype.cljs$core$async$impl$protocols$UnblockingBuffer$ = true; cljs.core.async.impl.buffers.PromiseBuffer.prototype.cljs$core$async$impl$protocols$Buffer$ = true; cljs.core.async.impl.buffers.PromiseBuffer.prototype.cljs$core$async$impl$protocols$Buffer$full_QMARK_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return false; }); cljs.core.async.impl.buffers.PromiseBuffer.prototype.cljs$core$async$impl$protocols$Buffer$remove_BANG_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.val; }); cljs.core.async.impl.buffers.PromiseBuffer.prototype.cljs$core$async$impl$protocols$Buffer$add_BANG__STAR_$arity$2 = (function (this$,itm){ var self__ = this; var this$__$1 = this; if(cljs.core.truth_(cljs.core.async.impl.buffers.undelivered_QMARK_.call(null,self__.val))){ self__.val = itm; } else { } return this$__$1; }); cljs.core.async.impl.buffers.PromiseBuffer.prototype.cljs$core$async$impl$protocols$Buffer$close_buf_BANG_$arity$1 = (function (_){ var self__ = this; var ___$1 = this; if(cljs.core.truth_(cljs.core.async.impl.buffers.undelivered_QMARK_.call(null,self__.val))){ return self__.val = null; } else { return null; } }); cljs.core.async.impl.buffers.PromiseBuffer.prototype.cljs$core$ICounted$_count$arity$1 = (function (_){ var self__ = this; var ___$1 = this; if(cljs.core.truth_(cljs.core.async.impl.buffers.undelivered_QMARK_.call(null,self__.val))){ return (0); } else { return (1); } }); cljs.core.async.impl.buffers.PromiseBuffer.getBasis = (function (){ return new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.with_meta(new cljs.core.Symbol(null,"val","val",1769233139,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null))], null); }); cljs.core.async.impl.buffers.PromiseBuffer.cljs$lang$type = true; cljs.core.async.impl.buffers.PromiseBuffer.cljs$lang$ctorStr = "cljs.core.async.impl.buffers/PromiseBuffer"; cljs.core.async.impl.buffers.PromiseBuffer.cljs$lang$ctorPrWriter = (function (this__21808__auto__,writer__21809__auto__,opt__21810__auto__){ return cljs.core._write.call(null,writer__21809__auto__,"cljs.core.async.impl.buffers/PromiseBuffer"); }); cljs.core.async.impl.buffers.__GT_PromiseBuffer = (function cljs$core$async$impl$buffers$__GT_PromiseBuffer(val){ return (new cljs.core.async.impl.buffers.PromiseBuffer(val)); }); cljs.core.async.impl.buffers.promise_buffer = (function cljs$core$async$impl$buffers$promise_buffer(){ return (new cljs.core.async.impl.buffers.PromiseBuffer(cljs.core.async.impl.buffers.NO_VAL)); }); //# sourceMappingURL=buffers.js.map
epl-1.0
viatra/VIATRA-Generator
Domains/ca.mcgill.rtgmrt.example.modes3/ecore-gen/modes3/impl/TurnoutImpl.java
5012
/** */ package modes3.impl; import modes3.Modes3Package; import modes3.Segment; import modes3.Turnout; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Turnout</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link modes3.impl.TurnoutImpl#getStraight <em>Straight</em>}</li> * <li>{@link modes3.impl.TurnoutImpl#getDivergent <em>Divergent</em>}</li> * </ul> * * @generated */ public class TurnoutImpl extends SegmentImpl implements Turnout { /** * The cached value of the '{@link #getStraight() <em>Straight</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getStraight() * @generated * @ordered */ protected Segment straight; /** * The cached value of the '{@link #getDivergent() <em>Divergent</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDivergent() * @generated * @ordered */ protected Segment divergent; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TurnoutImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Modes3Package.Literals.TURNOUT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Segment getStraight() { if (straight != null && straight.eIsProxy()) { InternalEObject oldStraight = (InternalEObject)straight; straight = (Segment)eResolveProxy(oldStraight); if (straight != oldStraight) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Modes3Package.TURNOUT__STRAIGHT, oldStraight, straight)); } } return straight; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Segment basicGetStraight() { return straight; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStraight(Segment newStraight) { Segment oldStraight = straight; straight = newStraight; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Modes3Package.TURNOUT__STRAIGHT, oldStraight, straight)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Segment getDivergent() { if (divergent != null && divergent.eIsProxy()) { InternalEObject oldDivergent = (InternalEObject)divergent; divergent = (Segment)eResolveProxy(oldDivergent); if (divergent != oldDivergent) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Modes3Package.TURNOUT__DIVERGENT, oldDivergent, divergent)); } } return divergent; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Segment basicGetDivergent() { return divergent; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDivergent(Segment newDivergent) { Segment oldDivergent = divergent; divergent = newDivergent; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Modes3Package.TURNOUT__DIVERGENT, oldDivergent, divergent)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Modes3Package.TURNOUT__STRAIGHT: if (resolve) return getStraight(); return basicGetStraight(); case Modes3Package.TURNOUT__DIVERGENT: if (resolve) return getDivergent(); return basicGetDivergent(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Modes3Package.TURNOUT__STRAIGHT: setStraight((Segment)newValue); return; case Modes3Package.TURNOUT__DIVERGENT: setDivergent((Segment)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Modes3Package.TURNOUT__STRAIGHT: setStraight((Segment)null); return; case Modes3Package.TURNOUT__DIVERGENT: setDivergent((Segment)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Modes3Package.TURNOUT__STRAIGHT: return straight != null; case Modes3Package.TURNOUT__DIVERGENT: return divergent != null; } return super.eIsSet(featureID); } } //TurnoutImpl
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/advanced/fetchgroup/ChestProtector.java
1333
/******************************************************************************* * Copyright (c) 2011, 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: * 01/19/2010-2.1 Guy Pelletier * - 211322: Add fetch-group(s) support to the EclipseLink-ORM.XML Schema ******************************************************************************/ package org.eclipse.persistence.testing.models.jpa.advanced.fetchgroup; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name="JPA_CHEST_PROTECT") @DiscriminatorValue("CHP") public class ChestProtector extends GoalieGear { @Column(name="C_SIZE") public String size; public String getSize() { return size; } public void setSize(String size) { this.size = size; } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/oxm/mappings/Mapping.java
4647
/******************************************************************************* * Copyright (c) 2012, 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: * Blaise Doughan - 2.5 - initial implementation ******************************************************************************/ package org.eclipse.persistence.internal.oxm.mappings; import java.util.Map; import org.eclipse.persistence.core.descriptors.CoreDescriptor; import org.eclipse.persistence.core.mappings.CoreAttributeAccessor; import org.eclipse.persistence.internal.core.helper.CoreField; import org.eclipse.persistence.internal.core.queries.CoreContainerPolicy; import org.eclipse.persistence.internal.core.sessions.CoreAbstractSession; import org.eclipse.persistence.internal.oxm.record.XMLRecord; public interface Mapping< ABSTRACT_SESSION extends CoreAbstractSession, ATTRIBUTE_ACCESSOR extends CoreAttributeAccessor, CONTAINER_POLICY extends CoreContainerPolicy, DESCRIPTOR extends CoreDescriptor, FIELD extends CoreField, XML_RECORD extends XMLRecord> { public void convertClassNamesToClasses(ClassLoader classLoader); public ATTRIBUTE_ACCESSOR getAttributeAccessor(); /** * The classification type for the attribute this mapping represents */ public abstract Class getAttributeClassification(); /** * Return the name of the attribute set in the mapping. */ public abstract String getAttributeName(); public Object getAttributeValueFromObject(Object object); public abstract CONTAINER_POLICY getContainerPolicy(); /** * Return the descriptor to which this mapping belongs */ public DESCRIPTOR getDescriptor(); public FIELD getField(); public DESCRIPTOR getReferenceDescriptor(); /** * Related mapping should implement this method to return true. */ public abstract boolean isAbstractCompositeCollectionMapping(); /** * Related mapping should implement this method to return true. */ public abstract boolean isAbstractCompositeDirectCollectionMapping(); /** * Related mapping should implement this method to return true. */ public abstract boolean isAbstractCompositeObjectMapping(); /** * Related mapping should implement this method to return true. */ public boolean isAbstractDirectMapping(); public boolean isCollectionMapping(); public boolean isReadOnly(); public boolean isReferenceMapping(); /** * Related mapping should implement this method to return true. */ public abstract boolean isTransformationMapping(); /** * ADVANCED: * Set the attributeAccessor. * The attribute accessor is responsible for setting and retrieving the attribute value * from the object for this mapping. * This can be set to an implementor of AttributeAccessor if the attribute * requires advanced conversion of the mapping value, or a real attribute does not exist. */ public void setAttributeAccessor(ATTRIBUTE_ACCESSOR attributeAccessor); /** * Sets the name of the attribute in the mapping. */ public void setAttributeName(String attributeName); public void setAttributeValueInObject(Object object, Object value); public void writeSingleValue(Object value, Object object, XML_RECORD record, ABSTRACT_SESSION session); /** * This method is invoked reflectively on the reference object to return the value of the * attribute in the object. This method sets the name of the getMethodName. */ public void setGetMethodName(String methodName); /** * Set this mapping to be read only. * Read-only mappings can be used if two attributes map to the same field. * Read-only mappings cannot be used for the primary key or other required fields. */ public void setIsReadOnly(boolean aBoolean); /** * INTERNAL: * Allow user defined properties. */ public void setProperties(Map properties); /** * Set the methodName used to set the value for the mapping's attribute into the object. */ public void setSetMethodName(String methodName); }
epl-1.0
inocybe/odl-bgpcep
bgp/parser-spi/src/main/java/org/opendaylight/protocol/bgp/parser/spi/extended/community/ExtendedCommunitySerializer.java
1443
/* * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.protocol.bgp.parser.spi.extended.community; import io.netty.buffer.ByteBuf; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.extended.community.ExtendedCommunity; /** * The Extended Community serializer (ExtendedCommunity to ByteBuf). * */ public interface ExtendedCommunitySerializer { /** * Serializes Extended Community value to the buffer. * @param extendedCommunity ExtendedCommuity to be encoded. * @param byteAggregator The output buffer where the extended community is written. */ void serializeExtendedCommunity(ExtendedCommunity extendedCommunity, ByteBuf byteAggregator); /** * Provides a type of the extended community for which the serializer is registered. * @param isTransitive Transitivity of the extended community. * @return A type of the extended community. */ int getType(boolean isTransitive); /** * Provides a sub-type of the extended community for which the serializer is registered. * @return A sub-type of the extended community. */ int getSubType(); }
epl-1.0
alovassy/titan.EclipsePlug-ins
org.eclipse.titan.designer/src/org/eclipse/titan/designer/AST/TTCN3/values/expressions/GetverdictExpression.java
3122
/****************************************************************************** * 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.designer.AST.TTCN3.values.expressions; import org.eclipse.titan.designer.AST.ASTVisitor; import org.eclipse.titan.designer.AST.IReferenceChain; import org.eclipse.titan.designer.AST.IValue; import org.eclipse.titan.designer.AST.IType.Type_type; import org.eclipse.titan.designer.AST.TTCN3.Expected_Value_type; import org.eclipse.titan.designer.AST.TTCN3.values.Expression_Value; import org.eclipse.titan.designer.parsers.CompilationTimeStamp; import org.eclipse.titan.designer.parsers.ttcn3parser.ReParseException; import org.eclipse.titan.designer.parsers.ttcn3parser.TTCN3ReparseUpdater; /** * @author Kristof Szabados * */ public final class GetverdictExpression extends Expression_Value { private static final String OPERATIONNAME = "getverdict"; @Override public Operation_type getOperationType() { return Operation_type.GETVERDICT_OPERATION; } @Override public Type_type getExpressionReturntype(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue) { return Type_type.TYPE_VERDICT; } @Override public String createStringRepresentation() { return "getverdict()"; } @Override public boolean isUnfoldable(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { return true; } /** * Checks the parameters of the expression and if they are valid in * their position in the expression or not. * * @param timestamp * the timestamp of the actual semantic check cycle. * @param expectedValue * the kind of value expected. * @param referenceChain * a reference chain to detect cyclic references. * */ private void checkExpressionOperands(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { checkExpressionDynamicPart(expectedValue, OPERATIONNAME, false, true, false); } @Override public IValue evaluateValue(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { if (lastTimeChecked != null && !lastTimeChecked.isLess(timestamp)) { return lastValue; } isErroneous = false; lastTimeChecked = timestamp; lastValue = this; checkExpressionOperands(timestamp, expectedValue, referenceChain); return lastValue; } @Override public void updateSyntax(final TTCN3ReparseUpdater reparser, final boolean isDamaged) throws ReParseException { if (isDamaged) { throw new ReParseException(); } } @Override protected boolean memberAccept(final ASTVisitor v) { // no members return true; } }
epl-1.0
dhuebner/che
core/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/notification/NotificationManagerImpl.java
11846
/******************************************************************************* * 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.ide.notification; import com.google.gwt.core.client.Scheduler; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.api.workspace.shared.dto.ProjectConfigDto; import org.eclipse.che.ide.Resources; import org.eclipse.che.ide.api.mvp.View; import org.eclipse.che.ide.api.notification.Notification; import org.eclipse.che.ide.api.notification.NotificationListener; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.notification.NotificationObserver; import org.eclipse.che.ide.api.notification.StatusNotification; import org.eclipse.che.ide.api.notification.StatusNotification.Status; import org.eclipse.che.ide.api.parts.HasView; import org.eclipse.che.ide.api.parts.base.BasePresenter; import org.vectomatic.dom.svg.ui.SVGResource; import java.util.ArrayList; import java.util.List; import static java.lang.Enum.valueOf; import static org.eclipse.che.ide.api.notification.ReadState.READ; /** * The implementation of {@link NotificationManager}. * Base notification part. Perform showing notification in the "Events panel". Also checking is performed on each created notification. * <p/> * Each notification may be simple notification {@link Notification} or status notification {@link StatusNotification}. * <p/> * If notification instance of {@link StatusNotification} then notification may be showed as balloon widget by need. By default all * notifications are showed only in events panel. * * @author Andrey Plotnikov * @author Dmitry Shnurenko */ @Singleton public class NotificationManagerImpl extends BasePresenter implements NotificationManager, NotificationObserver, NotificationManagerView.ActionDelegate, HasView { public static final String TITLE = "Events"; public static final String TOOLTIP = "Event Log"; private NotificationManagerView view; private NotificationContainer nContainer; private NotificationPopupStack nPopupStack; private List<Notification> notifications = new ArrayList<>(); private Resources resources; /** Count of unread notifications */ private int unread = 0; /** Flag that display panel open state */ private boolean opened; /** * Create instance of notification panel. * * @param view * the view * @param nContainer * notification container. It holds showed notifications * @param nPopupStack * popup notification stack. It showed each notification as balloon * @param resources * core resources */ @Inject public NotificationManagerImpl(NotificationManagerView view, NotificationContainer nContainer, NotificationPopupStack nPopupStack, Resources resources) { this.view = view; this.nContainer = nContainer; this.nContainer.setDelegate(this); this.nPopupStack = nPopupStack; this.nPopupStack.setDelegate(this); this.view.setDelegate(this); this.view.setContainer(nContainer); this.view.setTitle(TITLE); this.resources = resources; } /** {@inheritDoc} */ @Override public View getView() { return view; } /** {@inheritDoc} */ @Override public void onValueChanged() { unread = 0; if (!opened) { for (Notification notification : notifications) { if (!notification.isRead()) { unread++; } } } firePropertyChange(TITLE_PROPERTY); } /** {@inheritDoc} */ @Override public int getUnreadNotificationsCount() { return unread; } /** {@inheritDoc} */ @Override public <T extends Notification> T notify(T notification) { notification.addObserver(this); notifications.add(notification); if (notification instanceof StatusNotification && ((StatusNotification)notification).isBalloon()) { nPopupStack.push((StatusNotification)notification); } nContainer.addNotification(notification); onValueChanged(); Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { view.scrollBottom(); } }); return notification; } /** {@inheritDoc} */ @Override public Notification notify(String title) { return notify(new Notification(title)); } /** {@inheritDoc} */ @Override public Notification notify(String title, String content) { return notify(title, content, (NotificationListener)null); } /** {@inheritDoc} */ @Override public Notification notify(String title, String content, NotificationListener listener) { return notify(title, content, listener, null); } /** {@inheritDoc} */ @Override public Notification notify(String title, NotificationListener listener) { return notify(title, listener, null); } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, Status status, boolean balloon) { return notify(new StatusNotification(title, status, balloon)); } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, Status status, boolean balloon, NotificationListener listener) { return null; } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, String content, Status status, boolean balloon) { return notify(title, content, status, balloon, (NotificationListener)null); } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, String content, Status status, boolean balloon, NotificationListener listener) { return notify(title, content, status, balloon, listener, null); } /** {@inheritDoc} */ @Override public Notification notify(String title, String content, ProjectConfigDto project) { return notify(title, content, null, project); } /** {@inheritDoc} */ @Override public Notification notify(String title, ProjectConfigDto project) { return notify(title, (NotificationListener)null, project); } /** {@inheritDoc} */ @Override public Notification notify(String title, String content, NotificationListener listener, ProjectConfigDto project) { return notify(new Notification(title, content, project, listener)); } /** {@inheritDoc} */ @Override public Notification notify(String title, NotificationListener listener, ProjectConfigDto project) { return notify(title, null, listener, project); } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, String content, Status status, boolean balloon, ProjectConfigDto project) { return notify(title, content, status, balloon, null, project); } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, Status status, boolean balloon, ProjectConfigDto project) { return notify(title, null, status, balloon, null, project); } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, String content, Status status, boolean balloon, NotificationListener listener, ProjectConfigDto project) { return notify(new StatusNotification(title, content, status, balloon, project, listener)); } /** {@inheritDoc} */ @Override public StatusNotification notify(String title, Status status, boolean balloon, NotificationListener listener, ProjectConfigDto project) { return notify(title, null, status, balloon, listener, project); } /** * Remove notification. * * @param notification * notification that need to remove */ public void removeNotification(Notification notification) { notification.removeObserver(this); notifications.remove(notification); nContainer.removeNotification(notification); onValueChanged(); } /** {@inheritDoc} */ @Override public void onClick(Notification notification) { NotificationListener listener = notification.getListener(); if (listener != null) { listener.onClick(); } } /** {@inheritDoc} */ @Override public void onDoubleClick(Notification notification) { NotificationListener listener = notification.getListener(); if (listener != null) { listener.onDoubleClick(); } } /** {@inheritDoc} */ @Override public void onClose(Notification notification) { removeNotification(notification); NotificationListener listener = notification.getListener(); if (listener != null) { listener.onClose(); } } /** {@inheritDoc} */ @Override public String getTitle() { return TITLE; } /** {@inheritDoc} */ @Override public void setVisible(boolean visible) { view.setVisible(visible); } /** {@inheritDoc} */ @Override public SVGResource getTitleSVGImage() { return resources.eventsPartIcon(); } /** {@inheritDoc} */ @Override public String getTitleToolTip() { return TOOLTIP; } /** {@inheritDoc} */ @Override public void go(AcceptsOneWidget container) { container.setWidget(view); } /** {@inheritDoc} */ @Override public void onOpen() { super.onOpen(); for (Notification notification : notifications) { notification.setState(READ); } } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.luxtronikheatpump/src/main/java/org/openhab/binding/luxtronikheatpump/internal/HeatpumpConnector.java
7370
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.luxtronikheatpump.internal; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link HeatpumpConnector} reads / writes internal states of a Heat pump with Luxtronik control. * * Based on HeatpumpConnector class of novelanheatpump binding * * @author Stefan Giehl - Initial contribution */ @NonNullByDefault public class HeatpumpConnector { private static final int SOCKET_PARAM_WRITE_PARAMS = 3002; private static final int SOCKET_PARAM_READ_PARAMS = 3003; private static final int SOCKET_PARAM_READ_VALUES = 3004; private static final int SOCKET_PARAM_READ_VISIBILITIES = 3005; private final Logger logger = LoggerFactory.getLogger(HeatpumpConnector.class); private String serverIp; private int serverPort; private Integer[] heatpumpValues = new Integer[0]; private Integer[] heatpumpParams = new Integer[0]; private Integer[] heatpumpVisibilities = new Integer[0]; public HeatpumpConnector(String serverIp, int serverPort) { this.serverIp = serverIp; this.serverPort = serverPort; } /** * reads all values from the heatpump via network * * @throws UnknownHostException indicate that the IP address of a host could not be determined. * @throws IOException indicate that no data can be read from the heat pump */ public void read() throws UnknownHostException, IOException { try (Socket sock = new Socket(serverIp, serverPort)) { InputStream in = sock.getInputStream(); OutputStream out = sock.getOutputStream(); DataInputStream datain = new DataInputStream(in); DataOutputStream dataout = new DataOutputStream(out); heatpumpValues = readInt(datain, dataout, SOCKET_PARAM_READ_VALUES); // workaround for thermal energies // the thermal energies can be unreasonably high in some cases, probably due to a sign bug in the firmware // trying to correct this issue here for (int i = 151; i <= 154; i++) { if (heatpumpValues[i] >= 214748364) { heatpumpValues[i] -= 214748364; } } heatpumpParams = readInt(datain, dataout, SOCKET_PARAM_READ_PARAMS); heatpumpVisibilities = readInt(datain, dataout, SOCKET_PARAM_READ_VISIBILITIES); datain.close(); dataout.close(); } } /** * read the parameters of the heat pump */ public Integer[] getParams() { return heatpumpParams; } /** * set a parameter of the heat pump * * @param param * @param value * @throws IOException indicate that no data can be sent to the heat pump */ public boolean setParam(int param, int value) throws IOException { try (Socket sock = new Socket(serverIp, serverPort)) { InputStream in = sock.getInputStream(); OutputStream out = sock.getOutputStream(); DataInputStream datain = new DataInputStream(in); DataOutputStream dataout = new DataOutputStream(out); while (datain.available() > 0) { datain.readByte(); } // write command, param and value to heatpump socket dataout.writeInt(SOCKET_PARAM_WRITE_PARAMS); dataout.writeInt(param); dataout.writeInt(value); dataout.flush(); // first integer on socket output should represent the command int cmd = datain.readInt(); datain.readInt(); datain.close(); dataout.close(); if (cmd != SOCKET_PARAM_WRITE_PARAMS) { logger.debug("Couldn't write parameter {} with value {} to heat pump.", param, value); return false; } else { logger.debug("Parameter {} with value {} successfully written to heat pump.", param, value); return true; } } } /** * Returns the internal states of the heat pump * * @return a array with all internal data of the heat pump */ public Integer[] getValues() { return heatpumpValues; } /** * Returns the internal visibilities of the heat pump * * @return a array with all internal visibilities of the heat pump */ public Integer[] getVisibilities() { return heatpumpVisibilities; } /** * Reads all available values for the given parameter from socket * * @param datain data input stream of socket connection * @param dataout data output stream of socket connection * @param parameter int command to read from socket * @return an array with all values returned from heat pump socket * @throws IOException indicate that no data can be read from the heat pump */ private Integer[] readInt(DataInputStream datain, DataOutputStream dataout, int parameter) throws IOException { Integer[] result = null; while (datain.available() > 0) { datain.readByte(); } // to receive values we first need to write the command followed by four 0 byte values to the socket dataout.writeInt(parameter); dataout.writeInt(0); dataout.flush(); // the first integer received from socket should match the written command if (datain.readInt() != parameter) { return new Integer[0]; } if (parameter == SOCKET_PARAM_READ_VALUES) { // when reading values the next integer represents some kind of status datain.readInt(); } // the next integer value should define the number of values that are following // Currently the list or parameters is the longest list and contains around 1050 values // To avoid possible (memory) problems in case the returned number would be unexpected high we limit it to 2000 int arraylength = Integer.min(datain.readInt(), 2000); logger.debug("Found {} values for {}", arraylength, parameter); result = new Integer[arraylength]; // Note: the visibility params are returned as single byte values // probably as the are used as boolean values (0/1) only if (parameter == SOCKET_PARAM_READ_VISIBILITIES) { byte[] data = datain.readNBytes(arraylength); for (int i = 0; i < data.length; i++) { result[i] = (int) data[i]; } return result; } for (int i = 0; i < arraylength; i++) { result[i] = datain.readInt(); } return result; } }
epl-1.0
debabratahazra/DS
designstudio/components/page/core/com.odcgroup.page.generation/src/main/java/com/odcgroup/page/generation/AbstractXspCodeGenerator.java
4551
package com.odcgroup.page.generation; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; import org.apache.commons.io.FileUtils; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.odcgroup.page.common.PageConstants; import com.odcgroup.page.model.Model; import com.odcgroup.page.model.Widget; import com.odcgroup.page.transformmodel.util.TransformUtils; import com.odcgroup.workbench.core.IOfsModelResource; import com.odcgroup.workbench.core.InvalidMetamodelVersionException; import com.odcgroup.workbench.core.repository.OfsResourceHelper; import com.odcgroup.workbench.generation.cartridge.CodeGenerator; /** * Implementation of the <code>CodeGenerator</code> interface to allow integration with the workbench code generation * process. * * @author fch * @author Gary Hayes */ abstract public class AbstractXspCodeGenerator implements CodeGenerator { private static Logger logger = LoggerFactory.getLogger(AbstractXspCodeGenerator.class); /** * */ private static final String OAMS_PROFILES = "/oams-profiles"; /** * @param rootWidget * @return {@code true} if the generation must be done for this root widget */ protected boolean acceptGeneration(Widget rootWidget) { return true; } /** * Execute the code generation. * * @param project * @param modelResources * @param outputFolder * @throws CoreException */ public void run(IProgressMonitor monitor, IProject project, Collection<IOfsModelResource> modelResources, IFolder outputFolder, List<IStatus> nonOkStatuses) { Assert.isNotNull(outputFolder, "output folder must be not be null"); //PageGenerationCore.getDefault().logInfo("Start XSP Generator", null); long start = System.currentTimeMillis(); String baseOutputFilePath = outputFolder.getLocation().toOSString(); String extension = getHandledFileExtension(); Collection<IOfsModelResource> xspResources = OfsResourceHelper.filter(modelResources, new String[]{extension}); for (IOfsModelResource modelResource : xspResources) { // Alter the file extension String rn = modelResource.getURI().lastSegment(); String outputFileName = rn.substring(0, rn.indexOf('.')) + "." + PageConstants.XSP_FILE_EXTENSION; //String projectName = project.getName(); String outputFilePath = baseOutputFilePath + OAMS_PROFILES + getOutputFilePath(modelResource); File outputFile = new File(outputFilePath + "/" + outputFileName); try { Model model = (Model)modelResource.getEMFModel().get(0); Widget widget = model.getWidget(); // root widget if (acceptGeneration(widget)) { FileUtils.writeStringToFile(outputFile, TransformUtils.transformWidgetToXmlString(modelResource.getOfsProject().getProject(), widget)); } } catch (IOException e) { String errorMsg = "Error generating XML code for widget in " + getClass().getName() + " for resource '" + modelResource.getName() + "'"; newCoreException(e, nonOkStatuses, errorMsg); } catch (InvalidMetamodelVersionException e) { String errorMsg = "Error generating XML code for widget in " + getClass().getName() + " for resource '" + modelResource.getName() + "'"; newCoreException(e, nonOkStatuses, errorMsg); } } long stop = System.currentTimeMillis(); long duration = stop-start; PageGenerationCore.getDefault().logInfo("XSP Generator generates: " + xspResources.size() + " " + extension + "s in " + duration + " ms", null); } /** * Gets the files extension handled by this Code Generator. * * @return String The file extension handled by this Code Generator */ abstract protected String getHandledFileExtension(); /** * Gets the output file path relative to the project. * * @param resource The input resource * @return String The output file path */ abstract protected String getOutputFilePath(IOfsModelResource resource); protected void newCoreException(Exception e, List<IStatus> nonOkStatuses, String errorMsg) { logger.error(errorMsg, e); final IStatus errorStatus = new Status(IStatus.ERROR, PageGenerationCore.PLUGIN_ID, 0, errorMsg + ": " + e.getMessage(), e); nonOkStatuses.add(errorStatus); } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmladapter/property/AdapterOnPropertyTestCases.java
3381
/******************************************************************************* * 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: * dmccann - July 14/2009 - 2.0 - Initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.externalizedmetadata.xmladapter.property; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases; public class AdapterOnPropertyTestCases extends JAXBWithJSONTestCases{ private static final String XML_RESOURCE = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmladapter/myclass.xml"; private static final String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmladapter/myclass.json"; private final static int DAY = 12; private final static int MONTH = 4; private final static int YEAR = 1997; private static Calendar CALENDAR = new GregorianCalendar(YEAR, MONTH, DAY); private final static int ID = 66; public AdapterOnPropertyTestCases(String name) throws Exception { super(name); setClasses(new Class[]{org.eclipse.persistence.testing.jaxb.externalizedmetadata.xmladapter.property.MyClass.class}); setControlDocument(XML_RESOURCE); setControlJSON(JSON_RESOURCE); } protected Object getControlObject() { org.eclipse.persistence.testing.jaxb.externalizedmetadata.xmladapter.property.MyClass sc = new org.eclipse.persistence.testing.jaxb.externalizedmetadata.xmladapter.property.MyClass(); sc.cal = CALENDAR; sc.id = ID; return sc; } public Map getProperties(){ InputStream inputStream = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmladapter/property/eclipselink-oxm.xml"); HashMap<String, Source> metadataSourceMap = new HashMap<String, Source>(); metadataSourceMap.put("org.eclipse.persistence.testing.jaxb.externalizedmetadata.xmladapter.property", new StreamSource(inputStream)); Map<String, Map<String, Source>> properties = new HashMap<String, Map<String, Source>>(); properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadataSourceMap); return properties; } public void testSchemaGen() throws Exception { List controlSchemas = new ArrayList(); InputStream is = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/jaxb/externalizedmetadata/xmladapter/schema.xsd"); controlSchemas.add(is); super.testSchemaGen(controlSchemas); } }
epl-1.0
FTSRG/viatra-dse-distributed
org.eclipse.viatra.dse.cluster/src/org/eclipse/viatra/dse/cluster/interfaces/IStrategyFactory.java
177
package org.eclipse.viatra.dse.cluster.interfaces; import org.eclipse.viatra.dse.api.strategy.interfaces.IStrategy; public interface IStrategyFactory { IStrategy create(); }
epl-1.0
dhuebner/che
plugins/plugin-machine/che-plugin-machine-ext-client/src/main/java/org/eclipse/che/ide/extension/machine/client/command/valueproviders/ServerPortProvider.java
4713
/******************************************************************************* * 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.ide.extension.machine.client.command.valueproviders; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.web.bindery.event.shared.EventBus; import org.eclipse.che.api.machine.gwt.client.MachineServiceClient; import org.eclipse.che.api.machine.shared.dto.MachineDto; import org.eclipse.che.api.machine.shared.dto.ServerDto; import org.eclipse.che.api.promises.client.Operation; import org.eclipse.che.api.promises.client.OperationException; import org.eclipse.che.api.workspace.gwt.client.event.WorkspaceStartedEvent; import org.eclipse.che.api.workspace.gwt.client.event.WorkspaceStartedHandler; import org.eclipse.che.api.workspace.gwt.client.event.WorkspaceStoppedEvent; import org.eclipse.che.api.workspace.gwt.client.event.WorkspaceStoppedHandler; import org.eclipse.che.api.workspace.shared.dto.UsersWorkspaceDto; import org.eclipse.che.ide.api.app.AppContext; import java.util.Map; import java.util.Set; /** * Provide mapping internal port, i.e. ${server.port.8080} to 127.0.0.1:21212. * * @author Vlad Zhukovskiy */ @Singleton public class ServerPortProvider implements WorkspaceStartedHandler, WorkspaceStoppedHandler { public static final String KEY_TEMPLATE = "${server.port.%}"; private final MachineServiceClient machineServiceClient; private final CommandPropertyValueProviderRegistry commandPropertyRegistry; private final AppContext appContext; private Set<CommandPropertyValueProvider> providers; private final Operation<MachineDto> registerProviders = new Operation<MachineDto>() { @Override public void apply(MachineDto machine) throws OperationException { providers = getProviders(machine); commandPropertyRegistry.register(providers); } }; @Inject public ServerPortProvider(EventBus eventBus, MachineServiceClient machineServiceClient, CommandPropertyValueProviderRegistry commandPropertyRegistry, AppContext appContext) { this.machineServiceClient = machineServiceClient; this.commandPropertyRegistry = commandPropertyRegistry; this.appContext = appContext; eventBus.addHandler(WorkspaceStartedEvent.TYPE, this); eventBus.addHandler(WorkspaceStoppedEvent.TYPE, this); registerProviders(); } private void registerProviders() { String devMachineId = appContext.getDevMachineId(); if (devMachineId != null) { machineServiceClient.getMachine(devMachineId).then(registerProviders); } } private Set<CommandPropertyValueProvider> getProviders(MachineDto machine) { Set<CommandPropertyValueProvider> providers = Sets.newHashSet(); for (Map.Entry<String, ServerDto> entry : machine.getRuntime().getServers().entrySet()) { providers.add(new AddressProvider(entry.getKey(), entry.getValue().getAddress())); if (entry.getKey().endsWith("/tcp")) { providers.add(new AddressProvider(entry.getKey().substring(0, entry.getKey().length() - 4), entry.getValue().getAddress())); } } return providers; } @Override public void onWorkspaceStarted(UsersWorkspaceDto workspace) { registerProviders(); } @Override public void onWorkspaceStopped(WorkspaceStoppedEvent event) { for (CommandPropertyValueProvider provider : providers) { commandPropertyRegistry.unregister(provider); } providers.clear(); } private class AddressProvider implements CommandPropertyValueProvider { String variable; String address; AddressProvider(String internalPort, String address) { this.variable = KEY_TEMPLATE.replaceAll("%", internalPort); this.address = address; } @Override public String getKey() { return variable; } @Override public String getValue() { return address; } } }
epl-1.0
ddmarshall/Code-Eli
test/geom/bounding_box/bounding_box_test.cpp
4653
/********************************************************************************* * Copyright (c) 2013 David D. Marshall <ddmarsha@calpoly.edu> * * 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: * David D. Marshall - initial code and implementation ********************************************************************************/ #include <cstdlib> // EXIT_SUCCESS #include <ctime> // time functions #include <cstring> // std::strlen, std::strncmp #include <string> // std::string #include <fstream> // std::fstream #include <memory> // std::auto_ptr #include <ctime> // strftime #include <cpptest.h> // CppTest Framework #include "bounding_box_test_suite.hpp" // bounding_box_test_suite enum TestType {testTypeText, testTypeCompiler, testTypeHTML}; int main(int argc, char *argv[]) { Test::Output *pout; TestType tt(testTypeCompiler); int rtn(EXIT_SUCCESS); // if user passed command line argument then parse it if (argc==1) { tt=testTypeCompiler; } else if (argc==2) { size_t lenargv(strlen(argv[1])); // using short codes if (lenargv==2) { if (argv[1][0]=='-') { switch(argv[1][1]) { case('t'): tt=testTypeText; break; case('c'): tt=testTypeCompiler; break; case('h'): tt=testTypeHTML; break; default: std::cerr << "Unrecognized parameter: " << argv[1] << std::endl; rtn=EXIT_FAILURE; break; } } else { std::cerr << "Unrecognized parameter: " << argv[1] << std::endl; rtn=EXIT_FAILURE; } } else { if (lenargv==6) { if (std::strncmp(argv[1], "--text", lenargv)==0) tt=testTypeText; else if (std::strncmp(argv[1], "--html", lenargv)==0) tt=testTypeHTML; else if (std::strncmp(argv[1], "--help", lenargv)==0) rtn=EXIT_FAILURE; else { std::cerr << "Unrecognized parameter: " << argv[1] << std::endl; rtn=EXIT_FAILURE; } } else if (lenargv==10) { if (std::strncmp(argv[1], "--compiler", lenargv)==0) tt=testTypeCompiler; else { std::cerr << "Unrecognized parameter: " << argv[1] << std::endl; rtn=EXIT_FAILURE; } } } } else { std::cerr << "Can only pass one argument." << std::endl; rtn=EXIT_FAILURE; } if (rtn==EXIT_FAILURE) { std::cerr << " Usage: " << argv[0] << " [--text|-t|--compiler|-c|--html|-h]" << std::endl; return rtn; } // allocate the correct output type switch (tt) { case(testTypeText): { Test::TextOutput *po = new Test::TextOutput(Test::TextOutput::Verbose); pout = static_cast<Test::Output *>(po); break; } case(testTypeCompiler): { Test::CompilerOutput *po = new Test::CompilerOutput(Test::CompilerOutput::GCC); pout = static_cast<Test::Output *>(po); break; } case(testTypeHTML): { Test::HtmlOutput *po = new Test::HtmlOutput; pout = static_cast<Test::Output *>(po); break; } default: { rtn=EXIT_FAILURE; break; } } if (rtn == EXIT_SUCCESS) { // get the current time information time_t rawtime; struct tm * timeinfo; std::string datetime; time (&rawtime); timeinfo = localtime(&rawtime); datetime = asctime(timeinfo); // add the test suites to the test runner // NOTE: This is where changes should be needed // Test::Suite ts; std::string ostr_filename("fit_container_test_results.html"); // add the cppack test suites ts.add(std::auto_ptr<Test::Suite>(new bounding_box_test_suite<float>())); ts.add(std::auto_ptr<Test::Suite>(new bounding_box_test_suite<double>())); ts.add(std::auto_ptr<Test::Suite>(new bounding_box_test_suite<long double>())); // // NOTE: End of section that should be changed // run the test rtn = (ts.run(*pout)) ? EXIT_SUCCESS : EXIT_FAILURE; // generate the html data if requested if (tt==testTypeHTML) { std::ofstream ostr(ostr_filename.c_str()); Test::HtmlOutput *phtmlout=dynamic_cast<Test::HtmlOutput *>(pout); phtmlout->generate(ostr, true, datetime); ostr.close(); } delete pout; } return rtn; }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/directtofield/identifiedbyname/xmlelement/DirectToXMLElementIdentifiedByNameSpecialCharactersTestCases.java
2754
/******************************************************************************* * 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: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings.directtofield.identifiedbyname.xmlelement; import java.io.StringWriter; import org.eclipse.persistence.oxm.XMLContext; import org.eclipse.persistence.oxm.XMLMarshaller; import org.eclipse.persistence.testing.oxm.OXTestCase; import org.eclipse.persistence.testing.oxm.mappings.directtofield.identifiedbyname.Employee; import org.eclipse.persistence.internal.helper.Helper; public class DirectToXMLElementIdentifiedByNameSpecialCharactersTestCases extends OXTestCase { private final static int CONTROL_ID = 123; private final static String CONTROL_FIRST_NAME = "A<\"B&C<"; private final static String CONTROL_LAST_NAME = null; private final static String CONTROL_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Helper.cr() + "<employee><id>123</id><first-name>A&lt;&quot;B&amp;C&lt;</first-name></employee>"; private XMLMarshaller xmlMarshaller; public DirectToXMLElementIdentifiedByNameSpecialCharactersTestCases(String name) { super(name); } public void setUp() { DirectToXMLElementIdentifiedByNameProject project = new DirectToXMLElementIdentifiedByNameProject(); XMLContext xmlContext = new XMLContext(project); xmlMarshaller = xmlContext.createMarshaller(); xmlMarshaller.setFormattedOutput(false); } public void testMarshalSpecialCharacters() { StringWriter stringWriter = new StringWriter(); xmlMarshaller.marshal(getControlObject(), stringWriter); String testXML = stringWriter.toString(); log("EXPECTED:"); log(CONTROL_XML); log("ACTUAL:"); log(testXML); assertEquals(CONTROL_XML, testXML); } private Object getControlObject() { Employee employee = new Employee(); employee.setID(CONTROL_ID); employee.setFirstName(CONTROL_FIRST_NAME); employee.setLastName(CONTROL_LAST_NAME); return employee; } }
epl-1.0
remiverney/data-generator
event-data-generator-base/src/main/java/org/datagen/dataset/DataRecord.java
187
package org.datagen.dataset; import java.io.Serializable; public interface DataRecord extends Serializable { DataDefinition getDefinition(); Serializable[] getValues(); }
epl-1.0
1974kpkpkp/eclipse-integration-cloudfoundry
org.cloudfoundry.ide.eclipse.server.ui/src/org/cloudfoundry/ide/eclipse/internal/server/ui/wizards/WizardHandleContext.java
1499
/******************************************************************************* * Copyright (c) 2014 Pivotal Software, Inc. * 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: * Pivotal Software, Inc. - initial API and implementation *******************************************************************************/ package org.cloudfoundry.ide.eclipse.internal.server.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.wst.server.ui.wizard.IWizardHandle; /** * Provides a wizard context for UI Parts, that includes getting a runnable * context for performing operations in a wizard. */ public class WizardHandleContext { private final IWizardHandle wizardHandle; public WizardHandleContext(IWizardHandle wizardHandle) { this.wizardHandle = wizardHandle; } public IWizardHandle getWizardHandle() { return wizardHandle; } public IRunnableContext getRunnableContext() { return new IRunnableContext() { public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { wizardHandle.run(fork, cancelable, runnable); } }; } }
epl-1.0
corneil/spring-data-demo
spring-data-plain-demo/src/main/java/org/springframework/data/demo/data/DeviceInfo.java
783
package org.springframework.data.demo.data; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import org.springframework.data.mongodb.core.index.Indexed; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.NotNull; @Entity @org.springframework.data.mongodb.core.mapping.Document @Data public class DeviceInfo { @NotNull @Indexed(unique = true) @Column(unique = true) private String deviceId; private String deviceName; @Id @com.couchbase.client.java.repository.annotation.Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid2") private String id; }
epl-1.0
bradsdavis/cxml-api
src/main/java/org/cxml/v12028/Format.java
2016
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.09.23 at 11:14:20 AM CEST // package org.cxml.v12028; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "Format") public class Format { @XmlAttribute(name = "version", required = true) @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String version; @XmlValue protected String value; /** * Gets the value of the version property. * * @return * possible object is * {@link String } * */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link String } * */ public void setVersion(String value) { this.version = value; } /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getvalue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setvalue(String value) { this.value = value; } }
epl-1.0
paulvi/eclipse-integration-gradle
org.springsource.ide.eclipse.gradle.ui/src/org/springsource/ide/eclipse/gradle/ui/launch/GradleLaunchTasksTab.java
10013
/******************************************************************************* * Copyright (c) 2012 Pivotal Software, Inc. * 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: * Pivotal Software, Inc. - initial API and implementation *******************************************************************************/ package org.springsource.ide.eclipse.gradle.ui.launch; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.ui.AbstractLaunchConfigurationTab; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.springsource.ide.eclipse.gradle.core.GradleCore; import org.springsource.ide.eclipse.gradle.core.GradleNature; import org.springsource.ide.eclipse.gradle.core.GradleProject; import org.springsource.ide.eclipse.gradle.core.classpathcontainer.FastOperationFailedException; import org.springsource.ide.eclipse.gradle.core.launch.GradleLaunchConfigurationDelegate; import org.springsource.ide.eclipse.gradle.core.util.GradleProjectIndex; import org.springsource.ide.eclipse.gradle.ui.cli.editor.TasksViewer; /** * @author Kris De Volder * @author Alex Boyko */ public class GradleLaunchTasksTab extends AbstractLaunchConfigurationTab { private static final boolean DEBUG = false; private static final String CTRL_SPACE_LABEL = "<Ctrl> + <Space>"; private static final String EDITOR_INFO_LABEL = "Type tasks in the editor below. Use " + CTRL_SPACE_LABEL + " to activate content assistant."; private Combo projectCombo; private GradleProject project; private GradleProjectIndex tasksIndex= new GradleProjectIndex(); private TasksViewer tasksViewer; private Button refreshButton; public void createControl(Composite parent) { Composite page = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); page.setLayout(layout); createProjectCombo(page); createTaskEditor(page); setControl(page); } private void createProjectCombo(Composite _parent) { GridDataFactory grabHor = GridDataFactory.fillDefaults().grab(true, false); Composite parent = new Composite(_parent, SWT.NONE); parent.setLayout(new GridLayout(3,false)); grabHor.applyTo(parent); Label label = new Label(parent, SWT.NONE); label.setText("Project"); projectCombo = new Combo(parent, SWT.DROP_DOWN|SWT.READ_ONLY); List<GradleProject> projects = getGradleProjects(); String[] items = new String[projects.size()]; int i = 0; for (GradleProject p : projects) { items[i++] = p.getName(); } projectCombo.setItems(items); if (project!=null) { projectCombo.setText(project.getName()); } projectCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String newProjectName = projectCombo.getText(); if ("".equals(newProjectName)) { setProject(null); setTasksDocument(""); } else { IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(newProjectName); setProject(GradleCore.create(newProject)); setTasksDocument(tasksViewer.getSourceViewer().getDocument().get()); } } }); refreshButton = new Button(parent, SWT.PUSH); refreshButton.setText("Refresh"); refreshButton.setToolTipText("Rebuild the gradle model and refresh the task list"); refreshButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent evt) { GradleProject currentProject = project; if (currentProject != null) { try { project.requestGradleModelRefresh(); } catch (CoreException e) { // ignore } tasksIndex.setProject(project); } } }); grabHor.align(SWT.RIGHT, SWT.CENTER).applyTo(refreshButton); } private List<GradleProject> getGradleProjects() { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); ArrayList<GradleProject> result = new ArrayList<GradleProject>(); for (IProject p : projects) { try { if (p.isAccessible() && p.hasNature(GradleNature.NATURE_ID)) { result.add(GradleCore.create(p)); } } catch (CoreException e) { GradleCore.log(e); } } return result; } private void createTaskEditor(final Composite parent) { StyledText styledText = new StyledText(parent, SWT.READ_ONLY | SWT.WRAP); styledText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); styledText.setBackground(parent.getBackground()); styledText.setText(EDITOR_INFO_LABEL); styledText.setStyleRange(new StyleRange(EDITOR_INFO_LABEL .indexOf(CTRL_SPACE_LABEL), CTRL_SPACE_LABEL.length(), styledText.getForeground(), styledText.getBackground(), SWT.BOLD | SWT.ITALIC)); tasksViewer = new TasksViewer(parent, tasksIndex, false); tasksViewer.setActivateContentAssistOnEmptyDocument(true); tasksViewer.getSourceViewer().getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); setTasksDocument(""); } public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { setProject(getContext()); setTasksDocument(""); } private void setProject(GradleProject project) { //TODO: when restoring from persistent conf, can get non-existent projects... // how to handle that case? if (this.project==project) //Don't do anything if project is unchanged return; this.project = project; tasksIndex.setProject(project); if (projectCombo!=null) { if (project!=null) { projectCombo.setText(project.getName()); } else { projectCombo.deselectAll(); } } updateLaunchConfigurationDialog(); } private GradleProject getContext() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = win==null ? null : win.getActivePage(); if (page != null) { ISelection selection = page.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection)selection; if (!ss.isEmpty()) { Object obj = ss.getFirstElement(); if (obj instanceof IResource) { IResource rsrc = (IResource) obj; IProject prj = rsrc.getProject(); if (prj!=null) { return GradleCore.create(prj); } } } } IEditorPart part = page.getActiveEditor(); if (part != null) { IEditorInput input = part.getEditorInput(); IResource rsrc = (IResource) input.getAdapter(IResource.class); if (rsrc!=null) { IProject prj = rsrc.getProject(); if (prj!=null) { return GradleCore.create(prj); } } } } return null; } public void initializeFrom(ILaunchConfiguration conf) { debug(">>> initializing Gradle launch tab"); try { for (Object attName : conf.getAttributes().keySet()) { debug(""+attName); } } catch (CoreException e) { GradleCore.log(e); } debug("<<< initializing Gradle launch tab"); setProject(GradleLaunchConfigurationDelegate.getProject(conf)); setTasksDocument(GradleLaunchConfigurationDelegate.getTasks(conf)); } private void setTasksDocument(String tasks) { Document document = new Document(tasks); document.addDocumentListener(new IDocumentListener() { @Override public void documentChanged(DocumentEvent event) { GradleLaunchTasksTab.this.updateLaunchConfigurationDialog(); } @Override public void documentAboutToBeChanged(DocumentEvent event) { // empty } }); tasksViewer.setDocument(document); } @Override public void updateLaunchConfigurationDialog() { super.updateLaunchConfigurationDialog(); } private static void debug(String string) { if (DEBUG) { System.out.println(string); } } @Override public boolean canSave() { //Don't allow saving until the model is properly initialized. If it isn't, the checkboxes in the tree //don't have well defined state. return haveGradleModel(); } public boolean isValid() { return canSave(); } public void performApply(ILaunchConfigurationWorkingCopy conf) { GradleLaunchConfigurationDelegate.setProject(conf, project); GradleLaunchConfigurationDelegate.setTasks(conf, tasksViewer.getSourceViewer().getDocument().get()); } private boolean haveGradleModel() { try { return project != null && project.getGradleModel()!=null; } catch (FastOperationFailedException e) { } catch (CoreException e) { GradleCore.log(e); } return false; } public String getName() { return "Gradle Tasks"; } @Override public void dispose() { tasksViewer.dispose(); super.dispose(); } }
epl-1.0
sabev/sap-services-registry-eclipse
org.eclipse.servicesregistry.proxy/src/org/eclipse/servicesregistry/proxy/types/ServicesRegistrySipublishClassificationSystemsFault12.java
1775
/******************************************************************************* * Copyright (c) 2012 SAP AG 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: * SAP AG - initial API and implementation *******************************************************************************/ package org.eclipse.servicesregistry.proxy.types; /** * Exception class for service fault. */ @javax.xml.ws.WebFault(name = "SRPublicationException", targetNamespace = "http://sap.com/esi/uddi/sr/api/ws/", faultBean = "org.eclipse.servicesregistry.proxy.types.SRPublicationException") public class ServicesRegistrySipublishClassificationSystemsFault12 extends java.lang.Exception { private org.eclipse.servicesregistry.proxy.types.SRPublicationException _ServicesRegistrySipublishClassificationSystemsFault12; public ServicesRegistrySipublishClassificationSystemsFault12(String message, org.eclipse.servicesregistry.proxy.types.SRPublicationException faultInfo){ super(message); this._ServicesRegistrySipublishClassificationSystemsFault12 = faultInfo; } public ServicesRegistrySipublishClassificationSystemsFault12(String message, org.eclipse.servicesregistry.proxy.types.SRPublicationException faultInfo, Throwable cause){ super(message, cause); this._ServicesRegistrySipublishClassificationSystemsFault12 = faultInfo; } public org.eclipse.servicesregistry.proxy.types.SRPublicationException getFaultInfo(){ return this._ServicesRegistrySipublishClassificationSystemsFault12; } }
epl-1.0
vboar/ERPClient
src/ui/presentui/ShowPanel.java
2738
package ui.presentui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import org.dom4j.Element; import ui.util.DatePickerGroup; import ui.util.FrameUtil; import ui.util.MyButton; import ui.util.MyLabel; import ui.util.MyOptionPane; import config.ERPConfig; import config.PanelConfig; import config.TableConfig; /** * 显示赠品单面板 * @author JanelDQ * @date 2014/11/27 */ @SuppressWarnings("serial") public class ShowPanel extends JPanel { private DatePickerGroup start; private DatePickerGroup end; private MyButton find; private MyButton showAll; private PresentListTablePane tablepane; private PanelConfig pcfg; public ShowPanel() { this.pcfg = ERPConfig.getHOMEFRAME_CONFIG().getConfigMap() .get(this.getClass().getName()); // 设置基本属性 this.setSize(pcfg.getW(), pcfg.getH()); this.setLocation(pcfg.getX(), pcfg.getY()); this.setLayout(null); // 初始化组件 this.initComponent(); this.setVisible(true); } /** * 初始化组件 */ private void initComponent() { // 初始化日期选择器 this.start = new DatePickerGroup(pcfg.getDatepicker().element("start")); this.end = new DatePickerGroup(pcfg.getDatepicker().element("end")); this.add(this.start); this.add(this.end); // 初始化标签 this.add(new MyLabel(pcfg.getLabels().element("stocklist"))); this.add(new MyLabel(pcfg.getLabels().element("start"))); this.add(new MyLabel(pcfg.getLabels().element("end"))); // 初始化按钮 this.initButtons(pcfg.getButtons()); // 初始化表格面板 this.tablepane = new PresentListTablePane(new TableConfig( pcfg.getTablepane())); this.add(this.tablepane); } /** * 初始化按钮 * @param ele */ private void initButtons(Element ele){ this.find = new MyButton(pcfg.getButtons().element("find")); this.find.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String time1 = FrameUtil.getFormattedDate(start.getDate()); String time2 = FrameUtil.getFormattedDate(end.getDate()); if ((time1 != null) && (time2 != null) && (time1.compareTo(time2) > 0)) { MyOptionPane.showMessageDialog(ShowPanel.this, "请输入有效日期!", "错误提示", MyOptionPane.ERROR_MESSAGE); return; } tablepane.showFindTable(time1,time2); } }); this.add(this.find); this.showAll = new MyButton(ele.element("showall")); this.showAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tablepane.showFindTable(null,null); } }); this.add(this.showAll); } public void udpateData() { this.tablepane.updateData(); } }
epl-1.0
cmoen/mallet
src/cc/mallet/share/upenn/ner/FeatureWindow.java
1792
package cc.mallet.share.upenn.ner; import java.util.*; import cc.mallet.pipe.*; import cc.mallet.types.*; import cc.mallet.util.*; import com.carrotsearch.hppc.ObjectDoubleOpenHashMap; /** * Adds all features of tokens in the window to the center token. */ public class FeatureWindow extends Pipe implements java.io.Serializable { int left, right; public FeatureWindow (int left, int right) { assert (left >= 0 && right >= 0); this.left = left; this.right = right; } public Instance pipe (Instance carrier) { TokenSequence seq = (TokenSequence)carrier.getData(); ObjectDoubleOpenHashMap[] original = new ObjectDoubleOpenHashMap[seq.size()]; for (int i=0; i<seq.size(); i++) { Token t = seq.get(i); original[i] = new ObjectDoubleOpenHashMap(); PropertyList.Iterator pl = t.getFeatures().iterator(); while (pl.hasNext()) { pl.nextProperty(); original[i].put(pl.getKey(), pl.getNumericValue()); } } for (int i=0; i<original.length; i++) { // add to features of token i... for (int j = -1 * left; j <= right; j++) { int index = i + j; //...the features of token index String append = (j < 0) ? "/"+j : "/+"+j; if (index<0 || index==i || index>=original.length) continue; Token t = seq.get(i); Object[] features = original[index].keys().toArray(); for (int k=0; k<features.length; k++) t.setFeatureValue((String)features[k]+append, original[index].get(features[k])); } } return carrier; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpConfigConstants.java
20136
/******************************************************************************* * Copyright (c) 2004, 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.ws.http.channel.internal; /** * Container for all of the various constants used in the HTTP Channel's * configuration code. */ public class HttpConfigConstants { /** * Private constructor... this class just provides some constants * */ private HttpConfigConstants() { // nothing to do } /** * Maximum requests allowed on a single HTTP connection. */ public static final String PROPNAME_MAX_PERSIST = "MaxKeepAliveRequests"; /** * When creating an outbound HTTP request, this parameter controls * the default HTTP version in the message. Expected values are * 1.0 or 1.1 */ public static final String PROPNAME_OUTGOING_VERSION = "outgoingVersion"; /** * When allocating new WsByteBuffers in the channel, this parameter * controls whether to use direct or indirect byte buffers. This * is a boolean value. */ public static final String PROPNAME_DIRECT_BUFF = "useDirectBuffers"; /** * When sending an outgoing HTTP message, this controls whether or * not to default to a persistent connection (Keep-Alive) as opposed * to a connection that will close after one request/response exchange. * This is a boolean value. * <p> * If this is set to false, then it will override any other persistence setting such as MaxKeepAliveRequests. */ public static final String PROPNAME_KEEPALIVE_ENABLED = "KeepAliveEnabled"; /** * While parsing incoming HTTP headers, this parameter controls the * internal cache size. */ public static final String PROPNAME_BYTE_CACHE_SIZE = "byteCacheSize"; /** * When allocating buffers for sending outgoing HTTP headers, this is * the size of each individual buffers. */ public static final String PROPNAME_OUTGOING_HDR_BUFFSIZE = "outgoingHdrBufferSize"; /** * While parsing the headers of an incoming HTTP message, this * controls the size of each buffer that receives the data. */ public static final String PROPNAME_INCOMING_HDR_BUFFSIZE = "incomingHdrBufferSize"; /** * While reading the body of an incoming HTTP message, this * controls the size of each buffer being used. */ public static final String PROPNAME_INCOMING_BODY_BUFFSIZE = "incomingBodyBufferSize"; /** * This timeout value controls the allowed idle time on * a socket between client requests. Once this timeout is passed, * the connection will be closed. * <p> * This integer value represents time in milliseconds. */ public static final String PROPNAME_PERSIST_TIMEOUT = "persistTimeout"; /** * This timeout value controls the allowed time to wait while * performing a read of data on a socket. * <p> * This integer value represents time in milliseconds. */ public static final String PROPNAME_READ_TIMEOUT = "readTimeout"; /** * This timeout value controls the allowed time to wait while * performing a write of data on a socket. * <p * . This integer value represents time in milliseconds. */ public static final String PROPNAME_WRITE_TIMEOUT = "writeTimeout"; /** * Property name for the flag on whether to extract the header * values out of the incoming buffers immediately or to delay * that extraction until a channel requests the header value. * True means to extract immediately and is intended for situations * where the channel is always going to be requesting the * majority of the headers. False would be when only a few * header values are ever queried. */ public static final String PROPNAME_EXTRACT_VALUE = "extractValue"; /** * Outgoing and incoming data for this channel can be sent in the * regular String encoding, or with the optional binary transport * mode. The channel at the other end of the connection must use * the same encoding method for the connection to work correctly. * This is a boolean value. */ public static final String PROPNAME_BINARY_TRANSPORT = "enableBinaryTransport"; /** * Property name for the client access log id. */ public static final String PROPNAME_ACCESSLOG_ID = "accessLogID"; /** * Property name for the client error log path plus filename. This logging * handles all of the important information related to connections not * covered by the access log. */ public static final String PROPNAME_ERRORLOG_FILENAME = "errorLogFileName"; /** * Property name for the level of logging to enable on this channel. Only * used if the internal channel logging is enabled (not the global service) */ public static final String PROPNAME_LOGGING_LEVEL = "loggingLevel"; /** * Property name for the maximum number of backup files to keep of the * error logs. */ public static final String PROPNAME_ERRORLOG_MAXFILES = "MaximumErrorBackupFiles"; /** * The local HTTP channel will adjust the filenames of the access and error * logs by prepending this prefix onto the name, thus logs/httpaccess.log * would become logs/localhttpaccess.log if the prefix was set to "local". */ public static final String PROPNAME_LOCALLOG_PREFIX = "localLogFilenamePrefix"; /** * Property name for the maximum size of any parsed field in the HTTP * messages (header value, URI, etc) */ public static final String PROPNAME_LIMIT_FIELDSIZE = "limitFieldSize"; /** * Property name for the maximum number of headers allowed in each HTTP * message. */ public static final String PROPNAME_LIMIT_NUMHEADERS = "limitNumHeaders"; /** * Property name for whether any socket retries are allowed with outbound * connections (does not apply to inbound connections). This covers any * attempt to reconnec to a target server and/or rewrite or reread data. */ public static final String PROPNAME_ALLOW_RETRIES = "allowRetries"; /** * Property name used to store the value on whether we are running this * channel instance inside the Z/OS servant region. */ public static final String PROPNAME_SERVANT_REGION = "ServantRegion"; /** * Property name used to store the value on whether we are running this * channel instance inside the Z/OS control region. */ public static final String PROPNAME_CONTROL_REGION = "ControlRegion"; /** * Property used to stored whether the channel is running on z/OS or not, * any region. */ public static final String PROPNAME_RUNNING_ON_ZOS = "RunningOnZOS"; /** * Property name used to indicate that this channel should only use JIT * allocate reads (if set to true). If false, then the default behavior * of picking JIT allocate reads or providing a buffer is used as normal. */ public static final String PROPNAME_JIT_ONLY_READS = "JITOnlyReads"; /** * Property that indicates whether the outgoing header values should have * verification checks performed to ensure no CRLF characters are contained * inside them. */ public static final String PROPNAME_HEADER_VALIDATION = "splitResponseProtection"; /** * Property that is used to limit the acceptable size of an incoming * message. If one arrives larger than this, then an error scenario is * triggered. */ public static final String PROPNAME_MSG_SIZE_LIMIT = "MessageSizeLimit"; /** * Property that extends the message size limit by allowing a single message * over the standard limit but under this higher size. If one message is * active in the system already in this range, then no others are allowed * in over the standard size limit, until that active message finishs. */ public static final String PROPNAME_MSG_SIZE_LARGEBUFFER = "LargeMessageSize"; /** * Property that allows the admin to limit the number of temporary response * messages the HTTP channel will parse before closing down the connection. */ public static final String PROPNAME_LIMIT_NUMBER_RESPONSES = "LimitNumberResponses"; /** * Property controlling whether or not URL parsing obeys strict RFC * compliance. */ public static final String PROPNAME_STRICT_URL_FORMAT = "StrictURLFormat"; /** * Property that allows the user to configure the Server header that will * be sent out with response messages (inbound chains only). */ // @295174 - control Server header contents public static final String PROPNAME_SERVER_HEADER_VALUE = "ServerHeaderValue"; /** * Property that allows the user to force the removal of any existing Server * header in the outgoing response messages (inbound chains only). */ // @295174 - control Server header contents public static final String PROPNAME_REMOVE_SERVER_HEADER = "RemoveServerHeader"; /** * Property that allows the user to control the range of the cached Date * header to be used (i.e. if the cache value falls within the allowed range * then it will be used and not reformatted). */ // @313641 - control Date header formation public static final String PROPNAME_DATE_HEADER_RANGE = "DateHeaderRange"; /** * Property that allows the user to control whether or not the presence of * a Set-Cookie(2) header should update the Cache-Control header with a * matching no-cache value, as well as adding the Expires header. */ // PK20531 - add Cache-Control header public static final String PROPNAME_COOKIES_CONFIGURE_NOCACHE = "CookiesConfigureNoCache"; /** * Property that limits the number of allowed header changes before the * headers will be remarshalled. This is used for a proxy env where the * message was originally parsed on one side and will be sent out the other * side, and if the changes are under the limit then the original parse * buffers will be used. */ // @LIDB4530 public static final String PROPNAME_HEADER_CHANGE_LIMIT = "HeaderChangeLimit"; /** * Property controlling whether or not autodecompression of HTTP bodies is * on or off. */ // PK41619 - allow autodecompression to be disabled public static final String PROPNAME_AUTODECOMPRESSION = "AutoDecompression"; /** * Property to decide whether or not the request smuggling protection code * is on or off. If it's on, then malformed messages with both Content-Length * and Transfer-Encoding: chunked headers will disable HTTP persistence. */ // PK53193 public static final String PROPNAME_ENABLE_SMUGGLING_PROTECTION = "EnableSmugglingProtection"; /** * Property name for the FRCA specific access log file. */ public static final String PROPNAME_FRCALOG_NAME = "FRCALogName"; /** * Property name for the FRCA log's maximum allowed file size before rollover. */ public static final String PROPNAME_FRCALOG_MAXSIZE = "FRCALogMaximumSize"; /** * Property name for the FRCA log's maximum number of backup files to keep. */ public static final String PROPNAME_FRCALOG_MAXFILES = "FRCALogMaximumBackupFiles"; /** * Property name for the FRCA log's access log format to use. */ public static final String PROPNAME_FRCALOG_FORMAT = "FRCALogAccessFormat"; /** * Property controlling whether we should prevent multiple Set-Cookies with the same name. */ public static final String PROPNAME_DO_NOT_ALLOW_DUPLICATE_SET_COOKIES = "DoNotAllowDuplicateSetCookies"; /** * PI33453 - Property controlling whether to wait for data, if not immediately available, * to determine if end of message has been parsed. */ public static final String PROPNAME_WAIT_FOR_END_OF_MESSAGE = "WaitForEndOfMessage"; /** * Property controlling whether we send the content length on response messages * with 1xx or 204 status codes */ // PI35277 - Property to not send content-length header on 1xx and 204 status codes public static final String REMOVE_CLHEADER_IN_TEMP_STATUS_RFC7230_COMPAT = "RemoveCLHeaderInTempStatusRespRFC7230compat"; /** * Property controlling whether we should attempt to purge any left over data * if we are going to close the connection instead of persist it */ // PI11176 - Attempt to Flush the data at the end of the request public static final String PROPNAME_PURGE_DATA_DURING_CLOSE = "PurgeDataDuringClose"; public static final String PROPNAME_H2_CONN_CLOSE_TIMEOUT = "H2ConnCloseTimeout"; public static final String PROPNAME_H2_CONN_READ_WINDOW_SIZE = "H2ConnReadWindowSize"; //PI81572 - Purge the remaining response body off the wire public static final String PROPNAME_PURGE_REMAINING_RESPONSE = "PurgeRemainingResponseBody"; /** Minimum setting on the persistent requests (-1 is unlimited) */ public static final int MIN_PERSIST_REQ = -1; /** Minimum allowed size for the byte cache */ public static final int MIN_BYTE_CACHE_SIZE = 256; /** Minimum buffer size allowed to be allocated */ public static final int MIN_BUFFER_SIZE = 1024; /** Minimum allowed setting for the maximum number of headers allowed */ public static final int MIN_LIMIT_NUMHEADERS = 50; /** Minimum timeout value allowed */ public static final int MIN_TIMEOUT = 0; /** Minimum allowed setting for the limit on the field size */ public static final int MIN_LIMIT_FIELDSIZE = 50; /** Maximum buffer size allowed to be allocated */ public static final int MAX_BUFFER_SIZE = 1048576; /** Maximum size to allow the byte cache to be set to */ public static final int MAX_BYTE_CACHE_SIZE = 2048; /** Maximum allowed setting for the limit on the field size */ public static final int MAX_LIMIT_FIELDSIZE = 32768; /** Maximum allowed setting for the limit on the number of headers */ public static final int MAX_LIMIT_NUMHEADERS = 500; /** Maximum number of responses to skip past */ public static final int MAX_LIMIT_NUMRESPONSES = 50; /** Several configuration constants allow unlimited values */ public static final int UNLIMITED = -1; /** Will allow Cookie to be created with RFC1123 format i.e. 4 digit year */ public static final String PROPNAME_V0_COOKIE_RFC1123_COMPAT = "v0CookieDateRFC1123compat"; /** * Property controlling whether we should automatically add the quote to the cookie * path attribute */ public static final String PROPNAME_SKIP_PATH_QUOTE = "SkipCookiePathQuotes"; /** Will prevent response splitting */ public static final String PROPNAME_PREVENT_RESPONSE_SPLIT = "PreventReponseSplit"; //PI45266 /** Will swallow inbound connections IOE */ public static final String PROPNAME_THROW_IOE_FOR_INBOUND_CONNECTIONS = "ThrowIOEForInboundConnections"; //PI57542 /** Equivalent to CookiesConfigureNoCache - required due to 'configure' not being an allowed word for metatype **/ public static final String PROPNAME_NO_CACHE_COOKIES_CONTROL = "NoCacheCookiesControl"; //PI75280 /** The channel will never be enabled for HTTP/2.0. */ public static final String NEVER_20 = "2.0_Never"; /** HTTP/1.1 Version protocol */ public static final String PROTOCOL_VERSION_11 = "http/1.1"; /** HTTP/2 Version protocol */ public static final String PROTOCOL_VERSION_2 = "http/2"; /** Can be set to specify the http protocol version. Ex: http/1.1, http/2 */ public static final String PROPNAME_PROTOCOL_VERSION = "protocolVersionInternal"; public static final int MIN_LIMIT_FRAME_SIZE = 16384; public static final int MAX_LIMIT_FRAME_SIZE = 16777215; public static final String PROPNAME_H2_CONNECTION_IDLE_TIMEOUT = "http2ConnectionIdleTimeout"; public static final String PROPNAME_H2_MAX_CONCURRENT_STREAMS = "maxConcurrentStreams"; public static final String PROPNAME_H2_MAX_FRAME_SIZE = "maxFrameSize"; public static final String DEFAULT_PROXIES_REGEX = "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|192\\.168\\.\\d{1,3}\\.\\d{1,3}|169\\.254\\.\\d{1,3}\\.\\d{1,3}|127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|0:0:0:0:0:0:0:1|::1"; public static final String PROPNAME_REMOTE_PROXIES = "proxiesInternal"; public static final String PROPNAME_REMOTE_IP = "useRemoteIpInternal"; public static final String PROPNAME_REMOTE_IP_ACCESS_LOG = "useRemoteIpInAccessLogInternal"; public static final String PROPNAME_COMPRESSION = "useAutoCompressionInternal"; public static final String PROPNAME_COMPRESSION_CONTENT_TYPES = "compressionListByTypesInternal"; public static final String PROPNAME_COMPRESSION_PREFERRED_ALGORITHM = "serverPreferredAlgorithmInternal"; //Matches a 0 with optionally up to three decimal points or a 1 with up to three 0 //decimal spaces. //Section 5.3.1 defines this as: //qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] ) public static final String DEFAULT_QVALUE_REGEX = "^((0(\\.\\d{0,3})?)|1(\\.0{0,3})?)$"; /** * Specifies the maximum ratio of decompressed to compressed request body payload. This ratio is verified as the body is read by the HTTP channel, and if the * decompressionTolerance is reached, the request is ended. */ public static final String PROPNAME_DECOMPRESSION_RATIO_LIMIT = "decompressionRatioLimit"; /** Specifies the maximum number of times the HTTP channel can hit the decompressionRatioLimit as the request body is decompressed before the request is ended. */ public static final String PROPNAME_DECOMPRESSION_TOLERANCE = "decompressionTolerance"; public static final String PROPNAME_SAMESITE = "sameSiteInternal"; public static final String PROPNAME_SAMESITE_LAX = "sameSiteLaxInternal"; public static final String PROPNAME_SAMESITE_NONE = "sameSiteNoneInternal"; public static final String PROPNAME_SAMESITE_STRICT = "sameSiteStrictInternal"; public static final String WILDCARD_CHAR = "*"; public static final String PROPNAME_RESPONSE_HEADERS = "headersInternal"; public static final String PROPNAME_RESPONSE_HEADERS_ADD = "headersAddInternal"; public static final String PROPNAME_RESPONSE_HEADERS_SET = "headersSetInternal"; public static final String PROPNAME_RESPONSE_HEADERS_REMOVE = "headersRemoveInternal"; public static final String PROPNAME_RESPONSE_HEADERS_SET_IF_MISSING = "headersSetIfMissingInternal"; public static enum SameSite { LAX("Lax"), NONE("None"), STRICT("Strict"); SameSite(String name) { this.name = name; } private String name; public String getName() { return this.name; } } public static final String PROPNAME_HDR_HSTS_SHORTNAME = "addstricttransportsecurityheader"; public static final String PROPNAME_HDR_HSTS_FULLYQUALIFIED = "com.ibm.ws.webcontainer.addStrictTransportSecurityHeader"; public static enum Headers { ADD("add"), SET("set"), SET_IF_MISSING("setIfMissing"); Headers(String name) { this.name = name; } private String name; public String getName() { return this.name; } } }
epl-1.0
mbriskar/windup
rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/rules/AnalyzeJSPFileRuleProvider.java
7465
package org.jboss.windup.rules.apps.javaee.rules; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.jboss.windup.ast.java.data.ClassReference; import org.jboss.windup.ast.java.data.ResolutionStatus; import org.jboss.windup.ast.java.data.TypeReferenceLocation; import org.jboss.windup.config.AbstractRuleProvider; import org.jboss.windup.config.GraphRewrite; import org.jboss.windup.config.metadata.MetadataBuilder; import org.jboss.windup.config.operation.iteration.AbstractIterationOperation; import org.jboss.windup.config.phase.InitialAnalysisPhase; import org.jboss.windup.config.query.Query; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.reporting.service.ClassificationService; import org.jboss.windup.rules.apps.java.model.JavaClassModel; import org.jboss.windup.rules.apps.java.scan.ast.JavaTypeReferenceModel; import org.jboss.windup.rules.apps.java.scan.ast.TypeInterestFactory; import org.jboss.windup.rules.apps.java.service.JavaClassService; import org.jboss.windup.rules.apps.java.service.TypeReferenceService; import org.jboss.windup.rules.apps.javaee.model.JspSourceFileModel; import org.ocpsoft.rewrite.config.Configuration; import org.ocpsoft.rewrite.config.ConfigurationBuilder; import org.ocpsoft.rewrite.context.EvaluationContext; /** * Extracts type references from JSP files. * * @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a> */ public class AnalyzeJSPFileRuleProvider extends AbstractRuleProvider { public AnalyzeJSPFileRuleProvider() { super(MetadataBuilder.forProvider(AnalyzeJSPFileRuleProvider.class) .setPhase(InitialAnalysisPhase.class) .setHaltOnException(true)); } // @formatter:off @Override public Configuration getConfiguration(GraphContext context) { return ConfigurationBuilder.begin() .addRule() .when(Query.fromType(JspSourceFileModel.class)) .perform(new ParseSourceOperation()); } // @formatter:on private class ParseSourceOperation extends AbstractIterationOperation<JspSourceFileModel> { @Override public void perform(GraphRewrite event, EvaluationContext context, JspSourceFileModel sourceFile) { TypeReferenceService typeReferenceService = new TypeReferenceService(event.getGraphContext()); try { // Setup some basic details about the "Java Class" // source root, is decompiled, javaclass. package name sourceFile.setPackageName(""); JavaClassService javaClassService = new JavaClassService(event.getGraphContext()); JavaClassModel classModel = javaClassService.create(); classModel.setPackageName(""); classModel.setSimpleName(sourceFile.getFileName()); classModel.setQualifiedName(sourceFile.getFileName()); classModel.setExtends(javaClassService.getOrCreatePhantom("javax.servlet.http.HttpServlet")); sourceFile.addJavaClass(classModel); Iterable<ClassReference> references = getClassReferences(typeReferenceService, sourceFile); for (ClassReference reference : references) { JavaTypeReferenceModel typeReference = typeReferenceService.createTypeReference(sourceFile, reference.getLocation(), reference.getResolutionStatus(), reference.getLineNumber(), reference.getColumn(), reference.getLength(), reference.getQualifiedName(), reference.getLine()); } } catch (Exception e) { ClassificationService classificationService = new ClassificationService(event.getGraphContext()); classificationService.attachClassification(context, sourceFile, JspSourceFileModel.UNPARSEABLE_JSP_CLASSIFICATION, JspSourceFileModel.UNPARSEABLE_JSP_DESCRIPTION); } } } private Iterable<ClassReference> getClassReferences(TypeReferenceService service, JspSourceFileModel sourceFile) throws IOException { String source = FileUtils.readFileToString(sourceFile.asFile()); List<ClassReference> results = new ArrayList<>(); results.addAll(findImports(source)); results.addAll(findTaglib(source)); return results; } private List<ClassReference> findImports(String source) { List<ClassReference> results = new ArrayList<>(); Pattern jspImport = Pattern.compile("<%@\\s*page\\s+[^>]*\\s*import\\s*=\\s*['\"]([^'\"]+)['\"].*?%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher matcher = jspImport.matcher(source); while (matcher.find()) { String matched = matcher.group(1); if (StringUtils.isNotBlank(matched)) { String[] imports = StringUtils.split(matched, ","); if (imports != null) { for (String imported : imports) { imported = StringUtils.trim(imported); if (TypeInterestFactory.matchesAny(imported, TypeReferenceLocation.IMPORT)) { ClassReference reference = createClassReference(TypeReferenceLocation.IMPORT, source, imported, matcher.start()); results.add(reference); } } } } } return results; } private List<ClassReference> findTaglib(String source) { List<ClassReference> results = new ArrayList<>(); Pattern taglibPattern = Pattern.compile("<%@\\s*taglib\\s+[^>]*\\s*uri\\s*=\\s*['\"]([^'\"]+)['\"].*?%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); Matcher matcher = taglibPattern.matcher(source); while (matcher.find()) { String matched = matcher.group(1); if (StringUtils.isNotBlank(matched)) { if (TypeInterestFactory.matchesAny(matched, TypeReferenceLocation.TAGLIB_IMPORT)) { ClassReference reference = createClassReference(TypeReferenceLocation.TAGLIB_IMPORT, source, matched, matcher.start()); results.add(reference); } } } return results; } private ClassReference createClassReference(TypeReferenceLocation location, String source, String reference, int startPosition) { String subString = StringUtils.substring(source, 0, startPosition + 1); String[] lines = subString.split("\r\n|\r|\n"); int lineNumber = lines.length; int column = lines[lines.length - 1].indexOf(source.substring(startPosition)); int length = reference.length(); return new ClassReference(reference, null, null, null, ResolutionStatus.UNKNOWN, location, lineNumber, column, length, reference); } }
epl-1.0
gemoc/activitydiagram
dev/gemoc_sequential/language_workbench/org.gemoc.activitydiagram.sequential.xactivitydiagram.input.grammar/src-gen/org/gemoc/activitydiagram/sequential/xactivitydiagram/input/scoping/AbstractActivityDiagramInputScopeProvider.java
277
/* * generated by Xtext 2.9.1 */ package org.gemoc.activitydiagram.sequential.xactivitydiagram.input.scoping; import org.eclipse.xtext.scoping.impl.DelegatingScopeProvider; public abstract class AbstractActivityDiagramInputScopeProvider extends DelegatingScopeProvider { }
epl-1.0
opendaylight/controller
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataTreeCohortIntegrationTest.java
17346
/* * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.datastore; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import akka.actor.ActorSystem; import akka.actor.Address; import akka.actor.AddressFromURIString; import akka.cluster.Cluster; import akka.testkit.javadsl.TestKit; import com.google.common.base.Throwables; import com.google.common.util.concurrent.FluentFuture; import com.typesafe.config.ConfigFactory; import java.util.Collection; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.opendaylight.controller.md.cluster.datastore.model.CarsModel; import org.opendaylight.controller.md.cluster.datastore.model.TestModel; import org.opendaylight.mdsal.common.api.DataValidationFailedException; import org.opendaylight.mdsal.common.api.LogicalDatastoreType; import org.opendaylight.mdsal.common.api.PostCanCommitStep; import org.opendaylight.mdsal.common.api.PostPreCommitStep; import org.opendaylight.mdsal.common.api.ThreePhaseCommitStep; import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate; import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort; import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort; import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction; import org.opendaylight.yangtools.concepts.ObjectRegistration; import org.opendaylight.yangtools.util.concurrent.FluentFutures; import org.opendaylight.yangtools.yang.common.Uint64; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType; import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; import org.opendaylight.yangtools.yang.model.api.SchemaContext; public class DataTreeCohortIntegrationTest { private static final DataValidationFailedException FAILED_CAN_COMMIT = new DataValidationFailedException(YangInstanceIdentifier.class, TestModel.TEST_PATH, "Test failure."); private static final FluentFuture<PostCanCommitStep> FAILED_CAN_COMMIT_FUTURE = FluentFutures.immediateFailedFluentFuture(FAILED_CAN_COMMIT); private static final DOMDataTreeIdentifier TEST_ID = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, TestModel.TEST_PATH); private static ActorSystem system; private final DatastoreContext.Builder datastoreContextBuilder = DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(100); @BeforeClass public static void setUpClass() { system = ActorSystem.create("cluster-test", ConfigFactory.load().getConfig("Member1")); final Address member1Address = AddressFromURIString.parse("akka://cluster-test@127.0.0.1:2558"); Cluster.get(system).join(member1Address); } @AfterClass public static void tearDownClass() { TestKit.shutdownActorSystem(system); system = null; } protected ActorSystem getSystem() { return system; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testSuccessfulCanCommitWithNoopPostStep() throws Exception { final DOMDataTreeCommitCohort cohort = mock(DOMDataTreeCommitCohort.class); doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); ArgumentCaptor<Collection> candidateCapt = ArgumentCaptor.forClass(Collection.class); IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder); try (AbstractDataStore dataStore = kit.setupAbstractDataStore( DistributedDataStore.class, "testSuccessfulCanCommitWithNoopPostStep", "test-1")) { final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg = dataStore.registerCommitCohort(TEST_ID, cohort); assertNotNull(cohortReg); IntegrationTestKit.verifyShardState(dataStore, "test-1", state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size())); final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME); kit.testWriteTransaction(dataStore, TestModel.TEST_PATH, node); verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapt.capture()); assertDataTreeCandidate((DOMDataTreeCandidate) candidateCapt.getValue().iterator().next(), TEST_ID, ModificationType.WRITE, Optional.of(node), Optional.empty()); reset(cohort); doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); kit.testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME) .withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42)) .build()); verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); cohortReg.close(); IntegrationTestKit.verifyShardState(dataStore, "test-1", state -> assertEquals("Cohort registrations", 0, state.getCommitCohortActors().size())); kit.testWriteTransaction(dataStore, TestModel.TEST_PATH, node); verifyNoMoreInteractions(cohort); } } @SuppressWarnings("unchecked") @Test public void testFailedCanCommit() throws Exception { final DOMDataTreeCommitCohort failedCohort = mock(DOMDataTreeCommitCohort.class); doReturn(FAILED_CAN_COMMIT_FUTURE).when(failedCohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder); try (AbstractDataStore dataStore = kit.setupAbstractDataStore( DistributedDataStore.class, "testFailedCanCommit", "test-1")) { dataStore.registerCommitCohort(TEST_ID, failedCohort); IntegrationTestKit.verifyShardState(dataStore, "test-1", state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size())); DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction(); writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)); DOMStoreThreePhaseCommitCohort dsCohort = writeTx.ready(); try { dsCohort.canCommit().get(5, TimeUnit.SECONDS); fail("Exception should be raised."); } catch (ExecutionException e) { assertSame(FAILED_CAN_COMMIT, Throwables.getRootCause(e)); } } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testCanCommitWithListEntries() throws Exception { final DOMDataTreeCommitCohort cohort = mock(DOMDataTreeCommitCohort.class); doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder); try (AbstractDataStore dataStore = kit.setupAbstractDataStore( DistributedDataStore.class, "testCanCommitWithMultipleListEntries", "cars-1")) { final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg = dataStore.registerCommitCohort( new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH .node(CarsModel.CAR_QNAME)), cohort); assertNotNull(cohortReg); IntegrationTestKit.verifyShardState(dataStore, "cars-1", state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size())); // First write an empty base container and verify the cohort isn't invoked. DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction(); writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer()); writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode()); kit.doCommit(writeTx.ready()); verifyNoMoreInteractions(cohort); // Write a single car entry and verify the cohort is invoked. writeTx = dataStore.newWriteOnlyTransaction(); final YangInstanceIdentifier optimaPath = CarsModel.newCarPath("optima"); final MapEntryNode optimaNode = CarsModel.newCarEntry("optima", Uint64.valueOf(20000)); writeTx.write(optimaPath, optimaNode); kit.doCommit(writeTx.ready()); ArgumentCaptor<Collection> candidateCapture = ArgumentCaptor.forClass(Collection.class); verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapture.capture()); assertDataTreeCandidate((DOMDataTreeCandidate) candidateCapture.getValue().iterator().next(), new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, optimaPath), ModificationType.WRITE, Optional.of(optimaNode), Optional.empty()); // Write replace the cars container with 2 new car entries. The cohort should get invoked with 3 // DOMDataTreeCandidates: once for each of the 2 new car entries (WRITE mod) and once for the deleted prior // car entry (DELETE mod). reset(cohort); doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); writeTx = dataStore.newWriteOnlyTransaction(); final YangInstanceIdentifier sportagePath = CarsModel.newCarPath("sportage"); final MapEntryNode sportageNode = CarsModel.newCarEntry("sportage", Uint64.valueOf(20000)); final YangInstanceIdentifier soulPath = CarsModel.newCarPath("soul"); final MapEntryNode soulNode = CarsModel.newCarEntry("soul", Uint64.valueOf(20000)); writeTx.write(CarsModel.BASE_PATH, CarsModel.newCarsNode(CarsModel.newCarsMapNode(sportageNode,soulNode))); kit.doCommit(writeTx.ready()); candidateCapture = ArgumentCaptor.forClass(Collection.class); verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapture.capture()); assertDataTreeCandidate(findCandidate(candidateCapture, sportagePath), new DOMDataTreeIdentifier( LogicalDatastoreType.CONFIGURATION, sportagePath), ModificationType.WRITE, Optional.of(sportageNode), Optional.empty()); assertDataTreeCandidate(findCandidate(candidateCapture, soulPath), new DOMDataTreeIdentifier( LogicalDatastoreType.CONFIGURATION, soulPath), ModificationType.WRITE, Optional.of(soulNode), Optional.empty()); assertDataTreeCandidate(findCandidate(candidateCapture, optimaPath), new DOMDataTreeIdentifier( LogicalDatastoreType.CONFIGURATION, optimaPath), ModificationType.DELETE, Optional.empty(), Optional.of(optimaNode)); // Delete the cars container - cohort should be invoked for the 2 deleted car entries. reset(cohort); doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); writeTx = dataStore.newWriteOnlyTransaction(); writeTx.delete(CarsModel.BASE_PATH); kit.doCommit(writeTx.ready()); candidateCapture = ArgumentCaptor.forClass(Collection.class); verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapture.capture()); assertDataTreeCandidate(findCandidate(candidateCapture, sportagePath), new DOMDataTreeIdentifier( LogicalDatastoreType.CONFIGURATION, sportagePath), ModificationType.DELETE, Optional.empty(), Optional.of(sportageNode)); assertDataTreeCandidate(findCandidate(candidateCapture, soulPath), new DOMDataTreeIdentifier( LogicalDatastoreType.CONFIGURATION, soulPath), ModificationType.DELETE, Optional.empty(), Optional.of(soulNode)); } } @SuppressWarnings("rawtypes") private static DOMDataTreeCandidate findCandidate(final ArgumentCaptor<Collection> candidateCapture, final YangInstanceIdentifier rootPath) { for (Object obj: candidateCapture.getValue()) { DOMDataTreeCandidate candidate = (DOMDataTreeCandidate)obj; if (rootPath.equals(candidate.getRootPath().getRootIdentifier())) { return candidate; } } return null; } /** * FIXME: Since we invoke DOMDataTreeCommitCohort#canCommit on preCommit (as that's when we generate a * DataTreeCandidate) and since currently preCommit is a noop in the Shard backend (it is combined with commit), * we can't actually test abort after canCommit. */ @SuppressWarnings("unchecked") @Test @Ignore public void testAbortAfterCanCommit() throws Exception { final DOMDataTreeCommitCohort cohortToAbort = mock(DOMDataTreeCommitCohort.class); final PostCanCommitStep stepToAbort = mock(PostCanCommitStep.class); doReturn(ThreePhaseCommitStep.NOOP_ABORT_FUTURE).when(stepToAbort).abort(); doReturn(PostPreCommitStep.NOOP_FUTURE).when(stepToAbort).preCommit(); doReturn(FluentFutures.immediateFluentFuture(stepToAbort)).when(cohortToAbort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class)); IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder); try (AbstractDataStore dataStore = kit.setupAbstractDataStore( DistributedDataStore.class, "testAbortAfterCanCommit", "test-1", "cars-1")) { dataStore.registerCommitCohort(TEST_ID, cohortToAbort); IntegrationTestKit.verifyShardState(dataStore, "test-1", state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size())); DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction(); writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)); writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer()); DOMStoreThreePhaseCommitCohort dsCohort = writeTx.ready(); dsCohort.canCommit().get(5, TimeUnit.SECONDS); dsCohort.preCommit().get(5, TimeUnit.SECONDS); dsCohort.abort().get(5, TimeUnit.SECONDS); verify(stepToAbort).abort(); } } private static void assertDataTreeCandidate(final DOMDataTreeCandidate candidate, final DOMDataTreeIdentifier expTreeId, final ModificationType expType, final Optional<NormalizedNode> expDataAfter, final Optional<NormalizedNode> expDataBefore) { assertNotNull("Expected candidate for path " + expTreeId.getRootIdentifier(), candidate); assertEquals("rootPath", expTreeId, candidate.getRootPath()); assertEquals("modificationType", expType, candidate.getRootNode().getModificationType()); assertEquals("dataAfter present", expDataAfter.isPresent(), candidate.getRootNode().getDataAfter().isPresent()); if (expDataAfter.isPresent()) { assertEquals("dataAfter", expDataAfter.get(), candidate.getRootNode().getDataAfter().get()); } assertEquals("dataBefore present", expDataBefore.isPresent(), candidate.getRootNode().getDataBefore().isPresent()); if (expDataBefore.isPresent()) { assertEquals("dataBefore", expDataBefore.get(), candidate.getRootNode().getDataBefore().get()); } } }
epl-1.0
unverbraucht/kura
kura/org.eclipse.kura.camel/src/main/java/org/eclipse/kura/camel/cloud/KuraCloudConsumer.java
5006
/******************************************************************************* * Copyright (c) 2011, 2016 Red Hat and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.eclipse.kura.camel.cloud; import static org.apache.camel.builder.ExchangeBuilder.anExchange; import static org.eclipse.kura.camel.camelcloud.KuraCloudClientConstants.CAMEL_KURA_CLOUD_CONTROL; import static org.eclipse.kura.camel.camelcloud.KuraCloudClientConstants.CAMEL_KURA_CLOUD_DEVICEID; import static org.eclipse.kura.camel.camelcloud.KuraCloudClientConstants.CAMEL_KURA_CLOUD_QOS; import static org.eclipse.kura.camel.camelcloud.KuraCloudClientConstants.CAMEL_KURA_CLOUD_RETAIN; import static org.eclipse.kura.camel.camelcloud.KuraCloudClientConstants.CAMEL_KURA_CLOUD_TOPIC; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.impl.DefaultConsumer; import org.eclipse.kura.KuraException; import org.eclipse.kura.cloud.CloudClient; import org.eclipse.kura.cloud.CloudClientListener; import org.eclipse.kura.message.KuraPayload; /** * Consumer implementation for {@link KuraCloudComponent} */ public class KuraCloudConsumer extends DefaultConsumer implements CloudClientListener { private final CloudClient cloudClient; public KuraCloudConsumer(Endpoint endpoint, Processor processor, CloudClient cloudClient) { super(endpoint, processor); this.cloudClient = cloudClient; } // Life-cycle @Override protected void doStart() throws Exception { super.doStart(); this.log.debug("Starting CloudClientListener."); this.cloudClient.addCloudClientListener(this); performSubscribe(); } @Override protected void doStop() throws Exception { try { this.cloudClient.unsubscribe(getEndpoint().getTopic()); } catch (Exception e) { this.log.info("Failed to unsubscribe", e); } this.cloudClient.removeCloudClientListener(this); this.log.debug("Stopping CloudClientListener."); super.doStop(); } // CloudClientListener callbacks @Override public void onControlMessageArrived(String deviceId, String appTopic, KuraPayload msg, int qos, boolean retain) { onInternalMessageArrived(deviceId, appTopic, msg, qos, retain, true); } @Override public void onMessageArrived(String deviceId, String appTopic, KuraPayload msg, int qos, boolean retain) { onInternalMessageArrived(deviceId, appTopic, msg, qos, retain, false); } @Override public void onConnectionLost() { this.log.debug("Executing empty 'onConnectionLost' callback."); } @Override public void onConnectionEstablished() { this.log.debug("Executing empty 'onConnectionLost' callback."); performSubscribe(); } private void performSubscribe() { try { this.log.debug("Perform subscribe: {} / {}", this.cloudClient, getEndpoint().getTopic()); this.cloudClient.subscribe(getEndpoint().getTopic(), 0); } catch (KuraException e) { this.log.warn("Failed to subscribe", e); } } @Override public void onMessageConfirmed(int messageId, String appTopic) { this.log.debug("Executing empty 'onMessageConfirmed' callback with message ID {} and application topic {}.", messageId, appTopic); } @Override public void onMessagePublished(int messageId, String appTopic) { this.log.debug("Executing empty 'onMessagePublished' callback with message ID {} and application topic {}.", messageId, appTopic); } // Helpers private void onInternalMessageArrived(String deviceId, String appTopic, KuraPayload message, int qos, boolean retain, boolean control) { this.log.debug("Received message with deviceId {}, application topic {}.", deviceId, appTopic); Exchange exchange = anExchange(getEndpoint().getCamelContext()).withBody(message) .withHeader(CAMEL_KURA_CLOUD_TOPIC, appTopic).withHeader(CAMEL_KURA_CLOUD_DEVICEID, deviceId) .withHeader(CAMEL_KURA_CLOUD_QOS, qos).withHeader(CAMEL_KURA_CLOUD_CONTROL, control) .withHeader(CAMEL_KURA_CLOUD_RETAIN, retain).build(); exchange.setFromEndpoint(getEndpoint()); try { getProcessor().process(exchange); } catch (Exception e) { handleException("Error while processing an incoming message:", e); } } // Getters @Override public KuraCloudEndpoint getEndpoint() { return (KuraCloudEndpoint) super.getEndpoint(); } }
epl-1.0
FTSRG/iq-sirius-integration
host/org.eclipse.sirius.diagram/src-core/org/eclipse/sirius/diagram/tools/internal/command/builders/DragAndDropCommandBuilder.java
12215
/******************************************************************************* * Copyright (c) 2009, 2014 THALES GLOBAL SERVICES. * 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: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.sirius.diagram.tools.internal.command.builders; import java.util.HashMap; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.common.command.UnexecutableCommand; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.transaction.TransactionalEditingDomain; import org.eclipse.emf.transaction.util.TransactionUtil; import org.eclipse.sirius.business.api.helper.task.ICommandTask; import org.eclipse.sirius.business.api.helper.task.InitInterpreterVariablesTask; import org.eclipse.sirius.business.api.helper.task.UnexecutableTask; import org.eclipse.sirius.business.api.query.IdentifiedElementQuery; import org.eclipse.sirius.business.api.resource.WorkspaceDragAndDropSupport; import org.eclipse.sirius.business.api.session.Session; import org.eclipse.sirius.business.api.session.SessionManager; import org.eclipse.sirius.common.tools.api.interpreter.IInterpreter; import org.eclipse.sirius.diagram.DDiagram; import org.eclipse.sirius.diagram.DDiagramElement; import org.eclipse.sirius.diagram.DragAndDropTarget; import org.eclipse.sirius.diagram.business.api.query.EObjectQuery; import org.eclipse.sirius.diagram.business.internal.helper.task.DnDTasksOperations; import org.eclipse.sirius.diagram.description.ContainerMapping; import org.eclipse.sirius.diagram.description.DiagramElementMapping; import org.eclipse.sirius.diagram.description.EdgeMapping; import org.eclipse.sirius.diagram.description.NodeMapping; import org.eclipse.sirius.diagram.description.tool.ContainerDropDescription; import org.eclipse.sirius.ext.base.Option; import org.eclipse.sirius.ext.base.Options; import org.eclipse.sirius.tools.api.command.DCommand; import org.eclipse.sirius.tools.api.interpreter.InterpreterUtil; import org.eclipse.sirius.tools.api.ui.resource.ISiriusMessages; import org.eclipse.sirius.viewpoint.DModel; import org.eclipse.sirius.viewpoint.DRepresentation; import org.eclipse.sirius.viewpoint.DSemanticDecorator; import org.eclipse.sirius.viewpoint.SiriusPlugin; import org.eclipse.sirius.viewpoint.description.tool.AbstractVariable; /** * . * * @author mchauvin */ public class DragAndDropCommandBuilder extends AbstractDiagramCommandBuilder { private ContainerDropDescription tool; private DragAndDropTarget container; private DDiagramElement diagramElement; private EObject droppedElement; private boolean dragSemantic; /** * . * * @param tool * the dnd tool * @param container * the diagram container * @param diagramElement * the diagram element to drop */ public DragAndDropCommandBuilder(final ContainerDropDescription tool, final DragAndDropTarget container, final DDiagramElement diagramElement) { this.tool = tool; this.container = container; this.diagramElement = diagramElement; this.dragSemantic = false; } /** * . * * @param tool * the dnd tool * @param container * the diagram container * @param droppedElement * the semantic element to drop */ public DragAndDropCommandBuilder(final ContainerDropDescription tool, final DragAndDropTarget container, final EObject droppedElement) { this.tool = tool; this.container = container; this.droppedElement = droppedElement; this.dragSemantic = true; } private DSemanticDecorator getOldContainer() { EObject semanticOldContainer = null; DSemanticDecorator oldContainer = null; EObject currentOldContainer = diagramElement.eContainer(); while (currentOldContainer != null && semanticOldContainer == null) { if (currentOldContainer instanceof DSemanticDecorator) { oldContainer = (DSemanticDecorator) currentOldContainer; semanticOldContainer = oldContainer.getTarget(); } currentOldContainer = currentOldContainer.eContainer(); } return oldContainer; } /** * {@inheritDoc} * * @see org.eclipse.sirius.tools.internal.command.builders.CommandBuilder#buildCommand() */ public Command buildCommand() { if (permissionAuthority.canEditInstance(container) && permissionAuthority.canEditInstance(dragSemantic ? droppedElement : diagramElement) // Layouting mode on diagrams // if the ddiagram is in LayoutingMode, we do not allow DnD && !isInLayoutingModeDiagram(diagramElement)) { if (container instanceof DSemanticDecorator) { final EObject semanticContainer = ((DSemanticDecorator) container).getTarget(); if (!dragSemantic) { droppedElement = diagramElement.getTarget(); } final DSemanticDecorator oldContainer = dragSemantic ? null : getOldContainer(); final EObject semanticOldContainer = dragSemantic ? null : oldContainer.getTarget(); /* Check the precondition of the tool */ if (checkDragAndDropPrecondition(semanticOldContainer, semanticContainer)) { final DiagramElementMapping mapping = tool.getBestMapping(container, droppedElement); if (mapping != null || dragSemantic) { // Get the command which contains all the tasks describe // in the model operation of the VSM (viewpoint // specification model) final DCommand cmd = buildDropInContainerCommandFromTool(semanticContainer, droppedElement, container, semanticOldContainer); // Add new DNode in the new container fillDropinCommand(cmd, mapping, semanticContainer); // Delete the old DNode from the previous container cleanAfterDropinCommand(cmd, oldContainer); // Launch a refresh to build the GMF elements according // to the DDiagram modifications final DDiagram diagram = getDDiagram().get(); this.addRefreshTask(diagram, cmd, tool); return cmd; } } } else { SiriusPlugin.getDefault().error(ISiriusMessages.IS_NOT_A_DECORATE_SEMANTIC_ELEMENT, new RuntimeException()); } } return UnexecutableCommand.INSTANCE; } /** * Check the precondition of the tool. * * @param oldContainer * the old container, may be <code>null</code>. * @param newContainer * the new container.. * @return <code>true</code> if the precondition is OK, false otherwise. */ private boolean checkDragAndDropPrecondition(final EObject oldContainer, final EObject newContainer) { return DnDTasksOperations.checkDragAndDropPrecondition(tool, droppedElement, oldContainer, newContainer, container); } private void fillDropinCommand(final DCommand cmd, final DiagramElementMapping mapping, final EObject semanticContainer) { ICommandTask createElement = null; final boolean moveEdges = tool.isMoveEdges(); if (mapping instanceof NodeMapping) { createElement = DnDTasksOperations.createDropinForNodeTask(container, (NodeMapping) mapping, diagramElement, droppedElement, semanticContainer, moveEdges); } else if (mapping instanceof EdgeMapping) { /* we do not handle edge mapping yet */ } else if (mapping instanceof ContainerMapping) { createElement = DnDTasksOperations.createDropinForContainerTask(container, (ContainerMapping) mapping, diagramElement, droppedElement, semanticContainer, tool); } if (createElement != null) { cmd.getTasks().add(createElement); } } private void cleanAfterDropinCommand(final DCommand cmd, final DSemanticDecorator oldContainer) { if (!dragSemantic) { cmd.getTasks().add(DnDTasksOperations.createRemoveAfterDropInTask(oldContainer, diagramElement)); } } private DCommand buildDropInContainerCommandFromTool(final EObject newContainer, final EObject element, final EObject dContainer, final EObject oldContainer) { final DCommand result = createEnclosingCommand(); if (permissionAuthority.canEditInstance(newContainer) && permissionAuthority.canEditInstance(element)) { final IInterpreter interpreter = InterpreterUtil.getInterpreter(newContainer); final Map<AbstractVariable, Object> variables = new HashMap<AbstractVariable, Object>(); variables.put(tool.getElement(), element); variables.put(tool.getNewContainer(), newContainer); variables.put(tool.getNewViewContainer(), dContainer); if (oldContainer != null) { variables.put(tool.getOldContainer(), oldContainer); } result.getTasks().add(new InitInterpreterVariablesTask(variables, interpreter, uiCallback) { @Override public void execute() { if (element instanceof DModel) { setElementVariableWithModelContent((DModel) element); } super.execute(); } private void setElementVariableWithModelContent(final DModel model) { final WorkspaceDragAndDropSupport support = new WorkspaceDragAndDropSupport(); final TransactionalEditingDomain domain = TransactionUtil.getEditingDomain(newContainer); final IFile file = support.getWorkspaceFile(model); final Resource loadedResource = uiCallback.loadResource(domain, file); if (loadedResource != null) { final Session session = SessionManager.INSTANCE.getSession(model); support.addSemanticResourceToSession(loadedResource, session); if (!loadedResource.getContents().isEmpty()) { final EObject newElement = loadedResource.getContents().get(0); if (newElement != null) { variables.put(tool.getElement(), newElement); } } } } }); Option<DRepresentation> representation = new EObjectQuery(diagramElement).getRepresentation(); if (tool.getInitialOperation() != null && tool.getInitialOperation().getFirstModelOperations() != null) { result.getTasks().add(taskHelper.buildTaskFromModelOperation(representation.get(), newContainer, tool.getInitialOperation().getFirstModelOperations())); } } else { result.getTasks().add(UnexecutableTask.INSTANCE); } return result; } /** * {@inheritDoc} */ protected String getEnclosingCommandLabel() { return new IdentifiedElementQuery(tool).getLabel(); } /** * {@inheritDoc} */ @Override protected Option<DDiagram> getDDiagram() { DDiagram diag = null; if (container instanceof DDiagram) { diag = (DDiagram) container; } else { diag = ((DDiagramElement) container).getParentDiagram(); } return Options.newSome(diag); } }
epl-1.0
fabioz/Pydev
plugins/org.python.pydev.shared_core/src/org/python/pydev/shared_core/yaml/YamlWrapper.java
1164
package org.python.pydev.shared_core.yaml; import java.util.Map; import org.snakeyaml.engine.v2.api.Dump; import org.snakeyaml.engine.v2.api.DumpSettings; import org.snakeyaml.engine.v2.api.Load; import org.snakeyaml.engine.v2.api.LoadSettings; import org.snakeyaml.engine.v2.api.LoadSettingsBuilder; import org.snakeyaml.engine.v2.common.FlowStyle; public class YamlWrapper { public static String dumpAsMap(@SuppressWarnings("rawtypes") Map map) { Dump dump = new Dump( DumpSettings.builder() .setBestLineBreak("\n") .setMultiLineFlow(true) .setIndent(2) .setDefaultFlowStyle(FlowStyle.BLOCK) .build()); String output = dump.dumpToString(map); return output; } public static Object load(String yamlContents) { LoadSettingsBuilder builder = LoadSettings.builder(); LoadSettings settings = builder .setMaxAliasesForCollections(10) .build(); Load load = new Load(settings); return load.loadFromString(yamlContents); } }
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.jeview/src/org/eclipse/jdt/jeview/JEViewPlugin.java
2368
/******************************************************************************* * Copyright (c) 2005, 2008 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 org.eclipse.jdt.jeview; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; public class JEViewPlugin extends AbstractUIPlugin { private static JEViewPlugin fDefault; public JEViewPlugin() { fDefault= this; } public static String getPluginId() { return "org.eclipse.jdt.jeview"; //$NON-NLS-1$ } @Override public void stop(BundleContext context) throws Exception { super.stop(context); fDefault= null; } /** * @return the shared instance */ public static JEViewPlugin getDefault() { return fDefault; } /** * @return the workspace instance */ public static IWorkspace getWorkspace() { return ResourcesPlugin.getWorkspace(); } public static void log(IStatus status) { getDefault().getLog().log(status); } public static void logErrorMessage(String message) { log(new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, message, null)); } public static void logMessage(String message) { log(new Status(IStatus.INFO, getPluginId(), IStatus.INFO, message, null)); } public static void logErrorStatus(String message, IStatus status) { if (status == null) { logErrorMessage(message); return; } MultiStatus multi= new MultiStatus(getPluginId(), IStatus.ERROR, message, null); multi.add(status); log(multi); } public static void log(String message, Throwable e) { log(new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, message, e)); } public static void log(Throwable e) { log(new Status(IStatus.ERROR, getPluginId(), IStatus.ERROR, e.getLocalizedMessage(), e)); } }
epl-1.0
fabioz/eclipse.spellchecker
src/eclipse/spellchecker/SpellCheckEngine.java
15315
/******************************************************************************* * Copyright (c) 2000, 2011 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 eclipse.spellchecker; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.texteditor.spelling.SpellingService; import org.eclipse.ui.editors.text.EditorsUI; import eclipse.spellchecker.engine.DefaultSpellChecker; import eclipse.spellchecker.engine.ISpellCheckEngine; import eclipse.spellchecker.engine.ISpellChecker; import eclipse.spellchecker.engine.ISpellDictionary; import eclipse.spellchecker.engine.LocaleSensitiveSpellDictionary; import eclipse.spellchecker.engine.PersistentSpellDictionary; import eclipse.spellchecker.etc.PreferenceConstants; /** * Spell check engine for Java source spell checking. * * @since 3.0 */ public class SpellCheckEngine implements ISpellCheckEngine, IPropertyChangeListener { /** The dictionary location */ public static final String DICTIONARY_LOCATION= "dictionaries/"; //$NON-NLS-1$ /** The singleton engine instance */ private static ISpellCheckEngine fgEngine= null; /** * Caches the locales of installed dictionaries. * * @since 3.3 */ private static Set<Locale> fgLocalesWithInstalledDictionaries; /** * Returns the locales for which this * spell check engine has dictionaries in certain location. * * @param location dictionaries location * @return The available locales for this engine */ private static Set<Locale> getLocalesWithInstalledDictionaries(URL location) { String[] fileNames; try { URL url= FileLocator.toFileURL(location); File file= new File(url.getFile()); if (!file.isDirectory()) return Collections.emptySet(); fileNames= file.list(); if (fileNames == null) return Collections.emptySet(); } catch (IOException ex) { Activator.log(ex); return Collections.emptySet(); } Set<Locale> localesWithInstalledDictionaries= new HashSet<Locale>(); int fileNameCount= fileNames.length; for (int i= 0; i < fileNameCount; i++) { String fileName= fileNames[i]; int localeEnd= fileName.indexOf(".dictionary"); //$NON-NLS-1$ if (localeEnd > 1) { String localeName= fileName.substring(0, localeEnd); int languageEnd=localeName.indexOf('_'); if (languageEnd == -1) localesWithInstalledDictionaries.add(new Locale(localeName)); else if (languageEnd == 2 && localeName.length() == 5) localesWithInstalledDictionaries.add(new Locale(localeName.substring(0, 2), localeName.substring(3))); else if (localeName.length() > 6 && localeName.charAt(5) == '_') localesWithInstalledDictionaries.add(new Locale(localeName.substring(0, 2), localeName.substring(3, 5), localeName.substring(6))); } } return localesWithInstalledDictionaries; } /** * Returns the locales for which this * spell check engine has dictionaries. * * @return The available locales for this engine */ public static Set<Locale> getLocalesWithInstalledDictionaries() { if (fgLocalesWithInstalledDictionaries != null) return fgLocalesWithInstalledDictionaries; Enumeration<URL> locations; try { locations= getDictionaryLocations(); if (locations == null) return fgLocalesWithInstalledDictionaries= Collections.emptySet(); } catch (IOException ex) { Activator.log(ex); return fgLocalesWithInstalledDictionaries= Collections.emptySet(); } fgLocalesWithInstalledDictionaries= new HashSet<Locale>(); while (locations.hasMoreElements()) { URL location= locations.nextElement(); Set<Locale> locales= getLocalesWithInstalledDictionaries(location); fgLocalesWithInstalledDictionaries.addAll(locales); } return fgLocalesWithInstalledDictionaries; } /** * Returns the default locale for this engine. * * @return The default locale */ public static Locale getDefaultLocale() { return Locale.getDefault(); } /** * Returns the dictionary closest to the given locale. * * @param locale the locale * @return the dictionary or <code>null</code> if none is suitable * @since 3.3 */ public ISpellDictionary findDictionary(Locale locale) { ISpellDictionary dictionary= fLocaleDictionaries.get(locale); if (dictionary != null) return dictionary; // Try same language String language= locale.getLanguage(); Iterator<Entry<Locale, ISpellDictionary>> iter= fLocaleDictionaries.entrySet().iterator(); while (iter.hasNext()) { Entry<Locale, ISpellDictionary> entry= iter.next(); Locale dictLocale= entry.getKey(); if (dictLocale.getLanguage().equals(language)) return entry.getValue(); } return null; } /* * @see eclipse.spellchecker.engine.ISpellCheckEngine#findDictionary(java.util.Locale) * @since 3.3 */ public static Locale findClosestLocale(Locale locale) { if (locale == null || locale.toString().length() == 0) return locale; if (getLocalesWithInstalledDictionaries().contains(locale)) return locale; // Try same language String language= locale.getLanguage(); Iterator<Locale> iter= getLocalesWithInstalledDictionaries().iterator(); while (iter.hasNext()) { Locale dictLocale= iter.next(); if (dictLocale.getLanguage().equals(language)) return dictLocale; } // Try whether American English is present Locale defaultLocale= Locale.US; if (getLocalesWithInstalledDictionaries().contains(defaultLocale)) return defaultLocale; return null; } /** * Returns the enumeration of URLs for the dictionary locations where * the Platform dictionaries are located. * <p> * This is in <code>org.eclipse.jdt.ui/dictionaries/</code> * which can also be populated via fragments. * </p> * * @throws IOException if there is an I/O error * @return The dictionary locations, or <code>null</code> iff the locations are not known */ public static Enumeration<URL> getDictionaryLocations() throws IOException { final Activator plugin= Activator.getDefault(); if (plugin != null) return plugin.getBundle().getResources("/" + DICTIONARY_LOCATION); //$NON-NLS-1$ return null; } /** * Returns the singleton instance of the spell check engine. * * @return The singleton instance of the spell check engine */ public static synchronized final ISpellCheckEngine getInstance() { if (fgEngine == null) fgEngine= new SpellCheckEngine(); return fgEngine; } /** * Shuts down the singleton instance of the spell check engine. */ public static synchronized final void shutdownInstance() { if (fgEngine != null) { fgEngine.shutdown(); fgEngine= null; } } /** The registered locale insensitive dictionaries */ private Set<ISpellDictionary> fGlobalDictionaries= new HashSet<ISpellDictionary>(); /** The spell checker for fLocale */ private ISpellChecker fChecker= null; /** The registered locale sensitive dictionaries */ private Map<Locale, ISpellDictionary> fLocaleDictionaries= new HashMap<Locale, ISpellDictionary>(); /** The user dictionary */ private ISpellDictionary fUserDictionary= null; /** * Creates a new spell check manager. */ private SpellCheckEngine() { fGlobalDictionaries.add(new TaskTagDictionary()); fGlobalDictionaries.add(new HtmlTagDictionary()); fGlobalDictionaries.add(new JavaDocTagDictionary()); try { Locale locale= null; final Enumeration<URL> locations= getDictionaryLocations(); while (locations != null && locations.hasMoreElements()) { URL location= locations.nextElement(); for (final Iterator<Locale> iterator= getLocalesWithInstalledDictionaries(location).iterator(); iterator.hasNext();) { locale= iterator.next(); fLocaleDictionaries.put(locale, new LocaleSensitiveSpellDictionary(locale, location)); } } } catch (IOException exception) { // Do nothing } Activator.getDefault().getPreferenceStore().addPropertyChangeListener(this); EditorsUI.getPreferenceStore().addPropertyChangeListener(this); } /* * @see eclipse.spellchecker.engine.ISpellCheckEngine#getSpellChecker() */ public synchronized final ISpellChecker getSpellChecker() throws IllegalStateException { if (fGlobalDictionaries == null) throw new IllegalStateException("spell checker has been shut down"); //$NON-NLS-1$ IPreferenceStore store= Activator.getDefault().getPreferenceStore(); Locale locale= getCurrentLocale(store); if (fUserDictionary == null && "".equals(locale.toString())) //$NON-NLS-1$ return null; if (fChecker != null && fChecker.getLocale().equals(locale)) return fChecker; resetSpellChecker(); fChecker= new DefaultSpellChecker(store, locale); resetUserDictionary(); for (Iterator<ISpellDictionary> iterator= fGlobalDictionaries.iterator(); iterator.hasNext();) { ISpellDictionary dictionary= iterator.next(); fChecker.addDictionary(dictionary); } ISpellDictionary dictionary= findDictionary(fChecker.getLocale()); if (dictionary != null) fChecker.addDictionary(dictionary); return fChecker; } /** * Returns the current locale of the spelling preferences. * * @param store the preference store * @return The current locale of the spelling preferences */ private Locale getCurrentLocale(IPreferenceStore store) { return convertToLocale(store.getString(PreferenceConstants.SPELLING_LOCALE)); } public static Locale convertToLocale(String locale) { Locale defaultLocale= SpellCheckEngine.getDefaultLocale(); if (locale.equals(defaultLocale.toString())) return defaultLocale; int length= locale.length(); if (length >= 5) return new Locale(locale.substring(0, 2), locale.substring(3, 5)); if (length == 2 && locale.indexOf('_') == -1) return new Locale(locale); if (length == 3 && locale.charAt(0) == '_') return new Locale("", locale.substring(1)); //$NON-NLS-1$ return new Locale(""); //$NON-NLS-1$ } /* * @see org.eclipse.jdt.ui.text.spelling.engine.ISpellCheckEngine#getLocale() */ public synchronized final Locale getLocale() { if (fChecker == null) return null; return fChecker.getLocale(); } /* * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public final void propertyChange(final PropertyChangeEvent event) { if (event.getProperty().equals(PreferenceConstants.SPELLING_LOCALE)) { resetSpellChecker(); return; } if (event.getProperty().equals(PreferenceConstants.SPELLING_USER_DICTIONARY)) { resetUserDictionary(); return; } if (event.getProperty().equals(PreferenceConstants.SPELLING_USER_DICTIONARY_ENCODING)) { resetUserDictionary(); return; } if (event.getProperty().equals(SpellingService.PREFERENCE_SPELLING_ENABLED) && !EditorsUI.getPreferenceStore().getBoolean(SpellingService.PREFERENCE_SPELLING_ENABLED)) { if (this == fgEngine) SpellCheckEngine.shutdownInstance(); else shutdown(); } } /** * Resets the current checker's user dictionary. */ private synchronized void resetUserDictionary() { if (fChecker == null) return; // Update user dictionary if (fUserDictionary != null) { fChecker.removeDictionary(fUserDictionary); fUserDictionary.unload(); fUserDictionary= null; } IPreferenceStore store= Activator.getDefault().getPreferenceStore(); String filePath= store.getString(PreferenceConstants.SPELLING_USER_DICTIONARY); VariablesPlugin variablesPlugin= VariablesPlugin.getDefault(); if (variablesPlugin == null) return; IStringVariableManager variableManager= variablesPlugin.getStringVariableManager(); try { filePath= variableManager.performStringSubstitution(filePath); } catch (CoreException e) { Activator.log(e); return; } if (filePath.length() > 0) { try { File file= new File(filePath); if (!file.exists() && !file.createNewFile()) return; final URL url= new URL("file", null, filePath); //$NON-NLS-1$ InputStream stream= url.openStream(); if (stream != null) { try { fUserDictionary= new PersistentSpellDictionary(url); fChecker.addDictionary(fUserDictionary); } finally { stream.close(); } } } catch (MalformedURLException exception) { // Do nothing } catch (IOException exception) { // Do nothing } } } /* * @see eclipse.spellchecker.engine.ISpellCheckEngine#registerDictionary(eclipse.spellchecker.engine.ISpellDictionary) */ public synchronized final void registerGlobalDictionary(final ISpellDictionary dictionary) { fGlobalDictionaries.add(dictionary); resetSpellChecker(); } /* * @see eclipse.spellchecker.engine.ISpellCheckEngine#registerDictionary(java.util.Locale, eclipse.spellchecker.engine.ISpellDictionary) */ public synchronized final void registerDictionary(final Locale locale, final ISpellDictionary dictionary) { fLocaleDictionaries.put(locale, dictionary); resetSpellChecker(); } /* * @see eclipse.spellchecker.engine.ISpellCheckEngine#unload() */ public synchronized final void shutdown() { Activator.getDefault().getPreferenceStore().removePropertyChangeListener(this); EditorsUI.getPreferenceStore().removePropertyChangeListener(this); ISpellDictionary dictionary= null; for (final Iterator<ISpellDictionary> iterator= fGlobalDictionaries.iterator(); iterator.hasNext();) { dictionary= iterator.next(); dictionary.unload(); } fGlobalDictionaries= null; for (final Iterator<ISpellDictionary> iterator= fLocaleDictionaries.values().iterator(); iterator.hasNext();) { dictionary= iterator.next(); dictionary.unload(); } fLocaleDictionaries= null; fUserDictionary= null; fChecker= null; } private synchronized void resetSpellChecker() { if (fChecker != null) { ISpellDictionary dictionary= fLocaleDictionaries.get(fChecker.getLocale()); if (dictionary != null) dictionary.unload(); } fChecker= null; } /* * @see org.eclipse.jdt.ui.text.spelling.engine.ISpellCheckEngine#unregisterDictionary(org.eclipse.jdt.ui.text.spelling.engine.ISpellDictionary) */ public synchronized final void unregisterDictionary(final ISpellDictionary dictionary) { fGlobalDictionaries.remove(dictionary); fLocaleDictionaries.values().remove(dictionary); dictionary.unload(); resetSpellChecker(); } }
epl-1.0
nickmain/xmind
bundles/org.xmind.ui.toolkit/src/org/xmind/ui/richtext/StrikeoutAction.java
1993
/* ****************************************************************************** * Copyright (c) 2006-2012 XMind Ltd. and others. * * This file is a part of XMind 3. XMind releases 3 and * above are dual-licensed under the Eclipse Public License (EPL), * which is available at http://www.eclipse.org/legal/epl-v10.html * and the GNU Lesser General Public License (LGPL), * which is available at http://www.gnu.org/licenses/lgpl.html * See http://www.xmind.net/license.html for details. * * Contributors: * XMind Ltd. - initial API and implementation *******************************************************************************/ package org.xmind.ui.richtext; import org.eclipse.jface.action.Action; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ISelection; import org.xmind.ui.internal.ToolkitImages; public class StrikeoutAction extends Action implements IRichTextAction { private IRichTextEditViewer viewer; public StrikeoutAction(IRichTextEditViewer viewer) { this(viewer, RichTextMessages.StrikeoutAction_text, ToolkitImages .get(ToolkitImages.STRIKEOUT), RichTextMessages.StrikeoutAction_toolTip); } public StrikeoutAction(IRichTextEditViewer viewer, String text, ImageDescriptor image, String tooltip) { super(text, AS_CHECK_BOX); this.viewer = viewer; setId(TextActionConstants.STRIKEOUT_ID); setImageDescriptor(image); setToolTipText(tooltip); } public void dispose() { viewer = null; } public void selectionChanged(IRichTextEditViewer viewer, ISelection selection) { setChecked(viewer.getRenderer().getSelectionFontStrikeout()); } public void run() { if (viewer == null || viewer.getControl().isDisposed()) return; viewer.getRenderer().setSelectionFontStrikeout(isChecked()); } }
epl-1.0
amitmangalvedkar/iot-java
src/main/java/com/ibm/iotf/client/AbstractClient.java
35076
/** ***************************************************************************** Copyright (c) 2015-16 IBM Corporation and other Contributors. 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: Sathiskumar Palaniappan - Extended from DeviceClient - Added Client side Certificate Authentication ***************************************************************************** * */ package com.ibm.iotf.client; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyManagementException; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Security; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import org.apache.commons.net.util.Base64; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMReader; import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import com.google.gson.Gson; import com.google.gson.JsonObject; //import com.ibm.iotf.client.api.APIClient; import com.ibm.iotf.util.LoggerUtility; /** * A client that handles connections with the IBM Watson IoT Platform. <br> * This is an abstract class which has to be extended */ public abstract class AbstractClient { private static final String CLASS_NAME = AbstractClient.class.getName(); private static final String QUICK_START = "quickstart"; private static final int DEFAULT_MAX_INFLIGHT_MESSAGES = 100; private static final int DEFAULT_MESSAGING_QOS = 1; private static final String SERVER_MESSAGING_PEM = "messaging.pem"; protected static final String CLIENT_ID_DELIMITER = ":"; //protected static final String DOMAIN = "messaging.staging.internetofthings.ibmcloud.com"; public static final String DEFAULT_DOMAIN = "internetofthings.ibmcloud.com"; protected static final String MESSAGING = "messaging"; protected static final int MQTTS_PORT = 8883; protected static final int WSS_PORT = 443; protected static final int MQTT_PORT = 1883; protected static final int WS_PORT = 1883; private volatile boolean disconnectRequested = false; /* Wait for 1 second after each attempt for the first 10 attempts*/ private static final long RATE_0 = TimeUnit.SECONDS.toMillis(1); /* After 5 attempts throttle the rate of connection attempts to 1 per 10 second */ private static final int THROTTLE_1 = 5; private static final long RATE_1 = TimeUnit.SECONDS.toMillis(10); /* After 10 attempts throttle the rate of connection attempts to 1 per minute */ private static final int THROTTLE_2 = 10; private static final long RATE_2 = TimeUnit.MINUTES.toMillis(1); /* After 20 attempts throttle the rate of connection attempts to 1 per 5 minutes */ private static final int THROTTLE_3 = 20; private static final long RATE_3 = TimeUnit.MINUTES.toMillis(5); protected static final Gson gson = new Gson(); /** * A formatter for ISO 8601 compliant timestamps. */ protected static final DateFormat ISO8601_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); protected Properties options; protected String clientId; protected String clientUsername; protected String clientPassword; protected String serverURI; protected int messageCount = 0; protected MqttAsyncClient mqttAsyncClient = null; private static final MemoryPersistence DATA_STORE = new MemoryPersistence(); protected MqttConnectOptions mqttClientOptions; protected MqttCallback mqttCallback; protected int keepAliveInterval = -1; // default // Supported only for DM ManagedClient protected MqttClient mqttClient = null; protected MemoryPersistence persistence = null; protected static final boolean newFormat; static { newFormat = Boolean.parseBoolean(System.getProperty("com.ibm.iotf.enableCustomFormat", "true")); } /** * Note that this class does not have a default constructor <br> * @param options * Properties object which contains different artifacts such as auth-key * */ public AbstractClient(Properties options) { this.options = options; } /** * This constructor allows external user to pass the existing MqttAsyncClient * @param mqttAsyncClient the MQTTAsyncClient that has the connectivity parameters set */ protected AbstractClient(MqttAsyncClient mqttAsyncClient) { this.mqttAsyncClient = mqttAsyncClient; } /** * This constructor allows external user to pass the existing MqttClient * @param mqttClient the MQTTClient that has the connectivity parameters set */ protected AbstractClient(MqttClient mqttClient) { this.mqttClient = mqttClient; } /** * Create the Paho MQTT Client that will underpin the Device client. * @param callback * MqttCallback * @see <a href="http://www.eclipse.org/paho/files/javadoc/index.html">Paho Client Library</a> * */ protected void createClient(MqttCallback callback) { LoggerUtility.info(CLASS_NAME, "createClient", "Org ID = " + getOrgId() + "\n Client ID = " + clientId); this.mqttAsyncClient = null; this.mqttClientOptions = new MqttConnectOptions(); this.mqttCallback = callback; } /** * <p>Connects the device to IBM Watson IoT Platform and retries when there is an exception * based on the value set in retry parameter. <br> * * This method does not retry when the following exceptions occur.</p> * * <ul class="simple"> * <li> MqttSecurityException - One or more credentials are wrong * <li>UnKnownHostException - Host doesn't exist. For example, a wrong organization name is used to connect. * </ul> * * @param numberOfRetryAttempts - How many number of times to retry when there is a failure in connecting to Watson * IoT Platform. * @throws MqttException see above **/ public void connect(int numberOfRetryAttempts) throws MqttException { final String METHOD = "connect"; // return if its already connected if(mqttAsyncClient != null && mqttAsyncClient.isConnected()) { LoggerUtility.log(Level.WARNING, CLASS_NAME, METHOD, "Client is already connected"); return; } boolean tryAgain = true; int connectAttempts = 0; // clear the disconnect state when the user connects the client to Watson IoT Platform disconnectRequested = false; String userCertificate = trimedValue(options.getProperty("Use-Secure-Certificate")); if (getOrgId() == QUICK_START) { configureMqtt(); }else if ((getOrgId() != QUICK_START) && (userCertificate != null && userCertificate.equalsIgnoreCase("True"))){ LoggerUtility.info(CLASS_NAME, METHOD, "Initiating Certificate based authentication"); connectUsingCertificate(); if (isAutomaticReconnect()) { DisconnectedBufferOptions disconnectedOpts = new DisconnectedBufferOptions(); disconnectedOpts.setBufferEnabled(true); disconnectedOpts.setBufferSize(getDisconnectedBufferSize()); mqttAsyncClient.setBufferOpts(disconnectedOpts); } } else { LoggerUtility.info(CLASS_NAME, METHOD, "Initiating Token based authentication"); connectUsingToken(); if (isAutomaticReconnect()) { DisconnectedBufferOptions disconnectedOpts = new DisconnectedBufferOptions(); disconnectedOpts.setBufferEnabled(true); disconnectedOpts.setBufferSize(getDisconnectedBufferSize()); mqttAsyncClient.setBufferOpts(disconnectedOpts); } } while (tryAgain && disconnectRequested == false) { connectAttempts++; LoggerUtility.info(CLASS_NAME, METHOD, "Connecting client "+ this.clientId + " to " + mqttAsyncClient.getServerURI() + " (attempt #" + connectAttempts + ")..."); try { mqttAsyncClient.connect(mqttClientOptions).waitForCompletion(1000 * 60); } catch (MqttSecurityException e) { System.err.println("Looks like one or more connection parameters are wrong !!!"); LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Connecting to Watson IoT Platform failed - " + "one or more connection parameters are wrong !!!", e); throw e; } catch (MqttException e) { if(connectAttempts > numberOfRetryAttempts) { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Connecting to Watson IoT Platform failed", e); // We must give up as the host doesn't exist. throw e; } e.printStackTrace(); } if (mqttAsyncClient.isConnected()) { LoggerUtility.info(CLASS_NAME, METHOD, "Successfully connected " + "to the IBM Watson IoT Platform"); if (LoggerUtility.isLoggable(Level.FINEST)) { LoggerUtility.log(Level.FINEST, CLASS_NAME, METHOD, " * Connection attempts: " + connectAttempts); } tryAgain = false; } else { waitBeforeNextConnectAttempt(connectAttempts); } } } /** * <p>Connects the application to IBM Watson IoT Platform and retries when there is an exception * based on the value set in retry parameter. <br> * * This method does not retry when the following exceptions occur.</p> * * <ul class="simple"> * <li> MqttSecurityException - One or more credentials are wrong * <li>UnKnownHostException - Host doesn't exist. For example, a wrong organization name is used to connect. * </ul> * * @param autoRetry - tells whether to retry the connection when the connection attempt fails. * @throws MqttException refer above **/ public void connect(boolean autoRetry) throws MqttException { if(autoRetry == false) { connect(0); } else { connect(Integer.MAX_VALUE); } } /** * configureMqtt() is called when the User does not provide an Organization value and intends * to connect to Watson IoT Platform using the QUICKSTART mode. This type of connection is * In-secure in nature and is usually done over the 1883 Port Number. */ private void configureMqtt() { String protocol = null; int port = getPortNumber(); if (isWebSocket()) { protocol = "ws://"; // If there is no port specified use default if(port == -1) { port = WS_PORT; } } else { protocol = "tcp://"; // If there is no port specified use default if(port == -1) { port = MQTT_PORT; } } String mqttServer = getMQTTServer(); if(mqttServer != null){ serverURI = protocol + mqttServer + ":" + port; } else { serverURI = protocol + getOrgId() + "." + MESSAGING + "." + this.getDomain() + ":" + port; } try { persistence = new MemoryPersistence(); mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, persistence); mqttAsyncClient.setCallback(mqttCallback); mqttClientOptions = new MqttConnectOptions(); if (clientUsername != null) { mqttClientOptions.setUserName(clientUsername); } if (clientPassword != null) { mqttClientOptions.setPassword(clientPassword.toCharArray()); } mqttClientOptions.setCleanSession(this.isCleanSession()); if(this.keepAliveInterval != -1) { mqttClientOptions.setKeepAliveInterval(this.keepAliveInterval); } mqttClientOptions.setMaxInflight(getMaxInflight()); } catch (MqttException e) { e.printStackTrace(); } } /** * * @return the port number specified by the user */ private int getPortNumber() { String port = options.getProperty("port", "-1"); port = trimedValue(port); return Integer.parseInt(port); } /** * @return the MQTT Server specified by the user */ public String getMQTTServer() { String mqttServer; mqttServer = options.getProperty("mqtt-server"); if(mqttServer == null) { return null; } return trimedValue(mqttServer); } /** * Call to the configureConnOptionsWithToken() method is made, when the User chooses to connect to the * Watson IoT Platform using Device Token as the preferred Authentication mechanism. The Device Properties * file allows you enable either Token based or Certificate based or both mechanisms to authenticate. * However, setting the value to either 'True' or 'False' against the parameter 'Use-Secure-Certificate', * facilitates usage of Certificates for authentication or not, respectively. * Setting the value of parameter 'Use-Secure-Certificate' to 'False' in the Device.Properties file will * make a call to the following method. */ private void connectUsingToken() { String protocol = null; int port = getPortNumber(); if (isWebSocket()) { protocol = "wss://"; // If there is no port specified use default if(port == -1) { port = WSS_PORT; } } else { protocol = "ssl://"; // If there is no port specified use default if(port == -1) { port = MQTTS_PORT; } } String mqttServer = getMQTTServer(); if(mqttServer != null){ serverURI = protocol + mqttServer + ":" + port; } else { serverURI = protocol + getOrgId() + "." + MESSAGING + "." + this.getDomain() + ":" + port; } try { mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, DATA_STORE); mqttAsyncClient.setCallback(mqttCallback); mqttClientOptions = new MqttConnectOptions(); if (clientUsername != null) { mqttClientOptions.setUserName(clientUsername); } if (clientPassword != null) { mqttClientOptions.setPassword(clientPassword.toCharArray()); } mqttClientOptions.setCleanSession(this.isCleanSession()); if(this.keepAliveInterval != -1) { mqttClientOptions.setKeepAliveInterval(this.keepAliveInterval); } mqttClientOptions.setMaxInflight(getMaxInflight()); mqttClientOptions.setAutomaticReconnect(isAutomaticReconnect()); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); mqttClientOptions.setSocketFactory(sslContext.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } /** * Call to the connectUsingCertificate() method is made, when the User chooses to connect to the Watson * IoT Platform using Client Certificate as the preferred Authentication mechanism. The Device Properties * file allows you enable either Token based or Certificate based or both mechanisms to authenticate. * However, setting the value to either 'True' or 'False' against the parameter 'Use-Secure-Certificate', * facilitates usage of Certificates for authentication or not, respectively. * Setting the value of parameter 'Use-Secure-Certificate' to 'True' in the Device.Properties file will * make a call to the following method. */ private void connectUsingCertificate() { final String METHOD = "connectUsingCertificate"; String protocol = null; int port = getPortNumber(); if (isWebSocket()) { protocol = "wss://"; // If there is no port specified use default if(port == -1) { port = WSS_PORT; } } else { protocol = "ssl://"; // If there is no port specified use default if(port == -1) { port = MQTTS_PORT; } } String mqttServer = getMQTTServer(); if(mqttServer != null){ serverURI = protocol + mqttServer + ":" + port; } else { serverURI = protocol + getOrgId() + "." + MESSAGING + "." + this.getDomain() + ":" + port; } try { mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, DATA_STORE); mqttAsyncClient.setCallback(mqttCallback); mqttClientOptions = new MqttConnectOptions(); if (clientUsername != null) { mqttClientOptions.setUserName(clientUsername); } if (clientPassword != null) { mqttClientOptions.setPassword(clientPassword.toCharArray()); } mqttClientOptions.setCleanSession(this.isCleanSession()); if(this.keepAliveInterval != -1) { mqttClientOptions.setKeepAliveInterval(this.keepAliveInterval); } mqttClientOptions.setMaxInflight(getMaxInflight()); mqttClientOptions.setAutomaticReconnect(isAutomaticReconnect()); /* This isn't needed as the production messaging.internetofthings.ibmcloud.com * certificate should already be in trust chain. * * See: * http://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection * https://gerrydevstory.com/2014/05/01/trusting-x509-base64-pem-ssl-certificate-in-java/ * http://stackoverflow.com/questions/12501117/programmatically-obtain-keystore-from-pem * https://gist.github.com/sharonbn/4104301 * * CertificateFactory cf = CertificateFactory.getInstance("X.509"); * InputStream certFile = AbstractClient.class.getResourceAsStream("messaging.pem"); * Certificate ca = cf.generateCertificate(certFile); * * KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); * keyStore.load(null, null); * keyStore.setCertificateEntry("ca", ca); * TrustManager trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore); * SSLContext sslContext = SSLContextUtils.createSSLContext("TLSv1.2", null, trustManager); * */ SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); String serverCert = null; String clientCert = null; String clientCertKey = null; String certPassword = null; //Validate the availability of Server Certificate if (trimedValue(options.getProperty("Server-Certificate")) != null){ if (trimedValue(options.getProperty("Server-Certificate")).contains(".pem")||trimedValue(options.getProperty("Server-Certificate")).contains(".der")||trimedValue(options.getProperty("Server-Certificate")).contains(".cer")){ serverCert = trimedValue(options.getProperty("Server-Certificate")); } else{ LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Only PEM, DER & CER certificate formats are supported at this point of time"); throw new RuntimeException("Only PEM, DER & CER certificate formats are supported at this point of time"); } } else{ LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Server Certificate is missing, using default one"); } //Validate the availability of Client Certificate if (trimedValue(options.getProperty("Client-Certificate")) != null){ if (trimedValue(options.getProperty("Client-Certificate")).contains(".pem")||trimedValue(options.getProperty("Client-Certificate")).contains(".der")||trimedValue(options.getProperty("Client-Certificate")).contains(".cer")){ clientCert = trimedValue(options.getProperty("Client-Certificate")); } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Only PEM, DER & CER certificate formats are supported at this point of time"); throw new RuntimeException("Only PEM, DER & CER certificate formats are supported at this point of time"); } } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Client Certificate is missing"); throw new RuntimeException("Value for Client Certificate is missing"); } //Validate the availability of Client Certificate Key if (trimedValue(options.getProperty("Client-Key")) != null){ if (trimedValue(options.getProperty("Client-Key")).contains(".key")){ clientCertKey = trimedValue(options.getProperty("Client-Key")); } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Only Certificate key in .key format is supported at this point of time"); return; } } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Client Key is missing"); return; } //Validate the availability of Certificate Password try{ if (trimedValue(options.getProperty("Certificate-Password")) != null){ certPassword = trimedValue(options.getProperty("Certificate-Password")); } else { certPassword = ""; } } catch (RuntimeException e){ LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Certificate Password is missing", e); throw e; } mqttClientOptions.setSocketFactory(getSocketFactory(serverCert, clientCert, clientCertKey, certPassword)); } catch (Exception e) { LoggerUtility.warn(CLASS_NAME, METHOD, "Unable to configure TLSv1.2 connection: " + e.getMessage()); e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } public void setKeepAliveInterval(int keepAliveInterval) { this.keepAliveInterval = keepAliveInterval; } /** * * Check whether the clean session is disabled * * @return boolean value containing whether its a clean session or not. */ public boolean isCleanSession() { boolean enabled = true; String value = options.getProperty("Clean-Session"); if(value == null) { value = options.getProperty("clean-session"); } if(value != null) { enabled = Boolean.parseBoolean(trimedValue(value)); } return enabled; } public boolean isWebSocket() { boolean enabled = false; String value = options.getProperty("WebSocket"); if (value != null) { enabled = Boolean.parseBoolean(trimedValue(value)); } return enabled; } public boolean isAutomaticReconnect() { boolean enabled = false; String value = options.getProperty("Automatic-Reconnect"); if (value != null) { enabled = Boolean.parseBoolean(trimedValue(value)); } return enabled; } public int getDisconnectedBufferSize() { int size = 5000; String value = options.getProperty("Disconnected-Buffer-Size"); if (value != null) { size = Integer.parseInt(value); } return size; } public int getMaxInflight() { int maxInflight = DEFAULT_MAX_INFLIGHT_MESSAGES; String value = options.getProperty("MaxInflightMessages"); if (value != null) { maxInflight = Integer.parseInt(trimedValue(value)); } return maxInflight; } public int getMessagingQoS() { int qos = DEFAULT_MESSAGING_QOS; String value = options.getProperty("MessagingQoS"); if (value != null) { qos = Integer.parseInt(trimedValue(value)); if (qos < 0 || qos > 2) { qos = DEFAULT_MESSAGING_QOS; } } return qos; } /** * Sleep for a variable period of time between connect attempts. * * @param attempts * How many times have we tried (and failed) to connect */ private void waitBeforeNextConnectAttempt(final int attempts) { final String METHOD = "waitBeforeNextConnectAttempt"; // Log when throttle boundaries are reached if (attempts == THROTTLE_3) { LoggerUtility.warn(CLASS_NAME, METHOD, String.valueOf(attempts) + " consecutive failed attempts to connect. Retry delay increased to " + String.valueOf(RATE_3) + "ms"); } else if (attempts == THROTTLE_2) { LoggerUtility.warn(CLASS_NAME, METHOD, String.valueOf(attempts) + " consecutive failed attempts to connect. Retry delay increased to " + String.valueOf(RATE_2) + "ms"); } else if (attempts == THROTTLE_1) { LoggerUtility.info(CLASS_NAME, METHOD, String.valueOf(attempts) + " consecutive failed attempts to connect. Retry delay set to " + String.valueOf(RATE_1) + "ms"); } try { long delay = RATE_0; if (attempts >= THROTTLE_3) { delay = RATE_3; } else if (attempts >= THROTTLE_2) { delay = RATE_2; } else if (attempts >= THROTTLE_1) { delay = RATE_1; } Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Disconnect the device from the IBM Watson IoT Platform */ public void disconnect() { final String METHOD = "disconnect"; LoggerUtility.fine(CLASS_NAME, METHOD, "Disconnecting from the IBM Watson IoT Platform ..."); try { this.disconnectRequested = true; mqttAsyncClient.disconnect(); LoggerUtility.info(CLASS_NAME, METHOD, "Successfully disconnected " + "from the IBM Watson IoT Platform"); } catch (MqttException e) { e.printStackTrace(); } } /** * Determine whether this device is currently connected to the IBM Watson Internet * of Things Platform. * * @return Whether the device is connected to the IBM Watson IoT Platform */ public boolean isConnected() { final String METHOD = "isConnected"; boolean connected = false; if (mqttAsyncClient != null) { connected = mqttAsyncClient.isConnected(); } else if (mqttClient != null) { connected = mqttClient.isConnected(); } LoggerUtility.log(Level.FINEST, CLASS_NAME, METHOD, "Connected(" + connected + ")"); return connected; } /** * Provides a human readable String representation of this Device, including the number * of messages sent and the current connect status. * * @return String representation of the Device. */ public String toString() { return "[" + clientId + "] " + messageCount + " messages sent - Connected = " + String.valueOf(isConnected()); } /** * Parses properties file and returns back an object of Properties class * * @param propertiesFile * File object * @return properties * Properties object */ public static Properties parsePropertiesFile(File propertiesFile) { Properties clientProperties = new Properties(); FileInputStream in; try { in = new FileInputStream(propertiesFile); clientProperties.load(in); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return clientProperties; } catch (IOException e) { e.printStackTrace(); return clientProperties; } return clientProperties; } /** * * @return the domain */ protected String getDomain() { String domain; domain = options.getProperty("domain"); if(domain == null) { domain = options.getProperty("Domain"); } domain = trimedValue(domain); if(domain != null && !("".equals(domain))) { return domain; } else { return DEFAULT_DOMAIN; } } /** * * @return the organization id */ public String getOrgId() { String org; org = options.getProperty("org"); if(org == null) { org = options.getProperty("Organization-ID"); } return trimedValue(org); } /* * old style - id * new style - Device-ID */ public String getDeviceId() { String id; id = options.getProperty("id"); if(id == null) { id = options.getProperty("Device-ID"); } return trimedValue(id); } public static String trimedValue(String value) { if(value != null) { return value.trim(); } return value; } /** * Accessor method to retrieve Authendication Method * old style - auth-method * new style - Authentication-Method * * @return The Authentication method */ public String getAuthMethod() { String method = options.getProperty("auth-method"); if(method == null) { method = options.getProperty("Authentication-Method"); } return trimedValue(method); } /* * old style - auth-token * new style - Authentication-Token */ public String getAuthToken() { String token = options.getProperty("auth-token"); if(token == null) { token = options.getProperty("Authentication-Token"); } return trimedValue(token); } private static void validateNull(String property, String value) throws Exception { if(value == null || value == "") { throw new Exception(property +" cannot be null or empty !"); } } /** * @param organization Organization ID (Either "quickstart" or the registered organization ID) * @param domain Domain of the Watson IoT Platform, for example internetofthings.ibmcloud.com * @param deviceType Device Type * @param deviceId Device ID * @param eventName Name of the Event * @param device Boolean value indicating whether the request is originated from device or application * @param authKey Authentication Method * @param authToken Authentication Token to securely post this event (Can be null or empty if its quickstart) * @param payload The message to be published * @return int HTTP code indicating the status of the HTTP request * @throws Exception throws exception when http post fails */ protected static int publishEventsThroughHttps(String organization, String domain, String deviceType, String deviceId, String eventName, boolean device, String authKey, String authToken, Object payload) throws Exception { final String METHOD = "publishEventsThroughHttps"; validateNull("Organization ID", organization); validateNull("Domain", domain); validateNull("Device Type", deviceType); validateNull("Device ID", deviceId); validateNull("Event Name", eventName); if(QUICK_START.equalsIgnoreCase(organization) == false) { validateNull("Authentication Method", authKey); validateNull("Authentication Token", authToken); } StringBuilder sb = new StringBuilder(); // Form the URL if(QUICK_START.equalsIgnoreCase(organization)) { sb.append("http://"); } else { sb.append("https://"); } sb.append(organization) .append(".messaging.internetofthings.ibmcloud.com/api/v0002"); if(device == true) { sb.append("/device"); } else { sb.append("/application"); } sb.append("/types/") .append(deviceType) .append("/devices/") .append(deviceId) .append("/events/") .append(eventName); LoggerUtility.fine(CLASS_NAME, METHOD, "ReST URL::"+sb.toString()); BufferedReader br = null; // Create the payload message in Json format JsonObject message = (JsonObject) gson.toJsonTree(payload); StringEntity input = new StringEntity(message.toString(), StandardCharsets.UTF_8); // Create the Http post request HttpPost post = new HttpPost(sb.toString()); post.setEntity(input); post.addHeader("Content-Type", "application/json"); post.addHeader("Accept", "application/json"); if(QUICK_START.equalsIgnoreCase(organization) == false) { byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes() ); String encodedString = new String(encoding); post.addHeader("Authorization", "Basic " + encodedString); } try { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); HttpClient client = HttpClientBuilder.create().setSSLContext(sslContext).build(); HttpResponse response = client.execute(post); int httpCode = response.getStatusLine().getStatusCode(); if(httpCode >= 200 && httpCode < 300) { return httpCode; } /** * Looks like some error so log the header and response */ System.out.println("Looks like some error, so log the header and response"); StringBuilder log = new StringBuilder("HTTP Code: "+httpCode); log.append("\nURL: ") .append(sb.toString()) .append("\nHeader:\n"); Header[] headers = response.getAllHeaders(); for(int i = 0; i < headers.length; i++) { log.append(headers[i].getName()) .append(' ') .append(headers[i].getValue()) .append('\n'); } log.append("\nResponse \n"); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)); log.append(br.readLine()); LoggerUtility.severe(CLASS_NAME, METHOD, log.toString()); return httpCode; } catch (IOException e) { LoggerUtility.severe(CLASS_NAME, METHOD, e.getMessage()); throw e; } finally { if(br != null) { br.close(); } } } static SSLSocketFactory getSocketFactory (final String caCrtFile, final String crtFile, final String keyFile, final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { Security.addProvider(new BouncyCastleProvider()); X509Certificate caCert = null; if(caCrtFile != null) { // load CA certificate PEMReader reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))))); caCert = (X509Certificate)reader.readObject(); reader.close(); } else { ClassLoader classLoader = AbstractClient.class.getClassLoader(); PEMReader reader = new PEMReader(new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream())); caCert = (X509Certificate)reader.readObject(); reader.close(); } PEMReader reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))))); X509Certificate cert = (X509Certificate)reader.readObject(); reader.close(); // load client private key reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))) ); KeyPair key = (KeyPair)reader.readObject(); reader.close(); TrustManagerFactory tmf = null; if(caCert != null) { // CA certificate is used to authenticate server KeyStore caKs = KeyStore.getInstance("JKS"); //caKs.load(null, null); caKs.load(null, null); caKs.setCertificateEntry("ca-certificate", caCert); tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(caKs); } // client key and certificates are sent to server so it can authenticate us KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); ks.setCertificateEntry("certificate", cert); ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[]{cert}); KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX"); kmf.init(ks, password.toCharArray()); // finally, create SSL socket factory SSLContext context = SSLContext.getInstance("TLSv1.2"); if(tmf != null) { context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } else { context.init(kmf.getKeyManagers(), null, null); } return context.getSocketFactory(); } }
epl-1.0
abhijitk7/Attendance
attendance/src/main/java/com/abs/attendance/service/StaticDataService.java
769
package com.abs.attendance.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.abs.attendance.model.Classes; import com.abs.attendance.model.Students; import com.abs.attendance.repository.StudentRepository; import com.abs.attendance.service.Intf.IStaticDataService; @Service public class StaticDataService implements IStaticDataService { @Autowired private StudentRepository studentRepo; @Override public List<Students> findAllStudents() { return this.studentRepo.findAll(); } @Override public List<Students> findAllStudentsInClass(final Classes division) { return this.studentRepo.findStudentsByClasses(division); } }
epl-1.0
Achref001/My-Fashion-assistant--Android-
src/com/andy/myfashionassistant/fragments/MainFragment.java
2851
package com.andy.myfashionassistant.fragments; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.andy.myfashionassistant.LoginFacebookActivity; import com.andy.myfashionassistant.NavigationMain; import com.andy.myfashionassistant.utils.Utils; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.UiLifecycleHelper; import com.facebook.model.GraphUser; import com.facebook.widget.LoginButton; import com.fashion.R; public class MainFragment extends Fragment { private static final String TAG = "MainFragment"; private UiLifecycleHelper uiHelper; View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.facebook_activity, container, false); LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton); authButton.setFragment(this); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(getActivity(), callback); uiHelper.onCreate(savedInstanceState); } private void onSessionStateChange(Session session, SessionState state, Exception exception) { // makeMeRequest(session); if (state.isOpened()) { Log.i(TAG, "Logged in..."); Intent i = new Intent(getActivity(),NavigationMain.class); i.addCategory(Intent.CATEGORY_HOME); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } else if (state.isClosed()) { Log.i(TAG, "Logged out..."); Intent i = new Intent(getActivity(),LoginFacebookActivity.class); startActivity(i); } } @Override public void onResume() { super.onResume(); uiHelper.onResume(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data); } @Override public void onPause() { super.onPause(); uiHelper.onPause(); } @Override public void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); uiHelper.onSaveInstanceState(outState); } private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { onSessionStateChange(session, state, exception); } }; }
epl-1.0
worldwidewoogie/extraDimensions8
src/main/java/net/woogie/extraDimensions/network/CreateDimensionIdMessage.java
506
package net.woogie.extraDimensions.network; import io.netty.buffer.ByteBuf; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; public class CreateDimensionIdMessage implements IMessage { int dimensionId; public CreateDimensionIdMessage() { } public CreateDimensionIdMessage(int i) { this.dimensionId = i; } @Override public void fromBytes(ByteBuf buf) { this.dimensionId = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { buf.writeInt(dimensionId); } }
epl-1.0
OndraZizka/windup
graph/api/src/main/java/org/jboss/windup/graph/service/GraphService.java
9293
package org.jboss.windup.graph.service; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Iterator; import org.jboss.windup.graph.FramedElementInMemory; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.model.InMemoryVertexFrame; import org.jboss.windup.graph.model.WindupVertexFrame; import org.jboss.windup.graph.service.exception.NonUniqueResultException; import org.jboss.windup.util.ExecutionStatistics; import com.thinkaurelius.titan.core.TitanTransaction; import com.thinkaurelius.titan.core.attribute.Text; import com.thinkaurelius.titan.util.datastructures.IterablesUtil; import com.tinkerpop.blueprints.GraphQuery; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.frames.FramedGraphQuery; import com.tinkerpop.frames.VertexFrame; import com.tinkerpop.frames.modules.typedgraph.TypeValue; import com.tinkerpop.gremlin.java.GremlinPipeline; public class GraphService<T extends WindupVertexFrame> implements Service<T> { private final Class<T> type; private final GraphContext context; public GraphService(GraphContext context, Class<T> type) { this.context = context; this.type = type; } @SuppressWarnings("unchecked") public static <T extends WindupVertexFrame> T refresh(GraphContext context, T frame) { return (T) context.getFramed().frame(frame.asVertex(), WindupVertexFrame.class); } @Override public void commit() { ExecutionStatistics.performBenchmarked("GraphService.commit", () -> { getGraphContext().getGraph().getBaseGraph().commit(); return null; }); } @Override public long count(final Iterable<?> obj) { return ExecutionStatistics.performBenchmarked("GraphService.count", () -> { GremlinPipeline<Iterable<?>, Object> pipe = new GremlinPipeline<>(); long result = pipe.start(obj).count(); return result; }); } @SuppressWarnings("unchecked") @Override public T createInMemory() { Class<?>[] resolvedTypes = new Class<?>[] { VertexFrame.class, InMemoryVertexFrame.class, type }; return (T) Proxy.newProxyInstance(this.type.getClassLoader(), resolvedTypes, new FramedElementInMemory<>(this.type)); } /** * Create a new instance of the given {@link WindupVertexFrame} type. The ID is generated by the underlying graph database. */ @Override public T create() { return ExecutionStatistics.performBenchmarked("GraphService.create", () -> context.getFramed().addVertex(null, type)); } @Override public T addTypeToModel(final WindupVertexFrame model) { return ExecutionStatistics.performBenchmarked("GraphService.addTypeToModel", () -> GraphService.addTypeToModel(getGraphContext(), model, type)); } protected FramedGraphQuery findAllQuery() { return context.getQuery().type(type); } @Override public Iterable<T> findAll() { return findAllQuery().vertices(type); } @Override public Iterable<T> findAllByProperties(final String[] keys, final String[] vals) { return ExecutionStatistics.performBenchmarked("GraphService.findAllByProperties(" + Arrays.asList(keys) + ")", () -> { FramedGraphQuery query = findAllQuery(); for (int i = 0, j = keys.length; i < j; i++) { String key = keys[i]; String val = vals[i]; query = query.has(key, val); } return query.vertices(type); }); } @Override public Iterable<T> findAllByProperty(final String key, final Object value) { return ExecutionStatistics.performBenchmarked("GraphService.findAllByProperty(" + key + ")", () -> context.getFramed().getVertices(key, value, type)); } @Override public Iterable<T> findAllWithoutProperty(final String key, final Object value) { return ExecutionStatistics.performBenchmarked("GraphService.findAllWithoutProperty(" + key + ")", () -> findAllQuery().hasNot(key, value).vertices(type)); } @Override public Iterable<T> findAllWithoutProperty(final String key) { return ExecutionStatistics.performBenchmarked("GraphService.findAllWithoutProperty(" + key + ")", () -> findAllQuery().hasNot(key).vertices(type)); } @Override public Iterable<T> findAllByPropertyMatchingRegex(final String key, final String... regex) { return ExecutionStatistics.performBenchmarked("GraphService.findAllByPropertyMatchingRegex(" + key + ")", () -> { if (regex.length == 0) return IterablesUtil.emptyIterable(); final String regexFinal; if (regex.length == 1) { regexFinal = regex[0]; } else { StringBuilder builder = new StringBuilder(); builder.append("\\b("); int i = 0; for (String value : regex) { if (i > 0) builder.append("|"); builder.append(value); i++; } builder.append(")\\b"); regexFinal = builder.toString(); } return findAllQuery().has(key, Text.REGEX, regexFinal).vertices(type); }); } /** * Returns the vertex with given ID framed into given interface. */ @Override public T getById(Object id) { return context.getFramed().getVertex(id, this.type); } @Override public T frame(Vertex vertex) { return getGraphContext().getFramed().frame(vertex, this.getType()); } @Override public Class<T> getType() { return this.type; } protected GraphQuery getTypedQuery() { return getGraphContext().getQuery().type(type); } /** * Returns what this' frame has in @TypeValue(). */ protected String getTypeValueForSearch() { TypeValue typeValue = this.type.getAnnotation(TypeValue.class); if (typeValue == null) throw new IllegalArgumentException("Must be annotated with '@TypeValue': " + this.type.getName()); return typeValue.value(); } @Override public T getUnique() throws NonUniqueResultException { Iterable<T> results = findAll(); if (!results.iterator().hasNext()) { return null; } Iterator<T> iterator = results.iterator(); T result = iterator.next(); if (iterator.hasNext()) { throw new NonUniqueResultException("Expected unique value, but returned non-unique."); } return result; } @Override public T getUniqueByProperty(String property, Object value) throws NonUniqueResultException { Iterable<T> results = findAllByProperty(property, value); if (!results.iterator().hasNext()) { return null; } Iterator<T> iterator = results.iterator(); T result = iterator.next(); if (iterator.hasNext()) { throw new NonUniqueResultException("Expected unique value, but returned non-unique."); } return result; } protected T getUnique(GraphQuery framedQuery) { Iterable<Vertex> results = framedQuery.vertices(); if (!results.iterator().hasNext()) { return null; } Iterator<Vertex> iter = results.iterator(); Vertex result = iter.next(); if (iter.hasNext()) { throw new NonUniqueResultException("Expected unique value, but returned non-unique."); } return frame(result); } protected GraphContext getGraphContext() { return context; } @Override public TitanTransaction newTransaction() { return context.getGraph().getBaseGraph().newTransaction(); } /** * Adds the specified type to this frame, and returns a new object that implements this type. */ public static <T extends WindupVertexFrame> T addTypeToModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type) { Vertex vertex = frame.asVertex(); graphContext.getGraphTypeManager().addTypeToElement(type, vertex); return graphContext.getFramed().frame(vertex, type); } /** * Removes the specified type from the frame. */ public static <T extends WindupVertexFrame> T removeTypeFromModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type) { Vertex vertex = frame.asVertex(); graphContext.getGraphTypeManager().removeTypeFromElement(type, vertex); return graphContext.getFramed().frame(vertex, type); } @Override public void remove(final T model) { ExecutionStatistics.performBenchmarked("GraphService.commit", () -> { model.asVertex().remove(); return null; }); } }
epl-1.0
CloudScale-Project/Environment
plugins/eu.cloudscaleproject.env.extractor/src/eu/cloudscaleproject/env/extractor/handlers/OpenExtractorHandler.java
970
package eu.cloudscaleproject.env.extractor.handlers; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.model.application.MApplication; import org.eclipse.e4.ui.workbench.modeling.EModelService; import org.eclipse.e4.ui.workbench.modeling.EPartService; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.WorkbenchException; import eu.cloudscaleproject.env.product.branding.CloudScaleBranding; public class OpenExtractorHandler { @Execute public void execute(IWorkbench workbench, IWorkbenchWindow window, MApplication application, EModelService service, EPartService partService) { //using old e3 show perspective call try { window.getWorkbench().showPerspective("org.palladiosimulator.pcmbench.perspectives.palladio", window); CloudScaleBranding.initProjectExplorer(); } catch (WorkbenchException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
epl-1.0
mischwarz/Weasis
weasis-core/weasis-core-ui/src/main/java/org/weasis/core/ui/model/graphic/imp/line/PerpendicularLineGraphic.java
9707
/******************************************************************************* * Copyright (c) 2016 Weasis Team 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: * Nicolas Roduit - initial API and implementation *******************************************************************************/ package org.weasis.core.ui.model.graphic.imp.line; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.weasis.core.api.gui.util.GeomUtil; import org.weasis.core.api.gui.util.MathUtil; import org.weasis.core.api.image.measure.MeasurementsAdapter; import org.weasis.core.api.image.util.MeasurableLayer; import org.weasis.core.api.image.util.Unit; import org.weasis.core.ui.Messages; import org.weasis.core.ui.model.graphic.AbstractDragGraphic; import org.weasis.core.ui.model.utils.bean.AdvancedShape; import org.weasis.core.ui.model.utils.bean.MeasureItem; import org.weasis.core.ui.model.utils.bean.Measurement; import org.weasis.core.ui.model.utils.exceptions.InvalidShapeException; import org.weasis.core.ui.util.MouseEventDouble; @XmlType(name = "perpendicularLine") @XmlRootElement(name = "perpendicularLine") public class PerpendicularLineGraphic extends AbstractDragGraphic { private static final long serialVersionUID = -7056437654935777004L; public static final Integer POINTS_NUMBER = 4; public static final Icon ICON = new ImageIcon(PerpendicularLineGraphic.class.getResource("/icon/22x22/draw-perpendicular.png")); //$NON-NLS-1$ public static final Measurement LINE_LENGTH = new Measurement(Messages.getString("measure.length"), 1, true, true, true); //$NON-NLS-1$ public static final Measurement ORIENTATION = new Measurement(Messages.getString("measure.orientation"), 2, true, true, false); //$NON-NLS-1$ public static final Measurement AZIMUTH = new Measurement(Messages.getString("measure.azimuth"), 3, true, true, false); //$NON-NLS-1$ protected static final List<Measurement> MEASUREMENT_LIST = new ArrayList<>(); static { MEASUREMENT_LIST.add(LINE_LENGTH); MEASUREMENT_LIST.add(ORIENTATION); MEASUREMENT_LIST.add(AZIMUTH); } // Let AB & CD two perpendicular line segments with D being the projected point C on AB protected Point2D.Double ptA; protected Point2D.Double ptB; protected Point2D.Double ptC; protected Point2D.Double ptD; // estimate if line segments are valid or not protected boolean lineABvalid; protected boolean lineCDvalid; public PerpendicularLineGraphic() { super(POINTS_NUMBER); } public PerpendicularLineGraphic(PerpendicularLineGraphic graphic) { super(graphic); } @Override public PerpendicularLineGraphic copy() { return new PerpendicularLineGraphic(this); } @Override public Icon getIcon() { return ICON; } @Override public String getUIName() { return Messages.getString("measure.perpendicular"); //$NON-NLS-1$ } @Override protected void prepareShape() throws InvalidShapeException { if (!isShapeValid()) { throw new InvalidShapeException("This shape cannot be drawn"); //$NON-NLS-1$ } buildShape(null); } @Override public Integer moveAndResizeOnDrawing(Integer handlePointIndex, Double deltaX, Double deltaY, MouseEventDouble mouseEvent) { List<Point2D> prevHandlePointList = getHandlePointList(); handlePointIndex = super.moveAndResizeOnDrawing(handlePointIndex, deltaX, deltaY, mouseEvent); if (handlePointIndex >= 0 && handlePointIndex < getHandlePointListSize()) { updateTool(); if (handlePointIndex == 0 || handlePointIndex == 1) { // drag point is A or B Point2D prevPtA = (!prevHandlePointList.isEmpty()) ? prevHandlePointList.get(0) : null; Point2D prevPtB = (prevHandlePointList.size() > 1) ? prevHandlePointList.get(1) : null; if (lineABvalid && GeomUtil.isLineValid(prevPtA, prevPtB) && ptC != null && ptD != null) { // compute rotation from previous to actual position double theta = GeomUtil.getAngleRad(prevPtA, prevPtB) - GeomUtil.getAngleRad(ptA, ptB); Point2D anchor = (handlePointIndex == 0) ? ptB : ptA; // anchor is opposite point of A or B AffineTransform rotate = AffineTransform.getRotateInstance(theta, anchor.getX(), anchor.getY()); rotate.transform(ptC, ptC); rotate.transform(ptD, ptD); setHandlePoint(2, ptC); setHandlePoint(3, ptD); } } else if (handlePointIndex == 2) { // drag point is C if (lineABvalid && ptC != null) { ptD = GeomUtil.getPerpendicularPointToLine(ptA, ptB, ptC); setHandlePoint(3, ptD); } } else if (handlePointIndex == 3) { // drag point is D Point2D prevPtD = (prevHandlePointList.size() > 3) ? prevHandlePointList.get(3) : null; if (lineABvalid && ptD != null && prevPtD != null && ptC != null) { ptD = GeomUtil.getPerpendicularPointToLine(ptA, ptB, ptD); AffineTransform translate = AffineTransform.getTranslateInstance(ptD.getX() - prevPtD.getX(), ptD.getY() - prevPtD.getY()); translate.transform(ptC, ptC); setHandlePoint(2, ptC); setHandlePoint(3, ptD); } } } return handlePointIndex; } @Override public void buildShape(MouseEventDouble mouseEvent) { updateTool(); Shape newShape = null; Path2D path = new Path2D.Double(Path2D.WIND_NON_ZERO, 2); if (lineABvalid) { path.append(new Line2D.Double(ptA, ptB), false); } if (lineCDvalid) { path.append(new Line2D.Double(ptC, ptD), false); } if (lineABvalid && lineCDvalid) { newShape = new AdvancedShape(this, 3); AdvancedShape aShape = (AdvancedShape) newShape; aShape.addShape(path); if (!ptD.equals(ptA) && !ptD.equals(ptB)) { // Check D is outside of AB segment if (MathUtil.isEqual(Math.signum(GeomUtil.getAngleDeg(ptD, ptA)), Math.signum(GeomUtil.getAngleDeg(ptD, ptB)))) { Point2D ptE = ptD.distance(ptA) < ptD.distance(ptB) ? ptA : ptB; aShape.addShape(new Line2D.Double(ptD, ptE), getDashStroke(1.0f), true); } } double cornerLength = 10; double dMin = Math.min(ptD.distance(ptC), Math.max(ptD.distance(ptA), ptD.distance(ptB))) * 2 / 3; double scalingMin = cornerLength / dMin; Point2D f = GeomUtil.getMidPoint(ptA, ptB); Shape cornerShape = GeomUtil.getCornerShape(f, ptD, ptC, cornerLength); if (cornerShape != null) { aShape.addScaleInvShape(cornerShape, ptD, scalingMin, getStroke(1.0f), true); } } else if (path.getCurrentPoint() != null) { newShape = path; } setShape(newShape, mouseEvent); updateLabel(mouseEvent, getDefaultView2d(mouseEvent)); } @Override public List<MeasureItem> computeMeasurements(MeasurableLayer layer, boolean releaseEvent, Unit displayUnit) { if (layer != null && layer.hasContent() && isShapeValid()) { MeasurementsAdapter adapter = layer.getMeasurementAdapter(displayUnit); if (adapter != null) { ArrayList<MeasureItem> measVal = new ArrayList<>(3); if (LINE_LENGTH.getComputed()) { measVal.add( new MeasureItem(LINE_LENGTH, ptC.distance(ptD) * adapter.getCalibRatio(), adapter.getUnit())); } if (ORIENTATION.getComputed()) { measVal.add(new MeasureItem(ORIENTATION, MathUtil.getOrientation(ptC, ptD), Messages.getString("measure.deg"))); //$NON-NLS-1$ } if (AZIMUTH.getComputed()) { measVal.add( new MeasureItem(AZIMUTH, MathUtil.getAzimuth(ptC, ptD), Messages.getString("measure.deg"))); //$NON-NLS-1$ } return measVal; } } return Collections.emptyList(); } @Override public boolean isShapeValid() { updateTool(); return lineABvalid && lineCDvalid; } protected void updateTool() { ptA = getHandlePoint(0); ptB = getHandlePoint(1); ptC = getHandlePoint(2); ptD = getHandlePoint(3); lineABvalid = ptA != null && ptB != null && !ptB.equals(ptA); lineCDvalid = ptC != null && ptD != null && !ptC.equals(ptD); } @Override public List<Measurement> getMeasurementList() { return MEASUREMENT_LIST; } }
epl-1.0
lunifera/lunifera-ecview
org.lunifera.ecview.core.extension.model/src/org/lunifera/ecview/core/extension/model/datatypes/impl/YDateTimeDatatypeImpl.java
12239
/** * Copyright (c) 2011 - 2015, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg) * 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: * Florian Pirchner - Initial implementation */ package org.lunifera.ecview.core.extension.model.datatypes.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectResolvingEList; import org.lunifera.ecview.core.common.model.validation.YValidator; import org.lunifera.ecview.core.extension.model.datatypes.ExtDatatypesPackage; import org.lunifera.ecview.core.extension.model.datatypes.YDateTimeDatatype; import org.lunifera.ecview.core.extension.model.datatypes.YDateTimeFormat; import org.lunifera.ecview.core.extension.model.datatypes.YDateTimeResolution; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>YDate Time Datatype</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.lunifera.ecview.core.extension.model.datatypes.impl.YDateTimeDatatypeImpl#getId <em>Id</em>}</li> * <li>{@link org.lunifera.ecview.core.extension.model.datatypes.impl.YDateTimeDatatypeImpl#getName <em>Name</em>}</li> * <li>{@link org.lunifera.ecview.core.extension.model.datatypes.impl.YDateTimeDatatypeImpl#getDescription <em>Description</em>}</li> * <li>{@link org.lunifera.ecview.core.extension.model.datatypes.impl.YDateTimeDatatypeImpl#getValidators <em>Validators</em>}</li> * <li>{@link org.lunifera.ecview.core.extension.model.datatypes.impl.YDateTimeDatatypeImpl#getFormat <em>Format</em>}</li> * <li>{@link org.lunifera.ecview.core.extension.model.datatypes.impl.YDateTimeDatatypeImpl#getResolution <em>Resolution</em>}</li> * </ul> * </p> * * @generated */ public class YDateTimeDatatypeImpl extends MinimalEObjectImpl.Container implements YDateTimeDatatype { /** * The default value of the '{@link #getId() <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getId() * @generated * @ordered */ protected static final String ID_EDEFAULT = null; /** * The cached value of the '{@link #getId() <em>Id</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getId() * @generated * @ordered */ protected String id = ID_EDEFAULT; /** * 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 #getDescription() <em>Description</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDescription() * @generated * @ordered */ protected static final String DESCRIPTION_EDEFAULT = null; /** * The cached value of the '{@link #getDescription() <em>Description</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDescription() * @generated * @ordered */ protected String description = DESCRIPTION_EDEFAULT; /** * The cached value of the '{@link #getValidators() <em>Validators</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getValidators() * @generated * @ordered */ protected EList<YValidator> validators; /** * The default value of the '{@link #getFormat() <em>Format</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFormat() * @generated * @ordered */ protected static final YDateTimeFormat FORMAT_EDEFAULT = YDateTimeFormat.DATE; /** * The cached value of the '{@link #getFormat() <em>Format</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getFormat() * @generated * @ordered */ protected YDateTimeFormat format = FORMAT_EDEFAULT; /** * The default value of the '{@link #getResolution() <em>Resolution</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getResolution() * @generated * @ordered */ protected static final YDateTimeResolution RESOLUTION_EDEFAULT = YDateTimeResolution.UNDEFINED; /** * The cached value of the '{@link #getResolution() <em>Resolution</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getResolution() * @generated * @ordered */ protected YDateTimeResolution resolution = RESOLUTION_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected YDateTimeDatatypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ExtDatatypesPackage.Literals.YDATE_TIME_DATATYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getId() { return id; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setId(String newId) { String oldId = id; id = newId; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ExtDatatypesPackage.YDATE_TIME_DATATYPE__ID, oldId, id)); } /** * <!-- 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, ExtDatatypesPackage.YDATE_TIME_DATATYPE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getDescription() { return description; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDescription(String newDescription) { String oldDescription = description; description = newDescription; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ExtDatatypesPackage.YDATE_TIME_DATATYPE__DESCRIPTION, oldDescription, description)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<YValidator> getValidators() { if (validators == null) { validators = new EObjectResolvingEList<YValidator>(YValidator.class, this, ExtDatatypesPackage.YDATE_TIME_DATATYPE__VALIDATORS); } return validators; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public YDateTimeFormat getFormat() { return format; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setFormat(YDateTimeFormat newFormat) { YDateTimeFormat oldFormat = format; format = newFormat == null ? FORMAT_EDEFAULT : newFormat; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ExtDatatypesPackage.YDATE_TIME_DATATYPE__FORMAT, oldFormat, format)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public YDateTimeResolution getResolution() { return resolution; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setResolution(YDateTimeResolution newResolution) { YDateTimeResolution oldResolution = resolution; resolution = newResolution == null ? RESOLUTION_EDEFAULT : newResolution; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ExtDatatypesPackage.YDATE_TIME_DATATYPE__RESOLUTION, oldResolution, resolution)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ExtDatatypesPackage.YDATE_TIME_DATATYPE__ID: return getId(); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__NAME: return getName(); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__DESCRIPTION: return getDescription(); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__VALIDATORS: return getValidators(); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__FORMAT: return getFormat(); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__RESOLUTION: return getResolution(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ExtDatatypesPackage.YDATE_TIME_DATATYPE__ID: setId((String)newValue); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__NAME: setName((String)newValue); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__DESCRIPTION: setDescription((String)newValue); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__VALIDATORS: getValidators().clear(); getValidators().addAll((Collection<? extends YValidator>)newValue); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__FORMAT: setFormat((YDateTimeFormat)newValue); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__RESOLUTION: setResolution((YDateTimeResolution)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ExtDatatypesPackage.YDATE_TIME_DATATYPE__ID: setId(ID_EDEFAULT); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__NAME: setName(NAME_EDEFAULT); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__DESCRIPTION: setDescription(DESCRIPTION_EDEFAULT); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__VALIDATORS: getValidators().clear(); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__FORMAT: setFormat(FORMAT_EDEFAULT); return; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__RESOLUTION: setResolution(RESOLUTION_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ExtDatatypesPackage.YDATE_TIME_DATATYPE__ID: return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__DESCRIPTION: return DESCRIPTION_EDEFAULT == null ? description != null : !DESCRIPTION_EDEFAULT.equals(description); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__VALIDATORS: return validators != null && !validators.isEmpty(); case ExtDatatypesPackage.YDATE_TIME_DATATYPE__FORMAT: return format != FORMAT_EDEFAULT; case ExtDatatypesPackage.YDATE_TIME_DATATYPE__RESOLUTION: return resolution != RESOLUTION_EDEFAULT; } 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(" (id: "); result.append(id); result.append(", name: "); result.append(name); result.append(", description: "); result.append(description); result.append(", format: "); result.append(format); result.append(", resolution: "); result.append(resolution); result.append(')'); return result.toString(); } } //YDateTimeDatatypeImpl
epl-1.0
asupdev/asup
org.eclipse.datatools.enablement.asup/src/org/eclipse/datatools/enablement/asup/ASUPConnectionPing.java
1063
/** * Copyright (c) 2012, 2014 Sme.UP 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: * Mattia Rocchi - Initial API and implementation */ package org.eclipse.datatools.enablement.asup; import org.eclipse.datatools.connectivity.IConnection; import org.eclipse.datatools.connectivity.IConnectionProfile; public class ASUPConnectionPing implements IConnection { IConnectionProfile profile; public ASUPConnectionPing(IConnectionProfile profile) { this.profile = profile; } @Override public Object getRawConnection() { // TODO Auto-generated method stub return null; } @Override public void close() { } @Override public Throwable getConnectException() { // TODO Auto-generated method stub return null; } @Override public IConnectionProfile getConnectionProfile() { return profile; } }
epl-1.0
francoispfister/diagraph
org.isoe.extensionpoint.xmi/src/org/isoe/extensionpoint/xmi/IMetamodelRetriever.java
1397
/** * Copyright (c) 2014 Laboratoire de Genie Informatique et Ingenierie de Production - Ecole des Mines d'Ales * * 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: * Francois Pfister (ISOE-LGI2P) - initial API and implementation */ package org.isoe.extensionpoint.xmi; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EPackage; /** * * @author fpfister * */ import org.isoe.diagraph.controler.IDiagraphControler; //FP140707refactored public interface IMetamodelRetriever { //org.isoe.extensionpoint.xmi.IMetamodelRetriever IFile getCurrentFile(); String getMetamodelBase(); String getDomain(); String getNsPrefix(); String getNsURI(); EPackage getCurrentPackage(); void setCurrentFile(IFile cfile); void markUnregisteredModels(IProgressMonitor progressMonitor); boolean isInterrupted(); EPackage findRegisteredMetamodel(URI uri, IProgressMonitor progressMonitor); EPackage findRegisteredMetamodel(IFile file); boolean isQualified(); boolean isStub(); void setSilent(boolean silent); void setControler(IDiagraphControler controler); }
epl-1.0
jobez/nncloj
resources/public/javascripts/menu/out/om_sync/util.js
3226
// Compiled by ClojureScript 0.0-2173 goog.provide('om_sync.util'); goog.require('cljs.core'); goog.require('goog.events.EventType'); goog.require('goog.net.XhrIo'); goog.require('goog.events'); goog.require('goog.events'); goog.require('cljs.reader'); goog.require('cljs.reader'); om_sync.util.popn = (function popn(n,v){var n__$1 = n;var res = v;while(true){ if((n__$1 > 0)) {{ var G__10506 = (n__$1 - 1); var G__10507 = cljs.core.pop.call(null,res); n__$1 = G__10506; res = G__10507; continue; } } else {return res; } break; } }); om_sync.util.sub = (function sub(p0,p1){return cljs.core.vec.call(null,cljs.core.drop.call(null,(cljs.core.count.call(null,p0) - cljs.core.count.call(null,p1)),p0)); }); om_sync.util.tx_tag = (function tx_tag(p__10508){var map__10510 = p__10508;var map__10510__$1 = ((cljs.core.seq_QMARK_.call(null,map__10510))?cljs.core.apply.call(null,cljs.core.hash_map,map__10510):map__10510);var tx_data = map__10510__$1;var tag = cljs.core.get.call(null,map__10510__$1,new cljs.core.Keyword(null,"tag","tag",1014018828));if((tag instanceof cljs.core.Keyword)) {return tag; } else {return cljs.core.first.call(null,tag); } }); om_sync.util.subpath_QMARK_ = (function subpath_QMARK_(a,b){return cljs.core._EQ_.call(null,a,om_sync.util.popn.call(null,(cljs.core.count.call(null,b) - cljs.core.count.call(null,a)),b)); }); om_sync.util.error_QMARK_ = (function error_QMARK_(res){return cljs.core.contains_QMARK_.call(null,res,new cljs.core.Keyword(null,"error","error",1110689146)); }); om_sync.util.meths = new cljs.core.PersistentArrayMap(null, 4, [new cljs.core.Keyword(null,"get","get",1014006472),"GET",new cljs.core.Keyword(null,"put","put",1014015617),"PUT",new cljs.core.Keyword(null,"post","post",1017351186),"POST",new cljs.core.Keyword(null,"delete","delete",3973413149),"DELETE"], null); om_sync.util.edn_xhr = (function edn_xhr(p__10511){var map__10513 = p__10511;var map__10513__$1 = ((cljs.core.seq_QMARK_.call(null,map__10513))?cljs.core.apply.call(null,cljs.core.hash_map,map__10513):map__10513);var on_error = cljs.core.get.call(null,map__10513__$1,new cljs.core.Keyword(null,"on-error","on-error",1418576908));var on_complete = cljs.core.get.call(null,map__10513__$1,new cljs.core.Keyword(null,"on-complete","on-complete",2943599833));var data = cljs.core.get.call(null,map__10513__$1,new cljs.core.Keyword(null,"data","data",1016980252));var url = cljs.core.get.call(null,map__10513__$1,new cljs.core.Keyword(null,"url","url",1014020321));var method = cljs.core.get.call(null,map__10513__$1,new cljs.core.Keyword(null,"method","method",4231316563));var xhr = (new goog.net.XhrIo());goog.events.listen(xhr,goog.net.EventType.SUCCESS,(function (e){return on_complete.call(null,cljs.reader.read_string.call(null,xhr.getResponseText())); })); goog.events.listen(xhr,goog.net.EventType.ERROR,(function (e){return on_error.call(null,new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"error","error",1110689146),xhr.getResponseText()], null)); })); return xhr.send(url,om_sync.util.meths.call(null,method),(cljs.core.truth_(data)?cljs.core.pr_str.call(null,data):null),{"Accept": "application/edn", "Content-Type": "application/edn"}); }); //# sourceMappingURL=util.js.map
epl-1.0
nickmain/xmind
bundles/org.xmind.ui.toolkit/src/org/xmind/ui/richtext/Hyperlink.java
1464
package org.xmind.ui.richtext; public class Hyperlink implements Cloneable { public int start; public int length; public String href; public Hyperlink(int start, int length, String hyperlink) { this.start = start; this.length = length; this.href = hyperlink; } public int end() { return start + length; } public boolean equals(Object obj) { if (obj == this) return true; if (obj != null || !(obj instanceof Hyperlink)) return false; Hyperlink that = (Hyperlink) obj; return this.start == that.start && this.length == that.length && this.href.equals(that.href); } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("hyperlink{start="); //$NON-NLS-1$ stringBuilder.append(start); stringBuilder.append(","); //$NON-NLS-1$ stringBuilder.append("end="); //$NON-NLS-1$ stringBuilder.append(end()); stringBuilder.append(","); //$NON-NLS-1$ stringBuilder.append("hyperlimk="); //$NON-NLS-1$ stringBuilder.append(href); stringBuilder.append("}"); //$NON-NLS-1$ return stringBuilder.toString(); } public Object clone() { Hyperlink clone = new Hyperlink(this.start, this.length, this.href); return clone; } }
epl-1.0
Alisontalha/DP-57926
Duck example/src/Fly.java
109
public class Fly implements Flyable { public void fly() { System.out.println("I fly"); } }
epl-1.0
mbats/mindstorms
plugins/fr.obeo.dsl.mindstorms/src-gen/fr/obeo/dsl/mindstorms/ReturnBottleToBase.java
1145
/** * Copyright (c) 2015 Obeo. * 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: * Obeo - initial API and implementation */ package fr.obeo.dsl.mindstorms; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Return Bottle To Base</b></em>'. * <!-- end-user-doc --> * * * @see fr.obeo.dsl.mindstorms.MindstormsPackage#getReturnBottleToBase() * @model * @generated */ public interface ReturnBottleToBase extends Behavior { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String copyright = "Copyright (c) 2015 Obeo.\r\nAll rights reserved. This program and the accompanying materials\r\nare made available under the terms of the Eclipse Public License v1.0\r\nwhich accompanies this distribution, and is available at\r\nhttp://www.eclipse.org/legal/epl-v10.html\r\n\r\nContributors:\r\n Obeo - initial API and implementation"; } // ReturnBottleToBase
epl-1.0